From 24ab554c2e125d49b25250b2b0eb781039e27f0b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 12:42:43 +0000 Subject: [PATCH] =?UTF-8?q?[K4]=20Leistung:=20id-Suche=20indiziert=20(Kern?= =?UTF-8?q?-Index,=20Treffer-Positionen=20f=C3=BCr=20applyOps),=20Commit?= =?UTF-8?q?=20ohne=20Kopie=20(Verlauf=20nur=20inverse=20Ops),=20Dach-First?= =?UTF-8?q?h=C3=B6he=20nach=20Inhalt=20gemerkt,=20Polylinien-Punkttyp=20im?= =?UTF-8?q?=20Kern?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Objekt-Info und Griffe suchen über den Positions-Index des Dokuments (Lookup), TS-applyOps übernimmt die vom Kern getroffenen Positionen (doc_last_hits). Commit verschiebt die Ops ins Dokument; Redo entsteht beim Rückgängigmachen als Inverse der Inversen. setPolylineVertexType rechnet polyline_vertex.rs (bitgleich, 143 880 Fälle), TS-withVertexType gelöscht. --- TODO.md | 29 +- src-tauri/core/src/document.rs | 417 +++++++++++++++--------- src-tauri/core/src/grips.rs | 76 ++++- src-tauri/core/src/jsnum.rs | 14 +- src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/ops.rs | 132 ++++---- src-tauri/core/src/polyline_vertex.rs | 358 ++++++++++++++++++++ src-tauri/core/src/queries.rs | 8 +- src-tauri/core/src/selection_info.rs | 116 ++++--- src-tauri/core/src/web/document.rs | 12 +- src-tauri/core/src/web/grips.rs | 15 +- src/core/document.ts | 6 +- src/core/index.ts | 1 - src/core/ops.apply.test.ts | 41 +++ src/core/ops.ts | 111 +++++-- src/core/opsBuild.ts | 6 +- src/geometry/grips.ts | 1 + src/geometry/polylineVertexType.test.ts | 60 ++-- src/geometry/polylineVertexType.ts | 176 +--------- src/state/objectInfo.perf.test.ts | 93 ++++++ src/state/projectSlice.ts | 14 +- src/state/selectionInfo.ts | 19 +- 22 files changed, 1168 insertions(+), 538 deletions(-) create mode 100644 src-tauri/core/src/polyline_vertex.rs create mode 100644 src/state/objectInfo.perf.test.ts diff --git a/TODO.md b/TODO.md index 08dc6cec..f8572269 100644 --- a/TODO.md +++ b/TODO.md @@ -637,9 +637,9 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern Last; Stand nach dem Nachtrag unten): Wand-Griff an Position 10/1500/2990 32/150/315 µs → 28/116/262 µs (dominiert von der linearen id-Suche), Polylinien-Griff 78 → 58 µs, Polylinien-Kante 72 → 57 µs, Wand verschieben 131 → 115 µs, Griff an einer 5000-Punkte-Polylinie 13,7 → 9,1 ms; Griff-Liste der 5000-Punkte-Polylinie 2,7 → 1,1 ms (kleine Polylinie 2 µs, gleich). - Nicht in der Tauri-App geprüft (vitest/Linux, e2e im Browser). Offen: `setPolylineVertexType` + Nicht in der Tauri-App geprüft (vitest/Linux, e2e im Browser). ~~Offen: `setPolylineVertexType` (rechnet in `geometry/polylineVertexType.ts`), die lineare id-Suche je Mausschritt (im Kern beim Rechnen und beim Commit, - in TS in `applyOps`) und der Commit grosser Polylinien (~9 ms bei 5000 Punkten: Verlauf/Prüfung in `document.rs`/`ops.rs`). + in TS in `applyOps`) und der Commit grosser Polylinien (~9 ms bei 5000 Punkten: Verlauf/Prüfung in `document.rs`/`ops.rs`).~~ Erledigt 29.10., s. „Leistung nach der Zusammenführung“. **Objekt-Info im Kern (29.10.)** — erledigt damit (4): `selection_info.rs` (vorher `deriveSelection` in `state/selectionInfo.ts`, ~800 Zeilen Rechnung) liefert als Wurzel-Abfrage `selectionInfo` den Kontrakt `Selection` für das erste gewählte Element (Vorrang wie bisher): effektive Farbe/Strichstärke/Schraffur/Vorder-/Hintergrund (Element → Linienstil → Ebene → Bauteil), @@ -676,6 +676,31 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern zusammenlegen); `wallCorners` (Plan-Treffer `planHitTest`, Werkzeug-Vorschau, Griff-Vorschau, `voids`, STEP-Export — ein Kern-Aufruf je Wand wäre teurer als die vier Punkte) und `wallReferenceOffset` (Fang, `geometry/opening.ts`). Nicht in der Tauri-App geprüft (3D-Griffe nur über e2e im Browser). + **Leistung nach der Zusammenführung (29.10.)** — erledigt damit die Offen-Punkte der Griffe/Objekt-Info: + (a) **id-Suche indiziert:** der Positions-Index des Dokuments (`PosCache`) wird ab der ersten Suche gebaut (Listen + ≥ 32), überlebt `add` am Ende und ist über `Lookup` (`Document::lookup`) auch für die Wurzel-Abfragen da — Griffe + (`grips::run`) und Objekt-Info (`selection_info::derive`) suchen nicht mehr linear; die Fassade schickt keine + Lage-Hinweise mehr (`at` entfällt, TS-`findIndex` je Darstellung weg). TS-`applyOps` bekommt je Op die vom Kern + getroffene Position (`doc_last_hits` nach Commit/Griff/Undo/Redo, nachgeprüft) und sucht nicht mehr; ohne Hinweis + (`findItem`) hilft `indexOfId` (Index je Listen-Linie, ab der zweiten Suche — ein `Map` über 20 000 ids kostet in + V8 ~6 ms, das 20-fache einer linearen Suche). (b) **Commit ohne Kopie:** die Ops gehen ins Dokument über (Prüfung + der Werte vor, der doppelten ids nach dem Anwenden, `ops::value_problems`/`add_dup_problem`); der Verlauf hält nur + noch die inversen Ops, den Redo-Schritt liefert das Rückgängigmachen selbst (Inverse der Inversen) — halber + Verlaufsspeicher, keine Vorwärts-Kopie/-Verdichtung je Mausschritt. Nativ: Commit einer 5000-Punkte-Polylinie + 4,1 → 1,5 ms (`messung_grosse_polylinie`). (c) **Dach-Firsthöhe** nach Inhalt gemerkt (Hash + Vergleich, bis 4096 + Einträge) statt der letzten 16 Dächer. (d) **`setPolylineVertexType` im Kern:** `polyline_vertex.rs` (Ecke/Bogen/ + Spline, `tan` neu in `jsnum`), Griff-Änderung `vertexType`, Kontextmenü über `polyline_vertex_info`; TS-Rechnung + gelöscht (`withVertexType`). Gleichheit (einmalig, Test gelöscht): 143 880 Fälle (offene/geschlossene Polylinien, + doppelte/kollineare Punkte, fehlende Bögen, Massstäbe 1e-4…1e5) bitgleich, `vertexTypeOf`/`canSetVertexType` gleich. + Abweichung (gewollt): keine Änderung → keine Op (vorher ein leerer Undo-Schritt), ein Index ohne Punkt ändert nichts. + Messung (vitest/Store, 3000 Wände + 20 000 Zeichnungen + 40 Dächer, `objectInfo.perf.test.ts`, alt/neu abwechselnd, + Container stark unter Last — Werte streuen ±50 %): Objekt-Info Zeichnung (Pos. 10 000) 257–304 → 10–15 µs, Wand + 91–316 → 36–209 µs (ruhig gemessen: 47 µs, davon Kern 36 µs), Dach (40 im Wechsel) 44–109 → 40–102 µs; Griff an + Zeichnung 15 000 1,9–4,9 ms → 0,19–0,34 ms, Wand an Pos. 1500/2990 129–418 → 55–122 µs; Griff 5000-Punkte-Polylinie + 14–16 → 6,6–10 ms (Rest: JSON 200 KB hin und Parse in TS ≈ 2 ms, neue Polylinie im Kern); Punkttyp kleine Polylinie + ~1 ms → 0,2–0,5 ms, 5000 Punkte 18–22 → 9–16 ms; Auswahl (300 Wände) verschieben unverändert (5–11 ms). Bleibt: + die Kopie der Liste in TS je Änderung (`slice` von 20 000 Elementen ≈ 0,14 ms) — Preis der unveränderlichen + Leseansicht. Nicht in der Tauri-App geprüft. - ◐ **S4 Typen aus Rust**: `types.ts` wird aus den Rust-Strukturen erzeugt (ts-rs); Datei-I/O (`projectFormat`, Migration, IFC/DXF/ STEP-Ex- und -Import) im Kern. **Typen (28.10.):** Das Rust-Modell (`core/src/model/generated.rs`, `manual.rs`) ist die Quelle; ts-rs 12 (MIT, nur diff --git a/src-tauri/core/src/document.rs b/src-tauri/core/src/document.rs index b3f71c18..290ba71b 100644 --- a/src-tauri/core/src/document.rs +++ b/src-tauri/core/src/document.rs @@ -8,9 +8,10 @@ use crate::model::Project; pub use crate::ops::Op; -use crate::ops::{has_dup, id_of, unique_ids, History}; +use crate::ops::{has_dup, id_of, unique_ids, History, Step}; use serde::Deserialize; use serde_json::{Map, Value}; +use std::cell::RefCell; use std::collections::{HashMap, HashSet}; #[derive(Clone, Debug, Default)] @@ -28,9 +29,12 @@ pub struct Document { revs: Revs, /// Caches der Plan-Erzeugung (`plan::cache`), gültig über [`Revs`]. plan_cache: crate::plan::cache::PlanCache, - /// id → Position je Liste über die Aufrufe hinweg (eine Änderung an einem Element einer grossen - /// Liste sucht dann nicht jedes Mal linear); jede Op ausser `replace` verwirft ihre Liste. - pos: PosCache, + /// id → Position je Liste über die Aufrufe hinweg (s. [`PosCache`]); in einer `RefCell`, damit auch + /// lesende Abfragen ([`Lookup`]) den Index bauen und nutzen. + pos: RefCell, + /// Je Op der zuletzt angewendeten Folge (Commit, Abgleich, Undo/Redo) die Position des von `replace` + /// getroffenen Elements: TS führt die Leseansicht damit ohne Suche nach ([`Document::last_hits`]). + last_hits: Vec>, } /// Änderungsstände ([K4], Caches der Ableitungen): ein globaler Zähler; jede Op vergibt ihrem Feld @@ -92,53 +96,91 @@ impl Revs { &self.items[key] } - /// Element-Stände nach einer Op auf der Liste nachführen (`before` = Länge vor der Op). - fn item_op(&mut self, op: &Op, before: usize, removed: Option<&[bool]>, hit: Option) { - let key = op.key(); + /// Element-Stände nach einer Op auf der Liste `key` nachführen (`before` = Länge vor der Op). + fn item_op(&mut self, key: &str, shape: Shape, before: usize, removed: Option<&[bool]>, hit: Option) { self.touch(key); let Some(mut v) = self.items.remove(key) else { return }; if v.len() != before { return; } - match op { - Op::Add { items, at, .. } => { + match shape { + Shape::Add { n, at } => { let at = at.map_or(v.len(), |a| a.min(v.len())); let start = self.counter; - self.counter += items.len() as u64; - v.splice(at..at, start + 1..=start + items.len() as u64); + self.counter += n as u64; + v.splice(at..at, start + 1..=start + n as u64); } - Op::Replace { .. } => match hit { + Shape::Replace => match hit { Some(i) if i < v.len() => v[i] = self.next(), Some(_) => return, None => v.push(self.next()), }, - Op::Remove { .. } => match removed { + Shape::Remove => match removed { Some(keep) if keep.len() == v.len() => { let mut k = keep.iter(); v.retain(|_| *k.next().unwrap_or(&false)); } _ => return, }, - Op::Reorder { .. } | Op::SetField { .. } => return, + Shape::Other => return, } self.items.insert(key.to_owned(), v); } } -/// id → Position je Liste für die Dauer einer Op-Folge. Nur `replace` sucht darüber; jede andere Op -/// auf der Liste verwirft den Eintrag. Erst die zweite Suche in derselben Liste baut den Index — -/// ein einzelner Drag-Schritt bleibt bei der linearen Suche, Serien (Auswahl verschieben: hunderte -/// `replace`) kosten so O(Liste + Ops) statt O(Liste · Ops). Gleiche Semantik wie `position` -/// (erstes Vorkommen). Schlüssel ist ein Hash der id (keine Text-Kopien); jeder Treffer wird an der -/// Liste nachgeprüft, bei einer Kollision sucht `find` linear. -#[derive(Clone, Debug, Default)] -struct PosCache(HashMap); +/// Art einer Op für die Element-Stände (die Op selbst ist beim Nachführen schon ins Dokument übergegangen). +#[derive(Clone, Copy)] +enum Shape { + Add { n: usize, at: Option }, + Replace, + Remove, + Other, +} -#[derive(Clone, Debug)] -enum PosEntry { - /// Einmal linear gesucht. - Once, - Built(HashMap), +impl Shape { + fn of(op: &Op) -> Shape { + match op { + Op::Add { items, at, .. } => Shape::Add { n: items.len(), at: *at }, + Op::Replace { .. } => Shape::Replace, + Op::Remove { .. } => Shape::Remove, + Op::Reorder { .. } | Op::SetField { .. } => Shape::Other, + } + } +} + +/// id → Position je Liste, über die Aufrufe hinweg im Dokument gehalten: `replace` (Commit, Undo/Redo) +/// und die Abfragen, die ein Element per id suchen (Griffe, Objekt-Info, s. [`Lookup`]), finden es ab +/// der ersten Suche über den Index statt linear (eine Änderung an einem Element einer grossen Liste +/// kostete je Mausschritt eine lineare Suche im Kern und eine in TS). `add` am Ende führt den Index +/// nach, jede andere Struktur-Op (`add` mitten hinein, `remove`, `reorder`, `setField`) verwirft ihn. +/// Kleine Listen bleiben linear. Gleiche Semantik wie `position` (erstes Vorkommen). Schlüssel ist ein +/// Hash der id (keine Text-Kopien); jeder Treffer wird an der Liste nachgeprüft, bei einer Kollision +/// sucht `find` linear. +#[derive(Clone, Debug, Default)] +pub struct PosCache(HashMap); + +/// Index id-Hash → Position einer Liste. +type IdIndex = HashMap>; + +/// Ab dieser Länge baut `find` einen Index (darunter ist die lineare Suche billiger). +const INDEX_MIN_LEN: usize = 32; + +/// Reicht den schon gestreuten id-Hash ([`id_hash`]) durch (kein zweites Hashen). +#[derive(Default)] +struct IdHasher(u64); + +impl std::hash::Hasher for IdHasher { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + for b in bytes { + self.0 = (self.0 ^ *b as u64).wrapping_mul(0x0000_0100_0000_01b3); + } + } + fn write_u64(&mut self, n: u64) { + self.0 = n; + } } /// FNV-1a über die id. @@ -152,32 +194,28 @@ impl PosCache { let Some(id) = id else { return linear(None); }; - match self.0.get(collection) { - Some(PosEntry::Built(m)) => match m.get(&id_hash(id)) { - Some(&i) if list.get(i).and_then(id_of) == Some(id) => Some(i), - Some(_) => linear(Some(id)), - None => None, - }, - Some(PosEntry::Once) => { - let mut m: HashMap = HashMap::with_capacity(list.len()); - for (i, e) in list.iter().enumerate() { - if let Some(x) = id_of(e) { - m.entry(id_hash(x)).or_insert(i); - } + if list.len() < INDEX_MIN_LEN { + return linear(Some(id)); + } + let m = self.0.entry(collection.to_owned()).or_insert_with(|| { + let mut m = IdIndex::with_capacity_and_hasher(list.len(), Default::default()); + for (i, e) in list.iter().enumerate() { + if let Some(x) = id_of(e) { + m.entry(id_hash(x)).or_insert(i); } - self.0.insert(collection.to_owned(), PosEntry::Built(m)); - self.find(collection, list, Some(id)) - } - None => { - self.0.insert(collection.to_owned(), PosEntry::Once); - linear(Some(id)) } + m + }); + match m.get(&id_hash(id)) { + Some(&i) if list.get(i).and_then(id_of) == Some(id) => Some(i), + Some(_) => linear(Some(id)), + None => None, } } - /// Element `id` wurde an Position `at` angehängt (`replace` ohne Treffer). + /// Element `id` wurde an Position `at` angehängt (`replace` ohne Treffer, `add` am Ende). fn pushed(&mut self, collection: &str, id: Option<&str>, at: usize) { - if let (Some(PosEntry::Built(m)), Some(id)) = (self.0.get_mut(collection), id) { + if let (Some(m), Some(id)) = (self.0.get_mut(collection), id) { m.entry(id_hash(id)).or_insert(at); } } @@ -187,6 +225,29 @@ impl PosCache { } } +/// Elemente der Projekt-Wurzel per id finden: im Dokument über dessen Positions-Index ([`PosCache`]), +/// sonst (Tests, Wurzel ohne Dokument) linear. Für Abfragen auf der rohen Wurzel (Griffe, Objekt-Info). +pub struct Lookup<'a> { + pub root: &'a Map, + pos: Option<&'a RefCell>, +} + +impl<'a> Lookup<'a> { + /// Ohne Index (lineare Suche). + pub fn plain(root: &'a Map) -> Self { + Lookup { root, pos: None } + } + + /// Erstes Element mit `id` in der Liste `collection`. + pub fn find(&self, collection: &str, id: &str) -> Option<&'a Value> { + let list = self.root.get(collection).and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]); + match self.pos { + Some(pos) => pos.borrow_mut().find(collection, list, Some(id)).map(|i| &list[i]), + None => list.iter().find(|e| id_of(e) == Some(id)), + } + } +} + impl Document { pub fn from_json(text: &str) -> Result { match serde_json::from_str::(text) { @@ -204,7 +265,7 @@ impl Document { self.dirty.clear(); self.dirty_items.clear(); self.revs.reset(); - self.pos = PosCache::default(); + self.pos = RefCell::default(); self.history.clear(); } @@ -277,6 +338,17 @@ impl Document { &self.root } + /// Je Op der zuletzt angewendeten Folge die Position des von `replace` getroffenen Elements (None = + /// keine `replace`-Op oder kein Treffer); nach einer Zurückweisung leer. + pub fn last_hits(&self) -> &[Option] { + &self.last_hits + } + + /// Die Wurzel mit dem Positions-Index des Dokuments (Suche per id, s. [`Lookup`]). + pub fn lookup(&self) -> Lookup<'_> { + Lookup { root: &self.root, pos: Some(&self.pos) } + } + pub fn field(&self, key: &str) -> Option<&Value> { self.root.get(key) } @@ -290,60 +362,70 @@ impl Document { } - /// Wendet eine Op ohne Aufzeichnung an (Semantik wie `applyOps` in TS). Liefert bei `replace` - /// mit Treffer dessen Position; führt die Änderungsstände nach. - fn apply_raw(&mut self, op: &Op, pos: &mut PosCache) -> Option { - if !matches!(op, Op::Replace { .. }) { - pos.forget(op.key()); + /// Wendet eine Op ohne Aufzeichnung an (Semantik wie `applyOps` in TS); die Op geht ins Dokument + /// über (keine Kopie). Liefert bei `replace` mit Treffer dessen Position; führt die Änderungsstände + /// nach. + fn apply_raw(&mut self, op: Op, pos: &mut PosCache) -> Option { + let key = op.key().to_owned(); + let shape = Shape::of(&op); + // `add` am Ende einer vorhandenen Liste lässt die Positionen stehen (Index wird nachgeführt). + let current = self.root.get(&key).and_then(Value::as_array).map(Vec::len); + let appended = matches!(op, Op::Add { at, .. } if current.is_some_and(|n| at.is_none_or(|a| a >= n))); + if !matches!(op, Op::Replace { .. }) && !appended { + pos.forget(&key); } - let before = self.root.get(op.key()).and_then(Value::as_array).map_or(0, Vec::len); + let before = current.unwrap_or(0); let mut hit = None; let mut removed = None; match op { Op::SetField { key, value, at } => match value { Some(v) => match at { - Some(i) if !self.root.contains_key(key) => { - let i = (*i).min(self.root.len()); - self.root.shift_insert(i, key.clone(), v.clone()); + Some(i) if !self.root.contains_key(&key) => { + let i = i.min(self.root.len()); + self.root.shift_insert(i, key, v); } _ => { - self.root.insert(key.clone(), v.clone()); + self.root.insert(key, v); } }, None => { - self.root.shift_remove(key); + self.root.shift_remove(&key); } }, Op::Add { collection, items, at } => { - let list = self.list_mut(collection); + let list = self.list_mut(&collection); let at = at.map_or(list.len(), |a| a.min(list.len())); - list.splice(at..at, items.iter().cloned()); + if appended { + for (k, e) in items.iter().enumerate() { + pos.pushed(&collection, id_of(e), at + k); + } + } + list.splice(at..at, items); } Op::Replace { collection, entity } => { - let list = self.list_mut(collection); - let id = id_of(entity); - match pos.find(collection, list, id) { + let list = self.list_mut(&collection); + match pos.find(&collection, list, id_of(&entity)) { Some(i) => { - list[i] = entity.clone(); + list[i] = entity; hit = Some(i); } None => { - list.push(entity.clone()); - pos.pushed(collection, id, list.len() - 1); + pos.pushed(&collection, id_of(&entity), list.len()); + list.push(entity); } } } Op::Remove { collection, ids } => { let drop: HashSet<&str> = ids.iter().map(String::as_str).collect(); let tracked = self.revs.items.contains_key(collection.as_str()); - let list = self.list_mut(collection); + let list = self.list_mut(&collection); if tracked { removed = Some(list.iter().map(|e| !id_of(e).is_some_and(|i| drop.contains(i))).collect::>()); } list.retain(|e| !id_of(e).is_some_and(|i| drop.contains(i))); } Op::Reorder { collection, ids } => { - let list = std::mem::take(self.list_mut(collection)); + let list = std::mem::take(self.list_mut(&collection)); let listed: HashSet<&str> = ids.iter().map(String::as_str).collect(); let mut by_id: HashMap<&str, &Value> = HashMap::new(); for e in &list { @@ -354,44 +436,44 @@ impl Document { } let mut ordered: Vec = ids.iter().filter_map(|id| by_id.get(id.as_str()).map(|e| (*e).clone())).collect(); ordered.extend(list.iter().filter(|e| !id_of(e).is_some_and(|i| listed.contains(i))).cloned()); - *self.list_mut(collection) = ordered; + *self.list_mut(&collection) = ordered; } } - self.revs.item_op(op, before, removed.as_deref(), hit); + self.revs.item_op(&key, shape, before, removed.as_deref(), hit); hit } /// Nach einer angenommenen Op: was die typisierte Sicht neu lesen muss (ein Element nach /// `replace` mit Treffer, sonst das Feld). - fn mark_dirty(&mut self, op: &Op, hit: Option) { - match (op, hit) { - (Op::Replace { collection, .. }, Some(i)) if self.typed.is_some() => self.dirty_items.push((collection.clone(), i)), + fn mark_dirty(&mut self, key: String, replace: bool, hit: Option) { + match hit { + Some(i) if replace && self.typed.is_some() => self.dirty_items.push((key, i)), _ => { - self.dirty.insert(op.key().to_owned()); + self.dirty.insert(key); } } } - /// Wendet eine Op an und liefert (inverse Ops in Anwendungsreihenfolge, ob die Vorwärts-Op als - /// `add` aufzuzeichnen ist — `replace` ohne Treffer). Listen bekommen feine Inverse (`replace` ↔ altes Element, `add` ↔ `remove`, + /// Wendet eine Op an und liefert (inverse Ops in Anwendungsreihenfolge, Treffer-Position bei + /// `replace`). Listen bekommen feine Inverse (`replace` ↔ altes Element, `add` ↔ `remove`, /// `remove` ↔ `add` an den alten Positionen, `reorder` ↔ alte Reihenfolge), wo das exakt ist /// (`add`: ids neu und eindeutig; `reorder`: alle ids eindeutig); sonst (fehlendes Feld, kein /// Array, Alt-Doppelungen) wird das ganze Feld samt Position gesichert. Ohne Hash über die ganze - /// Liste — ein Drag-Schritt kostet nur das Suchen des Elements. - fn apply_recorded(&mut self, op: &Op, pos: &mut PosCache) -> (Vec, bool, Option) { + /// Liste — ein Drag-Schritt kostet nur das Suchen des Elements; das neue Element geht ohne Kopie + /// ins Dokument, das alte in die inverse Op. + fn apply_recorded(&mut self, op: Op, pos: &mut PosCache) -> (Vec, Option) { let key = op.key(); let old = self.root.get(key); let snapshot = || { let at = self.root.keys().position(|k| k == key); Op::SetField { key: key.to_owned(), value: old.cloned(), at } }; - let clean = match op { + let clean = match &op { Op::SetField { .. } => None, Op::Reorder { .. } => old.and_then(Value::as_array).filter(|a| a.iter().all(|e| id_of(e).is_some()) && unique_ids(a)), _ => old.and_then(Value::as_array), }; - let mut as_add = false; - let inverse = match (op, clean) { + let inverse = match (&op, clean) { (_, None) => vec![snapshot()], (Op::Add { collection, items, .. }, Some(list)) => { let mut new_ids: HashSet<&str> = HashSet::with_capacity(items.len()); @@ -406,17 +488,14 @@ impl Document { (Op::Replace { collection, entity }, Some(list)) => match pos.find(collection, list, id_of(entity)) { Some(i) => { // Direkt ersetzen (spart die zweite Suche in `apply_raw`). - let list = self.root.get_mut(key).and_then(Value::as_array_mut).expect("Liste geprüft"); let n = list.len(); - let prev = std::mem::replace(&mut list[i], entity.clone()); - self.revs.item_op(op, n, None, Some(i)); - return (vec![Op::Replace { collection: collection.clone(), entity: prev }], false, Some(i)); - } - None => { - // Aufgezeichnet als `add` (so trifft jedes aufgezeichnete `replace` ein vorhandenes Element). - as_add = true; - vec![Op::Remove { collection: collection.clone(), ids: vec![id_of(entity).unwrap_or("").to_owned()] }] + let Op::Replace { collection, entity } = op else { unreachable!() }; + let list = self.root.get_mut(&collection).and_then(Value::as_array_mut).expect("Liste geprüft"); + let prev = std::mem::replace(&mut list[i], entity); + self.revs.item_op(&collection, Shape::Replace, n, None, Some(i)); + return (vec![Op::Replace { collection, entity: prev }], Some(i)); } + None => vec![Op::Remove { collection: collection.clone(), ids: vec![id_of(entity).unwrap_or("").to_owned()] }], }, (Op::Remove { collection, ids }, Some(list)) => { let drop: HashSet<&str> = ids.iter().map(String::as_str).collect(); @@ -440,116 +519,128 @@ impl Document { (Op::SetField { .. }, Some(_)) => unreachable!("setField hat keine Liste"), }; let hit = self.apply_raw(op, pos); - (inverse, as_add, hit) + (inverse, hit) } - /// Wendet `ops` atomar an und prüft sie (`ops::validate`). Verstösse → `Err(Meldungen)`, - /// Dokument unverändert. Ok → (je Op: als `add` aufzuzeichnen, inverse Ops). `sanitize`: die Ops - /// können Nicht-endlich-Marken enthalten (s. `ops.rs`). - fn apply_checked(&mut self, ops: &[Op], sanitize: bool) -> Result<(Vec, Vec), Vec> { + /// Wendet `ops` an und liefert die inversen Ops (Anwendungsreihenfolge), ohne Prüfung (Undo/Redo: + /// die Inverse eines Schritts ist der Gegenschritt). + fn apply_inverting(&mut self, ops: Vec) -> Vec { + let mut pos = self.pos.take(); + self.last_hits.clear(); + let mut inverses: Vec> = Vec::with_capacity(ops.len()); + for op in ops { + let (key, replace) = (op.key().to_owned(), matches!(op, Op::Replace { .. })); + let (inv, hit) = self.apply_recorded(op, &mut pos); + self.mark_dirty(key, replace, hit); + self.last_hits.push(hit); + inverses.push(inv); + } + *self.pos.get_mut() = pos; + inverses.into_iter().rev().flatten().collect() + } + + /// Wendet `ops` atomar an und prüft sie (`ops::validate`, Werte vor dem Anwenden, neue doppelte ids + /// danach — die Ops gehen ohne Kopie ins Dokument über). Verstösse → `Err(Meldungen)`, Dokument + /// unverändert. Ok → inverse Ops. `sanitize`: die Ops können Nicht-endlich-Marken enthalten + /// (s. `ops.rs`). + fn apply_checked(&mut self, ops: Vec, sanitize: bool) -> Result, Vec> { // Alt-Doppelungen der Listen merken, in die eingefügt oder die gesetzt wird. let mut had_dup: HashSet = HashSet::new(); - for op in ops { + for op in &ops { if matches!(op, Op::Add { .. } | Op::SetField { .. }) && !had_dup.contains(op.key()) && has_dup(self.root.get(op.key())) { had_dup.insert(op.key().to_owned()); } } - let mut inverses: Vec> = Vec::with_capacity(ops.len()); - let mut as_add: Vec = Vec::with_capacity(ops.len()); - let mut hits: Vec> = Vec::with_capacity(ops.len()); - let mut pos = std::mem::take(&mut self.pos); + let had = |k: &str| had_dup.contains(k); + let n = ops.len(); + let mut inverses: Vec> = Vec::with_capacity(n); + let mut hits: Vec> = Vec::with_capacity(n); + // Je Op: Feld, ob `replace`, ob `add`, Befunde der Werte. + let mut info: Vec<(String, bool, bool, Vec)> = Vec::with_capacity(n); + let mut pos = self.pos.take(); for op in ops { - let (inv, add, hit) = self.apply_recorded(op, &mut pos); + let mut found = Vec::new(); + crate::ops::value_problems(&op, &had, &mut found); + info.push((op.key().to_owned(), matches!(op, Op::Replace { .. }), matches!(op, Op::Add { .. }), found)); + let (inv, hit) = self.apply_recorded(op, &mut pos); inverses.push(inv); - as_add.push(add); hits.push(hit); } - let problems = crate::ops::validate(&self.root, ops, &|k| had_dup.contains(k)); + let mut problems = Vec::new(); + let mut dup_checked: HashSet<&str> = HashSet::new(); + for (key, _, add, found) in &mut info { + problems.append(found); + if *add && dup_checked.insert(key.as_str()) { + problems.extend(crate::ops::add_dup_problem(&self.root, key, &had)); + } + } if !problems.is_empty() { // Nach der Rücknahme gilt keine gemerkte Position mehr sicher. let mut pos = PosCache::default(); - for inv in inverses.iter().rev() { + for inv in inverses.into_iter().rev() { for op in inv { self.apply_raw(op, &mut pos); } } + self.last_hits.clear(); return Err(problems); } - self.pos = pos; + *self.pos.get_mut() = pos; if sanitize { // Angenommene Nicht-endlich-Marken (zu tief für die Prüfung) als null speichern. - let keys: HashSet<&str> = ops.iter().map(Op::key).collect(); + let keys: HashSet<&str> = info.iter().map(|i| i.0.as_str()).collect(); for k in keys { if let Some(v) = self.root.get_mut(k) { crate::ops::sanitize_non_finite(v); } } } - for (op, hit) in ops.iter().zip(hits) { - self.mark_dirty(op, hit); + for ((key, replace, _, _), hit) in info.into_iter().zip(&hits) { + self.mark_dirty(key, replace, *hit); } - Ok((as_add, inverses.into_iter().rev().flatten().collect())) + self.last_hits = hits; + Ok(inverses.into_iter().rev().flatten().collect()) } /// Wendet `ops` atomar an, ohne Verlauf (Abgleich des Spiegels). Verstösse (NaN, neue /// doppelte ids) → `Err(Meldungen)`, Dokument unverändert. pub fn apply(&mut self, ops: &[Op]) -> Result<(), Vec> { - self.apply_checked(ops, false).map(|_| ()) + self.apply_checked(ops.to_vec(), false).map(|_| ()) } - /// Wie [`Document::apply`]; `sanitize` = die Ops können Nicht-endlich-Marken enthalten. - pub fn apply_marked(&mut self, ops: &[Op], sanitize: bool) -> Result<(), Vec> { + /// Wie [`Document::apply`] (die Ops gehen ins Dokument über); `sanitize` = die Ops können + /// Nicht-endlich-Marken enthalten. + pub fn apply_marked(&mut self, ops: Vec, sanitize: bool) -> Result<(), Vec> { self.apply_checked(ops, sanitize).map(|_| ()) } /// Eine Benutzer-Änderung: anwenden, prüfen und als Undo-Schritt aufzeichnen (`key` = - /// `coalesceKey`, `now` = Zeit in ms für das Koaleszenz-Fenster). Die Ops gehen in den Verlauf - /// über (Redo) — das Dokument hält eigene Kopien, so wird jedes Element nur einmal kopiert. + /// `coalesceKey`, `now` = Zeit in ms für das Koaleszenz-Fenster). Die Ops gehen ohne Kopie ins + /// Dokument über; der Verlauf hält nur die inversen Ops (den Redo-Schritt liefert das Rückgängig- + /// machen selbst: die Inverse der Inversen, s. [`Document::undo`]). pub fn commit(&mut self, ops: Vec, key: Option<&str>, now: f64, sanitize: bool) -> Result<(), Vec> { - let (as_add, inverse) = self.apply_checked(&ops, sanitize)?; - // Normalisiert: `replace` ohne Treffer wird als `add` aufgezeichnet (so trifft jedes - // aufgezeichnete `replace` ein vorhandenes Element, s. `ops::compact`). - let mut forward: Vec = ops - .into_iter() - .zip(as_add) - .map(|(op, add)| match op { - Op::Replace { collection, entity } if add => Op::Add { collection, items: vec![entity], at: None }, - op => op, - }) - .collect(); - if sanitize { - // Angenommene Nicht-endlich-Marken auch im Verlauf als null. - crate::ops::sanitize_ops(&mut forward); - } - self.history.record(forward, inverse, key, now); + let inverse = self.apply_checked(ops, sanitize)?; + self.history.record(inverse, key, now); Ok(()) } - fn apply_unchecked(&mut self, ops: &[Op]) { - let mut pos = std::mem::take(&mut self.pos); - for op in ops { - let hit = self.apply_raw(op, &mut pos); - self.mark_dirty(op, hit); - } - self.pos = pos; - } - /// Einen Schritt zurück; liefert die angewendeten Ops (für die TS-Leseansicht), `None` = nichts. + /// Die dabei entstehenden Inversen sind der Redo-Schritt. pub fn undo(&mut self) -> Option> { - let step = self.history.pop_undo()?; - self.apply_unchecked(&step.inverse); - let ops = step.inverse.clone(); - self.history.push_redo(step); - Some(ops) + let ops = self.history.pop_undo()?.ops; + let applied = ops.clone(); + let redo = self.apply_inverting(ops); + self.history.push_redo(Step::new(redo)); + Some(applied) } /// Einen Schritt vor; liefert die angewendeten Ops, `None` = nichts. pub fn redo(&mut self) -> Option> { - let step = self.history.pop_redo()?; - self.apply_unchecked(&step.forward); - let ops = step.forward.clone(); - self.history.push_undo(step); - Some(ops) + let ops = self.history.pop_redo()?.ops; + let applied = ops.clone(); + let undo = self.apply_inverting(ops); + self.history.push_undo(Step::new(undo)); + Some(applied) } pub fn history(&self) -> &History { @@ -892,6 +983,32 @@ mod tests { assert!(d.history().bytes() <= 20_000 && d.history().undo_depth() < 20 && d.history().undo_depth() >= 1); } + #[test] + #[ignore = "Messung: cargo test --release -- --ignored --nocapture"] + fn messung_grosse_polylinie() { + use std::time::Instant; + let pts: Vec = (0..5000).map(|k| json!({"x": k as f64 * 0.1, "y": (k as f64 / 50.0).sin()})).collect(); + let mut drawings: Vec = (0..20000).map(|i| json!({"id": format!("d{i}"), "levelId": "eg", "geom": {"shape": "polyline", "closed": false, "pts": [{"x": i, "y": 1}, {"x": i + 1, "y": 2}]}})).collect(); + drawings[19000] = json!({"id": "d19000", "levelId": "eg", "geom": {"shape": "polyline", "closed": false, "pts": pts}}); + let mut d = Document::from_json(&json!({"id": "p", "drawings2d": drawings}).to_string()).unwrap(); + let n = 30; + let (mut run, mut json, mut commit) = (0.0, 0.0, 0.0); + for k in 0..n { + let req: crate::grips::Request = serde_json::from_value(json!({"op": "moveGrip", "drawingId": "d19000", "index": 2500, "pt": [250.0 + (k % 5) as f64 * 0.01, 3], "scale": 100})).unwrap(); + let t = Instant::now(); + let res = crate::grips::run(&d.lookup(), &req).unwrap(); + run += t.elapsed().as_secs_f64(); + let t = Instant::now(); + let text = crate::grips::result_json(&res); + json += t.elapsed().as_secs_f64(); + let t = Instant::now(); + d.commit(res.ops, Some("g"), k as f64, text.contains("\\u0001")).unwrap(); + commit += t.elapsed().as_secs_f64(); + } + let ms = |x: f64| x * 1e3 / n as f64; + eprintln!("Polylinie 5000 Punkte: Griff {:.2} ms, JSON {:.2} ms, Commit {:.2} ms", ms(run), ms(json), ms(commit)); + } + #[test] #[ignore = "Messung: cargo test --release -- --ignored --nocapture"] fn messung_grosses_projekt() { diff --git a/src-tauri/core/src/grips.rs b/src-tauri/core/src/grips.rs index 687bf3c3..13bd9611 100644 --- a/src-tauri/core/src/grips.rs +++ b/src-tauri/core/src/grips.rs @@ -14,6 +14,7 @@ //! Abweichung (gewollt): Ein Griff-Index, unter dem kein Punkt liegt (negativ, gebrochen, zu gross), ist //! keine Änderung — TS warf dort beim Lesen von `undefined` einen Fehler. +pub use crate::document::Lookup; use crate::jsmath::hypot2; use crate::jsnum; use crate::ops::{id_of, Op}; @@ -266,6 +267,8 @@ pub struct Request { thickness: N, pt: [N; 2], delta: [N; 2], + /// Punkttyp der Polylinie (`vertexType`: "corner" | "arc" | "spline"). + vertex_type: Option, } impl Request { @@ -343,19 +346,21 @@ pub fn result_json(r: &GripResult) -> String { String::from_utf8(out).unwrap_or_default() } -/// Führt eine Griff-Änderung aus (`req.op` wählt die Art, s. `src/state/gripOps.ts`). -pub fn run(root: &Map, req: &Request) -> Result { +/// Führt eine Griff-Änderung aus (`req.op` wählt die Art, s. `src/state/gripOps.ts`). Das Element +/// sucht `lk` (im Dokument über den Positions-Index, je Mausschritt keine lineare Suche). +pub fn run(lk: &Lookup, req: &Request) -> Result { + let root = lk.root; let r = req; let op = req.op.as_str(); let patch = |coll: &str, id: Option<&str>, f: &dyn Fn(&Value) -> Option| -> Vec { - id.and_then(|id| find(root, coll, id)).and_then(f).map(|e| vec![replace(coll, e)]).unwrap_or_default() + id.and_then(|id| lk.find(coll, id)).and_then(f).map(|e| vec![replace(coll, e)]).unwrap_or_default() }; Ok(match op { "moveGrip" | "moveBy" | "moveEdge" => { let (did, wid) = (r.s("drawingId"), r.s("wallId")); - // Jedes Element nur einmal suchen (lineare Suche, je Mausschritt). - let d = did.and_then(|i| find(root, "drawings2d", i)); - let w = wid.and_then(|i| find(root, "walls", i)); + // Jedes Element nur einmal suchen. + let d = did.and_then(|i| lk.find("drawings2d", i)); + let w = wid.and_then(|i| lk.find("walls", i)); // Objekt-Sperre: gesperrte Elemente lassen sich anwählen, aber nicht ziehen. if d.is_some_and(|d| truthy(field(d, "locked"))) || w.is_some_and(|w| truthy(field(w, "locked"))) { return Ok(GripResult::default()); @@ -453,9 +458,16 @@ pub fn run(root: &Map, req: &Request) -> Result { + let Some(t) = req.vertex_type.as_deref().and_then(crate::polyline_vertex::VertexType::parse) else { + return Ok(GripResult::default()); + }; + let index = r.n("index"); + patch("drawings2d", r.s("id"), &|d| vertex_type(d, index, t)).into() + } "deletePoint" => { let index = r.n("index"); - let Some(d) = r.s("id").and_then(|i| find(root, "drawings2d", i)) else { return Ok(GripResult::default()) }; + let Some(d) = r.s("id").and_then(|i| lk.find("drawings2d", i)) else { return Ok(GripResult::default()) }; let g = field(d, "geom").unwrap_or(&Value::Null); if field(g, "shape").and_then(Value::as_str) != Some("polyline") { return Ok(GripResult::default()); @@ -927,6 +939,42 @@ fn roof_grip(r: &Value, index: f64, x: f64, y: f64) -> Option { /// Punkt in Segment `seg` einer Polylinie einfügen. Ein Bogen wird exakt über die Kreisgeometrie in der /// Winkel-Mitte geteilt (wie `kernel2d` Bogen-Segmente zuschneidet); eine Näherung über tessellierte /// Punkte wäre zu ungenau. Die Bulge-Liste wird nur mitgeführt, wenn es eine gab. +/// Punkttyp `t` am Punkt `index` einer Polylinie (`setPolylineVertexType`, `polyline_vertex.rs`): die +/// Bulges der beiden anliegenden Segmente; `bulge` steht danach am Ende der Geometrie und fällt weg, +/// wenn alle Segmente gerade sind. Gesperrt, keine Polylinie, Index ohne Punkt oder keine Änderung → +/// None (kein leerer Undo-Schritt). +fn vertex_type(d: &Value, index: f64, t: crate::polyline_vertex::VertexType) -> Option { + use crate::polyline_vertex::{index_of, with_type, Poly}; + if truthy(field(d, "locked")) { + return None; + } + let g = field(d, "geom")?; + if shape(g) != "polyline" { + return None; + } + let pts: Vec<(f64, f64)> = arr(field(g, "pts")).iter().map(xy).collect(); + let i = index_of(index, pts.len())?; + // `g.bulge?.[k] ?? 0` + let bulge: Vec = arr(field(g, "bulge")).iter().map(|b| if b.is_null() { 0.0 } else { num_of(Some(b)) }).collect(); + let nb = with_type(&Poly { pts: &pts, closed: truthy(field(g, "closed")), bulge: &bulge }, i, t); + let new_bulge = nb.iter().any(|b| *b != 0.0).then(|| Value::Array(nb.into_iter().map(js_num).collect())); + // Unverändert (ohne die grosse Geometrie zu vergleichen): gleiche Bögen, `bulge` steht schon am Ende. + let last_key = g.as_object().and_then(|m| m.keys().last()).map(String::as_str); + let same = match (field(g, "bulge"), &new_bulge) { + (None, None) => true, + (Some(old), Some(new)) => old == new && last_key == Some("bulge"), + _ => false, + }; + if same { + return None; + } + let mut geom = with_opt(g, vec![("bulge", None)]); + if let (Value::Object(m), Some(b)) = (&mut geom, new_bulge) { + m.insert("bulge".into(), b); + } + Some(with_geom(d, geom)) +} + fn insert_point(d: &Value, seg: f64, x: f64, y: f64) -> Option { let g = field(d, "geom")?; if shape(g) != "polyline" { @@ -1204,18 +1252,18 @@ mod tests { #[test] fn wand_griff_und_sperre() { let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}, "extra": 1}]})); - let res = run(&r, &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]}))).unwrap(); + let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]}))).unwrap(); assert_eq!(entity(&res).to_string(), r#"{"id":"w","start":{"x":0,"y":0},"end":{"x":2,"y":3},"extra":1}"#); let locked = root(json!({"walls": [{"id": "w", "locked": true, "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}}]})); - assert!(run(&locked, &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]}))).unwrap().ops.is_empty()); + assert!(run(&Lookup::plain(&locked), &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]}))).unwrap().ops.is_empty()); // Fehlendes Element: keine Op. - assert!(run(&r, &rq(json!({"op": "moveGrip", "wallId": "x", "index": 1, "pt": [2, 3]}))).unwrap().ops.is_empty()); + assert!(run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "wallId": "x", "index": 1, "pt": [2, 3]}))).unwrap().ops.is_empty()); } #[test] fn kreis_wird_ellipse() { let r = root(json!({"drawings2d": [{"id": "d", "geom": {"shape": "circle", "center": {"x": 0, "y": 0}, "r": 1}}]})); - let res = run(&r, &rq(json!({"op": "moveGrip", "drawingId": "d", "index": 0, "pt": [2, 0]}))).unwrap(); + let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "drawingId": "d", "index": 0, "pt": [2, 0]}))).unwrap(); assert_eq!(entity(&res)["geom"].to_string(), r#"{"shape":"ellipse","center":{"x":0,"y":0},"rx":2,"ry":1,"rotation":0}"#); } @@ -1231,14 +1279,14 @@ mod tests { #[test] fn nan_als_marke() { let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}}]})); - let res = run(&r, &rq(json!({"op": "moveBy", "wallId": "w", "delta": ["\u{1}NaN", 0]}))).unwrap(); + let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveBy", "wallId": "w", "delta": ["\u{1}NaN", 0]}))).unwrap(); assert_eq!(entity(&res)["start"]["x"], json!("\u{1}NaN")); } #[test] fn punkt_loeschen_mindestzahl() { let r = root(json!({"drawings2d": [{"id": "d", "geom": {"shape": "polyline", "closed": false, "pts": [{"x": 0, "y": 0}, {"x": 1, "y": 0}]}}]})); - let res = run(&r, &rq(json!({"op": "deletePoint", "id": "d", "index": 0}))).unwrap(); + let res = run(&Lookup::plain(&r), &rq(json!({"op": "deletePoint", "id": "d", "index": 0}))).unwrap(); assert_eq!(res.notice, Some("alert.polylineMinPoints")); assert!(res.ops.is_empty()); } @@ -1249,7 +1297,7 @@ mod tests { "wallTypes": [{"id": "wt", "name": "W", "layers": [{"componentId": "c", "thickness": 0.2}]}], "ceilings": [{"id": "c1", "wallTypeId": "wt", "thickness": 0.3}, {"id": "c2", "wallTypeId": "wt"}], })); - let ops = run(&r, &rq(json!({"op": "ceilingThickness", "id": "c1", "thickness": 0.25, "newId": "ct-1", "newName": "Decke"}))).unwrap().ops; + let ops = run(&Lookup::plain(&r), &rq(json!({"op": "ceilingThickness", "id": "c1", "thickness": 0.25, "newId": "ct-1", "newName": "Decke"}))).unwrap().ops; assert_eq!(crate::ops::ops_to_json(&ops), r#"[{"kind":"add","collection":"ceilingTypes","items":[{"id":"ct-1","name":"Decke","layers":[{"componentId":"c","thickness":0.25}]}]},{"kind":"replace","collection":"ceilings","entity":{"id":"c1","wallTypeId":"wt","ceilingTypeId":"ct-1"}}]"#); } diff --git a/src-tauri/core/src/jsnum.rs b/src-tauri/core/src/jsnum.rs index 6c317d43..c4bb0fee 100644 --- a/src-tauri/core/src/jsnum.rs +++ b/src-tauri/core/src/jsnum.rs @@ -3,7 +3,7 @@ //! - `Math.min/max` liefern bei NaN NaN (Rust `f64::min/max` ignorieren NaN). //! - `Math.round` rundet halbe Werte Richtung +∞ (Rust `round` weg von 0). //! - `x | 0` ist ToInt32 (Rest modulo 2³², Rust `as i32` sättigt). -//! - `Math.pow` (`x ** 3`) und Trigonometrie: im Web-Build (wasm32 + Feature "web") ruft der Kern `Math.cos/sin/atan2/acos` +//! - `Math.pow` (`x ** 3`) und Trigonometrie: im Web-Build (wasm32 + Feature "web") ruft der Kern `Math.cos/sin/tan/atan2/acos` //! der laufenden JS-Engine. Nur so sind die Werte bitgleich zur bisherigen TS-Fassung — V8 //! (glibc-abgeleitete sin/cos), JavaScriptCore (System-libm von macOS) und Rusts libm (musl) //! unterscheiden sich in einzelnen Fällen in der letzten Stelle. Nativ (`cargo test`, Tauri) @@ -25,6 +25,12 @@ mod trig { fn js_acos(x: f64) -> f64; #[wasm_bindgen(js_namespace = Math, js_name = pow)] fn js_pow(x: f64, y: f64) -> f64; + #[wasm_bindgen(js_namespace = Math, js_name = tan)] + fn js_tan(x: f64) -> f64; + } + #[inline] + pub fn tan(x: f64) -> f64 { + js_tan(x) } #[inline] pub fn pow(x: f64, y: f64) -> f64 { @@ -71,9 +77,13 @@ mod trig { pub fn pow(x: f64, y: f64) -> f64 { x.powf(y) } + #[inline] + pub fn tan(x: f64) -> f64 { + x.tan() + } } -pub use trig::{acos, atan2, cos, pow, sin}; +pub use trig::{acos, atan2, cos, pow, sin, tan}; /// `Math.min(a, b)` (NaN gewinnt; −0 < +0). #[inline] diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 26b35276..0a2285e7 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -87,6 +87,7 @@ pub mod text_layout; pub mod plan_text; pub mod grips; pub mod selection_info; +pub mod polyline_vertex; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/ops.rs b/src-tauri/core/src/ops.rs index e7fa692e..4b29948e 100644 --- a/src-tauri/core/src/ops.rs +++ b/src-tauri/core/src/ops.rs @@ -203,21 +203,6 @@ pub fn sanitize_non_finite(v: &mut Value) { } } -fn op_values_mut(op: &mut Op) -> Vec<&mut Value> { - match op { - Op::Add { items, .. } => items.iter_mut().collect(), - Op::Replace { entity, .. } => vec![entity], - Op::SetField { value: Some(v), .. } => vec![v], - _ => vec![], - } -} - -pub fn sanitize_ops(ops: &mut [Op]) { - for op in ops { - op_values_mut(op).into_iter().for_each(sanitize_non_finite); - } -} - // ── Validierung ([7]) ──────────────────────────────────────────────────────── /// Prüft eine angewendete Op-Folge (bitgleich zur früheren TS-Fassung `validateOps`): nicht @@ -228,41 +213,51 @@ pub fn validate(after: &Map, ops: &[Op], had_dup: &dyn Fn(&str) - let mut problems = Vec::new(); let mut dup_checked: HashSet<&str> = HashSet::new(); for op in ops { - match op { - Op::Add { collection, .. } | Op::Replace { collection, .. } => { - let ents: &[Value] = match op { - Op::Add { items, .. } => items, - Op::Replace { entity, .. } => std::slice::from_ref(entity), - _ => unreachable!(), - }; - for e in ents { - if let Some(bad) = find_non_finite(e, 0) { - problems.push(format!("„{collection}\" {}: {bad} ist nicht endlich.", id_of(e).unwrap_or("undefined"))); - } - } - if matches!(op, Op::Add { .. }) && dup_checked.insert(collection) { - if let Some(list) = after.get(collection) { - if is_id_list(list) && !unique_ids(list.as_array().unwrap()) && !had_dup(collection) { - problems.push(format!("Doppelte ids in „{collection}\".")); - } - } - } + value_problems(op, had_dup, &mut problems); + if let Op::Add { collection, .. } = op { + if dup_checked.insert(collection) { + problems.extend(add_dup_problem(after, collection, had_dup)); } - Op::SetField { key, value, .. } => { - if let Some(bad) = value.as_ref().and_then(non_finite_mark) { - problems.push(format!("Feld „{key}\": {bad} ist nicht endlich.")); - } else if let Some(v) = value { - if is_entity_list(v) && !unique_ids(v.as_array().unwrap()) && !had_dup(key) { - problems.push(format!("Doppelte ids in „{key}\".")); - } - } - } - _ => {} } } problems } +/// Der Teil von [`validate`], der nur die Op selbst liest (vor dem Anwenden prüfbar): nicht endliche +/// Zahlen in Elementen und Feldwerten, doppelte ids in einer gesetzten Liste. +pub fn value_problems(op: &Op, had_dup: &dyn Fn(&str) -> bool, problems: &mut Vec) { + match op { + Op::Add { collection, .. } | Op::Replace { collection, .. } => { + let ents: &[Value] = match op { + Op::Add { items, .. } => items, + Op::Replace { entity, .. } => std::slice::from_ref(entity), + _ => unreachable!(), + }; + for e in ents { + if let Some(bad) = find_non_finite(e, 0) { + problems.push(format!("„{collection}\" {}: {bad} ist nicht endlich.", id_of(e).unwrap_or("undefined"))); + } + } + } + Op::SetField { key, value, .. } => { + if let Some(bad) = value.as_ref().and_then(non_finite_mark) { + problems.push(format!("Feld „{key}\": {bad} ist nicht endlich.")); + } else if let Some(v) = value { + if is_entity_list(v) && !unique_ids(v.as_array().unwrap()) && !had_dup(key) { + problems.push(format!("Doppelte ids in „{key}\".")); + } + } + } + _ => {} + } +} + +/// Der Teil von [`validate`] nach dem Anwenden: doppelte ids in der Liste `collection` nach einem `add`. +pub fn add_dup_problem(after: &Map, collection: &str, had_dup: &dyn Fn(&str) -> bool) -> Option { + let list = after.get(collection)?; + (is_id_list(list) && !unique_ids(list.as_array().unwrap()) && !had_dup(collection)).then(|| format!("Doppelte ids in „{collection}\".")) +} + /// Wie [`validate`] mit dem Projekt vor den Ops (für die TS-Fassade `validateOps`). pub fn validate_ops(after: &Map, ops: &[Op], before: Option<&Map>) -> Vec { validate(after, ops, &|k| before.is_some_and(|b| has_dup(b.get(k)))) @@ -291,14 +286,22 @@ pub fn validate_project(root: &Map) -> Vec { // ── Verlauf ([8]) ──────────────────────────────────────────────────────────── -/// Ein Undo-Schritt: Vorwärts-Ops (Redo) und inverse Ops (Undo), beide in Anwendungsreihenfolge. +/// Ein Schritt des Verlaufs: die Ops, die ihn anwenden (Undo-Stapel: die inversen Ops der Änderung, +/// Redo-Stapel: die Änderung), in Anwendungsreihenfolge. Die Gegenrichtung entsteht beim Anwenden +/// (`Document::undo`/`redo`: die Inverse der Inversen) — so hält der Verlauf jedes Element nur einmal. #[derive(Clone, Debug, Default)] pub struct Step { - pub forward: Vec, - pub inverse: Vec, + pub ops: Vec, bytes: usize, } +impl Step { + pub fn new(ops: Vec) -> Step { + let bytes = ops_bytes(&ops); + Step { ops, bytes } + } +} + /// Geschätzter Speicherbedarf eines JSON-Werts (Bytes). fn approx_bytes(v: &Value) -> usize { match v { @@ -460,8 +463,8 @@ impl History { } } - /// Zeichnet eine angewendete Änderung auf. - pub fn record(&mut self, forward: Vec, inverse: Vec, key: Option<&str>, now: f64) { + /// Zeichnet eine angewendete Änderung auf (`inverse` = die Ops, die sie zurücknehmen). + pub fn record(&mut self, inverse: Vec, key: Option<&str>, now: f64) { for s in self.redo.drain(..) { self.bytes -= s.bytes; } @@ -475,19 +478,15 @@ impl History { match self.undo.back_mut().filter(|_| merge) { Some(top) => { self.bytes -= top.bytes; - let mut fwd = std::mem::take(&mut top.forward); - fwd.extend(forward); - top.forward = compact(fwd); let mut inv = inverse; - inv.append(&mut top.inverse); - top.inverse = compact(inv); - top.bytes = ops_bytes(&top.forward) + ops_bytes(&top.inverse); + inv.append(&mut top.ops); + *top = Step::new(compact(inv)); self.bytes += top.bytes; } None => { - let bytes = ops_bytes(&forward) + ops_bytes(&inverse); - self.bytes += bytes; - self.undo.push_back(Step { forward, inverse, bytes }); + let s = Step::new(inverse); + self.bytes += s.bytes; + self.undo.push_back(s); } } while self.undo.len() > self.max_steps || (self.bytes > self.max_bytes && self.undo.len() > 1) { @@ -611,21 +610,20 @@ mod tests { fn verlauf_koalesziert_und_begrenzt() { let mut h = History { max_steps: 3, ..Default::default() }; let op = |n: i32| ops(json!([{"kind":"setField","key":"s","value":n}])); - h.record(op(1), op(0), Some("k"), 0.0); - h.record(op(2), op(1), Some("k"), 100.0); + h.record(op(0), Some("k"), 0.0); + h.record(op(1), Some("k"), 100.0); assert_eq!(h.undo_depth(), 1); - h.record(op(3), op(2), Some("k"), 600.0); + h.record(op(2), Some("k"), 600.0); assert_eq!(h.undo_depth(), 2); - h.record(op(4), op(3), None, 700.0); - h.record(op(5), op(4), None, 800.0); + h.record(op(3), None, 700.0); + h.record(op(4), None, 800.0); assert_eq!(h.undo_depth(), 3); h.begin_group(); - h.record(op(6), op(5), None, 900.0); - h.record(op(7), op(6), Some("x"), 901.0); + h.record(op(5), None, 900.0); + h.record(op(6), Some("x"), 901.0); h.end_group(); assert_eq!(h.undo_depth(), 3); let s = h.pop_undo().unwrap(); - assert_eq!(s.inverse, op(5)); - assert_eq!(s.forward, op(7)); + assert_eq!(s.ops, op(5)); } } diff --git a/src-tauri/core/src/polyline_vertex.rs b/src-tauri/core/src/polyline_vertex.rs new file mode 100644 index 00000000..e6f4d931 --- /dev/null +++ b/src-tauri/core/src/polyline_vertex.rs @@ -0,0 +1,358 @@ +//! Punkttypen einer Polylinie ([K4] S3, vorher `src/geometry/polylineVertexType.ts`; ArchiCAD/ +//! Vectorworks-artig): Eckpunkt, Bogenpunkt, Splinepunkt. Rein als Umrechnung der Segment-Bögen +//! (`bulge`) der beiden am Punkt anliegenden Segmente — alle Renderer/Exporte verstehen Bulges +//! bereits, es gibt also kein neues Geometrie-Feld. +//! +//! - Eckpunkt: beide Segmente gerade (bulge 0). +//! - Bogenpunkt: EIN Kreisbogen durch Vorgänger, Punkt und Nachfolger. +//! - Splinepunkt: tangential glatter Übergang — die Tangente im Punkt ist parallel zur Verbindung +//! Vorgänger→Nachfolger (wie bei einer Catmull-Rom-Kurve), beide Segmente werden zu Bögen, die +//! diese Tangente teilen. +//! +//! Die Bögen werden über ihren SCHEITELPUNKT bestimmt und mit `bulge::from_sagitta_point` in einen +//! Bulge übersetzt — so bleibt die Vorzeichen-Konvention an EINER Stelle. Rechenreihenfolge und +//! Zahlsemantik wie in der früheren TS-Fassung (`Math.hypot`/`sin`/`cos`/`atan2`/`tan` über +//! `jsmath`/`jsnum`), Ergebnis bitgleich. + +use crate::jsmath::hypot2; +use crate::jsnum; + +type P = (f64, f64); + +const EPS: f64 = 1e-9; + +/// Punkttyp. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum VertexType { + Corner, + Arc, + Spline, +} + +impl VertexType { + pub fn parse(s: &str) -> Option { + match s { + "corner" => Some(VertexType::Corner), + "arc" => Some(VertexType::Arc), + "spline" => Some(VertexType::Spline), + _ => None, + } + } + + /// Kennzahl für die flache Grenze (0 Ecke, 1 Bogen, 2 Spline). + pub fn code(self) -> f64 { + match self { + VertexType::Corner => 0.0, + VertexType::Arc => 1.0, + VertexType::Spline => 2.0, + } + } +} + +/// Polylinie: Punkte, geschlossen, Bulge je Segment (fehlend = 0). +pub struct Poly<'a> { + pub pts: &'a [P], + pub closed: bool, + pub bulge: &'a [f64], +} + +impl Poly<'_> { + fn b(&self, k: Option) -> f64 { + k.and_then(|k| self.bulge.get(k).copied()).unwrap_or(0.0) + } + + /// Indizes des ein- und ausgehenden Segments von Punkt `i` (None = keins). + fn adjacent(&self, i: usize) -> (Option, Option) { + let n = self.pts.len(); + let in_seg = if i > 0 { Some(i - 1) } else if self.closed { Some(n - 1) } else { None }; + let out_seg = if i + 1 < n { Some(i) } else if self.closed { Some(n - 1) } else { None }; + (in_seg, out_seg) + } + + /// Nachbarpunkte von `i` (None an offenen Enden). + fn neighbors(&self, i: usize) -> (Option

, Option

) { + let n = self.pts.len(); + let prev = if i > 0 { Some(self.pts[i - 1]) } else if self.closed { Some(self.pts[n - 1]) } else { None }; + let next = if i + 1 < n { Some(self.pts[i + 1]) } else if self.closed { Some(self.pts[0]) } else { None }; + (prev, next) + } +} + +/// Punkt-Index aus einer JS-Zahl: nur ganze Zahlen im Bereich (sonst kein Punkt). +pub fn index_of(i: f64, n: usize) -> Option { + (i.fract() == 0.0 && i >= 0.0 && i < n as f64).then_some(i as usize) +} + +fn sub(a: P, b: P) -> P { + (a.0 - b.0, a.1 - b.1) +} + +fn cross(a: P, b: P) -> f64 { + a.0 * b.1 - a.1 * b.0 +} + +/// `Math.sign`. +fn sign(x: f64) -> f64 { + if x > 0.0 { + 1.0 + } else if x < 0.0 { + -1.0 + } else { + x + } +} + +/// `x || 1` für Zahlen (0, −0, NaN → 1). +fn or_one(x: f64) -> f64 { + if x == 0.0 || x.is_nan() { + 1.0 + } else { + x + } +} + +/// Bogen-Parameter `[cx, cy, r, a0, a1, sweep]` (wie `bulgeArc` in TS), None = gerade/entartet. +fn bulge_arc(a: P, b: P, bulge: f64) -> Option<[f64; 6]> { + if !(bulge.abs() >= EPS) { + return None; + } + let r = crate::bulge::arc(a.0, a.1, b.0, b.1, bulge); + (r.len() >= 6).then(|| [r[0], r[1], r[2], r[3], r[4], r[5]]) +} + +fn from_sagitta(a: P, b: P, p: P) -> f64 { + crate::bulge::from_sagitta_point(a.0, a.1, b.0, b.1, p.0, p.1) +} + +/// Umkreismittelpunkt von a, b, c (None bei kollinearen Punkten). +fn circumcenter(a: P, b: P, c: P) -> Option

