From 27fb681f7cea01d42805624ed99c8f96dcf19540 Mon Sep 17 00:00:00 2001 From: karim Date: Tue, 20 Oct 2026 00:31:03 +0200 Subject: [PATCH] Eckpunkt ziehen: Projekt aendert sich erst beim Setzen (bis dahin nur Vorschau); native Chunk-Updates senden nur geaenderte Blocke statt des ganzen Puffers --- src-tauri/render2d/src/chunks.rs | 25 ++++++- src-tauri/src/lib.rs | 33 +++++++++ src-tauri/src/native_embed.rs | 8 +++ src/plan/glPlan/nativeGl.test.ts | 68 ++++++++++++++++++ src/plan/glPlan/nativeGl.ts | 115 +++++++++++++++++++++++++++++-- src/state/useGripEditing.ts | 61 ++++++++++++---- 6 files changed, 289 insertions(+), 21 deletions(-) create mode 100644 src/plan/glPlan/nativeGl.test.ts diff --git a/src-tauri/render2d/src/chunks.rs b/src-tauri/render2d/src/chunks.rs index 38da52b1..7e0e5cda 100644 --- a/src-tauri/render2d/src/chunks.rs +++ b/src-tauri/render2d/src/chunks.rs @@ -402,11 +402,34 @@ impl ChunkRenderer { let buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("chunks.buf"), contents: &bytes[..len], - usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::INDEX, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, }); self.buffers.insert(id, buf); } + /// Aendert einen vorhandenen Puffer ab und legt ihn unter einer NEUEN ID ab: + /// nur die geaenderten Bereiche (`ranges` = (Offset, Laenge) in Bytes, `bytes` = + /// deren Inhalte hintereinander) werden geschrieben. Gibt `false` zurueck, wenn + /// der alte Puffer fehlt oder die Angaben nicht passen (Aufrufer sendet dann voll). + pub fn patch(&mut self, queue: &wgpu::Queue, from: u32, to: u32, ranges: &[(u64, u64)], bytes: &[u8]) -> bool { + let total: u64 = ranges.iter().map(|r| r.1).sum(); + if total != bytes.len() as u64 { + return false; + } + let Some(buf) = self.buffers.get(&from) else { return false }; + if ranges.iter().any(|(o, l)| o % 4 != 0 || l % 4 != 0 || o + l > buf.size()) { + return false; + } + let buf = self.buffers.remove(&from).unwrap(); + let mut pos = 0usize; + for (off, len) in ranges { + queue.write_buffer(&buf, *off, &bytes[pos..pos + *len as usize]); + pos += *len as usize; + } + self.buffers.insert(to, buf); + true + } + pub fn delete(&mut self, ids: &[u32]) { for id in ids { self.buffers.remove(id); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index b1424c1a..e9567b98 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -126,6 +126,37 @@ fn native2d_upload(app: tauri::AppHandle, request: tauri::ipc::Request<'_>) -> R Ok(()) } +/// Puffer-Patch: alten Puffer (`x-from`) unter neuer ID (`x-to`) weiterfuehren und +/// nur die Bereiche aus `x-ranges` ("offset:laenge,offset:laenge") ueberschreiben. +/// Body = die Bytes dieser Bereiche hintereinander. `false` → Aufrufer sendet voll. +#[tauri::command] +fn native2d_patch(app: tauri::AppHandle, request: tauri::ipc::Request<'_>) -> Result { + #[cfg(all(feature = "native2d", target_os = "macos"))] + { + let h = request.headers(); + let get = |k: &str| h.get(k).and_then(|v| v.to_str().ok()).map(|v| v.to_string()); + let from: u32 = get("x-from").and_then(|v| v.parse().ok()).ok_or("x-from fehlt")?; + let to: u32 = get("x-to").and_then(|v| v.parse().ok()).ok_or("x-to fehlt")?; + let ranges: Vec<(u64, u64)> = get("x-ranges") + .ok_or("x-ranges fehlt")? + .split(',') + .filter_map(|r| { + let (o, l) = r.split_once(':')?; + Some((o.parse().ok()?, l.parse().ok()?)) + }) + .collect(); + let tauri::ipc::InvokeBody::Raw(bytes) = request.body() else { + return Err("Rohdaten erwartet".into()); + }; + return Ok(native_embed::patch(&app, from, to, &ranges, bytes)); + } + #[cfg(not(all(feature = "native2d", target_os = "macos")))] + { + let _ = (app, request); + Ok(false) + } +} + #[tauri::command] fn native2d_layout(app: tauri::AppHandle, layout: serde_json::Value, delete: Vec) -> Result<(), String> { #[cfg(all(feature = "native2d", target_os = "macos"))] @@ -216,6 +247,7 @@ pub fn run() { native2d_embed_available, native2d_embed_hide, native2d_upload, + native2d_patch, native2d_layout, native2d_frame, native2d_texts, @@ -231,6 +263,7 @@ pub fn run() { native2d_embed_available, native2d_embed_hide, native2d_upload, + native2d_patch, native2d_layout, native2d_frame, native2d_texts, diff --git a/src-tauri/src/native_embed.rs b/src-tauri/src/native_embed.rs index 9600d25e..1cb53dec 100644 --- a/src-tauri/src/native_embed.rs +++ b/src-tauri/src/native_embed.rs @@ -232,3 +232,11 @@ pub fn set_texts(app: &AppHandle, upsert: Vec, remove: Vec) -> bool None => false, } } + +/// Geaenderte Bereiche eines Puffers einspielen und ihn unter neuer ID fuehren. +pub fn patch(app: &AppHandle, from: u32, to: u32, ranges: &[(u64, u64)], bytes: &[u8]) -> bool { + match app.state::().0.lock().unwrap().as_mut() { + Some(e) => e.renderer.patch(&e.queue, from, to, ranges, bytes), + None => false, + } +} diff --git a/src/plan/glPlan/nativeGl.test.ts b/src/plan/glPlan/nativeGl.test.ts new file mode 100644 index 00000000..2c2f2178 --- /dev/null +++ b/src/plan/glPlan/nativeGl.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from 'vitest'; +import { NativeGl, blockHashes, changedRanges } from './nativeGl'; + +const mk = (n: number, fill = 1) => { + const a = new Uint8Array(n); + for (let i = 0; i < n; i++) a[i] = (i * 31 + fill) & 255; + return a; +}; + +describe('Änderungsvergleich', () => { + it('findet nur geänderte, zusammengefasste Blöcke', () => { + const a = mk(100_000); + const b = a.slice(); + b[20_000] ^= 1; // Block 1 + b[36_000] ^= 1; // Block 2 (angrenzend) + b[90_000] ^= 1; // Block 5 + const r = changedRanges(blockHashes(a), blockHashes(b), a.byteLength); + expect(r).toEqual([[16384, 32768], [81920, 16384]]); + }); + it('identische Daten → keine Bereiche', () => { + const a = mk(50_000); + expect(changedRanges(blockHashes(a), blockHashes(a.slice()), a.byteLength)).toEqual([]); + }); +}); + +describe('NativeGl: Patch statt Voll-Upload', () => { + it('gleich grosser Ersatz eines freigegebenen Puffers geht als Patch', () => { + const calls: { cmd: string; headers?: Record; len: number }[] = []; + const gl = new NativeGl(async (cmd, body, opts) => { + calls.push({ cmd, headers: (opts as any)?.headers, len: (body as Uint8Array).byteLength }); + return true; + }); + const upload = (bytes: Uint8Array) => { + const b = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, b); + gl.bufferData(gl.ARRAY_BUFFER, bytes, gl.STATIC_DRAW); + return b; + }; + const first = mk(200_000); + const b1 = upload(first); + gl.takeLayout([]); + expect(calls.map((c) => c.cmd)).toEqual(['native2d_upload']); + + const second = first.slice(); + second[100_000] ^= 1; + gl.deleteBuffer(b1); + upload(second); + gl.takeLayout([]); + expect(calls[1].cmd).toBe('native2d_patch'); + expect(calls[1].len).toBeLessThan(40_000); + expect(calls[1].headers!['x-from']).toBe('1'); + expect(calls[1].headers!['x-to']).toBe('2'); + }); + it('andere Grösse → Voll-Upload', () => { + const cmds: string[] = []; + const gl = new NativeGl(async (cmd) => (cmds.push(cmd), true)); + const b = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, b); + gl.bufferData(gl.ARRAY_BUFFER, mk(100_000), gl.STATIC_DRAW); + gl.takeLayout([]); + gl.deleteBuffer(b); + const c = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, c); + gl.bufferData(gl.ARRAY_BUFFER, mk(120_000), gl.STATIC_DRAW); + gl.takeLayout([]); + expect(cmds).toEqual(['native2d_upload', 'native2d_upload']); + }); +}); diff --git a/src/plan/glPlan/nativeGl.ts b/src/plan/glPlan/nativeGl.ts index 85d973bf..0a0558d4 100644 --- a/src/plan/glPlan/nativeGl.ts +++ b/src/plan/glPlan/nativeGl.ts @@ -28,6 +28,50 @@ export interface NativeChunkLayout { greyed: boolean; } +/** Blockgrösse für den Änderungsvergleich (Bytes; Vielfaches von 4). */ +const BLOCK = 16 * 1024; +/** Mehr als dieser Anteil geänderter Blöcke → lieber komplett senden. */ +const PATCH_MAX_FRACTION = 0.35; + +/** FNV-1a über 32-Bit-Wörter je Block (Resttail wird mit Nullen aufgefüllt gedacht). */ +export function blockHashes(bytes: Uint8Array, block = BLOCK): Uint32Array { + const n = Math.ceil(bytes.byteLength / block); + const out = new Uint32Array(n); + const words = Math.floor(bytes.byteLength / 4); + const u32 = new Uint32Array(bytes.buffer, bytes.byteOffset, words); + const per = block / 4; + for (let b = 0; b < n; b++) { + let h = 0x811c9dc5; + const end = Math.min(words, (b + 1) * per); + for (let i = b * per; i < end; i++) { + h ^= u32[i]; + h = Math.imul(h, 0x01000193); + } + out[b] = h >>> 0; + } + return out; +} + +/** Zusammenhängende geänderte Byte-Bereiche (offset, länge) zwischen zwei Hash-Listen. */ +export function changedRanges(a: Uint32Array, b: Uint32Array, byteLength: number, block = BLOCK): [number, number][] { + const out: [number, number][] = []; + for (let i = 0; i < b.length; i++) { + if (a[i] === b[i]) continue; + const off = i * block; + const len = Math.min(block, byteLength - off); + const last = out[out.length - 1]; + if (last && last[0] + last[1] === off) last[1] += len; + else out.push([off, len]); + } + return out; +} + +interface PendingUpload { + id: number; + bytes: Uint8Array; + hashes: Uint32Array; +} + export class NativeGl implements BufferGl { readonly ARRAY_BUFFER = 0x8892; readonly ELEMENT_ARRAY_BUFFER = 0x8893; @@ -37,6 +81,10 @@ export class NativeGl implements BufferGl { private nextId = 1; private bound: NativeBuffer | null = null; private pendingDelete: number[] = []; + /** Hashes + Länge ALLER an Rust gesendeten Puffer (für den Änderungsvergleich). */ + private live = new Map(); + /** Seit dem letzten `takeLayout` neu befüllte Puffer, noch nicht gesendet. */ + private queue: PendingUpload[] = []; constructor(private readonly invoke: NativeInvoke) {} @@ -51,21 +99,76 @@ export class NativeGl implements BufferGl { bufferData(_target: number, data: ArrayBufferView, _usage: number): void { const buf = this.bound; if (!buf) return; - // KOPIE: die Quelle ist ein wiederverwendeter Wachstumspuffer, der Aufruf - // serialisiert asynchron. + // KOPIE: die Quelle ist ein wiederverwendeter Wachstumspuffer. const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength).slice(); - void this.invoke('native2d_upload', bytes, { headers: { 'x-buf-id': String(buf.id) } }).catch((e) => - console.debug('native2d_upload fehlgeschlagen', e), - ); + this.queue.push({ id: buf.id, bytes, hashes: blockHashes(bytes) }); } deleteBuffer(buffer: WebGLBuffer | null): void { if (buffer) this.pendingDelete.push((buffer as unknown as NativeBuffer).id); } + private sendFull(u: PendingUpload): void { + void this.invoke('native2d_upload', u.bytes, { headers: { 'x-buf-id': String(u.id) } }).catch((e) => + console.debug('native2d_upload fehlgeschlagen', e), + ); + } + + /** + * Gesammelte Uploads senden. Ersetzt ein neuer Puffer einen gleich grossen, + * gleichzeitig freigegebenen alten (Chunk-Neuberechnung nach einer kleinen + * Änderung), gehen NUR die geänderten Blöcke über die Schnittstelle: Rust führt + * den alten GPU-Puffer unter der neuen ID weiter. + */ + private flushUploads(deleted: number[]): void { + const free = new Map(); // Länge → freigegebene Puffer-IDs + for (const id of deleted) { + const e = this.live.get(id); + if (e) (free.get(e.len) ?? free.set(e.len, []).get(e.len)!).push(id); + } + for (const u of this.queue) { + this.live.set(u.id, { len: u.bytes.byteLength, hashes: u.hashes }); + const cands = free.get(u.bytes.byteLength); + const oldId = cands?.pop(); + if (oldId === undefined || u.bytes.byteLength < 4 * BLOCK) { + if (oldId !== undefined) cands!.push(oldId); + this.sendFull(u); + continue; + } + const old = this.live.get(oldId)!; + const ranges = changedRanges(old.hashes, u.hashes, u.bytes.byteLength); + const changedBytes = ranges.reduce((s, r) => s + r[1], 0); + if (changedBytes > u.bytes.byteLength * PATCH_MAX_FRACTION) { + cands!.push(oldId); + this.sendFull(u); + continue; + } + const body = new Uint8Array(changedBytes); + let pos = 0; + for (const [off, len] of ranges) { + body.set(u.bytes.subarray(off, off + len), pos); + pos += len; + } + this.live.delete(oldId); // der alte Puffer lebt unter der neuen ID weiter + void this.invoke('native2d_patch', body, { + headers: { 'x-from': String(oldId), 'x-to': String(u.id), 'x-ranges': ranges.map((r) => `${r[0]}:${r[1]}`).join(',') }, + }) + .then((ok) => { + if (ok !== true) this.sendFull(u); // Rust kannte den alten Puffer nicht → voll senden + }) + .catch(() => this.sendFull(u)); + } + this.queue = []; + for (const id of deleted) this.live.delete(id); + } + /** Geometrien (in Zeichenreihenfolge) → Layout für Rust, plus freizugebende Puffer. */ takeLayout(geometries: readonly GpuGeometry[]): { layout: NativeChunkLayout[]; delete: number[] } { const id = (b: WebGLBuffer | null): number | null => (b ? (b as unknown as NativeBuffer).id : null); + const del = this.pendingDelete; + this.pendingDelete = []; + // Erst die Uploads (in Reihenfolge VOR dem Layout-Aufruf des Aufrufers). + this.flushUploads(del); const layout = geometries.map((g) => ({ fill_pos: id(g.fill.positionBuffer), fill_idx: id(g.fill.indexBuffer), @@ -82,8 +185,6 @@ export class NativeGl implements BufferGl { origin: [g.origin?.x ?? 0, g.origin?.y ?? 0] as [number, number], greyed: !!g.greyed, })); - const del = this.pendingDelete; - this.pendingDelete = []; return { layout, delete: del }; } } diff --git a/src/state/useGripEditing.ts b/src/state/useGripEditing.ts index 90107f53..067419c9 100644 --- a/src/state/useGripEditing.ts +++ b/src/state/useGripEditing.ts @@ -9,7 +9,7 @@ import { useRef, useState, type RefObject } from "react"; import { add, dot, leftNormal, normalize, scale, sub } from "../model/geometry"; import type { Ceiling, Drawing2D, EdgeGrip, Project, Room, Stair, Vec2 } from "../model/types"; import { drawingVertices } from "./projectSlice"; -import type { SnapResult, SnapSettings, ToolDraft, ToolMods } from "../tools/types"; +import type { DraftShape, SnapResult, SnapSettings, ToolDraft, ToolMods } from "../tools/types"; import { applyAngleConstraint, computeSnap } from "../tools/snapping"; import { useCommandTabShortcut } from "./useKeyboardShortcuts"; import type { CommandLineHandle } from "../ui/CommandLine"; @@ -446,6 +446,11 @@ export function useGripEditing(opts: { // Letzter roher Cursor des laufenden Vertex-Drags (für die Lock-Auflösung beim // Tippen, wenn gerade kein Move-Event kommt). Plus der gezogene Griff-Index. const gripDragInfoRef = useRef<{ index: number; raw: Vec2 } | null>(null); + // AUSSTEHENDER Vertex-Zug eines Polylinien-Elements: Während des Ziehens wird das + // PROJEKT NICHT verändert (sonst rechnet jede Mausbewegung den ganzen Plan neu — + // bei Katasterdaten Sekunden); nur eine Vorschau (`gripPreviewShapes`) wird + // gezeichnet. Erst beim Setzen des Punkts (onGripEnd) geht EINE Mutation ins Projekt. + const pendingGripRef = useRef<{ drawingId: string; localIndex: number; flat: number; pt: Vec2 } | null>(null); // Position des gezogenen Griffs VOR dem Drag (beim ersten Move-Event nach dem // Grab verankert) — Bezugspunkt für die Flucht-Kandidaten unten (die // Nachbarkanten müssen an ihrer URSPRÜNGLICHEN, nicht der schon verschobenen @@ -817,15 +822,37 @@ export function useGripEditing(opts: { // Mehrfachauswahl: welchem Element dieser Griff gehört, kommt aus // `gripOwners` (nicht mehr aus den singulären selectedDrawingId/-WallId). const owner = gripOwners[index]; - moveGripOf( - owner?.drawingId ?? selectedDrawingId, - owner?.wallId ?? selectedWallId, - owner?.localIndex ?? index, - pt, - scaleDenominator, - ); + const dId = owner?.drawingId ?? selectedDrawingId; + const wId = owner?.wallId ?? selectedWallId; + const local = owner?.localIndex ?? index; + // Polylinien-Eckpunkt: nur merken + Vorschau, Projekt erst beim Setzen ändern. + if (dId && !wId) { + const d = project.drawings2d.find((x) => x.id === dId); + if (d && !d.locked && d.geom.shape === "polyline" && local < d.geom.pts.length) { + pendingGripRef.current = { drawingId: dId, localIndex: local, flat: index, pt }; + return; + } + } + moveGripOf(dId, wId, local, pt, scaleDenominator); } }; + + /** Vorschau-Form des ausstehenden Eckpunkt-Zugs (leer, wenn keiner läuft). */ + const gripPreviewShapes = (): DraftShape[] => { + const pend = pendingGripRef.current; + if (!pend) return []; + const d = project.drawings2d.find((x) => x.id === pend.drawingId); + if (!d || d.geom.shape !== "polyline") return []; + const pts = d.geom.pts.map((q, i) => (i === pend.localIndex ? pend.pt : q)); + return [{ kind: "poly", pts, closed: !!d.geom.closed }]; + }; + + /** Ausstehenden Zug jetzt in das Projekt schreiben (EINE Mutation). */ + const commitPendingGrip = () => { + const pend = pendingGripRef.current; + pendingGripRef.current = null; + if (pend) moveGripOf(pend.drawingId, null, pend.localIndex, pend.pt, scaleDenominator); + }; const applyEdge = (edge: EdgeGrip, delta: Vec2) => { if (selectedRoomId) moveRoomEdge(selectedRoomId, edge.aIndex, edge.bIndex, delta); else if (selectedCeilingId) moveCeilingEdge(selectedCeilingId, edge.aIndex, edge.bIndex, delta); @@ -880,6 +907,7 @@ export function useGripEditing(opts: { edgeAppliedDeltaRef.current = null; // Kanten-Drag beendet → Anker zurücksetzen moveCoincidentRef.current = null; // Körper-Koinzidenz-Gruppe verwerfen gripDragInfoRef.current = null; // (c) Vertex-Drag-Info verwerfen + pendingGripRef.current = null; // (commitPendingGrip hat sie vorher schon geschrieben) gripOriginRef.current = null; // Flucht-Bezugspunkt verwerfen setGripEdit(null); // (c) Feld-Controller schließen edgeDragInfoRef.current = null; // Kanten-Drag-Info verwerfen @@ -901,7 +929,7 @@ export function useGripEditing(opts: { if (ge && (ge.locks.length != null || ge.locks.angle != null)) { const pt = gripEditPoint(ge.anchor, ge.locks, raw); applyGrip(index, pt); - setDraft({ preview: [], vertices: [], snap: null, hud: hudFor(index, pt) }); + setDraft({ preview: gripPreviewShapes(), vertices: [], snap: null, hud: hudFor(index, pt) }); return; } // Mehrfachauswahl: das Element, dem DIESER Griff gehört (nicht zwingend @@ -944,7 +972,7 @@ export function useGripEditing(opts: { } const pt = closestAxisPoint(raw, candidates) ?? applyAngleConstraint(anchor, raw, 90); applyGrip(index, pt); - setDraft({ preview: [], vertices: [], snap: null, hud: hudFor(index, pt) }); + setDraft({ preview: gripPreviewShapes(), vertices: [], snap: null, hud: hudFor(index, pt) }); return; } // Snap gegen das Projekt OHNE das gerade gezogene Element (sonst fängt der @@ -964,7 +992,7 @@ export function useGripEditing(opts: { }); const pt = snapResult?.point ?? raw; applyGrip(index, pt); - setDraft({ preview: [], vertices: [], snap: snapResult, hud: hudFor(index, pt) }); + setDraft({ preview: gripPreviewShapes(), vertices: [], snap: snapResult, hud: hudFor(index, pt) }); }, onMoveBody: ( delta: Vec2, @@ -1079,13 +1107,16 @@ export function useGripEditing(opts: { }); }, onGripEnd: () => { + commitPendingGrip(); endEditing(); }, // Bewaffneten Punkt-Griff verwerfen (Escape): exakt auf `origin` // zurücksetzen — ohne Snap/Ortho-Neuauswertung, ein reiner Revert — und // danach wie onGripEnd aufräumen. onGripCancel: (index: number, origin: Vec2) => { - applyGrip(index, origin); + // Ausstehender Zug: einfach verwerfen (das Projekt wurde nie verändert). + if (pendingGripRef.current) pendingGripRef.current = null; + else applyGrip(index, origin); endEditing(); }, onEdgeEnd: () => { @@ -1100,8 +1131,12 @@ export function useGripEditing(opts: { }, }; + // Der gezogene Griff folgt der Vorschau (das Projekt bleibt bis zum Setzen unverändert). + const pendingNow = pendingGripRef.current; + const displayGrips = pendingNow ? grips.map((g, i) => (i === pendingNow.flat ? pendingNow.pt : g)) : grips; + return { - grips, + grips: displayGrips, gripHandleLines, edgeGrips, gripHandlers,