{ + let d = 2.0 * (a.0 * (b.1 - c.1) + b.0 * (c.1 - a.1) + c.0 * (a.1 - b.1)); + if d.abs() < EPS { + return None; + } + let (a2, b2, c2) = (a.0 * a.0 + a.1 * a.1, b.0 * b.0 + b.1 * b.1, c.0 * c.0 + c.1 * c.1); + Some(( + (a2 * (b.1 - c.1) + b2 * (c.1 - a.1) + c2 * (a.1 - b.1)) / d, + (a2 * (c.0 - b.0) + b2 * (a.0 - c.0) + c2 * (b.0 - a.0)) / d, + )) +} + +/// Bulge des Kreisbogens a→b auf dem Kreis um `c`, und zwar des Bogens, der NICHT durch `other` +/// läuft (Scheitel auf der anderen Seite der Sehne als `other`). +fn bulge_on_circle(a: P, b: P, c: P, other: P) -> f64 { + let r = hypot2(a.0 - c.0, a.1 - c.1); + let mid = ((a.0 + b.0) / 2.0, (a.1 + b.1) / 2.0); + let mut u = sub(mid, c); + let mut len = hypot2(u.0, u.1); + if len < EPS { + let d = sub(b, a); + u = (-d.1, d.0); + len = hypot2(u.0, u.1); + } + u = (u.0 / len, u.1 / len); + let side = |p: P| sign(cross(sub(b, a), sub(p, a))); + let cand1 = (c.0 + u.0 * r, c.1 + u.1 * r); + let cand2 = (c.0 - u.0 * r, c.1 - u.1 * r); + let apex = if side(cand1) != side(other) { cand1 } else { cand2 }; + from_sagitta(a, b, apex) +} + +/// Tangente (Fahrtrichtung a→b) des Bulge-Bogens am Anfang bzw. Ende. +fn arc_tangent(a: P, b: P, bulge: f64, at_end: bool) -> P { + let Some(arc) = bulge_arc(a, b, bulge) else { + let d = sub(b, a); + let l = or_one(hypot2(d.0, d.1)); + return (d.0 / l, d.1 / l); + }; + let ang = if at_end { arc[3] + arc[5] } else { arc[3] }; + let s = or_one(sign(arc[5])); + (-jsnum::sin(ang) * s, jsnum::cos(ang) * s) +} + +/// Bulge des Bogens a→b mit gegebener Tangente `t` am Ende (`at_end`) bzw. Anfang. Betrag aus dem +/// Winkel Sehne↔Tangente, Vorzeichen NUMERISCH gewählt (die Variante, deren tatsächliche Tangente zu +/// `t` passt). +fn bulge_with_tangent(a: P, b: P, t: P, at_end: bool) -> f64 { + let c = sub(b, a); + let ang = jsnum::atan2(cross(c, t), c.0 * t.0 + c.1 * t.1).abs(); + let mag = bulge_from_apex_angle(a, b, ang).abs(); + if mag < 1e-9 { + return 0.0; + } + let dot = |v: P| v.0 * t.0 + v.1 * t.1; + if dot(arc_tangent(a, b, mag, at_end)) >= dot(arc_tangent(a, b, -mag, at_end)) { + mag + } else { + -mag + } +} + +/// Bogen über der Sehne a→b mit halbem Öffnungswinkel |half| (Sehne↔Tangente); Vorzeichen: >0 Scheitel +/// links der Sehne, <0 rechts. Über den Scheitelpunkt in einen Bulge übersetzt. +fn bulge_from_apex_angle(a: P, b: P, half: f64) -> f64 { + if half.abs() < 1e-6 { + return 0.0; + } + // Begrenzen: knapp unter einem Halbkreis je Segment (sonst kippt der Bogen). + let h2 = jsnum::max(-std::f64::consts::PI / 2.0 + 0.01, jsnum::min(std::f64::consts::PI / 2.0 - 0.01, half)); + let d = sub(b, a); + let chord = hypot2(d.0, d.1); + if chord < EPS { + return 0.0; + } + let left = (-d.1 / chord, d.0 / chord); + let s = (chord / 2.0) * jsnum::tan(h2 / 2.0); // Pfeilhöhe + let apex = ((a.0 + b.0) / 2.0 + left.0 * s, (a.1 + b.1) / 2.0 + left.1 * s); + from_sagitta(a, b, apex) +} + +/// Ist Punkttyp `t` am Punkt `i` möglich? (Bogen/Spline brauchen beide Nachbarn.) +pub fn can_set(g: &Poly, i: usize, t: VertexType) -> bool { + if i >= g.pts.len() { + return false; + } + if t == VertexType::Corner { + return true; + } + let (prev, next) = g.neighbors(i); + prev.is_some() && next.is_some() +} + +/// Aktueller Typ (Heuristik): beide Nachbarsegmente gerade → Eckpunkt, sonst None (gemischt). +pub fn type_of(g: &Poly, i: usize) -> Option { + if i >= g.pts.len() { + return None; + } + let (in_seg, out_seg) = g.adjacent(i); + if g.b(in_seg).abs() < 1e-9 && g.b(out_seg).abs() < 1e-9 { + return Some(VertexType::Corner); + } + let (prev, next) = g.neighbors(i); + let (Some(prev), Some(next), Some(_), Some(_)) = (prev, next, in_seg, out_seg) else { return None }; + let a1 = bulge_arc(prev, g.pts[i], g.b(in_seg)); + let a2 = bulge_arc(g.pts[i], next, g.b(out_seg)); + match (a1, a2) { + (Some(a1), Some(a2)) if hypot2(a1[0] - a2[0], a1[1] - a2[1]) < 1e-6 * (1.0 + a1[2]) => Some(VertexType::Arc), + _ => Some(VertexType::Spline), + } +} + +/// Neue Bulge-Liste (je Segment) mit Punkttyp `t` an Punkt `i`. +pub fn with_type(g: &Poly, i: usize, t: VertexType) -> Vec { + let n = g.pts.len(); + let seg_count = if g.closed { n } else { n.saturating_sub(1) }; + let mut bulge: Vec = (0..seg_count).map(|k| g.b(Some(k))).collect(); + if !can_set(g, i, t) { + return bulge; + } + let (in_seg, out_seg) = g.adjacent(i); + let q = g.pts[i]; + let (prev, next) = g.neighbors(i); + let mut put = |k: Option, v: f64| { + if let Some(x) = k.and_then(|k| bulge.get_mut(k)) { + *x = v; + } + }; + let (Some(p), Some(r)) = (prev, next) else { + // Eckpunkt an einem offenen Ende. + put(in_seg, 0.0); + put(out_seg, 0.0); + return bulge; + }; + match t { + VertexType::Corner => { + put(in_seg, 0.0); + put(out_seg, 0.0); + } + VertexType::Arc => match circumcenter(p, q, r) { + None => { + put(in_seg, 0.0); + put(out_seg, 0.0); + } + Some(c) => { + put(in_seg, bulge_on_circle(p, q, c, r)); + put(out_seg, bulge_on_circle(q, r, c, p)); + } + }, + VertexType::Spline => { + // Tangente parallel zu prev→next. + let tv = sub(r, p); + let tl = hypot2(tv.0, tv.1); + if tl < EPS { + return bulge; + } + let tu = (tv.0 / tl, tv.1 / tl); + put(in_seg, bulge_with_tangent(p, q, tu, true)); + put(out_seg, bulge_with_tangent(q, r, tu, false)); + } + } + bulge +} + +#[cfg(test)] +mod tests { + use super::*; + + const G: [P; 4] = [(0.0, 0.0), (2.0, 1.0), (4.0, 0.0), (6.0, 1.0)]; + + fn poly<'a>(pts: &'a [P], closed: bool, bulge: &'a [f64]) -> Poly<'a> { + Poly { pts, closed, bulge } + } + + fn tangent(a: P, b: P, bulge: f64, at_end: bool) -> f64 { + let arc = bulge_arc(a, b, bulge).unwrap(); + let ang = if at_end { arc[3] + arc[5] } else { arc[3] }; + let sg = sign(arc[5]); + (ang.cos() * sg).atan2(-ang.sin() * sg) + } + + #[test] + fn eckpunkt_setzt_beide_nachbarsegmente_gerade() { + assert_eq!(with_type(&poly(&G, false, &[0.3, -0.2, 0.1]), 1, VertexType::Corner), vec![0.0, 0.0, 0.1]); + } + + #[test] + fn bogenpunkt_beide_segmente_auf_einem_kreis() { + let g = poly(&G, false, &[]); + let b = with_type(&g, 1, VertexType::Arc); + let a1 = bulge_arc(G[0], G[1], b[0]).unwrap(); + let a2 = bulge_arc(G[1], G[2], b[1]).unwrap(); + assert!(hypot2(a1[0] - a2[0], a1[1] - a2[1]) < 1e-6); + assert!((a1[2] - a2[2]).abs() < 1e-6); + assert_eq!(type_of(&poly(&G, false, &b), 1), Some(VertexType::Arc)); + // Der Bogen baucht NACH OBEN aus (Punkt 1 liegt oben): Scheitel über der Sehne. + let pts = crate::bulge::arc_points(G[0].0, G[0].1, G[1].0, G[1].1, b[0]); + let k = pts.len() / 4; + assert!(pts[2 * k + 1] > 0.5); + } + + #[test] + fn splinepunkt_tangenten_stimmen_ueberein() { + let pts = [(0.0, 0.0), (2.0, 1.0), (5.0, 0.2)]; + let b = with_type(&poly(&pts, false, &[]), 1, VertexType::Spline); + let t1 = tangent(pts[0], pts[1], b[0], true); + let t2 = tangent(pts[1], pts[2], b[1], false); + assert!((t1 - t2).abs() < 1e-6); + assert!((t2 - 0.2f64.atan2(5.0)).abs() < 1e-6); + assert_eq!(type_of(&poly(&pts, false, &b), 1), Some(VertexType::Spline)); + } + + #[test] + fn offene_enden_und_geschlossene_polylinie() { + let g = poly(&G, false, &[]); + assert!(!can_set(&g, 0, VertexType::Arc)); + assert!(!can_set(&g, 3, VertexType::Spline)); + assert!(can_set(&g, 0, VertexType::Corner)); + assert!(!can_set(&g, 4, VertexType::Corner)); + let sq = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]; + let b = with_type(&poly(&sq, true, &[]), 0, VertexType::Arc); + assert_eq!(b.len(), 4); + assert!(b[3] != 0.0 && b[0] != 0.0); + assert_eq!(b[1], 0.0); + // Kollinear: kein Kreis → gerade. + let line = [(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)]; + assert_eq!(with_type(&poly(&line, false, &[0.2, 0.3]), 1, VertexType::Arc), vec![0.0, 0.0]); + assert_eq!(index_of(1.5, 4), None); + assert_eq!(index_of(3.0, 4), Some(3)); + } +} diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs index dbc9c13e..caa36956 100644 --- a/src-tauri/core/src/queries.rs +++ b/src-tauri/core/src/queries.rs @@ -62,7 +62,9 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result, name: &str, text: &str) -> Result { +/// Elemente per id sucht `lk` (im Dokument über dessen Positions-Index). +pub fn run_root(lk: &crate::document::Lookup, name: &str, text: &str) -> Result { + let root = lk.root; match name { // Stiftsätze ([K4] S3, `pens.rs`): Ops statt Projekt-Kopien. "penRebakeOps" => json(&crate::pens::rebake_ops(root)), @@ -101,13 +103,13 @@ pub fn run_root(root: &serde_json::Map, name: &str, t // Griff-Änderungen ([K4] S3, `grips.rs`): `text` = JSON der Anfrage; Antwort `{ops, notice}` (ohne Commit). "gripOps" => { let req: crate::grips::Request = serde_json::from_str(text).map_err(|e| format!("gripOps: {e}"))?; - Ok(crate::grips::result_json(&crate::grips::run(root, &req)?)) + Ok(crate::grips::result_json(&crate::grips::run(lk, &req)?)) } // Objekt-Info der Auswahl ([K4] S3, `selection_info.rs`): `text` = JSON der gewählten ids je Art; Antwort // `Selection` (TS) oder null, Zahlen mit Nicht-endlich-Marken. "selectionInfo" => { let a: crate::selection_info::SelArgs = serde_json::from_str(text).map_err(|e| format!("selectionInfo: {e}"))?; - crate::selection_info::derive(root, &a).map(crate::selection_info::J::into_string) + crate::selection_info::derive(lk, &a).map(crate::selection_info::J::into_string) } // Bounding-Boxen von Zeichnungen (Ausrichten/Verteilen): `text` = JSON der ids. "drawingBBoxes" => { diff --git a/src-tauri/core/src/selection_info.rs b/src-tauri/core/src/selection_info.rs index b617198c..bf1b283e 100644 --- a/src-tauri/core/src/selection_info.rs +++ b/src-tauri/core/src/selection_info.rs @@ -14,6 +14,7 @@ //! Wo TS warf (unbekannter Wandtyp, Deckentyp oder Bauteil), kommt dieselbe Meldung als Fehler. //! Der B-Rep-Körper einer Extrusion (`spec`) bleibt in TS (truck-Pipeline, `plan/extrudedSolidSpec.ts`). +use crate::document::Lookup; use crate::grips::{field, js_num, num_of, truthy, xy}; use crate::jsmath::hypot2; use crate::jsnum; @@ -40,9 +41,6 @@ pub struct SelArgs { pub column_id: Option, pub roof_id: Option, pub context_object_id: Option, - /// Lage der Elemente in ihren Listen (Liste → Index), von der Leseansicht; der Kern prüft die id an - /// dieser Stelle und sucht sonst linear (die Suche über grosse Listen kostet je Element). - pub at: std::collections::HashMap, } // ── Hilfen ─────────────────────────────────────────────────────────────────── @@ -140,17 +138,6 @@ fn arr(v: Option<&Value>) -> &[Value] { v.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]) } -/// Erstes Element mit `id` in einer Liste der Wurzel (`hint`: vermutete Lage, wird geprüft). -fn find<'a>(root: &'a Map, list: &str, id: &str, hint: Option) -> Option<&'a Value> { - let l = arr(root.get(list)); - if let Some(e) = hint.filter(|h| h.fract() == 0.0 && *h >= 0.0).and_then(|h| l.get(h as usize)) { - if id_of(e) == Some(id) { - return Some(e); - } - } - l.iter().find(|e| id_of(e) == Some(id)) -} - /// Erstes Element, dessen Feld `key` gleich `val` ist (`===`; fehlend gleich fehlend). fn find_by<'a>(list: &'a [Value], key: &str, val: Option<&Value>) -> Option<&'a Value> { list.iter().find(|e| field(e, key) == val) @@ -433,43 +420,45 @@ fn effective(el: &Value, comp: Option<&Value>, cat: Option<&Value>) -> (Option, a: &SelArgs) -> Result { +/// Gesucht wird über `lk` (im Dokument mit dessen Positions-Index, keine lineare Suche je Darstellung). +pub fn derive(lk: &Lookup, a: &SelArgs) -> Result { fn id(o: &Option) -> Option<&str> { o.as_deref().filter(|s| !s.is_empty()) } + let root = lk.root; if let Some(i) = id(&a.context_object_id) { - if let Some(o) = find(root, "context", i, a.at.get("context").copied()) { + if let Some(o) = lk.find("context", i) { return Ok(context_selection(root, o)); } } if let Some(i) = id(&a.drawing_id) { - return Ok(find(root, "drawings2d", i, a.at.get("drawings2d").copied()).map_or(J::null(), |d| drawing_selection(root, d))); + return Ok(lk.find("drawings2d", i).map_or(J::null(), |d| drawing_selection(root, d))); } if let Some(i) = id(&a.extruded_solid_id) { - return Ok(find(root, "extrudedSolids", i, a.at.get("extrudedSolids").copied()).map_or(J::null(), |s| solid_selection(root, s))); + return Ok(lk.find("extrudedSolids", i).map_or(J::null(), |s| solid_selection(root, s))); } if let Some(i) = id(&a.column_id) { - return find(root, "columns", i, a.at.get("columns").copied()).map_or(Ok(J::null()), |c| column_selection(root, c)); + return lk.find("columns", i).map_or(Ok(J::null()), |c| column_selection(root, c)); } if let Some(i) = id(&a.opening_id) { - if let Some(o) = find(root, "openings", i, a.at.get("openings").copied()) { - return opening_selection(root, o); + if let Some(o) = lk.find("openings", i) { + return opening_selection(lk, o); } } if let Some(i) = a.wall_ids.first().filter(|s| !s.is_empty()) { - return find(root, "walls", i, a.at.get("walls").copied()).map_or(Ok(J::null()), |w| wall_selection(root, w)); + return lk.find("walls", i).map_or(Ok(J::null()), |w| wall_selection(root, w)); } if let Some(i) = id(&a.ceiling_id) { - return find(root, "ceilings", i, a.at.get("ceilings").copied()).map_or(Ok(J::null()), |c| ceiling_selection(root, c)); + return lk.find("ceilings", i).map_or(Ok(J::null()), |c| ceiling_selection(root, c)); } if let Some(i) = id(&a.roof_id) { - return find(root, "roofs", i, a.at.get("roofs").copied()).map_or(Ok(J::null()), |r| roof_selection(root, r)); + return lk.find("roofs", i).map_or(Ok(J::null()), |r| roof_selection(root, r)); } if let Some(i) = id(&a.stair_id) { - return find(root, "stairs", i, a.at.get("stairs").copied()).map_or(Ok(J::null()), |s| stair_selection(root, s)); + return lk.find("stairs", i).map_or(Ok(J::null()), |s| stair_selection(root, s)); } if let Some(i) = id(&a.room_id) { - return Ok(find(root, "rooms", i, a.at.get("rooms").copied()).map_or(J::null(), |r| room_selection(root, r))); + return Ok(lk.find("rooms", i).map_or(J::null(), |r| room_selection(root, r))); } Ok(J::null()) } @@ -698,16 +687,62 @@ fn roof_selection(root: &Map, r: &Value) -> Result { .done()) } +/// Gemerkte Firsthöhen, Schlüssel = Inhalts-Hash (Dach-JSON + Traufhöhe); je Eintrag Dach, Traufhöhe, +/// Firsthöhe (bei einem Treffer wird der Inhalt verglichen, nie veraltet). +type RidgeCache = std::collections::HashMap>; + +/// Höchstzahl gemerkter Firsthöhen (danach wird geleert). +const RIDGE_CACHE_MAX: usize = 4096; + thread_local! { - /// Zuletzt gerechnete Firsthöhen (Dach, Traufhöhe, Firsthöhe): die Objekt-Info fragt je Darstellung - /// neu, das Skelett eines Dachs kostet aber ein Vielfaches der übrigen Abfrage (TS merkte sich die - /// Geometrie je Dach-Objekt). - static RIDGE_CACHE: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + /// Gerechnete Firsthöhen: die Objekt-Info fragt je Darstellung neu, das Skelett eines Dachs kostet aber + /// ein Vielfaches der übrigen Abfrage (TS merkte sich die Geometrie je Dach-Objekt). Nach Inhalt + /// gemerkt, damit auch das Hin- und Herwählen zwischen vielen Dächern trifft. + static RIDGE_CACHE: std::cell::RefCell = std::cell::RefCell::new(RidgeCache::new()); } -/// Firsthöhe über der Traufe (Dach-Geometrie des Kerns, `roof.rs`), gemerkt für die letzten Dächer. +/// FNV-1a über einen JSON-Wert (Struktur, Schlüssel, Zahlen-Bits, Texte). +fn value_hash(v: &Value, h: &mut u64) { + let mut put = |bytes: &[u8]| { + for b in bytes { + *h = (*h ^ *b as u64).wrapping_mul(0x0000_0100_0000_01b3); + } + }; + match v { + Value::Null => put(b"n"), + Value::Bool(b) => put(if *b { b"t" } else { b"f" }), + Value::Number(n) => { + put(b"#"); + put(&n.as_f64().unwrap_or(f64::NAN).to_bits().to_le_bytes()); + } + Value::String(s) => { + put(b"s"); + put(s.as_bytes()); + put(&[0]); + } + Value::Array(a) => { + put(b"["); + for x in a { + value_hash(x, h); + } + *h = (*h ^ b']' as u64).wrapping_mul(0x0000_0100_0000_01b3); + } + Value::Object(m) => { + put(b"{"); + for (k, x) in m { + *h = k.bytes().fold(*h, |h, b| (h ^ b as u64).wrapping_mul(0x0000_0100_0000_01b3)); + value_hash(x, h); + } + *h = (*h ^ b'}' as u64).wrapping_mul(0x0000_0100_0000_01b3); + } + } +} + +/// Firsthöhe über der Traufe (Dach-Geometrie des Kerns, `roof.rs`), nach Inhalt gemerkt. fn roof_ridge_height(r: &Value, eaves: f64) -> Result { - let hit = RIDGE_CACHE.with(|c| c.borrow().iter().find(|(v, z, _)| z.to_bits() == eaves.to_bits() && v == r).map(|e| e.2)); + let mut key = 0xcbf2_9ce4_8422_2325u64 ^ eaves.to_bits(); + value_hash(r, &mut key); + let hit = RIDGE_CACHE.with(|c| c.borrow().get(&key).and_then(|l| l.iter().find(|(v, z, _)| *z == eaves.to_bits() && v == r).map(|e| e.2))); if let Some(h) = hit { return Ok(h); } @@ -715,10 +750,10 @@ fn roof_ridge_height(r: &Value, eaves: f64) -> Result { let h = crate::roof::roof_geometry(&typed.params(), eaves).ridge_height; RIDGE_CACHE.with(|c| { let mut c = c.borrow_mut(); - if c.len() >= 16 { - c.remove(0); + if c.len() >= RIDGE_CACHE_MAX { + c.clear(); } - c.push((r.clone(), eaves, h)); + c.entry(key).or_default().push((r.clone(), eaves.to_bits(), h)); }); Ok(h) } @@ -768,12 +803,17 @@ fn roof_edges(r: &Value) -> J { J::arr(out) } -fn opening_selection(root: &Map, o: &Value) -> Result { +fn opening_selection(lk: &Lookup, o: &Value) -> Result { use crate::opening_geom::{opening_gap_quad, v, WallRef}; + let root = lk.root; let cat = category(root, field(o, "categoryCode")); let color = color_of(o, cat, WALL_FALLBACK_COLOR); let weight = lw_or(None, cat, WALL_FALLBACK_MM); - let wall = find_by(arr(root.get("walls")), "id", field(o, "hostWallId")); + let host = field(o, "hostWallId"); + let wall = match host.and_then(Value::as_str) { + Some(i) => lk.find("walls", i), + None => find_by(arr(root.get("walls")), "id", host), + }; let floor = wall.and_then(|w| level(root, field(w, "floorId"))); let mut quad = None; if let Some(w) = wall { @@ -1213,7 +1253,7 @@ mod tests { } fn sel(r: &Map, a: Value) -> Result { - derive(r, &serde_json::from_value(a).unwrap()).map(|j| serde_json::from_str(&j.into_string()).unwrap()) + derive(&Lookup::plain(r), &serde_json::from_value(a).unwrap()).map(|j| serde_json::from_str(&j.into_string()).unwrap()) } #[test] diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index f1a7a6c1..c40b0741 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -87,7 +87,7 @@ fn problems_text(r: Option>>, parsed_err: Option) pub fn doc_apply(h: u32, ops_json: &str) -> String { match parse_ops(ops_json) { Err(e) => problems_text(None, Some(e)), - Ok(ops) => problems_text(with_doc(h, |d| d.apply_marked(&ops, may_have_marks(ops_json))), None), + Ok(ops) => problems_text(with_doc(h, |d| d.apply_marked(ops, may_have_marks(ops_json))), None), } } @@ -199,7 +199,7 @@ pub fn doc_query_args(h: u32, name: &str, args: &[f64], text: &str) -> String { /// Abfrage auf der rohen Projekt-Wurzel (`crate::queries::run_root`); Fehler wie bei [`doc_query`]. #[wasm_bindgen] pub fn doc_query_root(h: u32, name: &str, text: &str) -> String { - let result = with_doc(h, |d| crate::queries::run_root(d.root(), name, text)).unwrap_or_else(|| Err("Dokument nicht offen".to_string())); + let result = with_doc(h, |d| crate::queries::run_root(&d.lookup(), name, text)).unwrap_or_else(|| Err("Dokument nicht offen".to_string())); match result { Ok(json) => json, Err(e) => format!("\u{1}{e}"), @@ -226,3 +226,11 @@ pub fn doc_query_bin(h: u32, name: &str, args: &[f64], text: &str) -> Vec { let result = with_doc(h, |d| crate::queries::run_bin_doc(d, name, args, text)).unwrap_or_else(|| Err("Dokument nicht offen".to_string())); result.unwrap_or_else(|e| crate::plan_buf::encode_error(&e)) } + +/// Je Op der zuletzt angewendeten Folge (`doc_commit`, `doc_apply`, `doc_grip_commit`, `doc_undo`, +/// `doc_redo`) die Position des von `replace` getroffenen Elements, −1 = keine (TS führt die +/// Leseansicht damit ohne Suche nach, `applyOps`). +#[wasm_bindgen] +pub fn doc_last_hits(h: u32) -> Vec { + with_doc(h, |d| d.last_hits().iter().map(|p| p.map_or(-1.0, |i| i as f64)).collect()).unwrap_or_default() +} diff --git a/src-tauri/core/src/web/grips.rs b/src-tauri/core/src/web/grips.rs index 00bee250..5da97802 100644 --- a/src-tauri/core/src/web/grips.rs +++ b/src-tauri/core/src/web/grips.rs @@ -19,7 +19,7 @@ pub fn doc_grip_commit(h: u32, req_json: &str, key: &str, now_ms: f64) -> String let key = (!key.is_empty()).then_some(key); let now = if now_ms.is_finite() { now_ms } else { 0.0 }; let out = with_doc(h, |d| -> Result { - let res = crate::grips::run(d.root(), &req)?; + let res = crate::grips::run(&d.lookup(), &req)?; let text = crate::grips::result_json(&res); if res.ops.is_empty() { return Ok(text); @@ -79,3 +79,16 @@ pub fn edge_grips(pts: &[f64], closed: bool, bulge: &[f64], use_bulge: bool) -> } out } + +/// Punkttyp am Punkt `index` einer Polylinie (`crate::polyline_vertex`; `pts = [x0, y0, …]`, `bulge` je +/// Segment): `[typ, ecke, bogen, spline]` mit typ −1 = gemischt bzw. kein Punkt, 0 Ecke, 1 Bogen, +/// 2 Spline; danach je Typ 1/0, ob er sich setzen lässt. +#[wasm_bindgen] +pub fn polyline_vertex_info(pts: &[f64], bulge: &[f64], closed: bool, index: f64) -> Vec { + use crate::polyline_vertex::{can_set, index_of, type_of, Poly, VertexType}; + let verts: Vec<(f64, f64)> = pts.chunks_exact(2).map(|c| (c[0], c[1])).collect(); + let g = Poly { pts: &verts, closed, bulge }; + let Some(i) = index_of(index, verts.len()) else { return vec![-1.0, 0.0, 0.0, 0.0] }; + let can = |t| if can_set(&g, i, t) { 1.0 } else { 0.0 }; + vec![type_of(&g, i).map_or(-1.0, VertexType::code), can(VertexType::Corner), can(VertexType::Arc), can(VertexType::Spline)] +} diff --git a/src/core/document.ts b/src/core/document.ts index dd1d2b82..6fd3358c 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -234,7 +234,7 @@ export class ProjectDocument { } return { problems }; } - const project = applyOps(base, ops); + const project = applyOps(base, ops, core().doc_last_hits(this.handle)); this.mirror = project; return { project }; } @@ -253,7 +253,7 @@ export class ProjectDocument { const r = fromMarkedJson<{ ops: CoreOp[]; notice?: string } | { problems: string[] }>(out); if ("problems" in r) return r; if (r.ops.length === 0) return { project: base, ops: r.ops, notice: r.notice }; - const project = applyOps(base, r.ops); + const project = applyOps(base, r.ops, core().doc_last_hits(this.handle)); this.mirror = project; return { project, ops: r.ops, notice: r.notice }; } @@ -294,7 +294,7 @@ export class ProjectDocument { } const json = core()[fn](this.handle); if (!json) return null; - const project = applyOps(base, JSON.parse(json) as CoreOp[]); + const project = applyOps(base, JSON.parse(json) as CoreOp[], core().doc_last_hits(this.handle)); this.mirror = project; return project; } diff --git a/src/core/index.ts b/src/core/index.ts index 450dc930..ba4b9bc9 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -112,7 +112,6 @@ export { type PolylineVertexType, canSetVertexType, vertexTypeOf, - withVertexType, } from "../geometry/polylineVertexType"; export { diff --git a/src/core/ops.apply.test.ts b/src/core/ops.apply.test.ts index 194d9a4f..a42a0001 100644 --- a/src/core/ops.apply.test.ts +++ b/src/core/ops.apply.test.ts @@ -128,3 +128,44 @@ describe("applyOps (schnelle Fassung) = Referenz", () => { expect(out.walls).toEqual([{ id: "a", z: 1 }, { id: "b" }, { id: "c" }]); }); }); + +describe("applyOps: id-Index über die Aufrufe hinweg", () => { + it("Ketten und Verzweigungen grosser Listen (geteilter Index) = Referenz", () => { + const walls = Array.from({ length: 200 }, (_, i) => ({ ...sampleProject.walls[0], id: `w${i}` })); + const big: Project = { ...sampleProject, walls, drawings2d: [] }; + const r = rng(7); + const history: Project[] = [big]; + for (let step = 0; step < 600; step++) { + // Meist auf dem letzten Stand weiter, manchmal auf einem älteren (Undo-Basis, fremde Projekte). + const base = r() < 0.7 ? history[history.length - 1] : history[Math.floor(r() * history.length)]; + const ids = ["w0", "w5", "w199", "w150", `n${Math.floor(r() * 40)}`, `n${Math.floor(r() * 40)}`]; + const ops: CoreOp[] = []; + for (let k = 0, n = 1 + Math.floor(r() * 4); k < n; k++) { + const x = r(); + const id = ids[Math.floor(r() * ids.length)]; + if (x < 0.6) ops.push({ kind: "replace", collection: "walls", entity: { id, v: step } }); + else if (x < 0.8) ops.push({ kind: "add", collection: "walls", items: [{ id: `n${Math.floor(r() * 40)}` }] }); + else if (x < 0.9) ops.push({ kind: "add", collection: "walls", items: [{ id }], at: Math.floor(r() * 300) }); + else ops.push({ kind: "remove", collection: "walls", ids: [id] }); + } + // Positions-Hinweise des Kerns (erstes Vorkommen, wie `Document::last_hits`): richtig, auf ein + // anderes Element, ausserhalb oder fehlend — das Ergebnis bleibt gleich. + let hits: number[] | undefined; + if (r() < 0.6) { + hits = []; + let cur = base; + for (const op of ops) { + const list = cur.walls as unknown as Entity[]; + const first = op.kind === "replace" ? list.findIndex((e) => e.id === op.entity.id) : -1; + const other = list.findIndex((e, i) => i >= Math.floor(r() * list.length) && op.kind === "replace" && e.id !== op.entity.id); + const x = r(); + hits.push(x < 0.6 ? first : x < 0.8 ? other : x < 0.9 ? list.length + 3 : -1); + cur = referenceApplyOps(cur, [op]); + } + } + const a = applyOps(base, ops, hits); + expect(JSON.stringify(a.walls)).toBe(JSON.stringify(referenceApplyOps(base, ops).walls)); + history.push(a); + } + }); +}); diff --git a/src/core/ops.ts b/src/core/ops.ts index 4f107bb2..01728803 100644 --- a/src/core/ops.ts +++ b/src/core/ops.ts @@ -37,25 +37,79 @@ export type CoreOp = /** * Wendet eine Op-Folge rein an (kein Zugriff auf Store/UI). Unberührte Listen und Elemente behalten - * ihre Identität. Innerhalb eines Aufrufs wird jede Liste höchstens einmal kopiert und für - * `replace`-Serien (Auswahl verschieben: hunderte Elemente) über einen id-Index angesprochen — - * Ergebnis gleich der einfachen Fassung (Test `ops.apply.test.ts`). + * ihre Identität. Innerhalb eines Aufrufs wird jede Liste höchstens einmal kopiert. `replace` findet + * sein Element über `hits` (je Op die Position, die der Kern beim Anwenden getroffen hat, + * `ProjectDocument`; wird nachgeprüft) oder sonst über {@link indexOfId} — ein Griff-Schritt an einer + * grossen Liste sucht so nicht linear. Ergebnis gleich der einfachen Fassung (Test `ops.apply.test.ts`). */ -export function applyOps(project: Project, ops: readonly CoreOp[]): Project { +export function applyOps(project: Project, ops: readonly CoreOp[], hits?: ArrayLike): Project { if (ops.length === 0) return project; - const st: ApplyState = { cur: { ...(project as unknown as Record) }, owned: new Set(), index: new Map() }; - for (const op of ops) applyOne(st, op); + const st: ApplyState = { cur: { ...(project as unknown as Record) }, owned: new Set(), hit: -1 }; + for (let k = 0; k < ops.length; k++) { + st.hit = hits?.[k] ?? -1; + applyOne(st, ops[k]); + } return st.cur as unknown as Project; } /** Zustand eines `applyOps`-Aufrufs: `cur` ist eine eigene Kopie der obersten Ebene; Listen in - * `owned` wurden in diesem Aufruf neu angelegt (dürfen verändert werden), `index` = id → Position - * (erstes Vorkommen) solcher Listen. */ + * `owned` wurden in diesem Aufruf neu angelegt (dürfen verändert werden); `hit` = vermutete Position + * des Elements der laufenden `replace`-Op (−1 = keine). */ interface ApplyState { cur: Record; owned: Set; - /** `null` = einmal linear gesucht, der Index wird bei der nächsten Suche gebaut. */ - index: Map | null>; + hit: number; +} + +// ── id-Index der Listen ────────────────────────────────────────────────────── + +/** + * id → Position (erstes Vorkommen) je Liste, für Suchen ohne Positions-Hinweis des Kerns (Op-Bauer, + * `findItem`). Listen der Leseansicht ändern sich nie (jede Änderung legt eine neue an); eine Kopie mit + * denselben Positionen (`replace`, `add` am Ende) übernimmt den Index der Vorlage samt der neuen ids. + * Teilen sich so mehrere Listen einen Index, enthält er die ids jeder von ihnen; ein Treffer wird an + * der Liste nachgeprüft (sonst lineare Suche), kein Eintrag heisst „nicht enthalten". Der Index kostet + * in V8 etwa das Zwanzigfache einer linearen Suche (20 000 Elemente ≈ 6 ms): gebaut wird er erst bei + * der zweiten Suche in derselben Listen-Linie (`null` = einmal linear gesucht). + */ +const ID_INDEX = new WeakMap | null>(); + +/** Ab dieser Länge wird ein Index gebaut (darunter ist die lineare Suche billiger). */ +const INDEX_MIN_LEN = 32; + +/** Position des ersten Elements mit `id` in `list` (−1 = keins); Index je Listen-Linie gemerkt. */ +export function indexOfId(list: readonly unknown[], id: unknown): number { + const linear = () => list.findIndex((e) => (e as Entity | null)?.id === id); + if (list.length < INDEX_MIN_LEN) return linear(); + let idx = ID_INDEX.get(list); + if (idx === undefined) { + ID_INDEX.set(list, null); + return linear(); + } + if (idx === null) { + idx = new Map(); + for (let i = 0; i < list.length; i++) { + const k = (list[i] as Entity | null)?.id; + if (!idx.has(k)) idx.set(k, i); + } + ID_INDEX.set(list, idx); + } + const i = idx.get(id); + if (i === undefined) return -1; + return (list[i] as Entity | null)?.id === id ? i : linear(); +} + +/** `copy` hat dieselben Positionen wie `src` (plus Elemente am Ende): Index (bzw. Such-Marke) übernehmen. */ +function shareIndex(src: readonly unknown[], copy: readonly unknown[]): void { + const idx = ID_INDEX.get(src); + if (idx === undefined) return; + if (idx !== null) { + for (let i = src.length; i < copy.length; i++) { + const k = (copy[i] as Entity | null)?.id; + if (!idx.has(k)) idx.set(k, i); + } + } + ID_INDEX.set(copy, idx); } function listOf(cur: Record, collection: string): Entity[] { @@ -63,11 +117,10 @@ function listOf(cur: Record, collection: string): Entity[] { return Array.isArray(v) ? (v as Entity[]) : []; } -/** Setzt `collection` auf eine neue (eigene) Liste; ein vorhandener Index verfällt. */ +/** Setzt `collection` auf eine neue (eigene) Liste. */ function putList(st: ApplyState, collection: string, list: Entity[]): void { st.cur[collection] = list; st.owned.add(collection); - st.index.delete(collection); } function applyOne(st: ApplyState, op: CoreOp): void { @@ -76,7 +129,6 @@ function applyOne(st: ApplyState, op: CoreOp): void { case "setField": { // Der Wert gehört dem Aufrufer: nie verändern. st.owned.delete(op.key); - st.index.delete(op.key); if (op.value !== undefined && op.at !== undefined && !(op.key in cur)) { // Neues Feld an Position `at` (wie `shift_insert` im Kern). const entries = Object.entries(cur); @@ -91,7 +143,9 @@ function applyOne(st: ApplyState, op: CoreOp): void { case "add": { const list = listOf(cur, op.collection); const at = op.at === undefined ? list.length : Math.max(0, Math.min(list.length, op.at)); - putList(st, op.collection, [...list.slice(0, at), ...op.items, ...list.slice(at)]); + const next = [...list.slice(0, at), ...op.items, ...list.slice(at)]; + if (at === list.length) shareIndex(list, next); + putList(st, op.collection, next); return; } case "replace": { @@ -99,30 +153,17 @@ function applyOne(st: ApplyState, op: CoreOp): void { let list: Entity[]; if (st.owned.has(c)) list = cur[c] as Entity[]; else { - list = listOf(cur, c).slice(); + const src = listOf(cur, c); + list = src.slice(); + shareIndex(src, list); putList(st, c, list); } - // Erste Suche in dieser Liste linear (ein Drag-Schritt), ab der zweiten über den Index. - let idx = st.index.get(c); - let at: number | undefined; - if (idx === undefined) { - st.index.set(c, null); - const i = list.findIndex((e) => e?.id === op.entity.id); - at = i < 0 ? undefined : i; - } else { - if (idx === null) { - idx = new Map(); - for (let i = 0; i < list.length; i++) { - const id = list[i]?.id; - if (!idx.has(id)) idx.set(id, i); - } - st.index.set(c, idx); - } - at = idx.get(op.entity.id); - } - if (at === undefined) { - idx?.set(op.entity.id, list.length); + const h = st.hit; + const at = h >= 0 && h < list.length && list[h]?.id === op.entity.id ? h : indexOfId(list, op.entity.id); + if (at < 0) { list.push(op.entity); + const idx = ID_INDEX.get(list); + if (idx && !idx.has(op.entity.id)) idx.set(op.entity.id, list.length - 1); } else list[at] = op.entity; return; } diff --git a/src/core/opsBuild.ts b/src/core/opsBuild.ts index 9f47f323..533c3f37 100644 --- a/src/core/opsBuild.ts +++ b/src/core/opsBuild.ts @@ -9,7 +9,7 @@ // {@link opsMutation} die Ops mit — `setProject` nimmt dann die Ops ohne Differenz. import type { Project } from "../model/types"; -import { applyOps } from "./ops"; +import { applyOps, indexOfId } from "./ops"; import type { CoreOp } from "./ops"; /** Projekt-Felder, die Listen von Elementen mit `id` sind (walls, drawings2d, rooms, …). */ @@ -34,7 +34,9 @@ export function itemsOf(p: Project, collection: K): /** Element `id` aus `collection` (erstes Vorkommen). */ export function findItem(p: Project, collection: K, id: string): EntityOf | undefined { - return itemsOf(p, collection).find((e) => (e as { id: string }).id === id); + const list = itemsOf(p, collection); + const i = indexOfId(list, id); + return i < 0 ? undefined : list[i]; } /** Ersetzt ein Element (gleiche id, Position bleibt). */ diff --git a/src/geometry/grips.ts b/src/geometry/grips.ts index b7c5e8a9..62c942b6 100644 --- a/src/geometry/grips.ts +++ b/src/geometry/grips.ts @@ -28,6 +28,7 @@ export type GripRequest = | { op: "ceilingEdge" | "roomEdge"; id: string; a: number; b: number; delta: P } | { op: "insertPoint"; id: string; seg: number; pt: P } | { op: "deletePoint"; id: string; index: number } + | { op: "vertexType"; id: string; index: number; vertexType: "corner" | "arc" | "spline" } | { op: "wallThickness" | "ceilingThickness"; id: string; thickness: number; newId: string; newName: string }; /** Punkt als Anfrage-Paar. */ diff --git a/src/geometry/polylineVertexType.test.ts b/src/geometry/polylineVertexType.test.ts index efec60b5..4ec2ec30 100644 --- a/src/geometry/polylineVertexType.test.ts +++ b/src/geometry/polylineVertexType.test.ts @@ -1,59 +1,61 @@ +// Punkttypen einer Polylinie: Rechnung im Kern (`polyline_vertex.rs`, eigene Rust-Tests); hier die +// Fassade für das Kontextmenü und die Store-Aktion `setPolylineVertexType` (Griff-Änderung im Kern). import { describe, expect, it } from "vitest"; import { bulgeArc, bulgeArcPoints } from "./bulge"; -import { canSetVertexType, vertexTypeOf, withVertexType } from "./polylineVertexType"; +import { canSetVertexType, vertexTypeOf } from "./polylineVertexType"; +import { getState } from "../state/appStore"; +import { sampleProject } from "../model/sampleProject"; +import type { Drawing2D, Vec2 } from "../model/types"; const g = { pts: [{ x: 0, y: 0 }, { x: 2, y: 1 }, { x: 4, y: 0 }, { x: 6, y: 1 }], closed: false }; +/** Setzt den Punkttyp über den Store und liefert die Bulges (fehlend = alle gerade). */ +function setType(pts: Vec2[], closed: boolean, i: number, type: "corner" | "arc" | "spline", bulge?: number[]): number[] | undefined { + const d = { id: "pl", levelId: sampleProject.drawingLevels[0].id, categoryCode: "01", geom: { shape: "polyline", pts, closed, ...(bulge ? { bulge } : {}) } }; + getState().loadProject({ ...structuredClone(sampleProject), drawings2d: [d as Drawing2D] }); + getState().setPolylineVertexType("pl", i, type); + const geom = getState().project.drawings2d[0].geom; + return geom.shape === "polyline" ? geom.bulge : undefined; +} + describe("Punkttypen einer Polylinie", () => { it("Eckpunkt setzt beide Nachbarsegmente gerade", () => { - const b = withVertexType({ ...g, bulge: [0.3, -0.2, 0.1] }, 1, "corner"); - expect(b).toEqual([0, 0, 0.1]); + expect(setType(g.pts, false, 1, "corner", [0.3, -0.2, 0.1])).toEqual([0, 0, 0.1]); + expect(setType(g.pts, false, 1, "corner", [0.3, -0.2, 0])).toBeUndefined(); }); it("Bogenpunkt: beide Segmente liegen auf EINEM Kreis durch die drei Punkte", () => { - const b = withVertexType(g, 1, "arc"); + const b = setType(g.pts, false, 1, "arc")!; const a1 = bulgeArc(g.pts[0], g.pts[1], b[0])!; const a2 = bulgeArc(g.pts[1], g.pts[2], b[1])!; - expect(a1).not.toBeNull(); expect(Math.hypot(a1.center.x - a2.center.x, a1.center.y - a2.center.y)).toBeLessThan(1e-6); expect(a1.r).toBeCloseTo(a2.r, 6); expect(vertexTypeOf({ ...g, bulge: b }, 1)).toBe("arc"); // Die Bögen bauchen NACH OBEN aus (Punkt 1 liegt oben) — kein Zickzack über den Kreis const mid1 = bulgeArcPoints(g.pts[0], g.pts[1], b[0]); - const apex = mid1[mid1.length / 2 | 0]; - expect(apex.y).toBeGreaterThan(0.5); + expect(mid1[(mid1.length / 2) | 0].y).toBeGreaterThan(0.5); }); - it("Splinepunkt: Tangenten beider Segmente im Punkt stimmen überein", () => { - const g = { pts: [{ x: 0, y: 0 }, { x: 2, y: 1 }, { x: 5, y: 0.2 }], closed: false }; - const b = withVertexType(g, 1, "spline"); - // exakte Tangenten aus den Bögen (senkrecht zum Radius, Richtung nach Umlaufsinn) - const tan = (a: { x: number; y: number }, c: { x: number; y: number }, bb: number, atEnd: boolean) => { - const arc = bulgeArc(a, c, bb)!; - const ang = atEnd ? arc.a0 + arc.sweep : arc.a0; - const sg = Math.sign(arc.sweep); - return Math.atan2(Math.cos(ang) * sg, -Math.sin(ang) * sg); - }; - const t1 = tan(g.pts[0], g.pts[1], b[0], true); - const t2 = tan(g.pts[1], g.pts[2], b[1], false); - expect(Math.abs(t1 - t2)).toBeLessThan(1e-6); - // Tangente = Richtung Vorgänger→Nachfolger - expect(Math.abs(t2 - Math.atan2(0.2, 5))).toBeLessThan(1e-6); - expect(vertexTypeOf({ ...g, bulge: b }, 1)).toBe("spline"); - }); - - it("offene Enden: Bogen/Spline nicht möglich, Ecke schon", () => { + it("Splinepunkt: Typ wird erkannt, offene Enden lassen nur die Ecke zu", () => { + const pts = [{ x: 0, y: 0 }, { x: 2, y: 1 }, { x: 5, y: 0.2 }]; + expect(vertexTypeOf({ pts, closed: false, bulge: setType(pts, false, 1, "spline") }, 1)).toBe("spline"); + expect(vertexTypeOf(g, 1)).toBe("corner"); expect(canSetVertexType(g, 0, "arc")).toBe(false); expect(canSetVertexType(g, 3, "spline")).toBe(false); expect(canSetVertexType(g, 0, "corner")).toBe(true); + expect(canSetVertexType(g, 1, "spline")).toBe(true); }); - it("geschlossene Polylinie: erster Punkt hat beide Nachbarn", () => { - const sq = { pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }], closed: true }; - const b = withVertexType(sq, 0, "arc"); + it("geschlossene Polylinie: erster Punkt hat beide Nachbarn; gesperrt ändert nichts", () => { + const sq = [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }]; + const b = setType(sq, true, 0, "arc")!; expect(b.length).toBe(4); expect(b[3]).not.toBe(0); expect(b[0]).not.toBe(0); expect(b[1]).toBe(0); + const depth = getState().undoDepth; + getState().updateDrawing2D("pl", { locked: true }); + getState().setPolylineVertexType("pl", 0, "corner"); + expect(getState().undoDepth).toBe(depth + 1); }); }); diff --git a/src/geometry/polylineVertexType.ts b/src/geometry/polylineVertexType.ts index 0ded4ba1..5585ae8e 100644 --- a/src/geometry/polylineVertexType.ts +++ b/src/geometry/polylineVertexType.ts @@ -1,19 +1,11 @@ -// Punkttypen einer Polylinie (ArchiCAD/Vectorworks-artig): Eckpunkt, Bogenpunkt, -// Splinepunkt. Rein als Umrechnung der Segment-Bögen (`bulge`) der beiden am Punkt -// anliegenden Segmente — alle Renderer/Exporte verstehen Bulges bereits, es gibt -// also kein neues Geometrie-Feld. -// -// • Eckpunkt: beide Segmente gerade (bulge 0). -// • Bogenpunkt: EIN Kreisbogen durch Vorgänger, Punkt und Nachfolger. -// • Splinepunkt: tangential glatter Übergang — die Tangente im Punkt ist parallel -// zur Verbindung Vorgänger→Nachfolger (wie bei einer Catmull-Rom-Kurve), beide -// Segmente werden zu Bögen, die diese Tangente teilen. -// -// Die Bögen werden über ihren SCHEITELPUNKT bestimmt und mit `bulgeFromSagittaPoint` -// in einen Bulge übersetzt — so bleibt die Vorzeichen-Konvention an EINER Stelle. +// Punkttypen einer Polylinie (ArchiCAD/Vectorworks-artig): Eckpunkt, Bogenpunkt, Splinepunkt — als +// Umrechnung der Segment-Bögen (`bulge`) der beiden am Punkt anliegenden Segmente. Gerechnet im +// Rust-Kern (`src-tauri/core/src/polyline_vertex.rs`): das Setzen als Griff-Änderung auf dem Dokument +// (Store `setPolylineVertexType`, Anfrage `vertexType`), die Abfrage für das Kontextmenü hier über die +// Bindung `polyline_vertex_info`. import type { Vec2 } from "../model/types"; -import { bulgeArc, bulgeFromSagittaPoint } from "./bulge"; +import { core } from "../engine/coreWasm"; export type PolylineVertexType = "corner" | "arc" | "spline"; @@ -23,160 +15,24 @@ interface PolylineLike { bulge?: number[]; } -const EPS = 1e-9; +const TYPES: PolylineVertexType[] = ["corner", "arc", "spline"]; -/** Indizes des ein- und ausgehenden Segments von Punkt `i` (null = keins). */ -function adjacentSegments(n: number, closed: boolean, i: number): { inSeg: number | null; outSeg: number | null } { - const inSeg = i > 0 ? i - 1 : closed ? n - 1 : null; - const outSeg = i < n - 1 ? i : closed ? n - 1 : null; - return { inSeg, outSeg }; -} - -/** Nachbarpunkte von `i` (null an offenen Enden). */ -function neighbors(g: PolylineLike, i: number): { prev: Vec2 | null; next: Vec2 | null } { - const n = g.pts.length; - const prev = i > 0 ? g.pts[i - 1] : g.closed ? g.pts[n - 1] : null; - const next = i < n - 1 ? g.pts[i + 1] : g.closed ? g.pts[0] : null; - return { prev, next }; -} - -const cross = (a: Vec2, b: Vec2) => a.x * b.y - a.y * b.x; -const sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y }); - -/** Umkreismittelpunkt von a,b,c (null bei kollinearen Punkten). */ -function circumcenter(a: Vec2, b: Vec2, c: Vec2): Vec2 | null { - const d = 2 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)); - if (Math.abs(d) < EPS) return null; - const a2 = a.x * a.x + a.y * a.y, b2 = b.x * b.x + b.y * b.y, c2 = c.x * c.x + c.y * c.y; - return { - x: (a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d, - y: (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d, - }; -} - -/** - * Bulge des Kreisbogens a→b auf dem Kreis um `c`, und zwar des Bogens, der NICHT - * durch `other` läuft (Scheitel auf der anderen Seite der Sehne als `other`). - */ -function bulgeOnCircle(a: Vec2, b: Vec2, c: Vec2, other: Vec2): number { - const r = Math.hypot(a.x - c.x, a.y - c.y); - const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; - let u = sub(mid, c); - let len = Math.hypot(u.x, u.y); - if (len < EPS) { - const d = sub(b, a); - u = { x: -d.y, y: d.x }; - len = Math.hypot(u.x, u.y); +/** `[typ, ecke, bogen, spline]` des Kerns (typ −1 = gemischt/kein Punkt; danach setzbar 1/0). */ +function info(g: PolylineLike, i: number): Float64Array { + const pts = new Float64Array(g.pts.length * 2); + for (let k = 0; k < g.pts.length; k++) { + pts[2 * k] = g.pts[k].x; + pts[2 * k + 1] = g.pts[k].y; } - u = { x: u.x / len, y: u.y / len }; - const side = (p: Vec2) => Math.sign(cross(sub(b, a), sub(p, a))); - const cand1 = { x: c.x + u.x * r, y: c.y + u.y * r }; - const cand2 = { x: c.x - u.x * r, y: c.y - u.y * r }; - const apex = side(cand1) !== side(other) ? cand1 : cand2; - return bulgeFromSagittaPoint(a, b, apex); -} - -/** Tangente (Fahrtrichtung a→b) des Bulge-Bogens am Anfang bzw. Ende. */ -function arcTangent(a: Vec2, b: Vec2, bulge: number, atEnd: boolean): Vec2 { - const arc = bulgeArc(a, b, bulge); - if (!arc) { - const d = sub(b, a); - const l = Math.hypot(d.x, d.y) || 1; - return { x: d.x / l, y: d.y / l }; - } - const ang = atEnd ? arc.a0 + arc.sweep : arc.a0; - const s = Math.sign(arc.sweep) || 1; - return { x: -Math.sin(ang) * s, y: Math.cos(ang) * s }; -} - -/** - * Bulge des Bogens a→b mit gegebener Tangente `t` am Ende (atEnd) bzw. Anfang. - * Betrag aus dem Winkel Sehne↔Tangente, Vorzeichen NUMERISCH gewählt (die - * Variante, deren tatsächliche Tangente zu `t` passt). - */ -function bulgeWithTangent(a: Vec2, b: Vec2, t: Vec2, atEnd: boolean): number { - const c = sub(b, a); - const ang = Math.abs(Math.atan2(cross(c, t), c.x * t.x + c.y * t.y)); - const mag = Math.abs(bulgeFromApexAngle(a, b, ang)); - if (mag < 1e-9) return 0; - const dot = (v: Vec2) => v.x * t.x + v.y * t.y; - return dot(arcTangent(a, b, mag, atEnd)) >= dot(arcTangent(a, b, -mag, atEnd)) ? mag : -mag; -} - -const bulgeWithEndTangent = (a: Vec2, b: Vec2, t: Vec2) => bulgeWithTangent(a, b, t, true); -const bulgeWithStartTangent = (a: Vec2, b: Vec2, t: Vec2) => bulgeWithTangent(a, b, t, false); - -/** - * Bogen über der Sehne a→b mit halbem Öffnungswinkel |half| (Sehne↔Tangente); - * Vorzeichen: >0 Scheitel links der Sehne, <0 rechts. Über den Scheitelpunkt in - * einen Bulge übersetzt. - */ -function bulgeFromApexAngle(a: Vec2, b: Vec2, half: number): number { - if (Math.abs(half) < 1e-6) return 0; - // Begrenzen: knapp unter einem Halbkreis je Segment (sonst kippt der Bogen). - const h2 = Math.max(-Math.PI / 2 + 0.01, Math.min(Math.PI / 2 - 0.01, half)); - const d = sub(b, a); - const chord = Math.hypot(d.x, d.y); - if (chord < EPS) return 0; - const left = { x: -d.y / chord, y: d.x / chord }; - const s = (chord / 2) * Math.tan(h2 / 2); // Pfeilhöhe - const apex = { x: (a.x + b.x) / 2 + left.x * s, y: (a.y + b.y) / 2 + left.y * s }; - return bulgeFromSagittaPoint(a, b, apex); + return core().polyline_vertex_info(pts, Float64Array.from(g.bulge ?? []), !!g.closed, i); } /** Ist Punkttyp `type` am Punkt `i` möglich? (Bogen/Spline brauchen beide Nachbarn.) */ export function canSetVertexType(g: PolylineLike, i: number, type: PolylineVertexType): boolean { - if (i < 0 || i >= g.pts.length) return false; - if (type === "corner") return true; - const { prev, next } = neighbors(g, i); - return !!prev && !!next; + return info(g, i)[1 + TYPES.indexOf(type)] === 1; } /** Aktueller Typ (Heuristik): beide Nachbarsegmente gerade → Eckpunkt, sonst null (gemischt). */ export function vertexTypeOf(g: PolylineLike, i: number): PolylineVertexType | null { - const { inSeg, outSeg } = adjacentSegments(g.pts.length, g.closed, i); - const b = (k: number | null) => (k === null ? 0 : g.bulge?.[k] ?? 0); - if (Math.abs(b(inSeg)) < 1e-9 && Math.abs(b(outSeg)) < 1e-9) return "corner"; - const { prev, next } = neighbors(g, i); - if (!prev || !next || inSeg === null || outSeg === null) return null; - const a1 = bulgeArc(prev, g.pts[i], b(inSeg)); - const a2 = bulgeArc(g.pts[i], next, b(outSeg)); - if (a1 && a2 && Math.hypot(a1.center.x - a2.center.x, a1.center.y - a2.center.y) < 1e-6 * (1 + a1.r)) return "arc"; - return "spline"; -} - -/** Neue Bulge-Liste mit Punkttyp `type` an Punkt `i` (Eingabe bleibt unverändert). */ -export function withVertexType(g: PolylineLike, i: number, type: PolylineVertexType): number[] { - const n = g.pts.length; - const segCount = g.closed ? n : n - 1; - const bulge = Array.from({ length: segCount }, (_, k) => g.bulge?.[k] ?? 0); - if (!canSetVertexType(g, i, type)) return bulge; - const { inSeg, outSeg } = adjacentSegments(n, g.closed, i); - const q = g.pts[i]; - const { prev, next } = neighbors(g, i); - if (type === "corner") { - if (inSeg !== null) bulge[inSeg] = 0; - if (outSeg !== null) bulge[outSeg] = 0; - return bulge; - } - const p = prev!, r = next!; - if (type === "arc") { - const c = circumcenter(p, q, r); - if (!c) { - bulge[inSeg!] = 0; - bulge[outSeg!] = 0; - return bulge; - } - bulge[inSeg!] = bulgeOnCircle(p, q, c, r); - bulge[outSeg!] = bulgeOnCircle(q, r, c, p); - return bulge; - } - // spline: Tangente parallel zu prev→next - const t = sub(r, p); - const tl = Math.hypot(t.x, t.y); - if (tl < EPS) return bulge; - const tu = { x: t.x / tl, y: t.y / tl }; - bulge[inSeg!] = bulgeWithEndTangent(p, q, tu); - bulge[outSeg!] = bulgeWithStartTangent(q, r, tu); - return bulge; + return TYPES[info(g, i)[0]] ?? null; } diff --git a/src/state/objectInfo.perf.test.ts b/src/state/objectInfo.perf.test.ts new file mode 100644 index 00000000..4e51e926 --- /dev/null +++ b/src/state/objectInfo.perf.test.ts @@ -0,0 +1,93 @@ +// [K4] Messung: Objekt-Info (`deriveSelection`), Griff-Schritte und grosse Polylinien auf einem grossen +// Projekt (3000 Wände + 20 000 Zeichnungen, 40 Dächer) über den Store. Werte gehen nach stderr (TODO [K4]); +// die Grenzen sind grosszügig (Container unter Last), geprüft wird vor allem das Ergebnis. +import { describe, expect, it } from "vitest"; +import { getState } from "./appStore"; +import { deriveSelection } from "./selectionInfo"; +import { sampleProject } from "../model/sampleProject"; +import type { Drawing2D, Project, Roof, Wall } from "../model/types"; + +const st = () => getState(); + +function bigProject(): Project { + const base = sampleProject.walls; + const walls: Wall[] = Array.from({ length: 3000 }, (_, i) => ({ + ...base[i % base.length], + id: `w${i}`, + start: { x: i, y: 0 }, + end: { x: i + 1, y: 0 }, + })); + const level = sampleProject.drawingLevels[0].id; + const drawings: Drawing2D[] = Array.from({ length: 20000 }, (_, i) => ({ + id: `d${i}`, + levelId: level, + categoryCode: "01", + geom: + i === 19000 + ? { + shape: "polyline", + closed: false, + pts: Array.from({ length: 5000 }, (_, k) => ({ x: k * 0.1, y: Math.sin(k / 50) })), + } + : { shape: "polyline", closed: false, pts: [{ x: i, y: 1 }, { x: i + 1, y: 2 }, { x: i + 2, y: 1 }] }, + })) as Drawing2D[]; + const roof = sampleProject.roofs![0]; + const roofs: Roof[] = Array.from({ length: 40 }, (_, i) => ({ + ...roof, + id: `r${i}`, + outline: roof.outline.map((p) => ({ x: p.x + i * 10, y: p.y })), + })); + return { ...structuredClone(sampleProject), walls, drawings2d: drawings, roofs }; +} + +/** Kleinster Mittelwert (µs) aus `rounds` Läufen à `n` Aufrufen. */ +function bench(n: number, fn: (i: number) => void, rounds = 3): number { + let best = Infinity; + for (let i = 0; i < Math.ceil(n / 4); i++) fn(i); // Aufwärmen (JIT, Caches) + for (let r = 0; r < rounds; r++) { + const t = performance.now(); + for (let i = 0; i < n; i++) fn(i); + best = Math.min(best, ((performance.now() - t) * 1000) / n); + } + return best; +} + +const sel = (p: Project, k: { wall?: string; drawing?: string; roof?: string }) => + deriveSelection(p, k.wall ? [k.wall] : [], k.drawing ?? null, null, null, null, null, null, null, k.roof ?? null); + +describe("Messung Objekt-Info und Griffe, 3000 Wände + 20 000 Zeichnungen", () => { + it("Objekt-Info, Griff-Schritte, Polylinien-Punkttyp", { timeout: 120000 }, () => { + st().loadProject(bigProject()); + const p = st().project; + const out: string[] = []; + for (const i of [10, 1500, 2990]) { + expect(sel(p, { wall: `w${i}` })?.kind).toBe("wall"); + out.push(`Info Wand ${i} ${bench(200, () => sel(p, { wall: `w${i}` })).toFixed(0)} µs`); + } + expect(sel(p, { drawing: "d10000" })?.kind).toBe("drawing2d"); + out.push(`Info Zeichnung 10000 ${bench(200, () => sel(p, { drawing: "d10000" })).toFixed(0)} µs`); + expect(sel(p, { roof: "r20" })?.kind).toBe("roof"); + out.push(`Info Dach (40 im Wechsel) ${bench(200, (i) => sel(p, { roof: `r${i % 40}` })).toFixed(0)} µs`); + + for (const i of [10, 1500, 2990]) { + const us = bench(50, (k) => st().moveGripOf(null, `w${i}`, 0, { x: i + (k % 7) * 0.01, y: 0.5 })); + out.push(`Griff Wand ${i} ${us.toFixed(0)} µs`); + } + expect(st().project.walls[1500].start.y).toBe(0.5); + const big = (k: number) => st().moveGripOf("d19000", null, 2500, { x: 250 + (k % 5) * 0.01, y: 3 }); + out.push(`Griff Polylinie 5000 Punkte ${(bench(20, big) / 1000).toFixed(2)} ms`); + out.push(`Griff Zeichnung 15000 ${bench(50, (k) => st().moveGripOf("d15000", null, 1, { x: 15001, y: 2 + (k % 5) * 0.01 })).toFixed(0)} µs`); + + const types = ["arc", "spline", "corner"] as const; + out.push( + `Punkttyp Polylinie 5000 Punkte ${(bench(20, (k) => st().setPolylineVertexType("d19000", 100 + k, types[k % 3])) / 1000).toFixed(2)} ms`, + ); + out.push(`Punkttyp kleine Polylinie ${bench(50, (k) => st().setPolylineVertexType("d12000", 1, types[k % 3])).toFixed(0)} µs`); + st().setPolylineVertexType("d12000", 1, "arc"); + expect((st().project.drawings2d[12000].geom as { bulge?: number[] }).bulge?.length).toBe(2); + st().setPolylineVertexType("d12000", 1, "corner"); + expect((st().project.drawings2d[12000].geom as { bulge?: number[] }).bulge).toBeUndefined(); + + process.stderr.write(`Objekt-Info/Griffe (Store): ${out.join(", ")}\n`); + }); +}); diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index ec413466..90cbcdb6 100644 --- a/src/state/projectSlice.ts +++ b/src/state/projectSlice.ts @@ -22,7 +22,7 @@ import { setField, setFieldIfChanged, } from "../core"; -import { withVertexType, type PolylineVertexType } from "../core"; +import type { PolylineVertexType } from "../core"; import { sampleProject } from "../model/sampleProject"; import { addChildByCode, @@ -218,7 +218,7 @@ export interface ProjectSlice { deleteDrawingPoint: (drawingId: string, index: number) => void; /** * Punkttyp eines Polylinien-Stützpunkts setzen (Eckpunkt/Bogenpunkt/Splinepunkt), - * s. `geometry/polylineVertexType.ts` — rechnet nur die Bulges der beiden + * im Kern (`polyline_vertex.rs`, Griff-Änderung `vertexType`) — rechnet nur die Bulges der beiden * anliegenden Segmente um. */ setPolylineVertexType: (drawingId: string, index: number, type: PolylineVertexType) => void; @@ -1037,15 +1037,7 @@ export function createProjectSlice( applyGrip({ op: "insertPoint", id: drawingId, seg: segIndex, pt: gripPt(pt) }), setPolylineVertexType: (drawingId, index, type) => - applyChange((p) => - patchItem(p, "drawings2d", drawingId, (d) => { - if (d.geom.shape !== "polyline" || d.locked) return d; - const g = d.geom; - const bulge = withVertexType(g, index, type); - const { bulge: _old, ...rest } = g; - return { ...d, geom: bulge.some((b) => b !== 0) ? { ...rest, bulge } : rest }; - }), - ), + applyGrip({ op: "vertexType", id: drawingId, index, vertexType: type }), deleteDrawingPoint: (drawingId, index) => applyGrip({ op: "deletePoint", id: drawingId, index }), diff --git a/src/state/selectionInfo.ts b/src/state/selectionInfo.ts index ae4d4a51..f914b7a5 100644 --- a/src/state/selectionInfo.ts +++ b/src/state/selectionInfo.ts @@ -547,25 +547,8 @@ export function deriveSelection( columnId: selectedColumnId, roofId: selectedRoofId, contextObjectId: selectedContextObjectId, - // Lage in der Leseansicht (= Reihenfolge im Dokument): erspart dem Kern die lineare Suche. - at: {} as Record, }; - const P = project as unknown as Record; - const hint = (list: string, id: string | null | undefined) => { - if (!id) return; - const i = (P[list] ?? []).findIndex((x) => x.id === id); - if (i >= 0) args.at[list] = i; - }; - hint("context", selectedContextObjectId); - hint("drawings2d", selectedDrawingId); - hint("extrudedSolids", selectedExtrudedSolidId); - hint("columns", selectedColumnId); - hint("openings", selectedOpeningId); - hint("walls", selectedWallIds[0]); - hint("ceilings", selectedCeilingId); - hint("roofs", selectedRoofId); - hint("stairs", selectedStairId); - hint("rooms", selectedRoomId); + // Das Element sucht der Kern über den Positions-Index des Dokuments (keine lineare Suche). let sel: Selection | null; try { sel = documentFor(project).queryRootMarked("selectionInfo", JSON.stringify(args));