From b2e63822d440d6e445c1a3e66c9ab38c8b8715ff Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:39:23 +0000 Subject: [PATCH 1/5] [K3d] Render-Szene aus dem Plan-Puffer im Kern (Browser und natives Fenster) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit planToRenderScene/encodeRenderScene (TS) ersetzt durch core/src/plan_scene.rs: Füllungen, Umrisse, Polylinien, Bögen, Linien samt z, Verkettung, Kantennaht, Schraffur-Läufe, Zickzack/Motiv direkt aus den Abschnitten gehaltener Plan-Puffer (plan_parts.rs ↔ src/plan/planParts.ts: Kern-Abschnitte aus Plan.bufRuns ohne Umweg, Rest einmal kodiert; greyedRanges ohne Klonen). planSceneBin liefert render2d-Szene v1 (set_scene_bin, push_native_scene), planToRenderScene die verlustfreie Szene für Export/CLI-JSON. Text-Layout bleibt TS. renderSceneBin.ts gelöscht, Fixture-Test nach Rust. Bitgleich zur alten Fassung (Beispielprojekt alle Ebenen × Detailgrade × mono + Überlagerung, 400 Zufallslisten, grosses Projekt 20×20; JSON und Binärszene). Grosses Projekt 3125 → 133 ms. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src-tauri/core/src/lib.rs | 2 + src-tauri/core/src/plan_buf.rs | 37 +- src-tauri/core/src/plan_parts.rs | 111 ++++ src-tauri/core/src/plan_scene.rs | 886 ++++++++++++++++++++++++++ src-tauri/core/src/web/mod.rs | 1 + src-tauri/core/src/web/plan_buf.rs | 35 +- src-tauri/core/src/web/plan_scene.rs | 34 + src-tauri/render2d/src/scene_bin.rs | 4 +- src-tauri/render2d/src/web.rs | 4 +- src/core/extra.ts | 1 - src/core/index.ts | 1 + src/plan/planBuf.ts | 9 +- src/plan/planParts.ts | 152 +++++ src/plan/randomPrims.testing.ts | 177 +++++ src/plan/renderSceneBin.test.ts | 118 ---- src/plan/renderSceneBin.ts | 157 ----- src/plan/toRenderScene.test.ts | 70 ++ src/plan/toRenderScene.ts | 583 +++++------------ src/views/plan/nativeSync.ts | 12 +- src/views/plan/useWasmPlanRenderer.ts | 4 +- 20 files changed, 1664 insertions(+), 734 deletions(-) create mode 100644 src-tauri/core/src/plan_parts.rs create mode 100644 src-tauri/core/src/plan_scene.rs create mode 100644 src-tauri/core/src/web/plan_scene.rs create mode 100644 src/plan/planParts.ts create mode 100644 src/plan/randomPrims.testing.ts delete mode 100644 src/plan/renderSceneBin.test.ts delete mode 100644 src/plan/renderSceneBin.ts create mode 100644 src/plan/toRenderScene.test.ts diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 2b694b2b..604411fc 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -58,6 +58,8 @@ pub mod plan_section; pub mod voids; pub mod curves; pub mod skeleton; +pub mod plan_parts; +pub mod plan_scene; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/plan_buf.rs b/src-tauri/core/src/plan_buf.rs index 496b6567..07f9c785 100644 --- a/src-tauri/core/src/plan_buf.rs +++ b/src-tauri/core/src/plan_buf.rs @@ -212,7 +212,7 @@ impl PlanBuf { // ── Farben (früher `parseColor` in TS) ─────────────────────────────────────────────────────────── /// JS `parseInt(s, 16)` (Leerraum, Vorzeichen, `0x`, längster Ziffern-Präfix; NaN ohne Ziffer). -fn js_parse_hex(units: &[u16]) -> f64 { +pub(crate) fn js_parse_hex(units: &[u16]) -> f64 { let s = String::from_utf16_lossy(units); let t = s.trim_start_matches(crate::plan::overrides::js_space); let (neg, t) = match t.as_bytes().first() { @@ -391,7 +391,7 @@ impl<'a> Reader<'a> { } /// Nicht-negative ganze Zahl als Index/Anzahl. -fn whole(v: f64) -> Option { +pub(crate) fn whole(v: f64) -> Option { if !(v >= 0.0) || v.fract() != 0.0 || v > (u32::MAX as f64) { return None; } @@ -473,17 +473,17 @@ pub struct View<'a> { } /// Ein Primitiv-Eintrag, roh gelesen (Indizes noch nicht aufgelöst). -struct Rec { - tag: u32, - flags: u32, - pick: (u32, i32), +pub(crate) struct Rec { + pub(crate) tag: u32, + pub(crate) flags: u32, + pub(crate) pick: (u32, i32), /// Feste Felder nach dem Kopf (je Typ, s. Format). - f: Vec, - dash: Option<(usize, usize)>, - nse: Option<(usize, usize)>, - zigzag: Option<(f64, f64)>, - motif: Option<(f64, usize, usize)>, - ids: Option<(usize, usize)>, + pub(crate) f: Vec, + pub(crate) dash: Option<(usize, usize)>, + pub(crate) nse: Option<(usize, usize)>, + pub(crate) zigzag: Option<(f64, f64)>, + pub(crate) motif: Option<(f64, usize, usize)>, + pub(crate) ids: Option<(usize, usize)>, } fn fixed_len(tag: u32) -> Option { @@ -561,6 +561,11 @@ impl<'a> View<'a> { self.n_prims == 0 } + /// Anzahl Einträge der String-Tabelle. + pub(crate) fn n_strings(&self) -> usize { + self.n_strings + } + pub fn bounds(&self) -> Option<[f64; 4]> { self.bounds } @@ -609,7 +614,7 @@ impl<'a> View<'a> { Some(Some(self.string(whole(idx)?)?)) } - fn pool(&self, off: usize, n: usize) -> Option> { + pub(crate) fn pool(&self, off: usize, n: usize) -> Option> { if off.checked_add(n)? > self.n_pool { return None; } @@ -620,13 +625,13 @@ impl<'a> View<'a> { Some(out) } - fn pool_pts(&self, off: usize, n: usize) -> Option> { + pub(crate) fn pool_pts(&self, off: usize, n: usize) -> Option> { let l = self.pool(off, n.checked_mul(2)?)?; Some(l.chunks_exact(2).map(|c| V2 { x: c[0], y: c[1] }).collect()) } /// Hatch-Einträge: (JSON-String-Index, Hatch, Farb-String-Index). - fn hatch_table(&self) -> Option> { + pub(crate) fn hatch_table(&self) -> Option> { let mut r = Reader { w: self.w, pos: self.hatches_at, end: self.hatches_end }; let mut out = Vec::with_capacity(self.n_hatches); for _ in 0..self.n_hatches { @@ -643,7 +648,7 @@ impl<'a> View<'a> { Some(out) } - fn rec(&self, i: usize) -> Option { + pub(crate) fn rec(&self, i: usize) -> Option { if i >= self.n_prims { return None; } diff --git a/src-tauri/core/src/plan_parts.rs b/src-tauri/core/src/plan_parts.rs new file mode 100644 index 00000000..7d337ad7 --- /dev/null +++ b/src-tauri/core/src/plan_parts.rs @@ -0,0 +1,111 @@ +//! Zusammengesetzter Plan ([K3d]): ein Grundriss besteht aus Abschnitten mehrerer Plan-Puffer +//! (Kern-Puffer aus `planDomains` je Geschoss, dazu ein Puffer mit dem, was TS noch selbst +//! erzeugt: 2D-Zeichnungen, Schatten, Baurecht, zerlegte Polygone). Die Verbraucher im Kern +//! (Render-Szene `plan_scene`, Auswahl `plan_pick`, SVG-Export `plan_svg`) laufen über die +//! Abschnitte in Zeichenreihenfolge; der Index eines Primitivs im zusammengesetzten Plan ist +//! seine Stelle in `Plan.primitives` auf der TS-Seite. +//! +//! Eingabe der Bindungen: Abschnitte als Tripel `[Puffer-Nr, von, bis)` (Nummer = gehaltener +//! Puffer, s. `web/plan_buf.rs`), gedimmte Bereiche als Paare `[von, bis)` im zusammengesetzten +//! Index (wie `Plan.greyedRanges`: dort gilt `greyed = true`). + +use crate::plan_buf::{whole, Rec, View, F_GREYED, F_GREYED_SET, F_IDS}; + +/// Ein Abschnitt `[from, to)` eines Puffers. +pub struct Part<'a> { + pub view: View<'a>, + pub from: usize, + pub to: usize, + /// Gelesene Strings (Index → Text; `None` = noch nicht gelesen). + strs: Vec>, +} + +impl<'a> Part<'a> { + pub fn new(view: View<'a>, from: usize, to: usize) -> Option> { + if from > to || to > view.len() { + return None; + } + let n = view.n_strings(); + Some(Part { view, from, to, strs: vec![None; n] }) + } + + /// String `idx` (−1 = fehlt → `None`); kaputter Index → `None`. + pub fn str(&mut self, idx: f64) -> Option<&str> { + let i = whole(idx)?; + if i >= self.strs.len() { + return None; + } + if self.strs[i].is_none() { + self.strs[i] = Some(self.view.string(i)?); + } + self.strs[i].as_deref() + } +} + +/// Abschnitte aus `[nr, von, bis, …]` bilden; `buf(nr)` liefert die Bytes des Puffers. +pub fn parts_from<'a>(segs: &[f64], buf: impl Fn(u32) -> Option<&'a [u8]>) -> Option>> { + if segs.len() % 3 != 0 { + return None; + } + let mut out = Vec::with_capacity(segs.len() / 3); + for s in segs.chunks_exact(3) { + let nr = whole(s[0])? as u32; + let view = View::parse(buf(nr)?)?; + out.push(Part::new(view, whole(s[1])?, whole(s[2])?)?); + } + Some(out) +} + +/// Gedimmte Bereiche aus `[von, bis, …]` (sortiert, wie `Plan.greyedRanges`). +pub fn ranges_from(flat: &[f64]) -> Option> { + if flat.len() % 2 != 0 { + return None; + } + flat.chunks_exact(2).map(|c| Some((whole(c[0])?, whole(c[1])?))).collect() +} + +/// Liegt `i` in einem der Bereiche? +pub fn in_ranges(ranges: &[(usize, usize)], i: usize) -> bool { + ranges.iter().any(|&(a, b)| i >= a && i < b) +} + +/// `greyed` eines Eintrags: `Some(true/false)` gesetzt, `None` fehlt; in einem gedimmten Bereich +/// immer `Some(true)` (wie `greyedClone` in `generatePlan.ts`). +pub(crate) fn greyed_of(rec: &Rec, forced: bool) -> Option { + if forced { + return Some(true); + } + (rec.flags & F_GREYED_SET != 0).then_some(rec.flags & F_GREYED != 0) +} + +/// Alle Pick-Ids eines Eintrags als (Art 1…11, String-Index), erste aus dem Kopf. +pub(crate) fn pick_ids(view: &View, rec: &Rec) -> Option> { + let mut out = Vec::new(); + if rec.pick.0 > 0 { + out.push((rec.pick.0, rec.pick.1 as f64)); + } + if rec.flags & F_IDS != 0 { + if let Some((o, n)) = rec.ids { + let l = view.pool(o, n.checked_mul(2)?)?; + for c in l.chunks_exact(2) { + let k = whole(c[0])? as u32; + if k == 0 || k > 11 { + return None; + } + out.push((k, c[1])); + } + } + } + Some(out) +} + +/// String-Index der Pick-Id der Art `kind` (1 wall · 2 drawing · …) oder `None`. +pub(crate) fn pick_id(view: &View, rec: &Rec, kind: u32) -> Option { + if rec.pick.0 == kind { + return Some(rec.pick.1 as f64); + } + if rec.flags & F_IDS == 0 { + return None; + } + pick_ids(view, rec)?.into_iter().find(|e| e.0 == kind).map(|e| e.1) +} diff --git a/src-tauri/core/src/plan_scene.rs b/src-tauri/core/src/plan_scene.rs new file mode 100644 index 00000000..fdd57e7e --- /dev/null +++ b/src-tauri/core/src/plan_scene.rs @@ -0,0 +1,886 @@ +//! Render-Szene aus dem Plan-Puffer ([K3d], früher `planToRenderScene` in +//! `src/plan/toRenderScene.ts`): Füllungen, Umrisse, Polylinien, Bögen und Linien für render2d, +//! direkt aus den Abschnitten eines zusammengesetzten Plans ([`crate::plan_parts`]) — ohne Umweg +//! über `Primitive[]`. Texte setzt TS (Text-Layout bleibt dort) und gibt sie fertig mit. +//! +//! Bitgleich zur TS-Fassung: Farben wie `toRgba`, CSS-Klassen-Farben/-Deckkraft, Dimmen, +//! Maler-Reihenfolge `z`, Verkettung der 2D-Zeichenlinien, Kantenläufe mit Naht über +//! Polygon-Grenzen hinweg, Schraffur-Läufe, Zickzack/Motiv, Kreis-Tessellierung. +//! +//! Zwei Ausgaben: [`encode_scene_bin`] (render2d-Szene v1, s. `render2d/src/scene_bin.rs`) und +//! [`encode_scene_f64`] (verlustfrei für den Druck-/SVG-Export und `--format json`): +//! ```text +//! [nFills, nOutlines, nPolylines, nArcs, nLines] +//! Füllung n, z, r, g, b, a, x, y … +//! Umriss n, z, widthMm, dash, r, g, b, a, x, y … +//! Polylinie n, z, widthMm, dash, r, g, b, a, x, y … +//! Bogen r, widthMm, dash, r, g, b, a, cx, cy, fx, fy, tx, ty +//! Linie z, widthMm, dash, r, g, b, a, ax, ay, bx, by +//! dash = −2 (Feld fehlt) · −1 (null) · k ≥ 0 (k Werte folgen) +//! ``` + +use crate::hatch::{self, v2, HatchKind, Motif, Pattern, V2, DASH_MM_TO_M}; +use crate::jsnum; +use crate::plan::overrides::js_trim; +use crate::plan_buf::{js_parse_hex, whole, Rec, F_COLOR, F_DASH_LIST, F_DASH_NULL, F_MOTIF, F_NSE, F_ZIGZAG}; +use crate::plan_buf::{T_ARC, T_CIRCLE, T_DRAWING_ARC, T_DRAWING_TEXT, T_IMAGE, T_LINE, T_POLYGON, T_TEXT}; +use crate::plan_parts::{greyed_of, in_ranges, pick_id, Part}; +use std::collections::HashMap; +use std::f64::consts::PI; + +pub type Rgba = [f64; 4]; + +/// Strichmuster eines Szenen-Elements. +#[derive(Clone, Debug, PartialEq)] +pub enum SDash { + /// Feld fehlt (Umrisse, Schraffur-Läufe, Zickzack/Motiv, Nähte). + Absent, + Null, + List(Vec), +} + +impl SDash { + fn list(&self) -> &[f64] { + match self { + SDash::List(l) => l, + _ => &[], + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct SFill { + pub pts: Vec, + pub color: Rgba, + pub z: f64, +} + +/// Umriss (geschlossen) oder Polylinie (offen). +#[derive(Clone, Debug, PartialEq)] +pub struct SStroke { + pub pts: Vec, + pub color: Rgba, + pub width_mm: f64, + pub dash: SDash, + pub z: f64, + /// `widthMm` in Bildschirm-Einheiten (render2d-Flag; heute von keinem Primitiv gesetzt). + pub width_screen: bool, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct SArc { + pub center: V2, + pub from: V2, + pub to: V2, + pub r: f64, + pub color: Rgba, + pub width_mm: f64, + pub dash: SDash, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct SLine { + pub a: V2, + pub b: V2, + pub color: Rgba, + pub width_mm: f64, + pub dash: SDash, + pub z: f64, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Scene { + pub fills: Vec, + pub outlines: Vec, + pub polylines: Vec, + pub arcs: Vec, + pub lines: Vec, +} + +// ── Farben (wie `toRgba`/`withOpacity` der TS-Fassung) ────────────────────────────────────────── + +const DEFAULT_LINE: &str = "#1a1a1a"; +const INK: Rgba = [0.1, 0.1, 0.1, 1.0]; +/// Fester Grauton gedimmter Primitive (wie `GREY_RGB` in `gpu_compile.rs`). +const GREY_RGB: f64 = 0.549; + +/// CSS-Strichfarbe je Linienklasse (Spiegel der `.plan-svg .`-Regeln in styles.css). +fn cls_stroke(cls: Option<&str>) -> Option<&'static str> { + match cls? { + "door-leaf" | "door-swing" | "door-frame" | "window-glass" => Some("#1a1a1a"), + "wall-axis" => Some("#4a453e"), + _ => None, + } +} + +fn cls_opacity(cls: Option<&str>) -> f64 { + match cls { + Some("wall-axis") => 0.85, + Some("context-line") => 0.7, + _ => 1.0, + } +} + +/// Hex-/Namens-Farbe → RGBA (0…1) oder `None` bei "none"/leer — wie `toRgba(input, 1)`. +pub fn to_rgba(input: Option<&str>) -> Option { + let input = input?; + if input.is_empty() { + return None; + } + let alpha = 1.0; + let mut h: String = js_trim(input).to_lowercase(); + if h == "none" || h == "transparent" { + return None; + } + if !h.starts_with('#') { + h = match h.as_str() { + "black" => "#000000".into(), + "white" => "#ffffff".into(), + "red" => "#ff0000".into(), + _ => return Some([0.0, 0.0, 0.0, alpha]), + }; + } + let mut u: Vec = h.encode_utf16().skip(1).collect(); + if u.len() == 3 || u.len() == 4 { + u = u.iter().flat_map(|&c| [c, c]).collect(); + } + if u.len() != 6 && u.len() != 8 { + return Some([0.0, 0.0, 0.0, alpha]); + } + let r = js_parse_hex(&u[0..2]) / 255.0; + let g = js_parse_hex(&u[2..4]) / 255.0; + let b = js_parse_hex(&u[4..6]) / 255.0; + let a = if u.len() == 8 { js_parse_hex(&u[6..8]) / 255.0 } else { alpha }; + if ![r, g, b, a].iter().all(|v| v.is_finite()) { + return Some([0.0, 0.0, 0.0, alpha]); + } + Some([r, g, b, a]) +} + +fn with_opacity(col: Rgba, cls: Option<&str>, greyed: bool) -> Rgba { + let o = cls_opacity(cls); + let rgb = if greyed { [GREY_RGB, GREY_RGB, GREY_RGB, col[3]] } else { col }; + if o == 1.0 { + rgb + } else { + [rgb[0], rgb[1], rgb[2], rgb[3] * o] + } +} + +fn with_fill_opacity(col: Rgba, greyed: bool) -> Rgba { + if greyed { + [1.0, 1.0, 1.0, col[3]] + } else { + col + } +} + +/// Strichfarbe einer line/arc: CSS-Klassen-Farbe > Modell-Farbe > Tinte. +fn stroke_color_for(cls: Option<&str>, color: Option<&str>) -> Rgba { + to_rgba(Some(cls_stroke(cls).or(color).unwrap_or(DEFAULT_LINE))).unwrap_or(INK) +} + +// ── Schlüssel wie JS-Strings von Zahlen ───────────────────────────────────────────────────────── + +/// Zahl als Schlüssel mit der Gleichheit von `String(x)`: −0 = 0, alle NaN gleich. +#[inline] +fn num_key(x: f64) -> u64 { + if x.is_nan() { + 0x7ff8_0000_0000_0000 + } else if x == 0.0 { + 0 + } else { + x.to_bits() + } +} + +/// Gleichheit wie `JSON.stringify(a ?? null) === JSON.stringify(b ?? null)` für Strichmuster. +fn same_dash_json(a: &SDash, b: &SDash) -> bool { + match (a, b) { + (SDash::List(x), SDash::List(y)) => { + x.len() == y.len() && x.iter().zip(y).all(|(p, q)| (!p.is_finite() && !q.is_finite()) || p == q) + } + (SDash::List(_), _) | (_, SDash::List(_)) => false, + _ => true, + } +} + +#[inline] +fn same_pt(a: V2, b: V2) -> bool { + (a.x - b.x).abs() < 1e-6 && (a.y - b.y).abs() < 1e-6 +} + +// ── Kantenläufe (wie `visibleEdgeRuns`/`stitchRuns`) ──────────────────────────────────────────── + +/// Sichtbare Kantenläufe eines Rings (die Kanten aus `no_stroke` fehlen). +pub fn visible_edge_runs(pts: &[V2], no_stroke: &[f64]) -> Vec> { + let n = pts.len(); + let nf = n as f64; + let mut skip: Vec = no_stroke.iter().map(|&i| num_key(((i % nf) + nf) % nf)).collect(); + skip.sort_unstable(); + skip.dedup(); + if skip.len() >= n || n < 2 { + return Vec::new(); + } + let visible = |i: isize| -> bool { + let k = ((i as f64 % nf) + nf) % nf; + skip.binary_search(&num_key(k)).is_err() + }; + let mut runs = Vec::new(); + for s in 0..n as isize { + if !visible(s) || visible(s - 1 + n as isize) { + continue; + } + let mut run = vec![pts[s as usize]]; + let mut j = s; + while visible(j) && ((j - s) as usize) < n { + run.push(pts[((j + 1) as usize) % n]); + j += 1; + } + runs.push(run); + } + runs +} + +const STITCH_EPS: f64 = 1e-5; + +#[inline] +fn cell_of(p: V2) -> (f64, f64) { + (jsnum::round(p.x / STITCH_EPS), jsnum::round(p.y / STITCH_EPS)) +} + +#[inline] +fn stitch_key(p: V2) -> (u64, u64) { + let (x, y) = cell_of(p); + (num_key(x), num_key(y)) +} + +/// Näht Kantenläufe über Polygon-Grenzen hinweg zusammen (genau zwei Enden je Stelle). +/// Ergebnis: (Punkte, geschlossen). Gleiche Wahl wie die lineare Suche der TS-Fassung (der +/// erste passende Lauf in Pool-Reihenfolge); ein Raster über den Endpunkten findet die Kandidaten. +pub fn stitch_runs(runs: Vec>) -> Vec<(Vec, bool)> { + let mut end_count: HashMap<(u64, u64), u32> = HashMap::new(); + for r in &runs { + for p in [r[0], r[r.len() - 1]] { + *end_count.entry(stitch_key(p)).or_insert(0) += 1; + } + } + let joinable = |p: V2| end_count.get(&stitch_key(p)) == Some(&2); + // Raster: Zelle (gerundet) → Läufe mit einem Ende darin. `same_pt` (< 1e-6) liegt höchstens + // eine Zelle daneben. + let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); + let cell_int = |p: V2| -> Option<(i64, i64)> { + let (x, y) = cell_of(p); + (x.is_finite() && y.is_finite() && x.abs() < 9e15 && y.abs() < 9e15).then_some((x as i64, y as i64)) + }; + // Enden ausserhalb des Rasters (NaN/riesig) — immer prüfen. + let mut wild: Vec = Vec::new(); + for (i, r) in runs.iter().enumerate() { + for p in [r[0], r[r.len() - 1]] { + match cell_int(p) { + Some(c) => grid.entry(c).or_default().push(i), + None => wild.push(i), + } + } + } + let mut used = vec![false; runs.len()]; + let mut out = Vec::new(); + let mut cand: Vec = Vec::new(); + for seed in 0..runs.len() { + if used[seed] { + continue; + } + used[seed] = true; + let mut chain = runs[seed].clone(); + let mut extended = true; + while extended && !(chain.len() > 2 && same_pt(chain[0], chain[chain.len() - 1])) { + extended = false; + let head = chain[0]; + let tail = chain[chain.len() - 1]; + cand.clear(); + for p in [tail, head] { + if let Some((cx, cy)) = cell_int(p) { + for dx in -1..=1 { + for dy in -1..=1 { + if let Some(l) = grid.get(&(cx + dx, cy + dy)) { + cand.extend(l.iter().copied().filter(|&i| !used[i])); + } + } + } + } else { + // Kein Raster-Platz: alle Läufe prüfen (wie die lineare Suche). + cand.extend((0..runs.len()).filter(|&i| !used[i])); + } + } + cand.extend(wild.iter().copied().filter(|&i| !used[i])); + cand.sort_unstable(); + cand.dedup(); + let jt = joinable(tail); + let jh = joinable(head); + for &ci in &cand { + let c = &runs[ci]; + let cs = c[0]; + let ce = c[c.len() - 1]; + if jt && same_pt(tail, cs) { + chain.extend_from_slice(&c[1..]); + } else if jt && same_pt(tail, ce) { + chain.extend(c.iter().rev().skip(1).copied()); + } else if jh && same_pt(head, ce) { + let mut n = c.clone(); + n.extend_from_slice(&chain[1..]); + chain = n; + } else if jh && same_pt(head, cs) { + let mut n: Vec = c.iter().rev().copied().collect(); + n.extend_from_slice(&chain[1..]); + chain = n; + } else { + continue; + } + used[ci] = true; + extended = true; + break; + } + } + let closed = chain.len() > 3 && same_pt(chain[0], chain[chain.len() - 1]); + if closed { + chain.pop(); + } + out.push((chain, closed)); + } + out +} + +// ── Szene ──────────────────────────────────────────────────────────────────────────────────────── + +/// Quelle eines laufenden, verketteten 2D-Zeichnungs-Zugs. +struct RunSrc { + cls: Option, + color: Option, + weight: f64, + dash: SDash, + greyed: bool, +} + +struct EdgeGroup { + color: Rgba, + width_mm: f64, + runs: Vec>, + z: f64, +} + +struct Builder { + s: Scene, + zc: f64, + cur: Option<(Vec, RunSrc)>, + groups: Vec, + group_of: HashMap<[u64; 5], usize>, +} + +impl Builder { + fn z(&mut self) -> f64 { + let z = self.zc; + self.zc += 1.0; + z + } + + fn flush(&mut self) { + if let Some((pts, src)) = self.cur.take() { + if pts.len() >= 2 { + let col = with_opacity(stroke_color_for(src.cls.as_deref(), src.color.as_deref()), src.cls.as_deref(), src.greyed); + let closed = pts.len() > 2 && same_pt(pts[0], pts[pts.len() - 1]); + let dash = match src.dash { + SDash::Absent => SDash::Null, + d => d, + }; + let z = self.z(); + if closed { + let mut p = pts; + p.pop(); + self.s.outlines.push(SStroke { pts: p, color: col, width_mm: src.weight, dash, z, width_screen: false }); + } else { + self.s.polylines.push(SStroke { pts, color: col, width_mm: src.weight, dash, z, width_screen: false }); + } + } + } + } + + fn edge_run(&mut self, run: Vec, color: Rgba, width_mm: f64, z: f64) { + let k = [num_key(color[0]), num_key(color[1]), num_key(color[2]), num_key(color[3]), num_key(width_mm)]; + let gi = match self.group_of.get(&k) { + Some(&g) => g, + None => { + self.groups.push(EdgeGroup { color, width_mm, runs: Vec::new(), z }); + self.group_of.insert(k, self.groups.len() - 1); + self.groups.len() - 1 + } + }; + let g = &mut self.groups[gi]; + g.runs.push(run); + g.z = jsnum::max(g.z, z); + } +} + +/// Strichmuster eines Eintrags (`dash ?? null`). +fn dash_of(part: &Part, rec: &Rec) -> Option { + if rec.flags & F_DASH_NULL != 0 { + Some(SDash::Null) + } else if rec.flags & F_DASH_LIST != 0 { + let (o, n) = rec.dash?; + Some(SDash::List(part.view.pool(o, n)?)) + } else { + Some(SDash::Null) + } +} + +/// Render-Szene aus den Abschnitten; `None` bei kaputtem Puffer. +pub fn build_scene(parts: &mut [Part], greyed_ranges: &[(usize, usize)]) -> Option { + let mut b = Builder { s: Scene::default(), zc: 0.0, cur: None, groups: Vec::new(), group_of: HashMap::new() }; + let mut gi = 0usize; // Index im zusammengesetzten Plan + for part in parts.iter_mut() { + // Farben dieses Puffers (String-Index → RGBA), einmal je String. + let mut colors: HashMap> = HashMap::new(); + let mut hatches: Option> = None; + for i in part.from..part.to { + let forced = !greyed_ranges.is_empty() && in_ranges(greyed_ranges, gi); + gi += 1; + let rec = part.view.rec(i)?; + let greyed = greyed_of(&rec, forced) == Some(true); + let f = rec.f.clone(); + let mut color = |part: &mut Part, idx: f64| -> Option { + if idx < 0.0 { + return None; + } + let k = idx as i64; + if let Some(c) = colors.get(&k) { + return *c; + } + let c = to_rgba(part.str(idx)); + colors.insert(k, c); + c + }; + match rec.tag { + T_POLYGON => { + b.flush(); + let pts = part.view.pool_pts(whole(f[5])?, whole(f[6])?)?; + if pts.len() < 2 { + continue; + } + if let Some(fc) = color(part, f[0]) { + if pts.len() >= 3 { + let z = b.z(); + b.s.fills.push(SFill { pts: pts.clone(), color: with_fill_opacity(fc, greyed), z }); + } + } + if f[3] != -1.0 { + if hatches.is_none() { + hatches = Some(part.view.hatch_table()?); + } + let (_, h, hc) = hatches.as_ref()?.get(whole(f[3])?)?.clone(); + if h.kind != HatchKind::Image && h.kind != HatchKind::Gradient && h.pattern != Pattern::None && h.pattern != Pattern::Solid { + let hatch_col = with_opacity(color(part, hc as f64).unwrap_or(INK), None, greyed); + let hatch_mm = if h.line_weight > 0.0 { h.line_weight } else { 0.13 }; + let runs = if pts.len() < 3 { Vec::new() } else { hatch::build_hatch_runs(&pts, &h) }; + let runs = hatch::apply_dash_runs(runs, &h.dash); + let hz = b.z(); + for run in runs { + if run.len() >= 2 { + b.s.polylines.push(SStroke { pts: run, color: hatch_col, width_mm: hatch_mm, dash: SDash::Absent, z: hz, width_screen: false }); + } + } + } + } + if let Some(raw) = color(part, f[1]) { + let w = f[2]; + if w > 0.0 { + let sc = with_opacity(raw, None, greyed); + let nse = match (rec.flags & F_NSE != 0, rec.nse) { + (true, Some((o, n))) => part.view.pool(o, n)?, + _ => Vec::new(), + }; + if nse.is_empty() { + let z = b.z(); + b.s.outlines.push(SStroke { pts, color: sc, width_mm: w, dash: SDash::Absent, z, width_screen: false }); + } else { + let rz = b.z(); + for run in visible_edge_runs(&pts, &nse) { + b.edge_run(run, sc, w, rz); + } + } + } + } + } + T_LINE => { + let cls = part.str(f[0]).map(str::to_owned); + let col_s = if rec.flags & F_COLOR != 0 { part.str(f[1]).map(str::to_owned) } else { None }; + let a = v2(f[4], f[5]); + let bb = v2(f[6], f[7]); + let w = f[2]; + if rec.flags & F_ZIGZAG != 0 { + b.flush(); + let (amp, wav) = rec.zigzag?; + let zp = hatch::zigzag_points(a, bb, amp * DASH_MM_TO_M, wav * DASH_MM_TO_M).unwrap_or_else(|| vec![a, bb]); + let col = with_opacity(stroke_color_for(cls.as_deref(), col_s.as_deref()), cls.as_deref(), greyed); + if zp.len() >= 2 { + let z = b.z(); + b.s.polylines.push(SStroke { pts: zp, color: col, width_mm: w, dash: SDash::Absent, z, width_screen: false }); + } + } else if rec.flags & F_MOTIF != 0 { + b.flush(); + let (length, o, n) = rec.motif?; + let m = Motif { length, points: part.view.pool_pts(o, n)? }; + let mp = hatch::motif_points(a, bb, &m, DASH_MM_TO_M); + let col = with_opacity(stroke_color_for(cls.as_deref(), col_s.as_deref()), cls.as_deref(), greyed); + if mp.len() >= 2 { + let z = b.z(); + b.s.polylines.push(SStroke { pts: mp, color: col, width_mm: w, dash: SDash::Absent, z, width_screen: false }); + } + } else { + let dash = dash_of(part, &rec)?; + let drawing = match pick_id(&part.view, &rec, 2) { + Some(s) => part.str(s).is_some_and(|s| !s.is_empty()), + None => false, + }; + if drawing { + let src = RunSrc { cls, color: col_s, weight: w, dash, greyed }; + let cont = match &b.cur { + Some((pts, c)) => { + c.cls == src.cls + && c.weight == src.weight + && c.color.as_deref().unwrap_or("") == src.color.as_deref().unwrap_or("") + && same_dash_json(&c.dash, &src.dash) + && same_pt(pts[pts.len() - 1], a) + } + None => false, + }; + if cont { + b.cur.as_mut()?.0.push(bb); + } else { + b.flush(); + b.cur = Some((vec![a, bb], src)); + } + } else { + b.flush(); + let col = with_opacity(stroke_color_for(cls.as_deref(), col_s.as_deref()), cls.as_deref(), greyed); + let z = b.z(); + b.s.lines.push(SLine { a, b: bb, color: col, width_mm: w, dash, z }); + } + } + } + T_ARC => { + b.flush(); + let cls = part.str(f[0]).map(str::to_owned); + let col = with_opacity(stroke_color_for(cls.as_deref(), None), cls.as_deref(), greyed); + let dash = dash_of(part, &rec)?; + b.s.arcs.push(SArc { center: v2(f[4], f[5]), from: v2(f[6], f[7]), to: v2(f[8], f[9]), r: f[10], color: col, width_mm: f[2], dash }); + } + T_CIRCLE | T_DRAWING_ARC => { + b.flush(); + let circle = rec.tag == T_CIRCLE; + let stroke = if circle { f[1] } else { f[0] }; + let col = with_opacity(color(part, stroke).unwrap_or(INK), None, greyed); + let (w, c, r) = if circle { (f[2], v2(f[4], f[5]), f[6]) } else { (f[1], v2(f[3], f[4]), f[5]) }; + let tau = PI * 2.0; + let a0 = if circle { 0.0 } else { f[6] }; + let sweep = if circle { tau } else { (((f[7] - f[6]) % tau) + tau) % tau }; + let n = jsnum::max(8.0, (sweep / (PI / 32.0)).ceil()); + let mut pts = Vec::new(); + let mut k = 0.0f64; + while k <= n { + let t = a0 + (sweep * k) / n; + pts.push(v2(c.x + r * jsnum::cos(t), c.y + r * jsnum::sin(t))); + k += 1.0; + } + let dash = dash_of(part, &rec)?; + let z = b.z(); + b.s.polylines.push(SStroke { pts, color: col, width_mm: w, dash, z, width_screen: false }); + } + // Text, Einzeltext, Bild: Zeilen setzt TS; hier nur den Linienzug abschliessen + // (Textpfad und Platzhalter berühren ihn nicht, wie in der TS-Fassung). + T_TEXT | T_DRAWING_TEXT | T_IMAGE => b.flush(), + _ => {} + } + } + } + b.flush(); + let groups = std::mem::take(&mut b.groups); + for g in groups { + for (pts, closed) in stitch_runs(g.runs) { + if pts.len() < 2 { + continue; + } + let s = SStroke { pts, color: g.color, width_mm: g.width_mm, dash: SDash::Absent, z: g.z, width_screen: false }; + if closed { + b.s.outlines.push(s); + } else { + b.s.polylines.push(s); + } + } + } + Some(b.s) +} + +// ── Ausgaben ───────────────────────────────────────────────────────────────────────────────────── + +/// Eine Textzeile (von TS gesetzt) für die render2d-Szene. +pub struct SText { + pub pos: V2, + pub size_mm: f64, + pub color: Rgba, + /// 0 links · 1 Mitte · 2 rechts + pub align: u32, + pub content: Vec, +} + +/// Texte aus `[x, y, sizeMm, r, g, b, a, align, nBytes]*` und den UTF-8-Bytes; `None` bei Unsinn. +pub fn texts_from(nums: &[f64], bytes: &[u8]) -> Option> { + if nums.len() % 9 != 0 { + return None; + } + let mut out = Vec::with_capacity(nums.len() / 9); + let mut o = 0usize; + for t in nums.chunks_exact(9) { + let n = whole(t[8])?; + let content = bytes.get(o..o.checked_add(n)?)?.to_vec(); + o += n; + out.push(SText { pos: v2(t[0], t[1]), size_mm: t[2], color: [t[3], t[4], t[5], t[6]], align: whole(t[7])? as u32, content }); + } + (o == bytes.len()).then_some(out) +} + +/// `z >>> 0` (ToUint32). +fn u32_of(z: f64) -> u32 { + jsnum::to_int32(z) as u32 +} + +/// render2d-Szene v1 (Format s. `render2d/src/scene_bin.rs`), gleiche Bytes wie die frühere +/// TS-Kodierung `encodeRenderScene`. +pub fn encode_scene_bin(s: &Scene, texts: &[SText]) -> Vec { + let mut n_pts = 0usize; + let mut n_dash = 0usize; + for f in &s.fills { + n_pts += f.pts.len(); + } + for o in s.outlines.iter().chain(&s.polylines) { + n_pts += o.pts.len(); + n_dash += o.dash.list().len(); + } + for a in &s.arcs { + n_dash += a.dash.list().len(); + } + for l in &s.lines { + n_dash += l.dash.list().len(); + } + n_pts += s.arcs.len() * 3 + s.lines.len() * 2 + texts.len(); + let str_bytes: usize = texts.iter().map(|t| t.content.len()).sum(); + let words = s.fills.len() * 6 + s.outlines.len() * 8 + s.polylines.len() * 9 + s.arcs.len() * 7 + s.lines.len() * 7 + texts.len() * 8; + let total = 48 + n_pts * 16 + n_dash * 4 + words * 4 + str_bytes; + let mut pts: Vec = Vec::with_capacity(n_pts * 16); + let mut dash: Vec = Vec::with_capacity(n_dash * 4); + let mut rec: Vec = Vec::with_capacity(words * 4); + let mut strs: Vec = Vec::with_capacity(str_bytes); + let pt = |pts: &mut Vec, p: V2| { + pts.extend_from_slice(&p.x.to_le_bytes()); + pts.extend_from_slice(&p.y.to_le_bytes()); + }; + let u = |rec: &mut Vec, v: u32| rec.extend_from_slice(&v.to_le_bytes()); + let f = |rec: &mut Vec, v: f64| rec.extend_from_slice(&(v as f32).to_le_bytes()); + let col = |rec: &mut Vec, c: &Rgba| { + for &v in c { + rec.extend_from_slice(&(v as f32).to_le_bytes()); + } + }; + let dashes = |dash: &mut Vec, d: &SDash| -> u32 { + let l = d.list(); + for &v in l { + dash.extend_from_slice(&(v as f32).to_le_bytes()); + } + l.len() as u32 + }; + for x in &s.fills { + u(&mut rec, x.pts.len() as u32); + u(&mut rec, u32_of(x.z)); + col(&mut rec, &x.color); + for &p in &x.pts { + pt(&mut pts, p); + } + } + for x in &s.outlines { + u(&mut rec, x.pts.len() as u32); + u(&mut rec, u32_of(x.z)); + f(&mut rec, x.width_mm); + let n = dashes(&mut dash, &x.dash); + u(&mut rec, n); + col(&mut rec, &x.color); + for &p in &x.pts { + pt(&mut pts, p); + } + } + for x in &s.polylines { + u(&mut rec, x.pts.len() as u32); + u(&mut rec, u32_of(x.z)); + f(&mut rec, x.width_mm); + let n = dashes(&mut dash, &x.dash); + u(&mut rec, n); + u(&mut rec, x.width_screen as u32); + col(&mut rec, &x.color); + for &p in &x.pts { + pt(&mut pts, p); + } + } + for a in &s.arcs { + f(&mut rec, a.r); + f(&mut rec, a.width_mm); + let n = dashes(&mut dash, &a.dash); + u(&mut rec, n); + col(&mut rec, &a.color); + pt(&mut pts, a.center); + pt(&mut pts, a.from); + pt(&mut pts, a.to); + } + for l in &s.lines { + f(&mut rec, l.width_mm); + let n = dashes(&mut dash, &l.dash); + u(&mut rec, n); + u(&mut rec, u32_of(l.z)); + col(&mut rec, &l.color); + pt(&mut pts, l.a); + pt(&mut pts, l.b); + } + for t in texts { + f(&mut rec, t.size_mm); + u(&mut rec, t.align); + u(&mut rec, strs.len() as u32); + u(&mut rec, t.content.len() as u32); + col(&mut rec, &t.color); + pt(&mut pts, t.pos); + strs.extend_from_slice(&t.content); + } + let mut out = Vec::with_capacity(total); + out.extend_from_slice(b"DR2S"); + for v in [1u32, s.fills.len() as u32, s.outlines.len() as u32, s.polylines.len() as u32, s.arcs.len() as u32, s.lines.len() as u32, texts.len() as u32, n_pts as u32, n_dash as u32, str_bytes as u32, 0] { + out.extend_from_slice(&v.to_le_bytes()); + } + out.extend_from_slice(&pts); + out.extend_from_slice(&dash); + out.extend_from_slice(&rec); + out.extend_from_slice(&strs); + out +} + +fn push_dash(out: &mut Vec, d: &SDash) { + match d { + SDash::Absent => out.push(-2.0), + SDash::Null => out.push(-1.0), + SDash::List(l) => { + out.push(l.len() as f64); + out.extend_from_slice(l); + } + } +} + +/// Verlustfreie Ausgabe (Format s. Dateikopf). +pub fn encode_scene_f64(s: &Scene) -> Vec { + let mut out = vec![s.fills.len() as f64, s.outlines.len() as f64, s.polylines.len() as f64, s.arcs.len() as f64, s.lines.len() as f64]; + for x in &s.fills { + out.extend_from_slice(&[x.pts.len() as f64, x.z]); + out.extend_from_slice(&x.color); + for p in &x.pts { + out.extend_from_slice(&[p.x, p.y]); + } + } + for x in s.outlines.iter().chain(&s.polylines) { + out.extend_from_slice(&[x.pts.len() as f64, x.z, x.width_mm]); + push_dash(&mut out, &x.dash); + out.extend_from_slice(&x.color); + for p in &x.pts { + out.extend_from_slice(&[p.x, p.y]); + } + } + for a in &s.arcs { + out.extend_from_slice(&[a.r, a.width_mm]); + push_dash(&mut out, &a.dash); + out.extend_from_slice(&a.color); + out.extend_from_slice(&[a.center.x, a.center.y, a.from.x, a.from.y, a.to.x, a.to.y]); + } + for l in &s.lines { + out.extend_from_slice(&[l.z, l.width_mm]); + push_dash(&mut out, &l.dash); + out.extend_from_slice(&l.color); + out.extend_from_slice(&[l.a.x, l.a.y, l.b.x, l.b.y]); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn farben_wie_to_rgba() { + assert_eq!(to_rgba(Some("#fff")), Some([1.0, 1.0, 1.0, 1.0])); + assert_eq!(to_rgba(Some(" Black ")), Some([0.0, 0.0, 0.0, 1.0])); + assert_eq!(to_rgba(Some("none")), None); + assert_eq!(to_rgba(Some("")), None); + assert_eq!(to_rgba(None), None); + assert_eq!(to_rgba(Some("rgb(1,2,3)")), Some([0.0, 0.0, 0.0, 1.0])); + assert_eq!(to_rgba(Some("#12345")), Some([0.0, 0.0, 0.0, 1.0])); + assert_eq!(to_rgba(Some("#zz0000")), Some([0.0, 0.0, 0.0, 1.0])); + let c = to_rgba(Some("#ff000080")).unwrap(); + assert_eq!(c[3], 128.0 / 255.0); + } + + /// Beispielszene; MUSS mit `sample()` in `render2d/src/scene_bin.rs` übereinstimmen + /// (gemeinsame Bytes: `render2d/tests/fixtures/scene_v1.bin`). + fn sample() -> (Scene, Vec) { + let st = |pts: Vec, color: Rgba, width_mm: f64, dash: SDash, z: f64, width_screen: bool| SStroke { pts, color, width_mm, dash, z, width_screen }; + let s = Scene { + fills: vec![ + SFill { pts: vec![v2(0.0, 0.0), v2(4.0, 0.0), v2(4.0, 3.0)], color: [0.5, 0.25, 0.75, 1.0], z: 0.0 }, + SFill { pts: vec![v2(1.5, 1.5), v2(2.5, 1.5), v2(2.5, 2.5), v2(1.5, 2.5)], color: [1.0, 1.0, 1.0, 0.5], z: 7.0 }, + ], + outlines: vec![st(vec![v2(0.0, 0.0), v2(4.0, 0.0), v2(4.0, 3.0)], [0.0, 0.0, 0.0, 1.0], 0.25, SDash::List(vec![2.0, 1.0]), 1.0, false)], + polylines: vec![ + st(vec![v2(0.0, 0.0), v2(1.0, 1.0)], [0.25, 0.25, 0.25, 1.0], 0.5, SDash::Null, 2.0, false), + st(vec![v2(5.0, 5.0), v2(6.0, 5.0), v2(6.0, 6.0)], [0.5, 0.5, 0.5, 1.0], 1.0, SDash::List(vec![1.0]), 3.0, true), + ], + arcs: vec![SArc { center: v2(1.0, 1.0), from: v2(2.0, 1.0), to: v2(1.0, 2.0), r: 1.0, color: [1.0, 0.0, 0.0, 1.0], width_mm: 0.125, dash: SDash::Absent }], + lines: vec![SLine { a: v2(0.0, 0.0), b: v2(2600000.5, 1200000.25), color: [0.0, 0.5, 0.0, 1.0], width_mm: 0.35, dash: SDash::List(vec![3.0, 1.0, 0.5, 1.0]), z: 4.0 }], + }; + let t = |x: f64, y: f64, content: &str, size_mm: f64, color: Rgba, align: u32| SText { pos: v2(x, y), size_mm, color, align, content: content.as_bytes().to_vec() }; + let texts = vec![ + t(1.0, 2.0, "Küche 12,5 m²", 2.5, [0.0, 0.0, 0.0, 1.0], 1), + t(3.0, 4.0, "", 2.0, [0.0, 0.0, 0.0, 1.0], 2), + t(5.0, 6.0, "A", 1.0, [0.0, 0.0, 1.0, 1.0], 0), + ]; + (s, texts) + } + + #[test] + fn szene_bin_wie_fixture() { + const FIXTURE: &[u8] = include_bytes!("../../render2d/tests/fixtures/scene_v1.bin"); + let (s, t) = sample(); + assert_eq!(encode_scene_bin(&s, &t), FIXTURE); + // Leere Szene = reiner Kopf; Landeskoordinaten bleiben f64. + assert_eq!(encode_scene_bin(&Scene::default(), &[]).len(), 48); + let mut l = Scene::default(); + l.lines.push(SLine { a: v2(2600000.123456, 1200000.654321), b: v2(0.0, 0.0), color: [0.0; 4], width_mm: 0.1, dash: SDash::Null, z: 0.0 }); + let b = encode_scene_bin(&l, &[]); + assert_eq!(f64::from_le_bytes(b[48..56].try_into().unwrap()), 2600000.123456); + } + + #[test] + fn kantenlaeufe_und_naht() { + let sq = vec![v2(0.0, 0.0), v2(1.0, 0.0), v2(1.0, 1.0), v2(0.0, 1.0)]; + // Kante 3 (0,1)→(0,0) unterdrückt: ein Lauf über drei Kanten. + let runs = visible_edge_runs(&sq, &[3.0]); + assert_eq!(runs, vec![vec![v2(0.0, 0.0), v2(1.0, 0.0), v2(1.0, 1.0), v2(0.0, 1.0)]]); + assert!(visible_edge_runs(&sq, &[0.0, 1.0, 2.0, 3.0]).is_empty()); + // Zwei Läufe, die sich zu einem Ring schliessen. + let a = vec![v2(0.0, 0.0), v2(1.0, 0.0), v2(1.0, 1.0)]; + let b = vec![v2(1.0, 1.0), v2(0.0, 1.0), v2(0.0, 0.0)]; + let s = stitch_runs(vec![a, b]); + assert_eq!(s.len(), 1); + assert!(s[0].1); + assert_eq!(s[0].0.len(), 4); + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 0d13f959..2d3fd99c 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -32,6 +32,7 @@ mod voids; mod curves; mod hatch; mod skeleton; +mod plan_scene; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/plan_buf.rs b/src-tauri/core/src/web/plan_buf.rs index 7ed99649..c8610c42 100644 --- a/src-tauri/core/src/web/plan_buf.rs +++ b/src-tauri/core/src/web/plan_buf.rs @@ -6,13 +6,14 @@ //! ein verdrängter Puffer liefert leere Ergebnisse, TS übergibt ihn dann neu. use std::cell::RefCell; +use std::rc::Rc; use wasm_bindgen::prelude::wasm_bindgen; -const MAX_HELD: usize = 8; +const MAX_HELD: usize = 64; const MAX_HELD_BYTES: usize = 96 << 20; thread_local! { - static HELD: RefCell<(u32, Vec<(u32, Vec)>)> = const { RefCell::new((0, Vec::new())) }; + static HELD: RefCell<(u32, Vec<(u32, Rc<[u8]>)>)> = const { RefCell::new((0, Vec::new())) }; } /// Plan-Puffer lesen und neu schreiben (Hin-und-zurück-Prüfung der TS-Kodierung); leer bei @@ -32,7 +33,7 @@ pub fn plan_buf_hold(buf: &[u8]) -> u32 { let mut h = h.borrow_mut(); h.0 = h.0.wrapping_add(1).max(1); let id = h.0; - h.1.push((id, buf.to_vec())); + h.1.push((id, Rc::from(buf))); let mut bytes: usize = h.1.iter().map(|e| e.1.len()).sum(); while h.1.len() > MAX_HELD || (bytes > MAX_HELD_BYTES && h.1.len() > 1) { bytes -= h.1.remove(0).1.len(); @@ -51,3 +52,31 @@ pub fn plan_buf_release(id: u32) { pub(crate) fn with_held(id: u32, f: impl FnOnce(&[u8]) -> R) -> Option { HELD.with(|h| h.borrow().1.iter().find(|e| e.0 == id).map(|e| f(&e.1))) } + +/// Gehaltenen Puffer `id` teilen (bleibt am Leben, auch wenn er verdrängt wird); `None`, wenn er +/// nicht (mehr) da ist. +pub(crate) fn held_rc(id: u32) -> Option> { + HELD.with(|h| h.borrow().1.iter().find(|e| e.0 == id).map(|e| e.1.clone())) +} + +/// Die Puffer der Abschnitte `[nr, von, bis, …]` (s. `plan_parts`) in Abschnitts-Reihenfolge; +/// `None`, wenn einer fehlt oder die Liste kaputt ist. +pub(crate) fn held_for_segs(segs: &[f64]) -> Option)>> { + if segs.len() % 3 != 0 { + return None; + } + let mut out: Vec<(u32, Rc<[u8]>)> = Vec::new(); + for s in segs.chunks_exact(3) { + let nr = crate::plan_buf::whole(s[0])? as u32; + if !out.iter().any(|e| e.0 == nr) { + out.push((nr, held_rc(nr)?)); + } + } + Some(out) +} + +/// Ist der Puffer `id` noch gehalten? +#[wasm_bindgen] +pub fn plan_buf_is_held(id: u32) -> bool { + HELD.with(|h| h.borrow().1.iter().any(|e| e.0 == id)) +} diff --git a/src-tauri/core/src/web/plan_scene.rs b/src-tauri/core/src/web/plan_scene.rs new file mode 100644 index 00000000..f57ce18e --- /dev/null +++ b/src-tauri/core/src/web/plan_scene.rs @@ -0,0 +1,34 @@ +//! Bindungen der Render-Szene (`crate::plan_scene`) auf gehaltenen Plan-Puffern. Abschnitte als +//! `[Puffer-Nr, von, bis, …]`, gedimmte Bereiche als `[von, bis, …]` (s. `plan_parts`). Fehlt +//! ein Puffer (verdrängt) oder ist eine Eingabe kaputt, ist das Ergebnis leer — TS legt die +//! Puffer dann neu ab und fragt nochmals. + +use crate::plan_parts::{parts_from, ranges_from}; +use crate::plan_scene::{build_scene, encode_scene_bin, encode_scene_f64, texts_from, Scene}; +use wasm_bindgen::prelude::wasm_bindgen; + +fn scene_of(segs: &[f64], greyed: &[f64]) -> Option { + let held = super::plan_buf::held_for_segs(segs)?; + let mut parts = parts_from(segs, |nr| held.iter().find(|e| e.0 == nr).map(|e| &*e.1))?; + build_scene(&mut parts, &ranges_from(greyed)?) +} + +/// render2d-Szene v1 (Bytes für `set_scene_bin`/`push_native_scene`); Texte fertig gesetzt aus +/// TS: `[x, y, sizeMm, r, g, b, a, align, nBytes]*` + UTF-8-Bytes. Leer = Fehler. +#[wasm_bindgen] +pub fn plan_scene_bin(segs: &[f64], greyed: &[f64], text_nums: &[f64], text_bytes: &[u8]) -> Vec { + let Some(texts) = texts_from(text_nums, text_bytes) else { return Vec::new() }; + match scene_of(segs, greyed) { + Some(s) => encode_scene_bin(&s, &texts), + None => Vec::new(), + } +} + +/// Verlustfreie Szene (Format s. `plan_scene`) für Export und `--format json`. Leer = Fehler. +#[wasm_bindgen] +pub fn plan_scene_f64(segs: &[f64], greyed: &[f64]) -> Vec { + match scene_of(segs, greyed) { + Some(s) => encode_scene_f64(&s), + None => Vec::new(), + } +} diff --git a/src-tauri/render2d/src/scene_bin.rs b/src-tauri/render2d/src/scene_bin.rs index 89c62611..d5caa39a 100644 --- a/src-tauri/render2d/src/scene_bin.rs +++ b/src-tauri/render2d/src/scene_bin.rs @@ -1,4 +1,4 @@ -// Binaerformat der Plan-Szene (Version 1): TS schreibt (`src/plan/renderSceneBin.ts`), +// Binaerformat der Plan-Szene (Version 1): der Kern schreibt (`core/src/plan_scene.rs`), // Rust liest — ersetzt den JSON-Weg zwischen Webview und render2d. Alles little-endian. // // Aufbau (alle Abschnitte lueckenlos hintereinander, kein Fuellmaterial): @@ -214,7 +214,7 @@ pub fn decode_scene(bytes: &[u8]) -> Result { mod tests { use super::*; - /// Beispielszene; MUSS mit `sampleScene()` in `src/plan/renderSceneBin.test.ts` + /// Beispielszene; MUSS mit `sample()` in `core/src/plan_scene.rs` /// uebereinstimmen (gemeinsame Bytes: `tests/fixtures/scene_v1.bin`). fn sample() -> Scene { Scene { diff --git a/src-tauri/render2d/src/web.rs b/src-tauri/render2d/src/web.rs index 4274a36c..cb8e566f 100644 --- a/src-tauri/render2d/src/web.rs +++ b/src-tauri/render2d/src/web.rs @@ -133,8 +133,8 @@ impl WebPlanRenderer { }) } - /// Setzt die zu zeichnende Szene aus dem Binaerformat von `scene_bin.rs` (TS-Seite: - /// `src/plan/renderSceneBin.ts`). Fremde Version/kaputte Daten → Fehler, die alte + /// Setzt die zu zeichnende Szene aus dem Binaerformat von `scene_bin.rs` (Schreiber: + /// `src-tauri/core/src/plan_scene.rs`). Fremde Version/kaputte Daten → Fehler, die alte /// Szene bleibt. Re-tesselliert + laedt die GPU-Puffer; ruft NICHT selbst `render`. pub fn set_scene_bin(&mut self, bytes: &[u8]) -> Result<(), JsValue> { let scene = decode_scene(bytes).map_err(|e| JsValue::from_str(&format!("Szene lesen: {e}")))?; diff --git a/src/core/extra.ts b/src/core/extra.ts index 9c8a5556..26d37bd7 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -39,7 +39,6 @@ export { sunPosition, shadowPolygons, shadowOfPrism, projectLatLon } from "../an export type { SunPosition } from "../analysis/sun"; export { checkSiteRules, allowedArea, multiPolygonArea, buildingFootprint, modelTop } from "../analysis/siteRules"; export type { SiteCheck } from "../analysis/siteRules"; -export { encodeRenderScene } from "../plan/renderSceneBin"; export { sampleProject } from "../model/sampleProject"; export { parseDxf } from "../io/dxfParser"; export { contoursToDrawings, textsToDrawings, planImportCategories, distinctImportLayers } from "../io/dxfToDrawings"; diff --git a/src/core/index.ts b/src/core/index.ts index 1ef8ca4b..041a3d81 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -290,6 +290,7 @@ export { } from "../plan/toElevation"; export { + planSceneBin, planToRenderScene, } from "../plan/toRenderScene"; diff --git a/src/plan/planBuf.ts b/src/plan/planBuf.ts index 4c6ccea4..0cadd6fb 100644 --- a/src/plan/planBuf.ts +++ b/src/plan/planBuf.ts @@ -178,6 +178,12 @@ export interface EncodeOptions { * (tag 0). Schneller; {@link decodePlanBuf} kann so einen Puffer nicht vollständig lesen. */ lean?: boolean; + /** + * `false`: Texte/Bilder ohne JSON (String-Index −1), aber mit Typ und Pick-Ids — für Kern- + * Verbraucher, die Texte nicht lesen (Render-Szene, Auswahl). {@link decodePlanBuf} kann so + * einen Puffer nicht lesen. Standard `true`. + */ + textJson?: boolean; /** Gruppen `[start, end)` in den Kopf schreiben. */ groups?: ReadonlyArray; bounds?: readonly [number, number, number, number]; @@ -186,6 +192,7 @@ export interface EncodeOptions { /** Primitive → Plan-Puffer v2 (Format s. Dateikopf). */ export function encodePlanBuf(prims: readonly Primitive[], opts: EncodeOptions = {}): Uint8Array { const lean = opts.lean === true; + const textJson = opts.textJson !== false; const strParts: string[] = []; const strTab = new F64Writer(64); const strIdx = new Map(); @@ -385,7 +392,7 @@ export function encodePlanBuf(prims: readonly Primitive[], opts: EncodeOptions = } const tag = p.kind === "text" ? 6 : p.kind === "drawingText" ? 7 : p.kind === "drawingTextPath" ? 8 : 9; head(tag, 0, p); - w.push(str(JSON.stringify(p))); + w.push(textJson ? str(JSON.stringify(p)) : -1); } } } diff --git a/src/plan/planParts.ts b/src/plan/planParts.ts new file mode 100644 index 00000000..a0938a9b --- /dev/null +++ b/src/plan/planParts.ts @@ -0,0 +1,152 @@ +/** + * Zusammengesetzter Plan für Kern-Verbraucher ([K3d], Rust: `src-tauri/core/src/plan_parts.rs`): + * die Primitive eines {@link Plan} als Abschnitte gehaltener Plan-Puffer, in Zeichenreihenfolge. + * Was unverändert aus einem Kern-Puffer stammt (`Plan.bufRuns`, Objekt-Identität geprüft), geht + * ohne Umweg über Objekte; der Rest (2D-Zeichnungen, Schatten, Baurecht, zerlegte Polygone, + * gedimmte Klone) wird einmal in einen eigenen Puffer geschrieben. Der Index eines Primitivs im + * Kern ist seine Stelle in `plan.primitives`. + * + * Abschnitte reisen als `[Puffer-Nr, von, bis, …]` (Nr = `plan_buf_hold`), gedimmte Bereiche + * (`Plan.greyedRanges`) als `[von, bis, …]`. Verdrängt der Kern einen Puffer, liefert er ein + * leeres Ergebnis; {@link withPlanParts} legt dann alles neu ab und fragt nochmals. + */ + +import type { Plan, PlanBufRun, Primitive } from "./generatePlan"; +import { encodePlanBuf } from "./planBuf"; +import { core } from "../engine/coreWasm"; + +/** Ein im Kern ablegbarer Puffer (Kern-Ergebnis `DecodedPlanBuf` oder eigener). */ +interface HoldableBuf { + bytes: Uint8Array; + hold: number; +} + +export interface PlanParts { + bufs: HoldableBuf[]; + /** Abschnitte `[Index in bufs, von, bis, …]`. */ + segs: number[]; + /** Anzahl Primitive (= `plan.primitives.length`). */ + count: number; +} + +/** Unveränderte Kern-Abschnitte (Objekt-Identität) in Plan-Reihenfolge. */ +function verifiedRuns(primitives: readonly Primitive[], runs: readonly PlanBufRun[] | undefined) { + const out: Array<{ start: number; end: number; buf: PlanBufRun["buf"]; from: number }> = []; + for (const r of runs ?? []) { + const n = Math.min(r.to - r.from, primitives.length - r.at); + let k = 0; + while (k < n) { + while (k < n && primitives[r.at + k] !== r.buf.prims[r.from + k]) k++; + const k0 = k; + while (k < n && primitives[r.at + k] === r.buf.prims[r.from + k]) k++; + if (k > k0) out.push({ start: r.at + k0, end: r.at + k, buf: r.buf, from: r.from + k0 }); + } + } + out.sort((a, b) => a.start - b.start); + // Überlappungen (sollte es nicht geben) verwerfen. + const clean: typeof out = []; + let last = 0; + for (const s of out) { + if (s.start < last) continue; + clean.push(s); + last = s.end; + } + return clean; +} + +const cache = new WeakMap(); + +/** + * Abschnitte eines Plans; einmal je `plan.primitives` (und Modus) gebaut. `texts`: der eigene + * Puffer trägt Texte/Bilder mit JSON (SVG-Export) — sonst nur deren Typ (Szene, Auswahl). + */ +export function planParts(plan: Plan, texts = false): PlanParts { + const prims = plan.primitives; + let c = cache.get(prims); + if (!c) { + c = { text: null, noText: null }; + cache.set(prims, c); + } + const hit = texts ? c.text : c.noText; + if (hit) return hit; + const runs = verifiedRuns(prims, plan.bufRuns); + const bufs: HoldableBuf[] = []; + const bufIdx = new Map(); + const idx = (b: HoldableBuf): number => { + let i = bufIdx.get(b); + if (i === undefined) { + i = bufs.length; + bufs.push(b); + bufIdx.set(b, i); + } + return i; + }; + // Lücken zwischen den Kern-Abschnitten sammeln: [Plan-Start, Plan-Ende, Start im eigenen Puffer]. + const rest: Primitive[] = []; + const gaps: Array<[number, number, number]> = []; + let at = 0; + const gap = (end: number) => { + if (end <= at) return; + gaps.push([at, end, rest.length]); + for (let i = at; i < end; i++) rest.push(prims[i]); + }; + for (const r of runs) { + gap(r.start); + at = r.end; + } + gap(prims.length); + const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts }), hold: 0 } : null; + const segs: number[] = []; + let gi = 0; + let ri = 0; + // Abschnitte in Plan-Reihenfolge zusammenführen. + while (gi < gaps.length || ri < runs.length) { + const g = gaps[gi]; + const r = runs[ri]; + if (r === undefined || (g !== undefined && g[0] < r.start)) { + segs.push(idx(own!), g[2], g[2] + (g[1] - g[0])); + gi++; + } else { + segs.push(idx(r.buf), r.from, r.from + (r.end - r.start)); + ri++; + } + } + const out: PlanParts = { bufs, segs, count: prims.length }; + if (texts) c.text = out; + else c.noText = out; + return out; +} + +/** Gedimmte Bereiche flach (`Plan.greyedRanges`). */ +export function greyedFlat(plan: Plan): Float64Array { + const r = plan.greyedRanges ?? []; + const out = new Float64Array(r.length * 2); + r.forEach(([a, b], i) => { + out[2 * i] = a; + out[2 * i + 1] = b; + }); + return out; +} + +/** Abschnitte mit den Kern-Nummern der Puffer (legt fehlende ab). */ +function heldSegs(parts: PlanParts, fresh: boolean): Float64Array { + const c = core(); + for (const b of parts.bufs) if (!b.hold || (fresh && !c.plan_buf_is_held(b.hold))) b.hold = c.plan_buf_hold(b.bytes); + const s = new Float64Array(parts.segs.length); + for (let i = 0; i < parts.segs.length; i += 3) { + s[i] = parts.bufs[parts.segs[i]].hold; + s[i + 1] = parts.segs[i + 1]; + s[i + 2] = parts.segs[i + 2]; + } + return s; +} + +/** + * Kern-Aufruf mit den gehaltenen Abschnitten. `call` liefert ein leeres Ergebnis, wenn ein + * Puffer verdrängt ist — dann werden alle neu abgelegt und es wird einmal wiederholt. + */ +export function withPlanParts(parts: PlanParts, call: (segs: Float64Array) => T): T { + const out = call(heldSegs(parts, false)); + if (out.length > 0 || parts.segs.length === 0) return out; + return call(heldSegs(parts, true)); +} diff --git a/src/plan/randomPrims.testing.ts b/src/plan/randomPrims.testing.ts new file mode 100644 index 00000000..e5982822 --- /dev/null +++ b/src/plan/randomPrims.testing.ts @@ -0,0 +1,177 @@ +// Testhilfe ([K3d]): deterministische Zufalls-Primitive aller Arten für Gleichheitstests der +// Kern-Verbraucher (Render-Szene, Auswahl, SVG-Export) — Polygone mit allen Schraffur-Arten, +// unterdrückten Kanten, Farben in allen Schreibweisen, verkettete 2D-Zeichenlinien, Zickzack, +// Motiv, Strichmuster (fehlend/null/Liste), Bögen, Kreise, Texte, Bilder, gedimmt/deckend. + +import type { HatchRender, Plan, Primitive } from "./generatePlan"; +import type { Vec2 } from "../model/types"; + +export function rng(seed: number): () => number { + let s = seed >>> 0; + return () => { + s = (s + 0x6d2b79f5) >>> 0; + let t = s; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +const COLORS = ["#1a1a1a", "#fff", "#ff000080", "#abc", "#12345", "none", "", "black", "red", " White ", "rgb(1,2,3)", "#zz0000", "#336699", "transparent"]; +const CLS = ["wall", "door-leaf", "door-swing", "wall-axis", "context-line", "draw2d", "window-glass", "stair-line"]; +const PATTERNS: HatchRender["pattern"][] = ["diagonal", "crosshatch", "insulation", "custom", "solid", "none"]; + +export function randomPrims(seed: number, n: number, span = 20): Primitive[] { + const r = rng(seed); + const pick = (a: readonly T[]): T => a[Math.floor(r() * a.length)]; + const pt = (): Vec2 => ({ x: (r() - 0.5) * span, y: (r() - 0.5) * span }); + const dash = (): number[] | null | undefined => { + const k = r(); + return k < 0.4 ? undefined : k < 0.6 ? null : k < 0.7 ? [] : [0.5 + r(), 0.2 + r(), ...(r() < 0.3 ? [0.1] : [])]; + }; + const greyed = (): boolean | undefined => (r() < 0.6 ? undefined : r() < 0.5); + const hatch = (): HatchRender => { + const h: HatchRender = { + pattern: pick(PATTERNS), + scale: r() < 0.1 ? 0 : 0.5 + r() * 2, + angle: Math.floor(r() * 180), + color: pick(COLORS), + lineWeight: r() < 0.2 ? 0 : 0.05 + r() * 0.3, + dash: r() < 0.6 ? null : [0.5 + r(), 0.3], + }; + if (r() < 0.2) h.kind = pick(["vector", "image", "gradient"] as const); + if (r() < 0.2) h.lines = "random"; + if (r() < 0.3) h.origin = pt(); + if (h.pattern === "custom") h.motif = { points: [{ x: 0, y: 0 }, { x: 0.5, y: 0.3 }, { x: 1, y: 0 }], length: 1 }; + return h; + }; + const ring = (): Vec2[] => { + const c = pt(); + const k = 3 + Math.floor(r() * 5); + const rad = 0.3 + r() * 3; + const out: Vec2[] = []; + for (let i = 0; i < k; i++) { + const a = (i / k) * Math.PI * 2; + out.push({ x: c.x + Math.cos(a) * rad * (0.6 + r() * 0.4), y: c.y + Math.sin(a) * rad * (0.6 + r() * 0.4) }); + } + return out; + }; + const out: Primitive[] = []; + const ids = ["d1", "d2", "d3", ""]; + let last: Vec2 | null = null; + while (out.length < n) { + const k = r(); + if (k < 0.25) { + const pts = ring(); + const p: Primitive = { + kind: "polygon", + pts: r() < 0.05 ? pts.slice(0, 2) : pts, + fill: pick(COLORS), + stroke: pick(COLORS), + strokeWidthMm: r() < 0.1 ? 0 : 0.1 + r() * 0.5, + hatch: hatch(), + }; + if (r() < 0.4) delete (p as { hatch?: HatchRender }).hatch; + const g = greyed(); + if (g !== undefined) p.greyed = g; + if (r() < 0.2) p.opacity = r(); + if (r() < 0.4) p.noStrokeEdges = Array.from({ length: Math.floor(r() * pts.length) }, () => Math.floor(r() * pts.length * 2) - 1); + if (r() < 0.3) p.wallId = `w${Math.floor(r() * 5)}`; + else if (r() < 0.3) p.roomId = `r${Math.floor(r() * 5)}`; + else if (r() < 0.2) p.drawingId = pick(ids); + if (r() < 0.1) p.stairId = "s1"; + out.push(p); + } else if (k < 0.7) { + // Linien, oft als Zug (Ende = nächster Anfang). + const a: Vec2 = last && r() < 0.6 ? { ...last } : pt(); + const b: Vec2 = { x: a.x + (r() - 0.5) * 3, y: a.y + (r() - 0.5) * 3 }; + const p: Primitive = { kind: "line", a, b, cls: pick(CLS), weightMm: r() < 0.5 ? 0.25 : 0.18 }; + const d = dash(); + if (d !== undefined) p.dash = d; + if (r() < 0.5) p.color = pick(COLORS); + if (r() < 0.6) p.drawingId = pick(ids); + else if (r() < 0.3) p.openingId = "o1"; + if (r() < 0.05) p.zigzag = { amplitude: 0.5 + r(), wavelength: 2 + r() * 3 }; + else if (r() < 0.05) p.motif = { points: [{ x: 0, y: 0 }, { x: 0.5, y: 0.5 }, { x: 1, y: 0 }], length: 1 + r() }; + const g = greyed(); + if (g !== undefined) p.greyed = g; + out.push(p); + last = b; + } else if (k < 0.78) { + const c = pt(); + const rad = 0.5 + r(); + const a0 = r() * 6; + const a1 = a0 + r() * 3; + const p: Primitive = { + kind: "arc", + center: c, + from: { x: c.x + rad * Math.cos(a0), y: c.y + rad * Math.sin(a0) }, + to: { x: c.x + rad * Math.cos(a1), y: c.y + rad * Math.sin(a1) }, + r: rad, + cls: pick(CLS), + weightMm: 0.18, + }; + const d = dash(); + if (d !== undefined) p.dash = d; + if (r() < 0.5) p.openingId = "o2"; + const g = greyed(); + if (g !== undefined) p.greyed = g; + out.push(p); + } else if (k < 0.86) { + const circle = r() < 0.5; + const c = pt(); + const g = greyed(); + const d = dash(); + if (circle) { + const p: Primitive = { kind: "drawingCircle", center: c, r: 0.2 + r() * 2, fill: pick(COLORS), stroke: pick(COLORS), weightMm: 0.25 }; + if (d !== undefined) p.dash = d; + if (g !== undefined) p.greyed = g; + if (r() < 0.7) p.drawingId = pick(ids); + out.push(p); + } else { + const p: Primitive = { kind: "drawingArc", center: c, r: 0.2 + r() * 2, a0: (r() - 0.5) * 10, a1: (r() - 0.5) * 10, stroke: pick(COLORS), weightMm: 0.25 }; + if (d !== undefined) p.dash = d; + if (g !== undefined) p.greyed = g; + if (r() < 0.7) p.drawingId = pick(ids); + out.push(p); + } + } else if (k < 0.92) { + const g = greyed(); + if (r() < 0.5) { + const p = { + kind: "text", + at: pt(), + doc: { version: 1, paragraphs: [{ align: "center", runs: [{ text: `Raum ${out.length}`, marks: {} }] }] }, + extraLines: r() < 0.5 ? [{ text: "12.5 m²", align: "center" }] : [], + basePt: 8 + Math.floor(r() * 6), + color: pick(COLORS), + roomId: "r1", + } as unknown as Primitive; + if (g !== undefined) (p as { greyed?: boolean }).greyed = g; + out.push(p); + } else { + const p: Primitive = { kind: "drawingText", at: pt(), text: `T ${out.length}\nzwei`, heightM: 0.2 + r(), angle: r() < 0.5 ? 0 : r(), color: pick(COLORS), drawingId: pick(ids) }; + if (r() < 0.3) p.wrapWidth = 1 + r() * 2; + if (g !== undefined) p.greyed = g; + out.push(p); + } + } else if (k < 0.95) { + const a = pt(); + out.push({ kind: "drawingImage", min: a, max: { x: a.x + 1, y: a.y + 1 }, src: "data:image/png;base64,AA", opacity: r(), drawingId: pick(ids) }); + } else if (k < 0.97) { + out.push({ kind: "drawingTextPath", pathPts: [pt(), pt()], text: "Pfad", heightM: 0.3, color: "#000", drawingId: "d1" }); + } else { + // Exakte Wiederholung des letzten Polygons mit unterdrückten Kanten (Naht über Grenzen). + const sq: Vec2[] = [pt()]; + sq.push({ x: sq[0].x + 1, y: sq[0].y }, { x: sq[0].x + 1, y: sq[0].y + 1 }, { x: sq[0].x, y: sq[0].y + 1 }); + const sq2 = [sq[1], { x: sq[1].x + 1, y: sq[1].y }, { x: sq[1].x + 1, y: sq[2].y }, sq[2]]; + out.push({ kind: "polygon", pts: sq, fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [1], wallId: "wx" } as Primitive); + out.push({ kind: "polygon", pts: sq2, fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [3], wallId: "wy" } as Primitive); + } + } + return out; +} + +export function planOf(primitives: Primitive[], greyedRanges?: Array<[number, number]>): Plan { + return { primitives, bounds: { minX: -10, minY: -10, maxX: 10, maxY: 10 }, ...(greyedRanges ? { greyedRanges } : {}) }; +} diff --git a/src/plan/renderSceneBin.test.ts b/src/plan/renderSceneBin.test.ts deleted file mode 100644 index fb0ffcf2..00000000 --- a/src/plan/renderSceneBin.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { readFileSync, writeFileSync } from "node:fs"; -import { encodeRenderScene, SCENE_BIN_VERSION } from "./renderSceneBin"; -import type { RScene } from "./toRenderScene"; - -const FIXTURE = new URL("../../src-tauri/render2d/tests/fixtures/scene_v1.bin", import.meta.url); - -/** Beispielszene; MUSS mit `sample()` in `src-tauri/render2d/src/scene_bin.rs` übereinstimmen. */ -function sampleScene(): RScene { - return { - fills: [ - { pts: [[0, 0], [4, 0], [4, 3]], color: [0.5, 0.25, 0.75, 1], z: 0 }, - { pts: [[1.5, 1.5], [2.5, 1.5], [2.5, 2.5], [1.5, 2.5]], color: [1, 1, 1, 0.5], z: 7 }, - ], - outlines: [{ pts: [[0, 0], [4, 0], [4, 3]], color: [0, 0, 0, 1], widthMm: 0.25, dash: [2, 1], z: 1 }], - polylines: [ - { pts: [[0, 0], [1, 1]], color: [0.25, 0.25, 0.25, 1], widthMm: 0.5, dash: null, z: 2 }, - { pts: [[5, 5], [6, 5], [6, 6]], color: [0.5, 0.5, 0.5, 1], widthMm: 1, dash: [1], z: 3, widthScreen: true }, - ], - arcs: [{ center: [1, 1], from: [2, 1], to: [1, 2], r: 1, color: [1, 0, 0, 1], widthMm: 0.125 }], - lines: [{ a: [0, 0], b: [2600000.5, 1200000.25], color: [0, 0.5, 0, 1], widthMm: 0.35, dash: [3, 1, 0.5, 1], z: 4 }], - texts: [ - { pos: [1, 2], content: "Küche 12,5 m²", sizeMm: 2.5, color: [0, 0, 0, 1], align: "center" }, - { pos: [3, 4], content: "", sizeMm: 2, color: [0, 0, 0, 1], align: "right" }, - { pos: [5, 6], content: "A", sizeMm: 1, color: [0, 0, 1, 1], align: "left" }, - ], - images: [], - bounds: { minX: 0, minY: 0, maxX: 1, maxY: 1 }, - }; -} - -const empty = (): RScene => ({ - fills: [], outlines: [], polylines: [], arcs: [], lines: [], texts: [], images: [], - bounds: { minX: 0, minY: 0, maxX: 0, maxY: 0 }, -}); - -describe("encodeRenderScene", () => { - it("liefert byte-genau die Fixture, die der Rust-Dekodierer liest", () => { - const bytes = encodeRenderScene(sampleScene()); - if (process.env.UPDATE_SCENE_FIXTURE) writeFileSync(FIXTURE, bytes); - expect(Buffer.from(bytes).equals(readFileSync(FIXTURE))).toBe(true); - }); - - it("schreibt Kopf, Zähler und die exakte Länge", () => { - const bytes = encodeRenderScene(sampleScene()); - const h = new Uint32Array(bytes.buffer, bytes.byteOffset, 12); - expect(String.fromCharCode(...bytes.subarray(0, 4))).toBe("DR2S"); - expect(h[1]).toBe(SCENE_BIN_VERSION); - expect([...h.subarray(2, 8)]).toEqual([2, 1, 2, 1, 1, 3]); - const nPts = 3 + 4 + 3 + 2 + 3 + 3 + 2 + 3; - expect(h[8]).toBe(nPts); - expect(h[9]).toBe(2 + 1 + 4); - expect(h[10]).toBe(new TextEncoder().encode("Küche 12,5 m²A").length); - const words = 2 * 6 + 8 + 2 * 9 + 7 + 7 + 3 * 8; - expect(bytes.length).toBe(48 + nPts * 16 + 7 * 4 + words * 4 + h[10]); - }); - - it("behält Koordinaten als f64 (LV95-gross)", () => { - const s = empty(); - s.lines.push({ a: [2600000.123456, 1200000.654321], b: [0, 0], color: [0, 0, 0, 1], widthMm: 0.1, z: 0 }); - const bytes = encodeRenderScene(s); - const pts = new Float64Array(bytes.buffer, bytes.byteOffset + 48, 4); - expect(pts[0]).toBe(2600000.123456); - expect(pts[1]).toBe(1200000.654321); - }); - - it("kodiert die leere Szene als reinen Kopf und wirft bei Unsinn nicht", () => { - expect(encodeRenderScene(empty()).length).toBe(48); - const s = empty(); - s.fills.push({ pts: [], color: [NaN, 0, 0, 1], z: -1 }); - s.texts.push({ pos: [Infinity, 0], content: "\u{1F600}", sizeMm: 1, color: [0, 0, 0, 1], align: "left" }); - expect(() => encodeRenderScene(s)).not.toThrow(); - }); -}); - -/** Zufallsszene (deterministisch) für die Messung. */ -function bigScene(nLines: number, nFills: number, nTexts: number): RScene { - let seed = 42; - const rnd = () => ((seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) >>> 8) / 16777216; - const s = empty(); - for (let i = 0; i < nLines; i++) { - const x = rnd() * 500, y = rnd() * 500; - s.lines.push({ a: [x, y], b: [x + rnd(), y + rnd()], color: [0.1, 0.1, 0.1, 1], widthMm: 0.18, dash: i % 10 === 0 ? [2, 1] : null, z: i % 50 }); - } - for (let i = 0; i < nFills; i++) { - const x = rnd() * 500, y = rnd() * 500; - s.fills.push({ pts: [0, 1, 2, 3, 4, 5].map((k) => [x + k * rnd(), y + k * rnd()] as [number, number]), color: [0.8, 0.8, 0.75, 1], z: i % 50 }); - } - for (let i = 0; i < nTexts; i++) { - s.texts.push({ pos: [rnd() * 500, rnd() * 500], content: `Raum ${i} 12,5 m²`, sizeMm: 2, color: [0, 0, 0, 1], align: "center" }); - } - return s; -} - -describe("Messung JSON gegen Binär (Kodierung, Node)", () => { - it("kodiert kleine und grosse Szene und gibt die Zeiten aus", () => { - const best = (f: () => unknown) => { - let b = Infinity; - for (let i = 0; i < 5; i++) { - const t = performance.now(); - f(); - b = Math.min(b, performance.now() - t); - } - return b; - }; - for (const [name, sc] of [ - ["klein (200 Linien, 50 Füllungen, 20 Texte)", bigScene(200, 50, 20)], - ["gross (200000 Linien, 20000 Füllungen, 1000 Texte)", bigScene(200_000, 20_000, 1000)], - ] as const) { - const json = JSON.stringify(sc); - const bin = encodeRenderScene(sc); - const tj = best(() => JSON.stringify(sc)); - const tb = best(() => encodeRenderScene(sc)); - console.log(`${name}: JSON ${(json.length / 1024) | 0} KB ${tj.toFixed(2)} ms | binär ${(bin.length / 1024) | 0} KB ${tb.toFixed(2)} ms`); - expect(bin.length).toBeLessThan(json.length); - } - }); -}); diff --git a/src/plan/renderSceneBin.ts b/src/plan/renderSceneBin.ts deleted file mode 100644 index e054e2b7..00000000 --- a/src/plan/renderSceneBin.ts +++ /dev/null @@ -1,157 +0,0 @@ -// Binärkodierung der Render-Szene (`RScene`) für render2d — Gegenstück zu -// `src-tauri/render2d/src/scene_bin.rs` (dort steht die Formatbeschreibung; beide Seiten -// müssen Version und Aufbau gleich halten, die gemeinsame Fixture -// `src-tauri/render2d/tests/fixtures/scene_v1.bin` prüft das in beiden Tests). -// -// Zweiphasig: erst Zähler (Punkte, Strichmuster, Strings), dann ein einziger Puffer, in den -// über typisierte Sichten geschrieben wird (kein DataView je Wert, keine Zwischenarrays). -// Little-endian setzen wir voraus (alle Zielplattformen); `LITTLE_ENDIAN` prüft das einmal. - -import type { RScene, RTextAlign } from "./toRenderScene"; - -export const SCENE_BIN_VERSION = 1; -const HEADER_BYTES = 48; -const ALIGN: Record = { left: 0, center: 1, right: 2 }; - -const LITTLE_ENDIAN = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1; - -const textEncoder = new TextEncoder(); - -/** Kodiert die Szene (ohne `images`/`bounds`, die der Renderer nicht kennt). */ -export function encodeRenderScene(scene: RScene): Uint8Array { - if (!LITTLE_ENDIAN) throw new Error("Szenenkodierung setzt Little-Endian voraus"); - const { fills, outlines, polylines, arcs, lines, texts } = scene; - - let nPts = 0; - let nDash = 0; - for (const f of fills) nPts += f.pts.length; - for (const o of outlines) { - nPts += o.pts.length; - nDash += o.dash?.length ?? 0; - } - for (const p of polylines) { - nPts += p.pts.length; - nDash += p.dash?.length ?? 0; - } - for (const a of arcs) nDash += a.dash?.length ?? 0; - for (const l of lines) nDash += l.dash?.length ?? 0; - nPts += arcs.length * 3 + lines.length * 2 + texts.length; - - const strs: Uint8Array[] = new Array(texts.length); - let strBytes = 0; - for (let i = 0; i < texts.length; i++) { - strs[i] = textEncoder.encode(texts[i].content); - strBytes += strs[i].length; - } - - const words = - fills.length * 6 + outlines.length * 8 + polylines.length * 9 + arcs.length * 7 + lines.length * 7 + texts.length * 8; - const ptsOff = HEADER_BYTES; - const dashOff = ptsOff + nPts * 16; - const recOff = dashOff + nDash * 4; - const strOff = recOff + words * 4; - const total = strOff + strBytes; - if (total > 0xffffffff || nPts > 0xffffffff) throw new Error("Szene zu gross für das Binärformat"); - - const buf = new ArrayBuffer(total); - const bytes = new Uint8Array(buf); - const hdr = new Uint32Array(buf, 0, HEADER_BYTES / 4); - const pts = new Float64Array(buf, ptsOff, nPts * 2); - const dash = new Float32Array(buf, dashOff, nDash); - const u32 = new Uint32Array(buf, recOff, words); - const f32 = new Float32Array(buf, recOff, words); - - bytes.set([0x44, 0x52, 0x32, 0x53], 0); // "DR2S" - hdr[1] = SCENE_BIN_VERSION; - hdr[2] = fills.length; - hdr[3] = outlines.length; - hdr[4] = polylines.length; - hdr[5] = arcs.length; - hdr[6] = lines.length; - hdr[7] = texts.length; - hdr[8] = nPts; - hdr[9] = nDash; - hdr[10] = strBytes; - hdr[11] = 0; - - let pi = 0; // Index in pts (Doubles) - let di = 0; // Index in dash - let w = 0; // Index in u32/f32 - const ring = (a: ArrayLike) => { - for (let i = 0; i < a.length; i++) { - pts[pi++] = a[i][0]; - pts[pi++] = a[i][1]; - } - }; - const col = (c: readonly number[]) => { - f32[w++] = c[0]; - f32[w++] = c[1]; - f32[w++] = c[2]; - f32[w++] = c[3]; - }; - const dashes = (d: readonly number[] | null | undefined): number => { - if (!d || d.length === 0) return 0; - for (let i = 0; i < d.length; i++) dash[di++] = d[i]; - return d.length; - }; - - for (const f of fills) { - u32[w++] = f.pts.length; - u32[w++] = f.z >>> 0; - col(f.color); - ring(f.pts); - } - for (const o of outlines) { - u32[w++] = o.pts.length; - u32[w++] = o.z >>> 0; - f32[w++] = o.widthMm; - u32[w++] = dashes(o.dash); - col(o.color); - ring(o.pts); - } - for (const p of polylines) { - u32[w++] = p.pts.length; - u32[w++] = p.z >>> 0; - f32[w++] = p.widthMm; - u32[w++] = dashes(p.dash); - u32[w++] = p.widthScreen ? 1 : 0; - col(p.color); - ring(p.pts); - } - for (const a of arcs) { - f32[w++] = a.r; - f32[w++] = a.widthMm; - u32[w++] = dashes(a.dash); - col(a.color); - pts[pi++] = a.center[0]; - pts[pi++] = a.center[1]; - pts[pi++] = a.from[0]; - pts[pi++] = a.from[1]; - pts[pi++] = a.to[0]; - pts[pi++] = a.to[1]; - } - for (const l of lines) { - f32[w++] = l.widthMm; - u32[w++] = dashes(l.dash); - u32[w++] = l.z >>> 0; - col(l.color); - pts[pi++] = l.a[0]; - pts[pi++] = l.a[1]; - pts[pi++] = l.b[0]; - pts[pi++] = l.b[1]; - } - let so = 0; - for (let i = 0; i < texts.length; i++) { - const t = texts[i]; - f32[w++] = t.sizeMm; - u32[w++] = ALIGN[t.align] ?? 0; - u32[w++] = so; - u32[w++] = strs[i].length; - col(t.color); - pts[pi++] = t.pos[0]; - pts[pi++] = t.pos[1]; - bytes.set(strs[i], strOff + so); - so += strs[i].length; - } - return bytes; -} diff --git a/src/plan/toRenderScene.test.ts b/src/plan/toRenderScene.test.ts new file mode 100644 index 00000000..2bd0e453 --- /dev/null +++ b/src/plan/toRenderScene.test.ts @@ -0,0 +1,70 @@ +// Render-Szene aus dem Kern ([K3d], `core/src/plan_scene.rs`): Verkettung der 2D-Zeichenlinien, +// Kantennaht über Polygon-Grenzen, gedimmte Bereiche ohne Klonen, Binärszene passt zur +// Objekt-Szene, verdrängte Puffer werden neu abgelegt. (Bitgleich zur früheren TS-Fassung +// geprüft: Beispielprojekt, 400 Zufallslisten, grosses Projekt — s. TODO [K3d].) + +import { describe, expect, it } from "vitest"; +import { planSceneBin, planToRenderScene } from "./toRenderScene"; +import { generatePlan, generateVisibleLevelsPlan, materializeGreyed, materializeUnderlay } from "./generatePlan"; +import type { Primitive } from "./generatePlan"; +import { sampleProject } from "../model/sampleProject"; +import { flattenCategories } from "../model/types"; +import { planOf, randomPrims } from "./randomPrims.testing"; +import { planParts } from "./planParts"; +import { core } from "../engine/coreWasm"; + +const codes = new Set(flattenCategories(sampleProject.layers).map((c) => c.code)); + +const line = (ax: number, ay: number, bx: number, by: number, extra: Partial = {}): Primitive => + ({ kind: "line", a: { x: ax, y: ay }, b: { x: bx, y: by }, cls: "draw2d", weightMm: 0.25, drawingId: "d", ...extra }) as Primitive; + +describe("planToRenderScene (Kern)", () => { + it("verkettet 2D-Zeichenlinien zu Polylinie bzw. Umriss", () => { + const open = planToRenderScene(planOf([line(0, 0, 1, 0), line(1, 0, 1, 1), line(5, 5, 6, 6, { drawingId: undefined })])); + expect(open.polylines.map((p) => p.pts.length)).toEqual([3]); + expect(open.lines.length).toBe(1); + const ring = planToRenderScene(planOf([line(0, 0, 1, 0), line(1, 0, 1, 1), line(1, 1, 0, 0)])); + expect(ring.outlines.map((o) => o.pts.length)).toEqual([3]); + expect(ring.outlines[0].dash).toBeNull(); + }); + + it("näht unterdrückte Kanten zweier Polygone zu einem Ring", () => { + const a: Primitive = { kind: "polygon", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }], fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [1] }; + const b: Primitive = { kind: "polygon", pts: [{ x: 1, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 1 }, { x: 1, y: 1 }], fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [3] }; + const s = planToRenderScene(planOf([a, b])); + expect(s.fills.length).toBe(2); + expect(s.outlines.length).toBe(1); + expect(s.outlines[0].pts.length).toBe(6); + expect(s.outlines[0].z).toBe(3); + }); + + it("gedimmte Bereiche wirken wie materialisiertes `greyed`", () => { + for (let seed = 1; seed < 30; seed++) { + const prims = randomPrims(seed, 40); + const plan = planOf(prims, [[2, 15], [20, 33]]); + expect(JSON.stringify(planToRenderScene(plan))).toBe(JSON.stringify(planToRenderScene(materializeGreyed(plan, true)))); + expect(Buffer.from(planSceneBin(plan)).equals(Buffer.from(planSceneBin(materializeGreyed(plan, true))))).toBe(true); + } + const over = generateVisibleLevelsPlan(sampleProject, "og", codes, undefined, "mittel", false, false, () => ({ render: true, greyed: true, locked: false }), 100, true); + const plan = materializeUnderlay(over); + expect(plan.greyedRanges?.length).toBeGreaterThan(0); + expect(JSON.stringify(planToRenderScene(plan))).toBe(JSON.stringify(planToRenderScene(materializeGreyed(plan, true)))); + }); + + it("Binärszene: Zähler wie die Objekt-Szene", () => { + const plan = generatePlan(sampleProject, "eg", codes); + const s = planToRenderScene(plan); + const b = planSceneBin(plan); + const h = new Uint32Array(b.buffer, b.byteOffset, 12); + expect(String.fromCharCode(...b.subarray(0, 4))).toBe("DR2S"); + expect([...h.subarray(1, 8)]).toEqual([1, s.fills.length, s.outlines.length, s.polylines.length, s.arcs.length, s.lines.length, s.texts.length]); + expect(s.fills.length).toBeGreaterThan(10); + }); + + it("verdrängte Puffer werden neu abgelegt", () => { + const plan = generatePlan(sampleProject, "eg", codes); + const before = planSceneBin(plan); + for (const buf of planParts(plan).bufs) core().plan_buf_release(buf.hold); + expect(Buffer.from(planSceneBin(plan)).equals(Buffer.from(before))).toBe(true); + }); +}); diff --git a/src/plan/toRenderScene.ts b/src/plan/toRenderScene.ts index e3103326..0c7cd1c4 100644 --- a/src/plan/toRenderScene.ts +++ b/src/plan/toRenderScene.ts @@ -1,30 +1,24 @@ -// Flacht einen {@link Plan} (die eine Wahrheit aus generatePlan) auf das -// GPU-nahe Szenenformat des nativen render2d-Renderers ab: Füllpolygone, -// Umrisse, Linien und Textzeilen. Text wird zeilenweise geflacht (Rich-Text-Doc -// + Live-Zusatzzeilen) — die echten Glyphen rastert der Rust-Renderer über -// einen GPU-Glyphen-Atlas (glyphon/cosmic-text), keine Vektor-Ersatzschrift. +// Render-Szene eines {@link Plan} für render2d (Browser über WASM/WebGPU, natives Fenster über +// `push_native_scene`) und für den Druck-/SVG-Export. Die Geometrie (Füllungen, Umrisse, +// Polylinien, Bögen, Linien samt Maler-Reihenfolge `z`, Verkettung, Kantennaht, Schraffur-Läufe, +// Zickzack/Motiv) rechnet der Kern direkt aus dem Plan-Puffer ([K3d], `src-tauri/core/src/ +// plan_scene.rs`, über die Abschnitte aus `planParts.ts`) — ohne Umweg über `Primitive[]`. Hier +// bleibt das Text-Layout (Rich-Text-Zeilen + Live-Zusatzzeilen, die Glyphen rastert render2d) +// und das Durchreichen eingebetteter Bilder. // -// Das erzeugte Objekt matcht 1:1 die serde-Structs render2d::types::Scene +// Das Szenen-Objekt matcht 1:1 die serde-Structs render2d::types::Scene // { fills:[{pts,color}], outlines:[{pts,color,widthMm,dash}], // polylines:[{pts,color,widthMm,dash}], arcs:[{center,from,to,r,color,widthMm,dash}], // lines:[{a,b,color,widthMm,dash}], texts:[{pos,content,sizeMm,color,align}] } -// mit Point = [x,y] (Meter) und Rgba = [r,g,b,a] (0..1). -// -// Bögen werden NICHT hier tessellliert: der Rust-Renderer zeichnet sie -// mathematisch exakt per SDF-Fragment-Shader (`shaders::ARC_WGSL`, eine -// analytische Instanz je Bogen) — bei jeder Vergrößerung ein echter Kreis statt -// eines Vielecks, ohne Neu-Tessellierung. Strichmuster -// (`dash`, mm Papier) werden ebenfalls unverändert durchgereicht — das geometrische -// Zerschneiden in Teilstücke (`applyDashRuns`-Algorithmus) passiert erst NACH der -// Bogen-Tessellierung in Rust (`tessellate::split_dash`), damit die Phase über die -// gesamte (ggf. verkettete oder adaptiv tessellierte) Strecke durchläuft. +// mit Point = [x,y] (Meter) und Rgba = [r,g,b,a] (0..1). Bögen bleiben unvortesselliert +// (render2d zeichnet sie per SDF-Shader), Strichmuster (Papier-mm) werden durchgereicht. -import type { Plan, Primitive } from "./generatePlan"; -import { applyDashRuns, buildHatchRuns, zigzagPoints, motifPoints, DASH_MM_TO_M } from "./glPlan/glPlanHatch"; +import type { Plan } from "./generatePlan"; +import { inGreyedRange } from "./generatePlan"; import { docToLines, wrapDocToLines } from "../text/renderHtml"; import { docFromText } from "../text/richText"; - -type LinePrim = Extract; +import { core } from "../engine/coreWasm"; +import { greyedFlat, planParts, withPlanParts } from "./planParts"; export type RPoint = [number, number]; export type RRgba = [number, number, number, number]; @@ -133,57 +127,15 @@ export interface RScene { bounds: RBounds; } -const DEFAULT_LINE = "#1a1a1a"; - /** - * Strichfarben/-deckkraft je CSS-Klasse — Spiegel der `.plan-svg .`-Regeln - * in styles.css: Im SVG-Pfad ÜBERSTIMMT eine CSS-`stroke`-Property das inline - * gesetzte `stroke`-Attribut (Präsentationsattribut), d. h. für diese Klassen - * gilt IMMER die CSS-Farbe. Klassen ohne CSS-`stroke` (draw2d, stair-*, - * context-line) behalten die Modell-Farbe; context-line trägt zusätzlich - * `opacity: 0.7`, wall-axis `opacity: 0.85`. - */ -const CLS_STROKE: Record = { - "door-leaf": "#1a1a1a", - "door-swing": "#1a1a1a", - "door-frame": "#1a1a1a", - "window-glass": "#1a1a1a", - "wall-axis": "#4a453e", // var(--accent) des hellen Standard-Themes -}; -const CLS_OPACITY: Record = { - "wall-axis": 0.85, - "context-line": 0.7, -}; - -/** - * Fester Grauton gedimmter (greyed) Primitive — ECHTE Umfärbung statt - * Deckkraft (dünne Haarlinien auf dem hellen Zeichenblatt wären bei reiner - * Transparenz kaum erkennbar gedimmt). Gleicher Ton wie GREYED_COLOR in - * PlanView.tsx / GREY_RGB in glPlanCompile.ts (#8c8c8c ≈ 0.549). + * Fester Grauton gedimmter (greyed) Texte — gleicher Ton wie GREYED_COLOR in PlanView.tsx und + * `GREY_RGB` im Kern (#8c8c8c ≈ 0.549). */ const GREY_RGB = 0.549; -/** Farbe mit Klassen-Deckkraft multiplizieren, bei Greyed-Dimmung auf den festen Grauton umfärben. */ -function withOpacity(col: RRgba, cls: string | undefined, greyed: boolean | undefined): RRgba { - const o = cls ? CLS_OPACITY[cls] ?? 1 : 1; - const rgb: RRgba = greyed ? [GREY_RGB, GREY_RGB, GREY_RGB, col[3]] : col; - return o === 1 ? rgb : [rgb[0], rgb[1], rgb[2], rgb[3] * o]; -} - -/** - * Wie `withOpacity`, aber für FLÄCHEN-Füllung: gedimmte Flächen bleiben WEISS - * statt grau eingefärbt — nur der Umriss (weiterhin `withOpacity`) macht das - * Element als gedimmt erkennbar (Nutzer-Wunsch: "im Hintergrund nicht als - * graue Fläche gefüllt, sondern weiss mit nur den Linien sichtbar"). - */ -function withFillOpacity(col: RRgba, greyed: boolean | undefined): RRgba { - return greyed ? [1, 1, 1, col[3]] : col; -} - -/** Strichfarbe einer line/arc-Primitive: CSS-Klassen-Farbe > Modell-Farbe > Tinte. */ -function strokeColorFor(cls: string | undefined, color: string | undefined): RRgba { - const css = cls ? CLS_STROKE[cls] : undefined; - return toRgba(css ?? color ?? DEFAULT_LINE, 1) ?? [0.1, 0.1, 0.1, 1]; +/** Textfarbe gedimmt: auf den festen Grauton umfärben (Deckkraft bleibt). */ +function greyedColor(col: RRgba, greyed: boolean | undefined): RRgba { + return greyed ? [GREY_RGB, GREY_RGB, GREY_RGB, col[3]] : col; } /** 1 Punkt (pt) in Papier-Millimetern. */ @@ -194,8 +146,7 @@ const PT_TO_MM = 25.4 / 72; * Modus: dort belegt 1 pt Schrift (1/72)·0.0254·100 Modell-Meter. Der native * Renderer rechnet im Anzeigemodus mit `paper_scale_n = 100`, damit ist * `sizeMm = pt · PT_TO_MM` exakt die Browser-Darstellung. Für Aufrufer MIT - * Massstabskontext (z. B. PDF-Export) übersteuert `planToRenderScene`s - * `paperScaleN`-Parameter diesen Default — siehe `mmToM` dort. + * Massstabskontext (z. B. PDF-Export) übersteuert `paperScaleN` diesen Default. */ const STAMP_DEFAULT_N = 100; @@ -208,7 +159,7 @@ const NAMED: Record = { transparent: "none", }; -/** Hex/Named-Farbe → [r,g,b,a] in 0..1, oder null bei "none"/leer. */ +/** Hex/Named-Farbe → [r,g,b,a] in 0..1, oder null bei "none"/leer (Kern: `plan_scene::to_rgba`). */ function toRgba(input: string | undefined, alpha = 1): RRgba | null { if (!input) return null; let h = input.trim().toLowerCase(); @@ -232,318 +183,23 @@ function toRgba(input: string | undefined, alpha = 1): RRgba | null { return [r, g, b, a]; } -/** Zwei Modell-Punkte (Meter) als gleich behandeln (Verkettungs-Toleranz). */ -function samePt(a: RPoint, b: RPoint): boolean { - return Math.abs(a[0] - b[0]) < 1e-6 && Math.abs(a[1] - b[1]) < 1e-6; -} - -/** Gleicher Linienstil (für das Verketten aufeinanderfolgender 2D-Zeichenlinien). */ -function sameLineStyle(a: LinePrim, b: LinePrim): boolean { - return ( - a.cls === b.cls && - a.weightMm === b.weightMm && - (a.color ?? "") === (b.color ?? "") && - JSON.stringify(a.dash ?? null) === JSON.stringify(b.dash ?? null) - ); -} - /** - * Zerlegt einen Polygon-Ring in zusammenhängende Läufe SICHTBARER Kanten (die - * `noStroke`-Kanten werden ausgelassen). Jeder Lauf beginnt an einer sichtbaren - * Kante, deren Vorgänger unterdrückt ist. Portiert aus PlanView.visibleEdgeRuns — - * so bekommen die inneren Ecken eine Gehrung statt Stumpfkappen. + * Textzeilen und eingebettete Bilder eines Plans in Zeichenreihenfolge. Layout wie im SVG-Pfad + * (PlanView, case "text"): Rich-Text-Zeilen + Live-Zusatzzeilen, Block vertikal um den Anker + * zentriert, Zeilenvorschub 1.3·Basisgröße; Einzeltexte (`drawingText`) top-down ab `at` mit + * `heightM` als Basisgrösse. `paperScaleN` (1:N) rechnet Papier-mm in Modell-Meter um. */ -function visibleEdgeRuns(pts: RPoint[], noStroke: number[]): RPoint[][] { - const n = pts.length; - const skip = new Set(noStroke.map((i) => ((i % n) + n) % n)); - if (skip.size >= n || n < 2) return []; - const visible = (i: number) => !skip.has(((i % n) + n) % n); - const runs: RPoint[][] = []; - for (let s = 0; s < n; s++) { - if (!visible(s) || visible(s - 1 + n)) continue; // kein Lauf-Anfang - const run: RPoint[] = [pts[s]]; - let j = s; - while (visible(j) && j - s < n) { - run.push(pts[(j + 1) % n]); - j++; - } - runs.push(run); - } - return runs; -} - -/** - * Näht sichtbare Kantenläufe ÜBER Polygon-Grenzen hinweg zusammen: Läufe mit - * koinzidenten Endpunkten (und GENAU zwei beteiligten Enden — T-Stösse bleiben - * unangetastet) werden zu einer Kette verbunden, ggf. mit Richtungsumkehr. - * Schliesst sich eine Kette, wird sie als geschlossener Ring markiert. So - * bekommt eine Wandecke, deren zwei Schenkel aus VERSCHIEDENEN Wand-Polygonen - * stammen, dieselbe Gehrung wie die inneren Ecken eines einzelnen Laufs - * (statt zweier Stumpfkappen, die eine Kerbe bilden). - */ -function stitchRuns(runs: RPoint[][]): { pts: RPoint[]; closed: boolean }[] { - const eps = 1e-5; - const key = (p: RPoint) => `${Math.round(p[0] / eps)},${Math.round(p[1] / eps)}`; - // Endpunkt-Belegung zählen: verkettet wird nur, wo genau ZWEI Enden liegen. - const endCount = new Map(); - for (const r of runs) { - for (const p of [r[0], r[r.length - 1]]) { - endCount.set(key(p), (endCount.get(key(p)) ?? 0) + 1); - } - } - const joinable = (p: RPoint) => endCount.get(key(p)) === 2; - - const pool = runs.map((pts) => ({ pts, used: false })); - const out: { pts: RPoint[]; closed: boolean }[] = []; - for (const seed of pool) { - if (seed.used) continue; - seed.used = true; - let chain = seed.pts; - let extended = true; - while (extended && !(chain.length > 2 && samePt(chain[0], chain[chain.length - 1]))) { - extended = false; - const head = chain[0]; - const tail = chain[chain.length - 1]; - for (const cand of pool) { - if (cand.used) continue; - const cs = cand.pts[0]; - const ce = cand.pts[cand.pts.length - 1]; - if (joinable(tail) && samePt(tail, cs)) { - chain = chain.concat(cand.pts.slice(1)); - } else if (joinable(tail) && samePt(tail, ce)) { - chain = chain.concat([...cand.pts].reverse().slice(1)); - } else if (joinable(head) && samePt(head, ce)) { - chain = cand.pts.concat(chain.slice(1)); - } else if (joinable(head) && samePt(head, cs)) { - chain = [...cand.pts].reverse().concat(chain.slice(1)); - } else { - continue; - } - cand.used = true; - extended = true; - break; - } - } - const closed = chain.length > 3 && samePt(chain[0], chain[chain.length - 1]); - out.push({ pts: closed ? chain.slice(0, -1) : chain, closed }); - } - return out; -} - -/** - * Wandelt einen Plan in eine native render2d-Szene um. Zusammenhängende Umriss- - * und Zeichnungskanten werden zu OFFENEN Polylinien verkettet (gehrte Ecken); - * nur genuin einzelne Segmente (Türblätter, Referenzlinien) bleiben `lines`. - * - * `paperScaleN` ist der Massstab-Nenner N (1:N), mit dem die vertikale - * Zeilenposition mehrzeiliger Stempel-Texte in Modell-Meter umgerechnet wird - * (Papier-mm sind massstabsunabhängig, ihre Weltgrösse aber nicht — analog zu - * PlanViews `nRef`, s. `PlanView.tsx` case "text"). Default 100 für Aufrufer - * ohne Massstabskontext (WASM-Viewport, `nativeSync.ts`). - */ -export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): RScene { +export function planSceneTexts(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): { texts: RText[]; images: RImage[] } { const mmToM = paperScaleN / 1000; // Papier-mm → Modell-Meter beim gewählten Massstab. - const fills: RFill[] = []; - const outlines: ROutline[] = []; - const polylines: RPolyline[] = []; - const arcs: RArc[] = []; - const lines: RLine[] = []; const texts: RText[] = []; const images: RImage[] = []; - - // Sichtbare Umriss-Läufe werden erst GESAMMELT (nach Stil gruppiert) und am - // Ende über Polygon-Grenzen hinweg zusammengenäht — erst dadurch bekommen - // Wand-zu-Wand-Ecken (zwei Polygone!) eine Gehrung statt einer Kerbe. - const edgeRunGroups = new Map(); - const collectEdgeRun = (run: RPoint[], color: RRgba, widthMm: number, z: number) => { - const k = `${color.join(",")}|${widthMm}`; - let g = edgeRunGroups.get(k); - if (!g) { - g = { color, widthMm, runs: [], z }; - edgeRunGroups.set(k, g); - } - g.runs.push(run); - // Die Kette zeichnet, wenn ihr SPÄTESTER Beitrag im SVG zeichnen würde. - g.z = Math.max(g.z, z); - }; - - // Maler-Reihenfolge: läuft in EXAKT der Reihenfolge mit, in der der SVG-Pfad - // die Elemente zeichnet (Primitive in Array-Reihenfolge; je Polygon Füllung → - // Schraffur → Umriss). Jedes emittierte Szenen-Element bekommt das nächste z. - let zc = 0; - - // Laufender, verketteter 2D-Zeichnungs-Zug (gleiche drawingId + Stil, End-an-Start). - let curPts: RPoint[] | null = null; - let curSrc: LinePrim | null = null; - const flushRun = () => { - if (curPts && curSrc && curPts.length >= 2) { - const col = withOpacity(strokeColorFor(curSrc.cls, curSrc.color), curSrc.cls, curSrc.greyed); - const closed = curPts.length > 2 && samePt(curPts[0], curPts[curPts.length - 1]); - const dash = curSrc.dash ?? null; - if (closed) { - outlines.push({ pts: curPts.slice(0, -1), color: col, widthMm: curSrc.weightMm, dash, z: zc++ }); - } else { - polylines.push({ pts: curPts, color: col, widthMm: curSrc.weightMm, dash, z: zc++ }); - } - } - curPts = null; - curSrc = null; - }; - - for (const p of plan.primitives) { - if (p.kind === "polygon") { - flushRun(); - const pts: RPoint[] = p.pts.map((v) => [v.x, v.y]); - if (pts.length < 2) continue; - - // Füllung - const fillCol = toRgba(p.fill, 1); - if (fillCol && pts.length >= 3) { - fills.push({ pts, color: withFillOpacity(fillCol, p.greyed), z: zc++ }); - } - - // Schraffur: die aufs Polygon geclippten Musterlinien wie im Browser - // (glPlanHatch — identische Geometrie), als Polylinien. "none"/"solid" - // brauchen keine Linien (solid deckt die Füllung farbig ab). Bild-/ - // Verlauf-Schraffuren (kind==="image"/"gradient") kann die render2d- - // Szene nicht tragen (keine Textur/kein echter Verlauf) → FALLBACK: nur - // die neutrale Poché-Füllung (oben), keine Musterlinien. Der Random- - // Untermodus läuft transparent über `buildHatchRuns` (Streu-Striche). - if ( - p.hatch && - p.hatch.kind !== "image" && - p.hatch.kind !== "gradient" && - p.hatch.pattern !== "none" && - p.hatch.pattern !== "solid" - ) { - const hatchCol = withOpacity( - toRgba(p.hatch.color, 1) ?? [0.1, 0.1, 0.1, 1], - undefined, - p.greyed, - ); - // Strichbreite: ein GEWÖHNLICHER Papier-mm-Stift (0.02 mm), wie jede - // andere Linie — nicht mehr an die Musterkachel/Bildschirm-px - // gekoppelt (siehe RPolyline.widthScreen-Kommentar). - const hatchMm = p.hatch.lineWeight > 0 ? p.hatch.lineWeight : 0.13; - const runs = applyDashRuns(buildHatchRuns(p.pts, p.hatch), p.hatch.dash); - // Alle Musterläufe eines Polygons teilen EIN z (überlappen einander nicht). - const hatchZ = zc++; - for (const run of runs) { - if (run.length >= 2) { - polylines.push({ - pts: run.map((v) => [v.x, v.y]), - color: hatchCol, - widthMm: hatchMm, - z: hatchZ, - }); - } - } - } - - // Umriss - const strokeColRaw = toRgba(p.stroke, 1); - if (strokeColRaw && p.strokeWidthMm > 0) { - const strokeCol = withOpacity(strokeColRaw, undefined, p.greyed); - const suppressed = p.noStrokeEdges ?? []; - if (suppressed.length === 0) { - // Ganzer Ring → geschlossener, gehrter Umriss. - outlines.push({ pts, color: strokeCol, widthMm: p.strokeWidthMm, z: zc++ }); - } else { - // Nur die sichtbaren Kanten — sammeln, die Naht ans Ende verschoben. - const runZ = zc++; - for (const run of visibleEdgeRuns(pts, suppressed)) { - collectEdgeRun(run, strokeCol, p.strokeWidthMm, runZ); - } - } - } - } else if (p.kind === "line") { - if (p.zigzag) { - // Zickzack-Linie: als Polylinie tesselliert (render2d kennt keinen - // Zickzack-Primitiv). amplitude/wavelength sind Papier-mm → Modell-Meter - // über dieselbe Kopplung wie Strichmuster (DASH_MM_TO_M). Nicht verketten. - flushRun(); - const amp = p.zigzag.amplitude * DASH_MM_TO_M; - const wav = p.zigzag.wavelength * DASH_MM_TO_M; - const zpts = zigzagPoints(p.a, p.b, amp, wav); - const col = withOpacity(strokeColorFor(p.cls, p.color), p.cls, p.greyed); - if (zpts.length >= 2) { - polylines.push({ - pts: zpts.map((v) => [v.x, v.y]), - color: col, - widthMm: p.weightMm, - z: zc++, - }); - } - } else if (p.motif) { - // Custom-Motiv: entlang der Linie gekachelt (Papier-mm → Modell-Meter via - // DASH_MM_TO_M) → Polylinie. Nicht verketten (wie Zickzack). - flushRun(); - const mpts = motifPoints(p.a, p.b, p.motif, DASH_MM_TO_M); - const col = withOpacity(strokeColorFor(p.cls, p.color), p.cls, p.greyed); - if (mpts.length >= 2) { - polylines.push({ - pts: mpts.map((v) => [v.x, v.y]), - color: col, - widthMm: p.weightMm, - z: zc++, - }); - } - } else if (p.drawingId) { - // Aufeinanderfolgende 2D-Zeichenlinien gleicher drawingId/Stil verketten. - const a: RPoint = [p.a.x, p.a.y]; - const b: RPoint = [p.b.x, p.b.y]; - if (curPts && curSrc && sameLineStyle(curSrc, p) && samePt(curPts[curPts.length - 1], a)) { - curPts.push(b); - } else { - flushRun(); - curPts = [a, b]; - curSrc = p; - } - } else { - // Genuin einzelnes Segment (Türblatt, Referenzlinie, Symbol) → Stumpfkappen ok. - flushRun(); - const col = withOpacity(strokeColorFor(p.cls, p.color), p.cls, p.greyed); - lines.push({ a: [p.a.x, p.a.y], b: [p.b.x, p.b.y], color: col, widthMm: p.weightMm, dash: p.dash ?? null, z: zc++ }); - } - } else if (p.kind === "arc") { - flushRun(); - // Farbe wie im SVG: CSS-Klassen-Regel (z. B. .door-swing → #1a1a1a). - const col = withOpacity(strokeColorFor(p.cls, undefined), p.cls, p.greyed); - // Bogen unvortessellliert an Rust übergeben (`RArc`) — die exakte runde - // Darstellung (analytischer SDF-Shader, `ARC_WGSL`) und ein evtl. Strich- - // muster übernimmt der native Renderer (`compile_scene`) drüben. - arcs.push({ - center: [p.center.x, p.center.y], - from: [p.from.x, p.from.y], - to: [p.to.x, p.to.y], - r: p.r, - color: col, - widthMm: p.weightMm, - dash: p.dash ?? null, - }); - } else if (p.kind === "drawingCircle" || p.kind === "drawingArc") { - // Der native Renderer hat kein Kreis-/Bogen-Primitiv → hier tessellieren - // (der SVG-Pfad zeichnet sie glatt). Kreis = voller Umlauf, Bogen = a0..a1. - flushRun(); - const col = withOpacity(toRgba(p.stroke, 1) ?? [0.1, 0.1, 0.1, 1], undefined, p.greyed); - const TAU = Math.PI * 2; - const a0 = p.kind === "drawingArc" ? p.a0 : 0; - const sweep = p.kind === "drawingArc" ? (((p.a1 - p.a0) % TAU) + TAU) % TAU : TAU; - const N = Math.max(8, Math.ceil(sweep / (Math.PI / 32))); - const pts: RPoint[] = []; - for (let i = 0; i <= N; i++) { - const t = a0 + (sweep * i) / N; - pts.push([p.center.x + p.r * Math.cos(t), p.center.y + p.r * Math.sin(t)]); - } - polylines.push({ pts, color: col, widthMm: p.weightMm, dash: p.dash ?? null, z: zc++ }); - } else if (p.kind === "text") { - // "text": zeilenweise flachen — die ECHTEN Glyphen rastert der Rust- - // Renderer über einen GPU-Glyphen-Atlas (glyphon, dieselbe Font-Familie - // wie im Browser). Layout identisch zum SVG-Pfad in PlanView (case - // "text"): Rich-Text-Zeilen + Live-Zusatzzeilen, Block vertikal um den - // Anker zentriert, Zeilenvorschub 1.3·Basisgröße. - flushRun(); - const defCol = withOpacity(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], undefined, p.greyed); + const ranges = plan.greyedRanges; + const prims = plan.primitives; + for (let i = 0; i < prims.length; i++) { + const p = prims[i]; + if (p.kind === "text") { + const greyed = p.greyed || inGreyedRange(ranges, i); + const defCol = greyedColor(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], greyed); // unitPerPt = PT_TO_MM → tspan.fontSize ist direkt die Papier-mm-Größe. const docLines = docToLines(p.doc, { x: 0, @@ -560,14 +216,8 @@ export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAUL // Runs einer Zeile werden zusammengelegt (ein Buffer je Zeile); // Größe/Farbe des größten bzw. ersten Runs gelten für die Zeile. content: line.tspans.map((t) => t.text).join(""), - sizeMm: line.tspans.length - ? Math.max(...line.tspans.map((t) => t.fontSize)) - : baseMm, - color: withOpacity( - toRgba(line.tspans[0]?.fill ?? p.color, 1) ?? defCol, - undefined, - p.greyed, - ), + sizeMm: line.tspans.length ? Math.max(...line.tspans.map((t) => t.fontSize)) : baseMm, + color: greyedColor(toRgba(line.tspans[0]?.fill ?? p.color, 1) ?? defCol, greyed), align: line.align, }); } @@ -592,14 +242,11 @@ export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAUL }); } } else if (p.kind === "drawingText") { - // Modellverankerter Einzeltext (Text-Werkzeug/DXF-Import) — wie "text" - // oben zeilenweise geflacht, aber TOP-DOWN ab `at` (kein vertikal - // zentrierter Block) und `heightM` (Modell-Meter) als Basisgrösse statt - // `basePt` (Papier-Punkt) — der Text bleibt so, wie bisher, massstabsfrei - // an der Modellgeometrie verankert (kein Papier-Punkt-Bezug nötig). - flushRun(); + // Modellverankerter Einzeltext (Text-Werkzeug/DXF-Import): top-down ab `at`, `heightM` + // (Modell-Meter) als Basisgrösse — massstabsfrei an der Modellgeometrie verankert. + const greyed = p.greyed || inGreyedRange(ranges, i); const doc = p.doc ?? docFromText(p.text, p.marks ?? {}); - const defCol = withOpacity(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], undefined, p.greyed); + const defCol = greyedColor(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], greyed); const unitPerPt = PT_TO_MM * mmToM; // pt (Run-Override) -> Papier-mm -> Modell-Meter. const basePt = unitPerPt > 0 ? p.heightM / unitPerPt : 0; const lineHeight = p.heightM * 1.25; @@ -618,48 +265,132 @@ export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAUL if (k > 0) dy += line.lineHeight; const content = line.tspans.map((t) => t.text).join(""); if (!content.trim()) return; - const sizeM = line.tspans.length - ? Math.max(...line.tspans.map((t) => t.fontSize)) - : p.heightM; + const sizeM = line.tspans.length ? Math.max(...line.tspans.map((t) => t.fontSize)) : p.heightM; texts.push({ pos: [p.at.x, p.at.y - dy], content, sizeMm: unitPerPt > 0 ? sizeM / mmToM : sizeM, - color: withOpacity( - toRgba(line.tspans[0]?.fill ?? p.color, 1) ?? defCol, - undefined, - p.greyed, - ), + color: greyedColor(toRgba(line.tspans[0]?.fill ?? p.color, 1) ?? defCol, greyed), align: line.align, }); }); } else if (p.kind === "drawingImage") { - // Eingebettetes Rasterbild — keine Rust-Textur (s. `RImage`); wird vom - // GPU-Backend ignoriert (`useGpuRenderer` schaltet bei Bildern im Plan - // ohnehin auf den SVG-Pfad um), `sceneToPrintSvg.ts` liest es für den PDF-Export. - flushRun(); - images.push({ - min: [p.min.x, p.min.y], - max: [p.max.x, p.max.y], - src: p.src, - opacity: p.opacity, - }); + // Eingebettetes Rasterbild — keine Rust-Textur (s. `RImage`); `sceneToPrintSvg.ts` liest es. + images.push({ min: [p.min.x, p.min.y], max: [p.max.x, p.max.y], src: p.src, opacity: p.opacity }); } } - flushRun(); - - // Gesammelte Umriss-Läufe polygonübergreifend zusammennähen: geschlossene - // Ketten als Ring (Gehrung auch an der Naht), offene als Polylinie. - for (const g of edgeRunGroups.values()) { - for (const chain of stitchRuns(g.runs)) { - if (chain.pts.length < 2) continue; - if (chain.closed) { - outlines.push({ pts: chain.pts, color: g.color, widthMm: g.widthMm, z: g.z }); - } else { - polylines.push({ pts: chain.pts, color: g.color, widthMm: g.widthMm, z: g.z }); - } - } - } - - return { fills, outlines, polylines, arcs, lines, texts, images, bounds: { ...plan.bounds } }; + return { texts, images }; +} + +const ALIGN: Record = { left: 0, center: 1, right: 2 }; +const textEncoder = new TextEncoder(); + +/** Leere render2d-Szene (nur Kopf), falls der Kern nichts liefern kann. */ +function emptySceneBin(): Uint8Array { + const b = new Uint8Array(48); + b.set([0x44, 0x52, 0x32, 0x53], 0); // "DR2S" + new DataView(b.buffer).setUint32(4, 1, true); + return b; +} + +/** + * render2d-Szene (Binärformat v1, `render2d/src/scene_bin.rs`) für `set_scene_bin` bzw. + * `push_native_scene`. Geometrie aus dem Kern, Texte aus {@link planSceneTexts}; + * `plan.greyedRanges` gelten wie materialisiertes `greyed`. + */ +export function planSceneBin(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): Uint8Array { + const { texts } = planSceneTexts(plan, paperScaleN); + const nums = new Float64Array(texts.length * 9); + const strs = texts.map((t) => textEncoder.encode(t.content)); + let nBytes = 0; + for (const s of strs) nBytes += s.length; + const bytes = new Uint8Array(nBytes); + let o = 0; + texts.forEach((t, i) => { + nums.set([t.pos[0], t.pos[1], t.sizeMm, t.color[0], t.color[1], t.color[2], t.color[3], ALIGN[t.align] ?? 0, strs[i].length], i * 9); + bytes.set(strs[i], o); + o += strs[i].length; + }); + const greyed = greyedFlat(plan); + const out = withPlanParts(planParts(plan), (segs) => core().plan_scene_bin(segs, greyed, nums, bytes)); + return out.length ? out : emptySceneBin(); +} + +type SceneGeometry = Pick; + +/** Verlustfreie Kern-Szene (Format s. `plan_scene.rs`) → Szenen-Objekte (Feldreihenfolge wie früher). */ +function decodeSceneF64(f: Float64Array): SceneGeometry { + const out: SceneGeometry = { fills: [], outlines: [], polylines: [], arcs: [], lines: [] }; + if (f.length < 5) return out; + let k = 5; + const pts = (n: number): RPoint[] => { + const r: RPoint[] = new Array(n); + for (let i = 0; i < n; i++, k += 2) r[i] = [f[k], f[k + 1]]; + return r; + }; + const color = (): RRgba => { + const c: RRgba = [f[k], f[k + 1], f[k + 2], f[k + 3]]; + k += 4; + return c; + }; + /** −2 fehlt (undefined) · −1 null · n Werte. */ + const dash = (): number[] | null | undefined => { + const n = f[k++]; + if (n === -2) return undefined; + if (n === -1) return null; + const d = Array.from(f.subarray(k, k + n)); + k += n; + return d; + }; + for (let i = 0; i < f[0]; i++) { + const n = f[k]; + const z = f[k + 1]; + k += 2; + const c = color(); + out.fills.push({ pts: pts(n), color: c, z }); + } + for (let j = 0; j < 2; j++) { + const list = j === 0 ? out.outlines : out.polylines; + for (let i = 0; i < f[1 + j]; i++) { + const n = f[k]; + const z = f[k + 1]; + const widthMm = f[k + 2]; + k += 3; + const d = dash(); + const c = color(); + const p = pts(n); + list.push(d === undefined ? { pts: p, color: c, widthMm, z } : { pts: p, color: c, widthMm, dash: d, z }); + } + } + for (let i = 0; i < f[3]; i++) { + const r = f[k]; + const widthMm = f[k + 1]; + k += 2; + const d = dash() ?? null; + const c = color(); + const [center, from, to] = pts(3); + out.arcs.push({ center, from, to, r, color: c, widthMm, dash: d }); + } + for (let i = 0; i < f[4]; i++) { + const z = f[k]; + const widthMm = f[k + 1]; + k += 2; + const d = dash() ?? null; + const c = color(); + const [a, b] = pts(2); + out.lines.push({ a, b, color: c, widthMm, dash: d, z }); + } + return out; +} + +/** + * Plan → Render-Szene als Objekte (Druck-/SVG-Export, `dossier-cli plan --format json`). + * `paperScaleN` ist der Massstab-Nenner N (1:N) für die Zeilenlage der Texte (s. + * {@link planSceneTexts}). + */ +export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): RScene { + const greyed = greyedFlat(plan); + const geo = decodeSceneF64(withPlanParts(planParts(plan), (segs) => core().plan_scene_f64(segs, greyed))); + const { texts, images } = planSceneTexts(plan, paperScaleN); + return { ...geo, texts, images, bounds: { ...plan.bounds } }; } diff --git a/src/views/plan/nativeSync.ts b/src/views/plan/nativeSync.ts index d8d9a7fe..fdc3d9ae 100644 --- a/src/views/plan/nativeSync.ts +++ b/src/views/plan/nativeSync.ts @@ -1,7 +1,7 @@ // Live-Spiegelung in die nativen wgpu-Fenster (src-tauri/src/native.rs): schiebt // die AKTUELL sichtbare 2D-Szene bzw. die geflachten 3D-Wände debounced per // Tauri-Command an die native Event-Loop. Es wird EXAKT dieselbe Ableitung -// benutzt wie für die Browser-Ansicht (planToRenderScene auf dem sichtbaren +// benutzt wie für die Browser-Ansicht (planSceneBin aus dem Kern auf dem sichtbaren // Plan, projectToWalls3d aufs Projekt) — 1:1-Parität inkl. Türschwenk, // Fenster-Symbolen und Raumstempel-Text (echte Glyphen via GPU-Atlas in Rust). // @@ -10,9 +10,9 @@ // geschluckt (console.debug), damit die App nie daran scheitert. import type { Plan } from "../../core"; -import { materializeGreyed, materializeUnderlay } from "../../core"; +import { materializeUnderlay } from "../../core"; import type { Project } from "../../model/types"; -import { encodeRenderScene, planToRenderScene } from "../../core"; +import { planSceneBin } from "../../core"; import { projectToModel3d, TRUCK_MESH_READY_EVENT } from "../../core"; /** Sammel-Fenster: Modelländerungen werden gebündelt gepusht (nicht je Frame). */ @@ -71,9 +71,9 @@ export function pushNativeScene(plan: Plan): void { clearTimeout(sceneTimer); sceneTimer = setTimeout(async () => { if (!(await isNativeEnabled())) return; - // planToRenderScene liest `greyed` am Primitiv → gedimmte Referenz-Ebenen materialisieren. - // Binärpuffer als Request-Body (Rust: `render2d::scene_bin`), kein JSON. - void invokeNative("push_native_scene", encodeRenderScene(planToRenderScene(materializeGreyed(materializeUnderlay(plan), true)))); + // Szene aus dem Kern (Plan-Puffer, gedimmte Referenz-Ebenen über `greyedRanges`), als + // Binärpuffer im Request-Body (Rust: `render2d::scene_bin`), kein JSON. + void invokeNative("push_native_scene", planSceneBin(materializeUnderlay(plan))); }, DEBOUNCE_MS); } diff --git a/src/views/plan/useWasmPlanRenderer.ts b/src/views/plan/useWasmPlanRenderer.ts index 3d822b07..b6cc13b5 100644 --- a/src/views/plan/useWasmPlanRenderer.ts +++ b/src/views/plan/useWasmPlanRenderer.ts @@ -14,7 +14,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import type { Plan } from "../../core"; -import { encodeRenderScene, planToRenderScene } from "../../core"; +import { planSceneBin } from "../../core"; interface ViewBox { x: number; @@ -115,7 +115,7 @@ export function useWasmPlanRenderer( const r = rendererRef.current; if (!r || !plan) return; try { - r.set_scene_bin(encodeRenderScene(planToRenderScene(plan))); + r.set_scene_bin(planSceneBin(plan)); } catch (e) { console.warn("render2d set_scene_bin fehlgeschlagen:", e); } From 1a90f954dab24dc42ecdca6a6afa44af54a15dd6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 23:14:48 +0000 Subject: [PATCH 2/5] =?UTF-8?q?[K3d]=20Auswahl/Picken=20im=20Kern=20auf=20?= =?UTF-8?q?dem=20Plan-Puffer=20(r=C3=A4umlicher=20Index)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit core/src/plan_pick.rs (+ web/plan_pick.rs, TS-Fassade src/plan/planView/planPick.ts): Index je Plan über die Abschnitte gehaltener Plan-Puffer — Raster der 2D-Zeichenlinien (gleiche Zellen/Reihenfolge wie segmentIndex.ts → gleiche Treffer), Polygone unter dem Punkt (oberstes/ unterstes, mit Pick-Feld), Symbol-Linien/-Bögen in Client-Pixeln, Kreis-/Bogen-Ringe, Besitzer (ownedBy). PlanView fragt nur noch ab (hitTest, pickRoom/Roof/Stair/Opening/…, pickDrawing, nearDrawingIds, Hervorhebung); segmentIndex.ts, ownerIndex.ts und die Schleifen über alle Primitive je Mausbewegung gelöscht. Gleich zur alten Fassung (25k Abfragen: Beispielprojekt + Überlagerung, 150 Zufallspläne, grosses Projekt). Grosses Projekt + 100k 2D-Linien: alle Hover-Abfragen zusammen 90 ms → 30 µs je Mausbewegung, Aufbau ~100 ms (lazy). Kern-only-Puffer ohne Schraffur-JSON (hatchJson: false). Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/plan_buf.rs | 17 + src-tauri/core/src/plan_pick.rs | 693 +++++++++++++++++++++++ src-tauri/core/src/web/mod.rs | 1 + src-tauri/core/src/web/plan_pick.rs | 76 +++ src/core/index.ts | 14 +- src/plan/planBuf.ts | 5 +- src/plan/planParts.ts | 8 +- src/plan/planView/ownerIndex.test.ts | 44 -- src/plan/planView/ownerIndex.ts | 66 --- src/plan/planView/planPick.test.ts | 132 +++++ src/plan/planView/planPick.ts | 149 +++++ src/plan/planView/segmentIndex.test.ts | 75 --- src/plan/planView/segmentIndex.ts | 163 ------ src/plan/planView/underlayAccess.test.ts | 8 +- src/plan/toRenderScene.test.ts | 4 +- src/views/plan/PlanView.tsx | 284 +++------- 17 files changed, 1173 insertions(+), 567 deletions(-) create mode 100644 src-tauri/core/src/plan_pick.rs create mode 100644 src-tauri/core/src/web/plan_pick.rs delete mode 100644 src/plan/planView/ownerIndex.test.ts delete mode 100644 src/plan/planView/ownerIndex.ts create mode 100644 src/plan/planView/planPick.test.ts create mode 100644 src/plan/planView/planPick.ts delete mode 100644 src/plan/planView/segmentIndex.test.ts delete mode 100644 src/plan/planView/segmentIndex.ts diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 604411fc..6a16805c 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -60,6 +60,7 @@ pub mod curves; pub mod skeleton; pub mod plan_parts; pub mod plan_scene; +pub mod plan_pick; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/plan_buf.rs b/src-tauri/core/src/plan_buf.rs index 07f9c785..90ff7109 100644 --- a/src-tauri/core/src/plan_buf.rs +++ b/src-tauri/core/src/plan_buf.rs @@ -648,6 +648,23 @@ impl<'a> View<'a> { Some(out) } + /// Absoluter Wortindex des Eintrags `i` (Kopf `[tag, flags, pickKind, pickStr]`, danach die + /// festen Felder) — für Leser, die nur wenige Wörter brauchen ([`View::word`]). + pub(crate) fn rec_at(&self, i: usize) -> Option { + if i >= self.n_prims { + return None; + } + let off = whole(self.w.get(self.offsets_at + i)?)?; + let at = self.recs_at.checked_add(off)?; + (at < self.recs_end).then_some(at) + } + + /// Wort `k` des `f64`-Teils (s. [`View::rec_at`]). + #[inline] + pub(crate) fn word(&self, k: usize) -> Option { + self.w.get(k) + } + pub(crate) fn rec(&self, i: usize) -> Option { if i >= self.n_prims { return None; diff --git a/src-tauri/core/src/plan_pick.rs b/src-tauri/core/src/plan_pick.rs new file mode 100644 index 00000000..11d9637b --- /dev/null +++ b/src-tauri/core/src/plan_pick.rs @@ -0,0 +1,693 @@ +//! Auswahl/Picken im Grundriss ([K3d], früher `segmentIndex.ts`, `ownerIndex.ts` und die +//! Schleifen über `plan.primitives` in `PlanView.tsx`): ein räumlicher Index über einem +//! zusammengesetzten Plan ([`crate::plan_parts`]), den TS nur noch abfragt. Ergebnisse sind +//! Indizes in `plan.primitives`. +//! +//! - 2D-Zeichenlinien (`line` mit nicht-leerer `drawingId`): gleichförmiges Raster wie die frühere +//! TS-Fassung (gleiche Zellgrösse, gleiche Reihenfolge → gleiche Treffer, auch bei Gleichstand): +//! nächstes Segment bzw. alle Segmente im Umkreis. +//! - Polygone (Punkt-in-Polygon wie `pointInPolygon`): oberstes bzw. unterstes Polygon unter dem +//! Punkt, wahlweise nur mit einer bestimmten Pick-Id (Raum, Dach, Treppe, …), oder alle. +//! - Symbol-Linien und -Bögen mit Öffnungs-/Treppen-Id: nächste in Bildschirm-Pixeln (dieselbe +//! Abbildung Modell → Client wie `toScreen` + `vbToClient` in PlanView). +//! - Kreise/Bögen der 2D-Zeichnung: Abstand zum Ring wie `distToDrawingRing`. +//! - Besitzer: alle Primitive einer Id (wie `ownedBy`). +//! +//! Pick-Arten (Bit `1 << art`): 1 wall · 2 drawing · 3 ceiling · 4 opening · 5 stair · 6 room · +//! 7 extrudedSolid · 8 contextObject · 9 column · 10 roof · 11 sectionLine. Das Bit einer Art ist +//! gesetzt, wenn ihre Id nicht leer ist (TS: `p.roomId && …`). + +use crate::jsmath::hypot; +use crate::jsnum; +use crate::plan_buf::{whole, View, F_IDS, T_ARC, T_CIRCLE, T_DRAWING_ARC, T_LINE, T_POLYGON}; +use crate::plan_parts::pick_ids; +use std::collections::HashMap; +use std::rc::Rc; + +const TARGET_PER_CELL: f64 = 8.0; +const MAX_CELLS: f64 = 4_000_000.0; +const MAX_CELLS_PER_ITEM: f64 = 1024.0; + +/// Gleichförmiges Raster (CSR) über Bounding-Boxen; Einträge sind Index-Werte. +#[derive(Default)] +struct Grid { + min_x: f64, + min_y: f64, + cell: f64, + cols: f64, + rows: f64, + cell_start: Vec, + items: Vec, + /// Einträge mit zu vielen Zellen — immer geprüft. + long: Vec, +} + +impl Grid { + /// Wie `buildSegmentIndex`: `boxes` = (Wert, minX, minY, maxX, maxY) in Einfüge-Reihenfolge. + fn build(boxes: &[(u32, f64, f64, f64, f64)], n: usize, min_x: f64, min_y: f64, max_x: f64, max_y: f64) -> Grid { + let w = jsnum::max(max_x - min_x, 1e-6); + let h = jsnum::max(max_y - min_y, 1e-6); + let cell_count = jsnum::min(MAX_CELLS, jsnum::max(1.0, (n as f64 / TARGET_PER_CELL).ceil())); + let mut cell = ((w * h) / cell_count).sqrt(); + if !(cell > 0.0) { + cell = jsnum::max(w, h); + } + let cols = jsnum::max(1.0, (w / cell).ceil()); + let rows = jsnum::max(1.0, (h / cell).ceil()); + let mut g = Grid { min_x, min_y, cell, cols, rows, ..Default::default() }; + let total = cols * rows; + if !(total.is_finite() && total <= 1e8) { + // Entartet (NaN/riesig): alles in die immer geprüfte Liste. + g.cols = 1.0; + g.rows = 1.0; + g.cell_start = vec![0, 0]; + g.long = boxes.iter().map(|b| b.0).collect(); + return g; + } + let n_cells = total as usize; + let cx = |x: f64| jsnum::min(cols - 1.0, jsnum::max(0.0, ((x - min_x) / cell).floor())); + let cy = |y: f64| jsnum::min(rows - 1.0, jsnum::max(0.0, ((y - min_y) / cell).floor())); + let range = |b: &(u32, f64, f64, f64, f64)| (cx(b.1), cx(b.3), cy(b.2), cy(b.4)); + let mut counts = vec![0u32; n_cells + 1]; + let mut is_long = vec![false; boxes.len()]; + for (k, b) in boxes.iter().enumerate() { + let (x0, x1, y0, y1) = range(b); + if (x1 - x0 + 1.0) * (y1 - y0 + 1.0) > MAX_CELLS_PER_ITEM { + g.long.push(b.0); + is_long[k] = true; + continue; + } + let mut y = y0; + while y <= y1 { + let mut x = x0; + while x <= x1 { + counts[(y * cols + x) as usize + 1] += 1; + x += 1.0; + } + y += 1.0; + } + } + for c in 1..counts.len() { + counts[c] += counts[c - 1]; + } + let mut fill: Vec = counts[..n_cells].to_vec(); + let mut items = vec![0u32; counts[n_cells] as usize]; + for (k, b) in boxes.iter().enumerate() { + if is_long[k] { + continue; + } + let (x0, x1, y0, y1) = range(b); + let mut y = y0; + while y <= y1 { + let mut x = x0; + while x <= x1 { + let c = (y * cols + x) as usize; + items[fill[c] as usize] = b.0; + fill[c] += 1; + x += 1.0; + } + y += 1.0; + } + } + g.cell_start = counts; + g.items = items; + g + } + + /// Alle Einträge der Zellen um `(x, y)` im Umkreis `r` (zuerst `long`), wie `nearestSegment`. + fn visit(&self, x: f64, y: f64, r: f64, mut f: impl FnMut(u32)) { + for &i in &self.long { + f(i); + } + if self.items.is_empty() { + return; + } + let x0 = ((x - r - self.min_x) / self.cell).floor(); + let x1 = ((x + r - self.min_x) / self.cell).floor(); + let y0 = ((y - r - self.min_y) / self.cell).floor(); + let y1 = ((y + r - self.min_y) / self.cell).floor(); + if x1 < 0.0 || y1 < 0.0 || x0 >= self.cols || y0 >= self.rows { + return; + } + let mut yy = jsnum::max(0.0, y0); + let ye = jsnum::min(self.rows - 1.0, y1); + while yy <= ye { + let mut xx = jsnum::max(0.0, x0); + let xe = jsnum::min(self.cols - 1.0, x1); + while xx <= xe { + let c = (yy * self.cols + xx) as usize; + for k in self.cell_start[c]..self.cell_start[c + 1] { + f(self.items[k as usize]); + } + xx += 1.0; + } + yy += 1.0; + } + } +} + +/// Raster über Bounding-Boxen (Einträge mit nicht endlicher Box werden immer geprüft) — nur +/// Vorauswahl, die genaue Prüfung macht der Aufrufer in Index-Reihenfolge. +#[derive(Default)] +struct BoxIndex { + grid: Option, + wild: Vec, +} + +impl BoxIndex { + fn build(boxes: Vec<(u32, f64, f64, f64, f64)>) -> BoxIndex { + let mut wild = Vec::new(); + let mut fin = Vec::with_capacity(boxes.len()); + let (mut a, mut b, mut c, mut d) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for e in boxes { + if e.1.is_finite() && e.2.is_finite() && e.3.is_finite() && e.4.is_finite() { + a = a.min(e.1); + b = b.min(e.2); + c = c.max(e.3); + d = d.max(e.4); + fin.push(e); + } else if !(e.3 < e.1 || e.4 < e.2) { + // NaN/unendlich (nicht leer): immer prüfen. + wild.push(e.0); + } + } + let grid = (!fin.is_empty()).then(|| Grid::build(&fin, fin.len(), a, b, c, d)); + BoxIndex { grid, wild } + } + + /// Einträge, deren Box den Kreis `(x, y, r)` berühren kann — aufsteigend, ohne Doppel. + fn candidates(&self, x: f64, y: f64, r: f64) -> Vec { + let mut out = self.wild.clone(); + if let Some(g) = &self.grid { + g.visit(x, y, r, |k| out.push(k)); + } + out.sort_unstable(); + out.dedup(); + out + } +} + +/// Rand für Rundung bei Box-Tests: relativ zur Koordinatengrösse. +fn pad(v: &[f64]) -> f64 { + 1e-9 * (1.0 + v.iter().fold(0.0f64, |m, x| m.max(x.abs()))) +} + +/// `pointSegDist` (Modell-Meter). +pub fn point_seg_dist(px: f64, py: f64, ax: f64, ay: f64, bx: f64, by: f64) -> f64 { + let dx = bx - ax; + let dy = by - ay; + let len2 = dx * dx + dy * dy; + let mut t = if len2 > 0.0 { ((px - ax) * dx + (py - ay) * dy) / len2 } else { 0.0 }; + t = jsnum::max(0.0, jsnum::min(1.0, t)); + hypot(&[px - (ax + t * dx), py - (ay + t * dy)]) +} + +/// `pointSegDistPx` (Client-Pixel). +pub fn point_seg_dist_px(px: f64, py: f64, ax: f64, ay: f64, bx: f64, by: f64) -> f64 { + let dx = bx - ax; + let dy = by - ay; + let len2 = dx * dx + dy * dy; + if len2 < 1e-9 { + return hypot(&[px - ax, py - ay]); + } + let mut t = ((px - ax) * dx + (py - ay) * dy) / len2; + t = jsnum::max(0.0, jsnum::min(1.0, t)); + hypot(&[px - (ax + dx * t), py - (ay + dy * t)]) +} + +/// `pointInPolygon` (gerade/ungerade, wie `planView/geometry.ts`). +pub fn point_in_polygon(x: f64, y: f64, poly: &[f64]) -> bool { + let n = poly.len() / 2; + let mut inside = false; + let mut j = n.wrapping_sub(1); + for i in 0..n { + let (xi, yi, xj, yj) = (poly[2 * i], poly[2 * i + 1], poly[2 * j], poly[2 * j + 1]); + if (yi > y) != (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi { + inside = !inside; + } + j = i; + } + inside +} + +/// Abbildung Modell → Client-Pixel: `toScreen` (·90, Y gespiegelt), dann `vbToClient`. +#[derive(Clone, Copy)] +pub struct ClientMap { + /// `left + offX` + pub left: f64, + /// `top + offY` + pub top: f64, + pub view_x: f64, + pub view_y: f64, + pub scale: f64, +} + +impl ClientMap { + #[inline] + fn at(&self, x: f64, y: f64) -> (f64, f64) { + let vx = x * 90.0; + let vy = -y * 90.0; + (self.left + (vx - self.view_x) * self.scale, self.top + (vy - self.view_y) * self.scale) + } +} + +struct Sym { + gi: u32, + mask: u16, + arc: bool, + seg: [f64; 4], +} + +struct Ring { + gi: u32, + arc: bool, + cx: f64, + cy: f64, + r: f64, + a0: f64, + a1: f64, + filled: bool, +} + +struct PolyEntry { + gi: u32, + mask: u16, +} + +/// Index über einen zusammengesetzten Plan (besitzt seine Puffer). +pub struct PickIndex { + bufs: Vec>, + /// Abschnitte: (Puffer, von, erster Index im Plan). + parts: Vec<(usize, usize, usize)>, + count: usize, + segs: Option, + polys: Vec, + poly_grid: Option, + /// Polygone mit nicht endlichem Ausmass (immer geprüft). + poly_wild: Vec, + /// Symbol-Linien/-Bögen mit Pick-Id (Bogen: Sehne `from → to`). + sym: Vec, + sym_ix: BoxIndex, + /// Kreise/Bögen der 2D-Zeichnung (nicht-leere `drawingId`). + rings: Vec, + ring_ix: BoxIndex, + /// (Art, Id) → Indizes aufsteigend. + owners: HashMap<(u32, u32), Vec>, + interned: HashMap, +} + +/// Bounding-Box, NaN ausgelassen (wie `f64::min`). +fn bbox(pts: &[f64]) -> (f64, f64, f64, f64) { + let (mut a, mut b, mut c, mut d) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for q in pts.chunks_exact(2) { + a = a.min(q[0]); + b = b.min(q[1]); + c = c.max(q[0]); + d = d.max(q[1]); + } + (a, b, c, d) +} + +impl PickIndex { + /// Index bauen; `segs` = `[Puffer-Nr, von, bis, …]`, `bufs` = (Nr, Bytes). `None` bei Unsinn. + pub fn build(segs: &[f64], bufs: Vec<(u32, Rc<[u8]>)>) -> Option { + if segs.len() % 3 != 0 { + return None; + } + let mut ix = PickIndex { + bufs: bufs.iter().map(|b| b.1.clone()).collect(), + parts: Vec::new(), + count: 0, + segs: None, + polys: Vec::new(), + poly_grid: None, + poly_wild: Vec::new(), + sym: Vec::new(), + sym_ix: BoxIndex::default(), + rings: Vec::new(), + ring_ix: BoxIndex::default(), + owners: HashMap::new(), + interned: HashMap::new(), + }; + // Segment-Raster wie `buildSegmentIndex` (Ausmass mit Math.min/max, NaN steckt an). + let mut seg_boxes: Vec<(u32, f64, f64, f64, f64)> = Vec::new(); + let (mut sminx, mut sminy, mut smaxx, mut smaxy) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + let mut poly_boxes: Vec<(u32, f64, f64, f64, f64)> = Vec::new(); + let (mut pminx, mut pminy, mut pmaxx, mut pmaxy) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + let mut gi = 0usize; + for s in segs.chunks_exact(3) { + let nr = whole(s[0])? as u32; + let bi = bufs.iter().position(|b| b.0 == nr)?; + let (from, to) = (whole(s[1])?, whole(s[2])?); + let view = View::parse(&bufs[bi].1)?; + if from > to || to > view.len() { + return None; + } + ix.parts.push((bi, from, gi)); + // String-Index → (Id-Nummer, nicht leer); einmal je Abschnitt. + let mut strs: HashMap = HashMap::new(); + for i in from..to { + let g = gi as u32; + gi += 1; + let at = view.rec_at(i)?; + let tag = whole(view.word(at)?)? as u32; + let flags = whole(view.word(at + 1)?)? as u32; + let pk = whole(view.word(at + 2)?)? as u32; + // Pick-Ids: (Art, String-Index). + let ids: Vec<(u32, f64)> = if flags & F_IDS != 0 { + pick_ids(&view, &view.rec(i)?)? + } else if pk > 0 { + vec![(pk, view.word(at + 3)?)] + } else { + Vec::new() + }; + let mut mask: u16 = 0; + let mut drawing: Option = None; + let mut owned: Vec<(u32, u32)> = Vec::with_capacity(ids.len()); + for &(kind, si) in &ids { + let key = si as i64; + let (id, non_empty) = match strs.get(&key) { + Some(&v) => v, + None => { + let text = view.string(whole(si)?)?; + let ne = !text.is_empty(); + let n = ix.interned.len() as u32; + let id = *ix.interned.entry(text).or_insert(n); + strs.insert(key, (id, ne)); + (id, ne) + } + }; + if non_empty { + mask |= 1 << kind; + } + if kind == 2 { + drawing = Some(id); + } + owned.push((kind, id)); + } + // Besitzer (wie `buildOwnerIndex`: mit drawingId nur diese). + match drawing { + Some(id) => ix.owners.entry((2, id)).or_default().push(g), + None => { + for (kind, id) in owned { + ix.owners.entry((kind, id)).or_default().push(g); + } + } + } + let f = |k: usize| view.word(at + 4 + k); + match tag { + T_LINE => { + if mask & (1 << 2) != 0 { + let (ax, ay, bx, by) = (f(4)?, f(5)?, f(6)?, f(7)?); + sminx = jsnum::min(sminx, jsnum::min(ax, bx)); + smaxx = jsnum::max(smaxx, jsnum::max(ax, bx)); + sminy = jsnum::min(sminy, jsnum::min(ay, by)); + smaxy = jsnum::max(smaxy, jsnum::max(ay, by)); + seg_boxes.push((g, jsnum::min(ax, bx), jsnum::min(ay, by), jsnum::max(ax, bx), jsnum::max(ay, by))); + } + let m = mask & ((1 << 4) | (1 << 5)); + if m != 0 { + ix.sym.push(Sym { gi: g, mask: m, arc: false, seg: [f(4)?, f(5)?, f(6)?, f(7)?] }); + } + } + T_ARC => { + let m = mask & ((1 << 4) | (1 << 5)); + if m != 0 { + ix.sym.push(Sym { gi: g, mask: m, arc: true, seg: [f(6)?, f(7)?, f(8)?, f(9)?] }); + } + } + T_CIRCLE => { + if mask & (1 << 2) != 0 { + // `fill !== "none"` (fehlende Füllung zählt als gefüllt, wie in TS). + let fi = f(0)?; + let filled = !(fi >= 0.0 && view.string(whole(fi)?)? == "none"); + ix.rings.push(Ring { gi: g, arc: false, cx: f(4)?, cy: f(5)?, r: f(6)?, a0: 0.0, a1: 0.0, filled }); + } + } + T_DRAWING_ARC => { + if mask & (1 << 2) != 0 { + ix.rings.push(Ring { gi: g, arc: true, cx: f(3)?, cy: f(4)?, r: f(5)?, a0: f(6)?, a1: f(7)?, filled: false }); + } + } + T_POLYGON => { + let pts = view.pool(whole(f(5)?)?, whole(f(6)?)?.checked_mul(2)?)?; + let (a, b, c, d) = bbox(&pts); + ix.polys.push(PolyEntry { gi: g, mask }); + let k = (ix.polys.len() - 1) as u32; + if a.is_finite() && b.is_finite() && c.is_finite() && d.is_finite() { + pminx = pminx.min(a); + pminy = pminy.min(b); + pmaxx = pmaxx.max(c); + pmaxy = pmaxy.max(d); + // Etwas Rand: Punkt-in-Polygon rechnet mit Rundung. + let e = 1e-9 * (1.0 + a.abs().max(b.abs()).max(c.abs()).max(d.abs())); + poly_boxes.push((k, a - e, b - e, c + e, d + e)); + } else if c >= a && d >= b { + ix.poly_wild.push(k); + } + } + _ => {} + } + } + } + ix.count = gi; + if !seg_boxes.is_empty() { + ix.segs = Some(Grid::build(&seg_boxes, seg_boxes.len(), sminx, sminy, smaxx, smaxy)); + } + if !poly_boxes.is_empty() { + ix.poly_grid = Some(Grid::build(&poly_boxes, poly_boxes.len(), pminx, pminy, pmaxx, pmaxy)); + } + ix.sym_ix = BoxIndex::build( + ix.sym + .iter() + .enumerate() + .map(|(k, s)| { + let [ax, ay, bx, by] = s.seg; + let e = pad(&s.seg); + (k as u32, ax.min(bx) - e, ay.min(by) - e, ax.max(bx) + e, ay.max(by) + e) + }) + .collect(), + ); + ix.ring_ix = BoxIndex::build( + ix.rings + .iter() + .enumerate() + .map(|(k, g)| { + let r = g.r.abs(); + let e = pad(&[g.cx, g.cy, r]); + (k as u32, g.cx - r - e, g.cy - r - e, g.cx + r + e, g.cy + r + e) + }) + .collect(), + ); + Some(ix) + } + + pub fn len(&self) -> usize { + self.count + } + + pub fn is_empty(&self) -> bool { + self.count == 0 + } + + /// Puffer und Eintrag zu einem Plan-Index. + fn locate(&self, gi: u32) -> Option<(View<'_>, usize)> { + let gi = gi as usize; + let p = match self.parts.binary_search_by(|e| e.2.cmp(&gi)) { + Ok(k) => { + // Leere Abschnitte überspringen: der letzte mit diesem Start. + let mut k = k; + while k + 1 < self.parts.len() && self.parts[k + 1].2 == gi { + k += 1; + } + k + } + Err(k) => k.checked_sub(1)?, + }; + let (bi, from, start) = self.parts[p]; + Some((View::parse(&self.bufs[bi])?, from + gi - start)) + } + + /// Feste Felder ab `k` eines Eintrags. + fn fields(&self, gi: u32, k: usize) -> Option<[f64; N]> { + let (v, i) = self.locate(gi)?; + let at = v.rec_at(i)? + 4 + k; + let mut out = [0.0; N]; + for (j, o) in out.iter_mut().enumerate() { + *o = v.word(at + j)?; + } + Some(out) + } + + fn line(&self, gi: u32) -> Option<[f64; 4]> { + self.fields::<4>(gi, 4) + } + + fn polygon_pts(&self, gi: u32) -> Option> { + let (v, i) = self.locate(gi)?; + let at = v.rec_at(i)? + 4; + v.pool(whole(v.word(at + 5)?)?, whole(v.word(at + 6)?)?.checked_mul(2)?) + } + + /// Nächstes Segment einer 2D-Zeichnung zu `(x, y)` mit Abstand < `max_dist` (wie `nearestSegment`). + pub fn nearest_segment(&self, x: f64, y: f64, max_dist: f64) -> Option<(u32, f64)> { + let g = self.segs.as_ref()?; + let mut best = None; + let mut best_d = max_dist; + g.visit(x, y, max_dist, |i| { + if let Some([ax, ay, bx, by]) = self.line(i) { + let d = point_seg_dist(x, y, ax, ay, bx, by); + if d < best_d { + best_d = d; + best = Some(i); + } + } + }); + best.map(|i| (i, best_d)) + } + + /// Alle Segmente mit Abstand < `max_dist`, nächste zuerst (wie `segmentsNear`). + pub fn segments_near(&self, x: f64, y: f64, max_dist: f64) -> Vec<(u32, f64)> { + let Some(g) = self.segs.as_ref() else { return Vec::new() }; + let mut found: Vec<(u32, f64)> = Vec::new(); + let mut pos: HashMap = HashMap::new(); + g.visit(x, y, max_dist, |i| { + if let Some([ax, ay, bx, by]) = self.line(i) { + let d = point_seg_dist(x, y, ax, ay, bx, by); + if d < max_dist { + match pos.get(&i) { + Some(&k) => found[k].1 = d, + None => { + pos.insert(i, found.len()); + found.push((i, d)); + } + } + } + } + }); + // Stabil nach Abstand (Gleichstand: Einfüge-Reihenfolge, wie `Array.sort`). + found.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal)); + found + } + + /// Polygone, die `(x, y)` enthalten, mit Pick-Maske (0 = alle Polygone), absteigend nach Index. + pub fn polygons_at(&self, x: f64, y: f64, mask: u16) -> Vec { + let mut cand: Vec = self.poly_wild.clone(); + if let Some(g) = &self.poly_grid { + g.visit(x, y, 0.0, |k| cand.push(k)); + } + cand.sort_unstable(); + cand.dedup(); + let mut out: Vec = Vec::new(); + for k in cand { + let p = &self.polys[k as usize]; + if mask != 0 && p.mask & mask == 0 { + continue; + } + if let Some(pts) = self.polygon_pts(p.gi) { + if point_in_polygon(x, y, &pts) { + out.push(p.gi); + } + } + } + out.sort_unstable_by(|a, b| b.cmp(a)); + out + } + + /// Nächste Symbol-Linie (bzw. Bogen über die Sehne `from → to`) mit einer Pick-Id aus + /// `line_mask` bzw. `arc_mask`, in Client-Pixeln < `max_px` (erster bei Gleichstand). + pub fn nearest_symbol_px(&self, line_mask: u16, arc_mask: u16, map: ClientMap, cx: f64, cy: f64, max_px: f64) -> Option { + let mut best = None; + let mut best_d = max_px; + // Vorauswahl im Modell: `max_px` Pixel = `max_px / (90·scale)` Meter (grosszügig). + let cand: Vec = { + let (mx, my) = ((cx - map.left) / map.scale / 90.0 + map.view_x / 90.0, -((cy - map.top) / map.scale + map.view_y) / 90.0); + let r = max_px / (90.0 * map.scale.abs()); + if mx.is_finite() && my.is_finite() && r.is_finite() { + self.sym_ix.candidates(mx, my, r * (1.0 + 1e-6) + pad(&[mx, my])) + } else { + (0..self.sym.len() as u32).collect() + } + }; + for k in cand { + let s = &self.sym[k as usize]; + if s.mask & (if s.arc { arc_mask } else { line_mask }) == 0 { + continue; + } + let gi = s.gi; + let [ax, ay, bx, by] = s.seg; + let (a0, a1) = map.at(ax, ay); + let (b0, b1) = map.at(bx, by); + let d = point_seg_dist_px(cx, cy, a0, a1, b0, b1); + if d < best_d { + best_d = d; + best = Some(gi); + } + } + best + } + + /// Kreise/Bögen der 2D-Zeichnung mit Ring-Abstand < `tol_px` (Pixel), in Plan-Reihenfolge: + /// (Index, Abstand in Pixeln) — wie `distToDrawingRing`. + pub fn rings_near(&self, x: f64, y: f64, px_per_m: f64, tol_px: f64) -> Vec<(u32, f64)> { + let tau = std::f64::consts::PI * 2.0; + let mut out = Vec::new(); + // Vorauswahl: Ring-Abstand < `tol_px` Pixel liegt innerhalb der Kreis-Box + `tol_px/px_per_m`. + let rq = tol_px / px_per_m; + let cand: Vec = if rq.is_finite() && rq >= 0.0 && x.is_finite() && y.is_finite() { + self.ring_ix.candidates(x, y, rq * (1.0 + 1e-6) + pad(&[x, y])) + } else { + (0..self.rings.len() as u32).collect() + }; + for k in cand { + let g = &self.rings[k as usize]; + let dist_c = hypot(&[x - g.cx, y - g.cy]); + if g.arc { + let mut sweep = (((g.a1 - g.a0) % tau) + tau) % tau; + if sweep == 0.0 || sweep.is_nan() { + sweep = tau; + } + let ang = jsnum::atan2(y - g.cy, x - g.cx); + let rel = (((ang - g.a0) % tau) + tau) % tau; + let ang_tol = if dist_c > 1e-6 { tol_px / (px_per_m * jsnum::max(dist_c, 0.05)) } else { f64::INFINITY }; + if rel > sweep + ang_tol && tau - rel > ang_tol { + continue; + } + } + let dm = if g.filled { jsnum::max(0.0, dist_c - g.r) } else { (dist_c - g.r).abs() }; + let d = dm * px_per_m; + if d < tol_px { + out.push((g.gi, d)); + } + } + out + } + + /// Alle Primitive, deren Id der Art `kind` in `ids` liegt, aufsteigend (wie `ownedBy`). + pub fn owned_by(&self, kind: u32, ids: &[&str]) -> Vec { + let mut hits: Vec = Vec::new(); + for id in ids { + if let Some(n) = self.interned.get(*id) { + if let Some(l) = self.owners.get(&(kind, *n)) { + hits.extend_from_slice(l); + } + } + } + hits.sort_unstable(); + hits + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn punkt_in_polygon_und_abstand() { + let sq = [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]; + assert!(point_in_polygon(0.5, 0.5, &sq)); + assert!(!point_in_polygon(1.5, 0.5, &sq)); + assert_eq!(point_seg_dist(0.5, 1.0, 0.0, 0.0, 1.0, 0.0), 1.0); + assert_eq!(point_seg_dist_px(3.0, 4.0, 0.0, 0.0, 0.0, 0.0), 5.0); + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 2d3fd99c..18680fdf 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -33,6 +33,7 @@ mod curves; mod hatch; mod skeleton; mod plan_scene; +mod plan_pick; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/plan_pick.rs b/src-tauri/core/src/web/plan_pick.rs new file mode 100644 index 00000000..3f45177c --- /dev/null +++ b/src-tauri/core/src/web/plan_pick.rs @@ -0,0 +1,76 @@ +//! Bindungen der Auswahl (`crate::plan_pick`). Ein Index wird einmal je Plan gebaut +//! (`pick_index_build`, Abschnitte wie `plan_parts`) und bleibt, bis TS ihn freigibt +//! (`pick_index_release`); er hält seine Puffer selbst, Verdrängen im Puffer-Speicher stört ihn +//! nicht. Unbekannter Index oder kaputte Eingabe → leeres Ergebnis bzw. −1, nie Panic. + +use crate::plan_pick::{ClientMap, PickIndex}; +use std::cell::RefCell; +use wasm_bindgen::prelude::wasm_bindgen; + +thread_local! { + static INDEXES: RefCell<(u32, Vec<(u32, PickIndex)>)> = const { RefCell::new((0, Vec::new())) }; +} + +fn with(id: u32, f: impl FnOnce(&PickIndex) -> R) -> Option { + INDEXES.with(|h| h.borrow().1.iter().find(|e| e.0 == id).map(|e| f(&e.1))) +} + +/// Index über die Abschnitte `[Puffer-Nr, von, bis, …]` bauen; Nummer ≥ 1, 0 = Fehler (Puffer +/// fehlt oder kaputt — TS legt neu ab und baut nochmals). +#[wasm_bindgen] +pub fn pick_index_build(segs: &[f64]) -> u32 { + let Some(bufs) = super::plan_buf::held_for_segs(segs) else { return 0 }; + let Some(ix) = PickIndex::build(segs, bufs) else { return 0 }; + INDEXES.with(|h| { + let mut h = h.borrow_mut(); + h.0 = h.0.wrapping_add(1).max(1); + let id = h.0; + h.1.push((id, ix)); + id + }) +} + +#[wasm_bindgen] +pub fn pick_index_release(id: u32) { + INDEXES.with(|h| h.borrow_mut().1.retain(|e| e.0 != id)); +} + +/// Nächstes 2D-Zeichnungs-Segment als `[Index, Abstand]`, leer ohne Treffer. +#[wasm_bindgen] +pub fn pick_nearest_segment(id: u32, x: f64, y: f64, max_dist: f64) -> Vec { + with(id, |ix| ix.nearest_segment(x, y, max_dist)).flatten().map_or(Vec::new(), |(i, d)| vec![i as f64, d]) +} + +/// Segmente im Umkreis als `[Index, Abstand, …]`, nächste zuerst. +#[wasm_bindgen] +pub fn pick_segments_near(id: u32, x: f64, y: f64, max_dist: f64) -> Vec { + with(id, |ix| ix.segments_near(x, y, max_dist).into_iter().flat_map(|(i, d)| [i as f64, d]).collect()).unwrap_or_default() +} + +/// Polygone unter dem Punkt (Maske der Pick-Arten, 0 = alle), oberstes zuerst. +#[wasm_bindgen] +pub fn pick_polygons_at(id: u32, x: f64, y: f64, mask: u32) -> Vec { + with(id, |ix| ix.polygons_at(x, y, mask as u16)).unwrap_or_default() +} + +/// Nächste Symbol-Linie/-Bogen in Client-Pixeln (Abbildung `left+offX, top+offY, view.x, +/// view.y, scale`) oder −1. +#[wasm_bindgen] +#[allow(clippy::too_many_arguments)] +pub fn pick_nearest_symbol_px(id: u32, line_mask: u32, arc_mask: u32, left: f64, top: f64, view_x: f64, view_y: f64, scale: f64, cx: f64, cy: f64, max_px: f64) -> f64 { + let map = ClientMap { left, top, view_x, view_y, scale }; + with(id, |ix| ix.nearest_symbol_px(line_mask as u16, arc_mask as u16, map, cx, cy, max_px)).flatten().map_or(-1.0, |i| i as f64) +} + +/// Kreise/Bögen der 2D-Zeichnung nahe am Punkt: `[Index, Abstand px, …]` in Plan-Reihenfolge. +#[wasm_bindgen] +pub fn pick_rings_near(id: u32, x: f64, y: f64, px_per_m: f64, tol_px: f64) -> Vec { + with(id, |ix| ix.rings_near(x, y, px_per_m, tol_px).into_iter().flat_map(|(i, d)| [i as f64, d]).collect()).unwrap_or_default() +} + +/// Primitive der Ids (jede mit `\0` davor) der Pick-Art `kind`, aufsteigend. +#[wasm_bindgen] +pub fn pick_owned_by(id: u32, kind: u32, ids: &str) -> Vec { + let list: Vec<&str> = ids.split('\0').skip(1).collect(); + with(id, |ix| ix.owned_by(kind, &list)).unwrap_or_default() +} diff --git a/src/core/index.ts b/src/core/index.ts index 041a3d81..073e4034 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -264,18 +264,10 @@ export { } from "../plan/planView/geometry"; export { + type ClientMap, type OwnerField, - type OwnerIndex, - buildOwnerIndex, - ownedBy, -} from "../plan/planView/ownerIndex"; - -export { - buildSegmentIndex, - nearestSegment, - pointSegDist as pointSegDist__plan_planView_segmentIndex, - segmentsNear, -} from "../plan/planView/segmentIndex"; + PlanPickIndex, +} from "../plan/planView/planPick"; export { marqueeHitUnderlay, diff --git a/src/plan/planBuf.ts b/src/plan/planBuf.ts index 0cadd6fb..c5ca8575 100644 --- a/src/plan/planBuf.ts +++ b/src/plan/planBuf.ts @@ -184,6 +184,8 @@ export interface EncodeOptions { * einen Puffer nicht lesen. Standard `true`. */ textJson?: boolean; + /** `false`: Schraffuren ohne JSON (nur das Hatch-Format, wie `lean`). Standard `true`. */ + hatchJson?: boolean; /** Gruppen `[start, end)` in den Kopf schreiben. */ groups?: ReadonlyArray; bounds?: readonly [number, number, number, number]; @@ -193,6 +195,7 @@ export interface EncodeOptions { export function encodePlanBuf(prims: readonly Primitive[], opts: EncodeOptions = {}): Uint8Array { const lean = opts.lean === true; const textJson = opts.textJson !== false; + const hatchJson = !lean && opts.hatchJson !== false; const strParts: string[] = []; const strTab = new F64Writer(64); const strIdx = new Map(); @@ -217,7 +220,7 @@ export function encodePlanBuf(prims: readonly Primitive[], opts: EncodeOptions = let i = hatchIdx.get(h); if (i === undefined) { i = hatchIdx.size; - hatchW.push(lean ? -1 : str(JSON.stringify(h))); + hatchW.push(hatchJson ? str(JSON.stringify(h)) : -1); writeHatch(hatchW, h, str(h.color)); hatchIdx.set(h, i); } diff --git a/src/plan/planParts.ts b/src/plan/planParts.ts index a0938a9b..29b56eb9 100644 --- a/src/plan/planParts.ts +++ b/src/plan/planParts.ts @@ -95,7 +95,7 @@ export function planParts(plan: Plan, texts = false): PlanParts { at = r.end; } gap(prims.length); - const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts }), hold: 0 } : null; + const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts, hatchJson: false }), hold: 0 } : null; const segs: number[] = []; let gi = 0; let ri = 0; @@ -128,8 +128,10 @@ export function greyedFlat(plan: Plan): Float64Array { return out; } -/** Abschnitte mit den Kern-Nummern der Puffer (legt fehlende ab). */ -function heldSegs(parts: PlanParts, fresh: boolean): Float64Array { +/** + * Abschnitte mit den Kern-Nummern der Puffer; legt fehlende ab (`fresh`: auch verdrängte). + */ +export function heldSegs(parts: PlanParts, fresh: boolean): Float64Array { const c = core(); for (const b of parts.bufs) if (!b.hold || (fresh && !c.plan_buf_is_held(b.hold))) b.hold = c.plan_buf_hold(b.bytes); const s = new Float64Array(parts.segs.length); diff --git a/src/plan/planView/ownerIndex.test.ts b/src/plan/planView/ownerIndex.test.ts deleted file mode 100644 index f0a86a9b..00000000 --- a/src/plan/planView/ownerIndex.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, it, expect } from "vitest"; -import type { Primitive } from "../generatePlan"; -import { buildOwnerIndex, ownedBy } from "./ownerIndex"; - -const line = (drawingId: string): Primitive => - ({ kind: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 }, cls: "draw2d", weightMm: 0.1, drawingId }) as Primitive; -const poly = (extra: Record): Primitive => - ({ kind: "polygon", pts: [], fill: "#fff", stroke: "#000", strokeWidthMm: 0.1, ...extra }) as unknown as Primitive; - -describe("ownerIndex", () => { - const prims: Primitive[] = [ - poly({ wallId: "w1" }), - line("d1"), - poly({ roomId: "r1" }), - line("d2"), - poly({ wallId: "w2", openingId: "o1" }), - line("d1"), - ]; - const idx = buildOwnerIndex(prims); - - it("findet Primitive je Besitzer-ID in Plan-Reihenfolge", () => { - expect(ownedBy(idx, prims, "drawingId", ["d1"])).toEqual([prims[1], prims[5]]); - expect(ownedBy(idx, prims, "wallId", ["w2", "w1"])).toEqual([prims[0], prims[4]]); - expect(ownedBy(idx, prims, "roomId", ["r1"])).toEqual([prims[2]]); - }); - - it("ein Primitiv kann mehrere Besitzer-Felder tragen (ausser Zeichnungs-Primitive)", () => { - expect(ownedBy(idx, prims, "openingId", ["o1"])).toEqual([prims[4]]); - expect(ownedBy(idx, prims, "wallId", ["w2"])).toEqual([prims[4]]); - }); - - it("liefert nichts für unbekannte IDs/leere Mengen und gleicht dem früheren filter()", () => { - expect(ownedBy(idx, prims, "drawingId", ["x"])).toEqual([]); - expect(ownedBy(idx, prims, "wallId", [])).toEqual([]); - const ids = new Set(["d2", "w1"]); - const viaFilter = prims.filter( - (p) => ids.has((p as any).drawingId) || ids.has((p as any).wallId), - ); - const viaIndex = [...ownedBy(idx, prims, "drawingId", ids), ...ownedBy(idx, prims, "wallId", ids)].sort( - (a, b) => prims.indexOf(a) - prims.indexOf(b), - ); - expect(viaIndex).toEqual(viaFilter); - }); -}); diff --git a/src/plan/planView/ownerIndex.ts b/src/plan/planView/ownerIndex.ts deleted file mode 100644 index 367da3e1..00000000 --- a/src/plan/planView/ownerIndex.ts +++ /dev/null @@ -1,66 +0,0 @@ -// Besitzer-Index über die Primitive eines Plans: welche Primitive gehören zu -// Wand/Decke/Raum/Zeichnung/…-ID X? Die Auswahl-Hervorhebung in PlanView hat -// das bisher mit je einem `plan.primitives.filter(...)` PRO Elementart gelöst — -// zehn Durchgänge über alle Primitive bei jeder Plan-Änderung (bei einem -// Kataster-Import 3,7 Mio. → ~300 ms pro Änderung). Der Index braucht EINEN -// Durchgang je Plan; danach kostet jede Abfrage nur die Treffer. - -import type { Primitive } from "../generatePlan"; - -export const OWNER_FIELDS = [ - "wallId", - "drawingId", - "ceilingId", - "openingId", - "stairId", - "roomId", - "roofId", - "contextObjectId", - "sectionLineId", - "extrudedSolidId", - "columnId", -] as const; -export type OwnerField = (typeof OWNER_FIELDS)[number]; - -export type OwnerIndex = Record>; - -export function buildOwnerIndex(prims: readonly Primitive[]): OwnerIndex { - const index = Object.fromEntries(OWNER_FIELDS.map((f) => [f, new Map()])) as OwnerIndex; - const add = (field: OwnerField, id: string, i: number) => { - const m = index[field]; - const list = m.get(id); - if (list) list.push(i); - else m.set(id, [i]); - }; - for (let i = 0; i < prims.length; i++) { - const rec = prims[i] as unknown as Record; - // Schnellpfad: Primitive aus 2D-Zeichnungen (der Massenfall) tragen NUR eine - // drawingId, nie eine andere Besitzer-ID (s. generatePlan/drawing2d.ts). - const did = rec.drawingId; - if (typeof did === "string") { - add("drawingId", did, i); - continue; - } - for (const f of OWNER_FIELDS) { - const v = rec[f]; - if (typeof v === "string") add(f, v, i); - } - } - return index; -} - -/** Primitive, deren `field` in `ids` liegt — in Plan-Reihenfolge (wie `filter`). */ -export function ownedBy( - index: OwnerIndex, - prims: readonly Primitive[], - field: OwnerField, - ids: Iterable, -): Primitive[] { - const hits: number[] = []; - for (const id of ids) { - const list = index[field].get(id); - if (list) for (const i of list) hits.push(i); - } - hits.sort((a, b) => a - b); - return hits.map((i) => prims[i]); -} diff --git a/src/plan/planView/planPick.test.ts b/src/plan/planView/planPick.test.ts new file mode 100644 index 00000000..df2eff27 --- /dev/null +++ b/src/plan/planView/planPick.test.ts @@ -0,0 +1,132 @@ +// Auswahl über den Kern ([K3d], `core/src/plan_pick.rs`): nächstes Segment, Segmente im Umkreis, +// Polygone unter dem Punkt (mit Pick-Feld), Symbol-Linien in Pixeln, Kreis-/Bogen-Ringe und +// Besitzer — gegen einfache lineare Suchen. (Gleichheit zur früheren TS-Fassung — segmentIndex, +// ownerIndex, PlanView-Schleifen — mit Beispielprojekt, 150 Zufallsplänen und grossem Projekt +// geprüft, s. TODO [K3d].) + +import { describe, it, expect } from "vitest"; +import type { Plan, Primitive } from "../generatePlan"; +import { generatePlan } from "../generatePlan"; +import { PlanPickIndex } from "./planPick"; +import { pointInPolygon } from "./geometry"; +import { sampleProject } from "../../model/sampleProject"; +import { flattenCategories } from "../../model/types"; + +const plan = (primitives: Primitive[]): Plan => ({ primitives, bounds: { minX: 0, minY: 0, maxX: 1, maxY: 1 } }); + +const line = (ax: number, ay: number, bx: number, by: number, drawingId: string | undefined = "d"): Primitive => + ({ kind: "line", a: { x: ax, y: ay }, b: { x: bx, y: by }, cls: "draw2d", weightMm: 0.18, drawingId }) as Primitive; +const poly = (pts: Array<[number, number]>, extra: Record = {}): Primitive => + ({ kind: "polygon", pts: pts.map(([x, y]) => ({ x, y })), fill: "#fff", stroke: "#000", strokeWidthMm: 0.1, ...extra }) as unknown as Primitive; + +function bruteForce(prims: Primitive[], m: { x: number; y: number }, maxDist: number): number | null { + let best: number | null = null; + let bestDist = maxDist; + prims.forEach((p, i) => { + if (p.kind !== "line" || !p.drawingId) return; + const dx = p.b.x - p.a.x, dy = p.b.y - p.a.y; + const len2 = dx * dx + dy * dy; + const t = len2 > 0 ? Math.max(0, Math.min(1, ((m.x - p.a.x) * dx + (m.y - p.a.y) * dy) / len2)) : 0; + const d = Math.hypot(m.x - (p.a.x + t * dx), m.y - (p.a.y + t * dy)); + if (d < bestDist) { + bestDist = d; + best = i; + } + }); + return best; +} + +describe("PlanPickIndex: Segmente", () => { + it("nächstes Segment wie die lineare Suche (Zufallsdaten, Überlauf-Segment, Nicht-2D-Strich)", () => { + let seed = 1; + const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647); + const prims: Primitive[] = []; + for (let i = 0; i < 20000; i++) { + const x = rnd() * 1000, y = rnd() * 1000; + prims.push(line(x, y, x + (rnd() - 0.5) * 20, y + (rnd() - 0.5) * 20)); + } + prims.push(line(-5000, -5000, 5000, 5000)); + prims.push(line(500, 500, 501, 501, undefined)); + const ix = new PlanPickIndex(plan(prims)); + for (let k = 0; k < 500; k++) { + const m = { x: rnd() * 1100 - 50, y: rnd() * 1100 - 50 }; + expect(ix.nearestSegment(m, 3)?.i ?? null).toBe(bruteForce(prims, m, 3)); + } + ix.release(); + }); + + it("nichts ausserhalb der Toleranz, nichts ohne 2D-Linien", () => { + const ix = new PlanPickIndex(plan([line(0, 0, 10, 0)])); + expect(ix.nearestSegment({ x: 5, y: 0.5 }, 1)).toEqual({ i: 0, dist: 0.5 }); + expect(ix.nearestSegment({ x: 5, y: 2 }, 1)).toBeNull(); + expect(ix.nearestSegment({ x: 500, y: 500 }, 1)).toBeNull(); + expect(new PlanPickIndex(plan([])).nearestSegment({ x: 0, y: 0 }, 1)).toBeNull(); + }); + + it("alle Segmente in Reichweite, nächste zuerst", () => { + const prims: Primitive[] = [line(0, 0, 10, 0, "a"), line(0, 0.5, 10, 0.5, "b"), line(0, 5, 10, 5, "c"), line(-2000, -2000, 2000, 2000, "long")]; + for (let i = 0; i < 300; i++) prims.push(line(50 + i, 50, 51 + i, 51, `f${i}`)); + const hits = new PlanPickIndex(plan(prims)).segmentsNear({ x: 5, y: 0.2 }, 1); + expect(hits.map((h) => (prims[h.i] as { drawingId?: string }).drawingId)).toEqual(["a", "b"]); + expect(hits[0].dist).toBeLessThanOrEqual(hits[1].dist); + }); +}); + +describe("PlanPickIndex: Polygone, Symbole, Ringe, Besitzer", () => { + const prims: Primitive[] = [ + poly([[0, 0], [4, 0], [4, 4], [0, 4]], { roomId: "r1" }), + poly([[1, 1], [3, 1], [3, 3], [1, 3]], { wallId: "w1", openingId: "o1" }), + line(0, 0, 1, 0, "d1"), + poly([[2, 2], [5, 2], [5, 5], [2, 5]], { stairId: "s1" }), + { kind: "line", a: { x: 10, y: 0 }, b: { x: 10, y: 5 }, cls: "door-leaf", weightMm: 0.25, openingId: "o2" } as Primitive, + { kind: "drawingCircle", center: { x: 20, y: 0 }, r: 1, fill: "none", stroke: "#000", weightMm: 0.25, drawingId: "c1" } as Primitive, + { kind: "drawingCircle", center: { x: 30, y: 0 }, r: 1, fill: "#f00", stroke: "#000", weightMm: 0.25, drawingId: "c2" } as Primitive, + line(0, 0, 1, 0, "d1"), + poly([[0, 0], [1, 0], [1, 1]], { roomId: "" }), + ]; + const ix = new PlanPickIndex(plan(prims)); + + it("Polygone unter dem Punkt: oberstes zuerst, mit Feld-Filter (leere Id zählt nicht)", () => { + const m = { x: 2.5, y: 2.5 }; + const all = prims.flatMap((p, i) => (p.kind === "polygon" && pointInPolygon(m, p.pts) ? [i] : [])).reverse(); + expect(ix.polygonsAt(m)).toEqual(all); + expect(ix.topPolygon(m)).toBe(3); + expect(ix.topPolygon(m, "roomId")).toBe(0); + expect(ix.bottomPolygon(m, "openingId")).toBe(1); + expect(ix.topPolygon({ x: 0.8, y: 0.2 }, "roomId")).toBe(0); + expect(ix.topPolygon({ x: 50, y: 50 })).toBeNull(); + }); + + it("Symbol-Linie in Client-Pixeln", () => { + const map = { left: 0, top: 0, viewX: 0, viewY: 0, scale: 1 }; + // Linie bei x = 10 m → 900 px; Punkt 3 px daneben. + expect(ix.nearestSymbolPx(["openingId"], [], map, { x: 903, y: -200 }, 6)).toBe(4); + expect(ix.nearestSymbolPx(["openingId"], [], map, { x: 910, y: -200 }, 6)).toBeNull(); + expect(ix.nearestSymbolPx(["stairId"], [], map, { x: 903, y: -200 }, 6)).toBeNull(); + }); + + it("Ringe: leerer Kreis nur am Rand, gefüllter auch innen", () => { + expect(ix.ringsNear({ x: 21.01, y: 0 }, 100, 6).map((r) => r.i)).toEqual([5]); + expect(ix.ringsNear({ x: 20, y: 0 }, 100, 6)).toEqual([]); + expect(ix.ringsNear({ x: 30, y: 0 }, 100, 6)).toEqual([{ i: 6, dpx: 0 }]); + }); + + it("Besitzer in Plan-Reihenfolge (Zeichnungs-Primitive nur über drawingId)", () => { + expect(ix.ownedBy("drawingId", ["d1"])).toEqual([prims[2], prims[7]]); + expect(ix.ownedBy("wallId", ["w1"])).toEqual([prims[1]]); + expect(ix.ownedBy("openingId", ["o1", "o2"])).toEqual([prims[1], prims[4]]); + expect(ix.ownedBy("roomId", [""])).toEqual([prims[8]]); + expect(ix.ownedBy("roomId", ["x"])).toEqual([]); + expect(ix.ownedBy("wallId", [])).toEqual([]); + }); + + it("Beispielprojekt: Kern-Abschnitte und eigener Puffer gemischt", () => { + const codes = new Set(flattenCategories(sampleProject.layers).map((c) => c.code)); + const p = generatePlan(sampleProject, "eg", codes); + const pi = new PlanPickIndex(p); + const wall = p.primitives.findIndex((q) => q.kind === "polygon" && !!q.wallId); + const w = p.primitives[wall] as Extract; + expect(pi.ownedBy("wallId", [w.wallId!])).toEqual(p.primitives.filter((q) => (q as { wallId?: string }).wallId === w.wallId)); + pi.release(); + }); +}); diff --git a/src/plan/planView/planPick.ts b/src/plan/planView/planPick.ts new file mode 100644 index 00000000..ce1b4b51 --- /dev/null +++ b/src/plan/planView/planPick.ts @@ -0,0 +1,149 @@ +// Auswahl/Picken im Grundriss über den Kern ([K3d], `src-tauri/core/src/plan_pick.rs`): ein +// räumlicher Index je Plan (2D-Zeichenlinien, Polygone, Symbol-Linien, Kreise/Bögen, Besitzer), +// gebaut direkt aus den Plan-Puffern (`planParts.ts`). TS fragt nur ab; Ergebnisse sind Indizes in +// `plan.primitives`. Ersetzt `segmentIndex.ts`, `ownerIndex.ts` und die Schleifen über alle +// Primitive bei jeder Mausbewegung (Treffer, Raum/Dach/Treppe/Öffnung …). +// +// Lebensdauer: der Index liegt im Kern, bis {@link PlanPickIndex.release} ihn freigibt (PlanView +// gibt den alten frei, sobald ein neuer Plan einen neuen braucht). + +import type { Vec2 } from "../../model/types"; +import type { Plan, Primitive } from "../generatePlan"; +import { heldSegs, planParts } from "../planParts"; +import { core } from "../../engine/coreWasm"; + +/** Pick-Felder eines Primitivs (Besitzer-Ids). */ +export const OWNER_FIELDS = [ + "wallId", + "drawingId", + "ceilingId", + "openingId", + "stairId", + "roomId", + "roofId", + "contextObjectId", + "sectionLineId", + "extrudedSolidId", + "columnId", +] as const; +export type OwnerField = (typeof OWNER_FIELDS)[number]; + +/** Pick-Art im Plan-Puffer (s. `plan_buf.rs`). */ +const KIND: Record = { + wallId: 1, + drawingId: 2, + ceilingId: 3, + openingId: 4, + stairId: 5, + roomId: 6, + extrudedSolidId: 7, + contextObjectId: 8, + columnId: 9, + roofId: 10, + sectionLineId: 11, +}; + +/** Bit-Maske der Felder (0 = keine Einschränkung). */ +const mask = (fields: readonly OwnerField[]): number => fields.reduce((m, f) => m | (1 << KIND[f]), 0); + +/** Abbildung Modell → Client-Pixel (`toScreen` + `vbToClient` der PlanView). */ +export interface ClientMap { + /** `rect.left + offX` */ + left: number; + /** `rect.top + offY` */ + top: number; + viewX: number; + viewY: number; + scale: number; +} + +export class PlanPickIndex { + private id = 0; + readonly prims: readonly Primitive[]; + + constructor(private readonly plan: Plan) { + this.prims = plan.primitives; + } + + /** Kern-Index (lazy beim ersten Abfragen gebaut). */ + private ix(): number { + if (this.id) return this.id; + const c = core(); + const parts = planParts(this.plan); + this.id = c.pick_index_build(heldSegs(parts, false)); + if (!this.id) this.id = c.pick_index_build(heldSegs(parts, true)); + return this.id; + } + + /** Kern-Index freigeben (danach baut eine Abfrage ihn neu). */ + release(): void { + if (this.id) core().pick_index_release(this.id); + this.id = 0; + } + + /** + * Nächstes Segment einer 2D-Zeichnung (`line` mit `drawingId`) mit Abstand < `maxDist` (Meter): + * Index und Abstand, oder null. + */ + nearestSegment(m: Vec2, maxDist: number): { i: number; dist: number } | null { + const f = core().pick_nearest_segment(this.ix(), m.x, m.y, maxDist); + return f.length === 2 ? { i: f[0], dist: f[1] } : null; + } + + /** Alle solchen Segmente mit Abstand < `maxDist`, nächste zuerst. */ + segmentsNear(m: Vec2, maxDist: number): Array<{ i: number; dist: number }> { + const f = core().pick_segments_near(this.ix(), m.x, m.y, maxDist); + const out: Array<{ i: number; dist: number }> = []; + for (let k = 0; k + 1 < f.length; k += 2) out.push({ i: f[k], dist: f[k + 1] }); + return out; + } + + /** + * Polygone, die `m` enthalten, oberstes (zuletzt gezeichnetes) zuerst; mit `fields` nur solche + * mit einer nicht-leeren Id eines dieser Felder. + */ + polygonsAt(m: Vec2, ...fields: OwnerField[]): number[] { + return Array.from(core().pick_polygons_at(this.ix(), m.x, m.y, mask(fields))); + } + + /** Oberstes Polygon unter `m` (s. {@link polygonsAt}) oder null. */ + topPolygon(m: Vec2, ...fields: OwnerField[]): number | null { + const l = this.polygonsAt(m, ...fields); + return l.length ? l[0] : null; + } + + /** Unterstes (zuerst gezeichnetes) Polygon unter `m` oder null. */ + bottomPolygon(m: Vec2, ...fields: OwnerField[]): number | null { + const l = this.polygonsAt(m, ...fields); + return l.length ? l[l.length - 1] : null; + } + + /** + * Nächste Symbol-Linie mit einer Id aus `lineFields` (bzw. Bogen über die Sehne `from → to` mit + * `arcFields`) zum Client-Punkt, Abstand in Pixeln < `maxPx`; erster bei Gleichstand. + */ + nearestSymbolPx(lineFields: OwnerField[], arcFields: OwnerField[], map: ClientMap, client: { x: number; y: number }, maxPx: number): number | null { + const i = core().pick_nearest_symbol_px(this.ix(), mask(lineFields), mask(arcFields), map.left, map.top, map.viewX, map.viewY, map.scale, client.x, client.y, maxPx); + return i >= 0 ? i : null; + } + + /** + * Kreise/Bögen der 2D-Zeichnung (`drawingCircle`/`drawingArc` mit `drawingId`), deren Ring + * näher als `tolPx` Pixel liegt (gefüllte Kreise auch innen; Bögen nur in ihrer Spanne mit + * `tolPx`-Saum) — in Plan-Reihenfolge, Abstand in Pixeln. + */ + ringsNear(m: Vec2, pxPerM: number, tolPx: number): Array<{ i: number; dpx: number }> { + const f = core().pick_rings_near(this.ix(), m.x, m.y, pxPerM, tolPx); + const out: Array<{ i: number; dpx: number }> = []; + for (let k = 0; k + 1 < f.length; k += 2) out.push({ i: f[k], dpx: f[k + 1] }); + return out; + } + + /** Primitive, deren `field` in `ids` liegt — in Plan-Reihenfolge. */ + ownedBy(field: OwnerField, ids: Iterable): Primitive[] { + const list = [...ids]; + if (list.length === 0) return []; + const hits = core().pick_owned_by(this.ix(), KIND[field], list.map((s) => "\u0000" + s).join("")); + return Array.from(hits, (i) => this.prims[i]); + } +} diff --git a/src/plan/planView/segmentIndex.test.ts b/src/plan/planView/segmentIndex.test.ts deleted file mode 100644 index e925c6de..00000000 --- a/src/plan/planView/segmentIndex.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { describe, it, expect } from "vitest"; -import type { Primitive } from "../generatePlan"; -import { buildSegmentIndex, nearestSegment } from "./segmentIndex"; - -const line = (ax: number, ay: number, bx: number, by: number, drawingId = "d"): Primitive => ({ - kind: "line", - a: { x: ax, y: ay }, - b: { x: bx, y: by }, - cls: "draw2d", - weightMm: 0.18, - drawingId, -}); - -function bruteForce(prims: Primitive[], m: { x: number; y: number }, maxDist: number): number | null { - let best: number | null = null; - let bestDist = maxDist; - prims.forEach((p, i) => { - if (p.kind !== "line" || !p.drawingId) return; - const dx = p.b.x - p.a.x, dy = p.b.y - p.a.y; - const len2 = dx * dx + dy * dy; - const t = len2 > 0 ? Math.max(0, Math.min(1, ((m.x - p.a.x) * dx + (m.y - p.a.y) * dy) / len2)) : 0; - const d = Math.hypot(m.x - (p.a.x + t * dx), m.y - (p.a.y + t * dy)); - if (d < bestDist) { - bestDist = d; - best = i; - } - }); - return best; -} - -describe("segmentIndex", () => { - it("liefert dasselbe Ergebnis wie die lineare Suche (Zufallsdaten)", () => { - let seed = 1; - const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647); - const prims: Primitive[] = []; - for (let i = 0; i < 20000; i++) { - const x = rnd() * 1000, y = rnd() * 1000; - prims.push(line(x, y, x + (rnd() - 0.5) * 20, y + (rnd() - 0.5) * 20)); - } - // Ein sehr langes Segment (landet in der Überlauf-Liste) + ein Nicht-2D-Strich. - prims.push(line(-5000, -5000, 5000, 5000)); - prims.push({ ...line(500, 500, 501, 501), drawingId: undefined } as Primitive); - const idx = buildSegmentIndex(prims)!; - expect(idx.long.length).toBe(1); - for (let k = 0; k < 500; k++) { - const m = { x: rnd() * 1100 - 50, y: rnd() * 1100 - 50 }; - expect(nearestSegment(idx, prims, m, 3)).toBe(bruteForce(prims, m, 3)); - } - }); - - it("null ohne indizierbare Linien", () => { - expect(buildSegmentIndex([])).toBeNull(); - }); - - it("findet nichts ausserhalb der Toleranz", () => { - const prims = [line(0, 0, 10, 0)]; - const idx = buildSegmentIndex(prims)!; - expect(nearestSegment(idx, prims, { x: 5, y: 0.5 }, 1)).toBe(0); - expect(nearestSegment(idx, prims, { x: 5, y: 2 }, 1)).toBeNull(); - expect(nearestSegment(idx, prims, { x: 500, y: 500 }, 1)).toBeNull(); - }); -}); - -describe("segmentsNear (alle Treffer, nächster zuerst)", () => { - it("liefert alle Segmente in Reichweite, sortiert, und entspricht der linearen Suche", async () => { - const { segmentsNear } = await import("./segmentIndex"); - const prims: Primitive[] = [line(0, 0, 10, 0, "a"), line(0, 0.5, 10, 0.5, "b"), line(0, 5, 10, 5, "c"), line(-2000, -2000, 2000, 2000, "long")]; - for (let i = 0; i < 300; i++) prims.push(line(50 + i, 50, 51 + i, 51, `f${i}`)); - const idx = buildSegmentIndex(prims)!; - const hits = segmentsNear(idx, prims, { x: 5, y: 0.2 }, 1); - expect(hits.map((h) => (prims[h.i] as any).drawingId)).toEqual(["a", "b"].concat(hits.length > 2 ? ["long"] : []).slice(0, hits.length)); - expect(hits[0].dist).toBeLessThanOrEqual(hits[1].dist); - expect(hits.every((h) => h.dist < 1)).toBe(true); - }); -}); diff --git a/src/plan/planView/segmentIndex.ts b/src/plan/planView/segmentIndex.ts deleted file mode 100644 index b4ce8031..00000000 --- a/src/plan/planView/segmentIndex.ts +++ /dev/null @@ -1,163 +0,0 @@ -// Uniformes Raster über die 'line'-Primitive eines Plans (Modell-Meter), damit -// Nächstes-Segment-Abfragen unter dem Cursor nur die Segmente der umliegenden -// Zellen prüfen statt ALLE Primitive. Ein Kataster-Import liefert 3,7 Mio. -// Segmente; die frühere lineare Suche lief bei JEDER Mausbewegung über alle. -// -// Speicher als CSR (Zell-Offsets + flacher Index-Array, Typed Arrays) statt -// eines Arrays pro Zelle: Millionen kleiner JS-Arrays wären selbst teuer. - -import type { Vec2 } from "../../model/types"; -import type { Primitive } from "../generatePlan"; - -export interface SegmentIndex { - minX: number; - minY: number; - cell: number; - cols: number; - rows: number; - /** cellStart[c]..cellStart[c+1] = Bereich in `items` für Zelle c. */ - cellStart: Uint32Array; - /** Primitiv-Indizes, nach Zelle gruppiert. */ - items: Uint32Array; - /** Segmente, deren Bounding-Box zu viele Zellen überdeckt — immer geprüft. */ - long: Uint32Array; -} - -/** Ziel: im Mittel so viele Segmente je Zelle. */ -const TARGET_PER_CELL = 8; -/** Obergrenze der Zellzahl (Speicher für `cellStart`). */ -const MAX_CELLS = 4_000_000; -/** Ab so vielen überdeckten Zellen landet ein Segment in `long` statt im Raster. */ -const MAX_CELLS_PER_SEGMENT = 1024; - -/** Ob ein Primitiv in den Index gehört (2D-Zeichenlinien, s. Hover-Teilpunkte). */ -const indexed = (p: Primitive): p is Extract => - p.kind === "line" && !!p.drawingId; - -export function buildSegmentIndex(prims: readonly Primitive[]): SegmentIndex | null { - let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; - let n = 0; - for (const p of prims) { - if (!indexed(p)) continue; - n++; - minX = Math.min(minX, p.a.x, p.b.x); - maxX = Math.max(maxX, p.a.x, p.b.x); - minY = Math.min(minY, p.a.y, p.b.y); - maxY = Math.max(maxY, p.a.y, p.b.y); - } - if (n === 0) return null; - - const w = Math.max(maxX - minX, 1e-6); - const h = Math.max(maxY - minY, 1e-6); - const cellCount = Math.min(MAX_CELLS, Math.max(1, Math.ceil(n / TARGET_PER_CELL))); - let cell = Math.sqrt((w * h) / cellCount); - if (!(cell > 0)) cell = Math.max(w, h); - const cols = Math.max(1, Math.ceil(w / cell)); - const rows = Math.max(1, Math.ceil(h / cell)); - - const cx = (x: number) => Math.min(cols - 1, Math.max(0, Math.floor((x - minX) / cell))); - const cy = (y: number) => Math.min(rows - 1, Math.max(0, Math.floor((y - minY) / cell))); - - // Zwei Durchläufe (zählen, dann füllen) — jedes Segment landet in jeder Zelle, - // die seine Bounding-Box berührt. - const counts = new Uint32Array(cols * rows + 1); - const long: number[] = []; - for (let i = 0; i < prims.length; i++) { - const p = prims[i]; - if (!indexed(p)) continue; - const x0 = cx(Math.min(p.a.x, p.b.x)), x1 = cx(Math.max(p.a.x, p.b.x)); - const y0 = cy(Math.min(p.a.y, p.b.y)), y1 = cy(Math.max(p.a.y, p.b.y)); - if ((x1 - x0 + 1) * (y1 - y0 + 1) > MAX_CELLS_PER_SEGMENT) { - long.push(i); - continue; - } - for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) counts[y * cols + x + 1]++; - } - const longSet = new Set(long); - for (let c = 1; c < counts.length; c++) counts[c] += counts[c - 1]; - const cellStart = counts; - const fill = cellStart.slice(0, cols * rows); - const items = new Uint32Array(cellStart[cols * rows]); - for (let i = 0; i < prims.length; i++) { - const p = prims[i]; - if (!indexed(p) || longSet.has(i)) continue; - const x0 = cx(Math.min(p.a.x, p.b.x)), x1 = cx(Math.max(p.a.x, p.b.x)); - const y0 = cy(Math.min(p.a.y, p.b.y)), y1 = cy(Math.max(p.a.y, p.b.y)); - for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) items[fill[y * cols + x]++] = i; - } - return { minX, minY, cell, cols, rows, cellStart, items, long: Uint32Array.from(long) }; -} - -export function pointSegDist(p: Vec2, a: Vec2, b: Vec2): number { - const dx = b.x - a.x, dy = b.y - a.y; - const len2 = dx * dx + dy * dy; - let t = len2 > 0 ? ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2 : 0; - t = Math.max(0, Math.min(1, t)); - return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy)); -} - -/** - * Nächstes indiziertes Segment zu `m` (Modell-Meter) mit Abstand < `maxDist` - * (Modell-Meter), oder null. Liefert den Primitiv-Index. - */ -export function nearestSegment( - index: SegmentIndex, - prims: readonly Primitive[], - m: Vec2, - maxDist: number, -): number | null { - const { minX, minY, cell, cols, rows, cellStart, items, long } = index; - let best: number | null = null; - let bestDist = maxDist; - const consider = (i: number) => { - const p = prims[i] as Extract; - const d = pointSegDist(m, p.a, p.b); - if (d < bestDist) { - bestDist = d; - best = i; - } - }; - for (const i of long) consider(i); - const x0 = Math.floor((m.x - maxDist - minX) / cell); - const x1 = Math.floor((m.x + maxDist - minX) / cell); - const y0 = Math.floor((m.y - maxDist - minY) / cell); - const y1 = Math.floor((m.y + maxDist - minY) / cell); - if (x1 < 0 || y1 < 0 || x0 >= cols || y0 >= rows) return best; - for (let y = Math.max(0, y0); y <= Math.min(rows - 1, y1); y++) { - for (let x = Math.max(0, x0); x <= Math.min(cols - 1, x1); x++) { - const c = y * cols + x; - for (let k = cellStart[c]; k < cellStart[c + 1]; k++) consider(items[k]); - } - } - return best; -} - -/** ALLE indizierten Segmente mit Abstand < `maxDist` (Modell-Einheiten), nächste zuerst. */ -export function segmentsNear( - index: SegmentIndex, - prims: readonly Primitive[], - m: Vec2, - maxDist: number, -): Array<{ i: number; dist: number }> { - const { minX, minY, cell, cols, rows, cellStart, items, long } = index; - const found = new Map(); - const consider = (i: number) => { - const p = prims[i] as Extract; - const d = pointSegDist(m, p.a, p.b); - if (d < maxDist) found.set(i, d); - }; - for (const i of long) consider(i); - const x0 = Math.floor((m.x - maxDist - minX) / cell); - const x1 = Math.floor((m.x + maxDist - minX) / cell); - const y0 = Math.floor((m.y - maxDist - minY) / cell); - const y1 = Math.floor((m.y + maxDist - minY) / cell); - if (!(x1 < 0 || y1 < 0 || x0 >= cols || y0 >= rows)) { - for (let y = Math.max(0, y0); y <= Math.min(rows - 1, y1); y++) { - for (let x = Math.max(0, x0); x <= Math.min(cols - 1, x1); x++) { - const c = y * cols + x; - for (let k = cellStart[c]; k < cellStart[c + 1]; k++) consider(items[k]); - } - } - } - return [...found].map(([i, dist]) => ({ i, dist })).sort((a, b) => a.dist - b.dist); -} diff --git a/src/plan/planView/underlayAccess.test.ts b/src/plan/planView/underlayAccess.test.ts index 04cae340..32235861 100644 --- a/src/plan/planView/underlayAccess.test.ts +++ b/src/plan/planView/underlayAccess.test.ts @@ -5,7 +5,7 @@ import { describe, it, expect } from "vitest"; import type { Drawing2D, Project } from "../../model/types"; import { generatePlan, materializeUnderlay } from "../generatePlan"; import { marqueeHitDrawings } from "./geometry"; -import { buildSegmentIndex, nearestSegment } from "./segmentIndex"; +import { PlanPickIndex } from "./planPick"; import { buildDrawingIndex, marqueeHitUnderlay, nearestInDrawings } from "./underlayAccess"; let seed = 7; @@ -53,12 +53,12 @@ describe("underlayAccess == Primitiv-Varianten", () => { it("nächstes Segment == Segment-Index der Primitive", () => { const idx = buildDrawingIndex(under)!; - const segIdx = buildSegmentIndex(normal.primitives)!; + const segIdx = new PlanPickIndex(normal); for (let k = 0; k < 400; k++) { const m = { x: rnd() * 540 - 20, y: rnd() * 540 - 20 }; const a = nearestInDrawings(idx, m, 2); - const bi = nearestSegment(segIdx, normal.primitives, m, 2); - const b = bi === null ? null : (normal.primitives[bi] as any); + const bi = segIdx.nearestSegment(m, 2); + const b = bi === null ? null : (normal.primitives[bi.i] as any); expect(a?.drawing.id ?? null).toBe(b?.drawingId ?? null); } }); diff --git a/src/plan/toRenderScene.test.ts b/src/plan/toRenderScene.test.ts index 2bd0e453..3dd64cdf 100644 --- a/src/plan/toRenderScene.test.ts +++ b/src/plan/toRenderScene.test.ts @@ -29,8 +29,8 @@ describe("planToRenderScene (Kern)", () => { }); it("näht unterdrückte Kanten zweier Polygone zu einem Ring", () => { - const a: Primitive = { kind: "polygon", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }], fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [1] }; - const b: Primitive = { kind: "polygon", pts: [{ x: 1, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 1 }, { x: 1, y: 1 }], fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [3] }; + const a: Primitive = { kind: "polygon", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }], fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [1] } as Primitive; + const b: Primitive = { kind: "polygon", pts: [{ x: 1, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 1 }, { x: 1, y: 1 }], fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [3] } as Primitive; const s = planToRenderScene(planOf([a, b])); expect(s.fills.length).toBe(2); expect(s.outlines.length).toBe(1); diff --git a/src/views/plan/PlanView.tsx b/src/views/plan/PlanView.tsx index 6aa3066d..4a5fc7dc 100644 --- a/src/views/plan/PlanView.tsx +++ b/src/views/plan/PlanView.tsx @@ -31,7 +31,7 @@ import { isGpuText } from "../../core"; import { LiveMeet, LiveValue, createMeetStore, createValueStore } from "./planView/liveMeet"; import { useWasmPlanRenderer } from "./useWasmPlanRenderer"; import { DEFAULT_MARQUEE_COLOR, DEFAULT_SNAP_COLOR } from "../../theme/accents"; -import { type ViewBox__plan_planView_geometry as ViewBox, PX_PER_M, PAD, toScreen, clamp, meetScale, scaleFromView, viewForScale, viewForCamera, fitBoxFor, pointInPolygon, pointSegDistPx, marqueeHit, marqueeHitDrawings, type ModelRect, marqueeHitCeilings, marqueeHitRooms, marqueeHitStairs } from "../../core"; +import { type ViewBox__plan_planView_geometry as ViewBox, PX_PER_M, PAD, toScreen, clamp, meetScale, scaleFromView, viewForScale, viewForCamera, fitBoxFor, marqueeHit, marqueeHitDrawings, type ModelRect, marqueeHitCeilings, marqueeHitRooms, marqueeHitStairs } from "../../core"; import { polyUsesPattern, HatchPattern, @@ -44,8 +44,7 @@ import { DraftOverlay } from "./planView/overlays"; import { PlanRulers } from "./planView/PlanRulers"; import { PlanGrid } from "./planView/PlanGrid"; import { expandRegion, indexedInRegion, regionContains, type Bounds } from "../../core"; -import { buildSegmentIndex, nearestSegment, pointSegDist__plan_planView_segmentIndex as pointSegDist, segmentsNear } from "../../core"; -import { buildOwnerIndex, ownedBy, type OwnerField, type OwnerIndex } from "../../core"; +import { PlanPickIndex, type ClientMap, type OwnerField } from "../../core"; import { buildDrawingIndex, drawingsWithinDistance, marqueeHitUnderlay, nearestInDrawings, type DrawingIndex } from "../../core"; import { endBusyAfterPaint } from "../../state/busyStore"; import { createCursorStore, useCursorValue, type CursorStore } from "../../state/cursorStore"; @@ -760,17 +759,19 @@ export const PlanView = forwardRef( // zoomen (view schrumpft stark — reines "liegt noch drin" reicht hier // NICHT, ein View, der nur kleiner wird, bleibt sonst fälschlich innerhalb // der alten, zu grosszügigen Region) wird neu gerechnet. - // Raster-Index der 2D-Zeichenlinien für Hover-/Pick-Abfragen (s. segmentIndex.ts). - // LAZY (erst beim ersten Hover/Klick je Plan): der Aufbau kostet bei 3,7 Mio. - // Segmenten ~250 ms und lief sonst bei JEDEM Plan-/Ebenenwechsel. - const segmentIndexRef = useRef<{ prims: readonly Primitive[]; index: ReturnType } | null>(null); - const getSegmentIndex = () => { - const cached = segmentIndexRef.current; - if (cached && cached.prims === planRaw.primitives) return cached.index; - const index = buildSegmentIndex(planRaw.primitives); - segmentIndexRef.current = { prims: planRaw.primitives, index }; - return index; + // Auswahl-Index im Kern (s. planView/planPick.ts): 2D-Zeichenlinien, Polygone, Symbol-Linien, + // Kreise/Bögen und Besitzer über `plan.primitives` (dieselben Indizes). LAZY: der Kern baut ihn + // erst bei der ersten Abfrage je Plan; der vorige wird dann freigegeben. + const pickIndexRef = useRef(null); + const getPick = (): PlanPickIndex => { + const cached = pickIndexRef.current; + if (cached && cached.prims === plan.primitives) return cached; + cached?.release(); + const ix = new PlanPickIndex(plan); + pickIndexRef.current = ix; + return ix; }; + useEffect(() => () => pickIndexRef.current?.release(), []); const svgRef = useRef(null); const canvasRef = useRef(null); @@ -831,6 +832,17 @@ export const PlanView = forwardRef( const lines = !useGpuRenderer || wantWasm; return materializeGreyed(lines ? materializeUnderlay(planRaw) : planRaw, lines); }, [planRaw, useGpuRenderer, wantWasm]); + // Einzeltexte und Bilder (eigene Bbox-Treffer): einmal je Plan gesammelt statt bei jeder + // Mausbewegung über alle Primitive zu laufen. + const textImageIdx = useMemo(() => { + const texts: number[] = []; + const images: number[] = []; + plan.primitives.forEach((p, i) => { + if (p.kind === "drawingText") texts.push(i); + else if (p.kind === "drawingImage") images.push(i); + }); + return { texts, images }; + }, [plan.primitives]); // Kompakte Linien-Unterlage (nur im reinen WebGL-Modus noch als `plan.underlay` // vorhanden): Hover/Pick/Marquee/Hervorhebung greifen direkt auf die Zeichnungen @@ -1347,6 +1359,11 @@ export const PlanView = forwardRef( const top = rect?.top ?? 0; return { x: left + offX + (vbX - view.x) * scale, y: top + offY + (vbY - view.y) * scale }; }; + // Abbildung Modell → Client-Pixel (toScreen + vbToClient) für Pixel-Abfragen im Kern. + const clientMap = (): ClientMap => { + const { rect, scale, offX, offY } = measure(view); + return { left: (rect?.left ?? 0) + offX, top: (rect?.top ?? 0) + offY, viewX: view.x, viewY: view.y, scale }; + }; // Index des Griffs unter dem Cursor (Bildschirm-Pixel) oder null. const gripAt = (clientX: number, clientY: number): number | null => { if (!grips) return null; @@ -1410,13 +1427,7 @@ export const PlanView = forwardRef( // Reihenfolge testen, damit das zuletzt gezeichnete (oberste) zuerst trifft. const hitTest = (clientX: number, clientY: number): number | null => { const v = clientToView(clientX, clientY, view); - const m = viewToModel(v.x, v.y); - const prims = plan.primitives; - for (let i = prims.length - 1; i >= 0; i--) { - const p = prims[i]; - if (p.kind === "polygon" && pointInPolygon(m, p.pts)) return i; - } - return null; + return getPick().topPolygon(viewToModel(v.x, v.y)); }; // Irgendein Element (Wand/Decke/Raum/Treppe/Stütze/Dach/2D) unter dem @@ -1443,64 +1454,32 @@ export const PlanView = forwardRef( return did ? { drawingId: did } : null; }; - // Abstand (Bildschirm-Pixel) eines Klicks vom Ring eines Kreis/Bogen-2D- - // Elements — bei gefüllten Kreisen zählt auch INNERHALB als Treffer (d=0). - // Bögen zusätzlich auf ihre Winkel-Spanne begrenzt (CCW, Modell-Radiant, s. - // toRenderScene.ts für dieselbe Normalisierung). - const distToDrawingRing = ( - clientX: number, - clientY: number, - p: Extract, - ): number => { - const m = rawModelAt(clientX, clientY); - const distFromCenter = Math.hypot(m.x - p.center.x, m.y - p.center.y); - if (p.kind === "drawingArc") { - const TAU = Math.PI * 2; - const sweep = (((p.a1 - p.a0) % TAU) + TAU) % TAU || TAU; - const ang = Math.atan2(m.y - p.center.y, m.x - p.center.x); - const rel = (((ang - p.a0) % TAU) + TAU) % TAU; - // Kleiner Winkel-Toleranzsaum (in Bogenmass, radiusabhängig), damit die - // Enden eines kurzen Bogens nicht unerreichbar schmal werden. - const angTolRad = distFromCenter > 1e-6 ? LINE_PICK_PX / (currentPxPerMeter() * Math.max(distFromCenter, 0.05)) : Infinity; - if (rel > sweep + angTolRad && TAU - rel > angTolRad) return Infinity; - } - const filled = p.kind === "drawingCircle" && p.fill !== "none"; - const dMeters = filled ? Math.max(0, distFromCenter - p.r) : Math.abs(distFromCenter - p.r); - return dMeters * currentPxPerMeter(); - }; - // Nächstgelegenes 2D-Zeichenelement (Drawing2D) zum Cursor per Linien-Nähe in // Bildschirm-Pixeln (zoom-unabhängige Toleranz). Liefert die drawingId oder null. const pickDrawing = (clientX: number, clientY: number): string | null => { let bestId: string | null = null; let bestDist = LINE_PICK_PX; - const segmentIndex = getSegmentIndex(); - if (segmentIndex) { - const pxPerM = currentPxPerMeter(); - const m = rawModelAt(clientX, clientY); - const i = nearestSegment(segmentIndex, plan.primitives, m, LINE_PICK_PX / pxPerM); - if (i !== null) { - const p = plan.primitives[i] as Extract; - bestId = p.drawingId!; - bestDist = pointSegDist(m, p.a, p.b) * pxPerM; - } + const pick = getPick(); + const pxPerM = currentPxPerMeter(); + const m = rawModelAt(clientX, clientY); + const seg = pick.nearestSegment(m, LINE_PICK_PX / pxPerM); + if (seg) { + bestId = (plan.primitives[seg.i] as Extract).drawingId!; + bestDist = seg.dist * pxPerM; } const uIndex = getUnderlayIndex(); if (uIndex) { - const pxPerM = currentPxPerMeter(); - const hit = nearestInDrawings(uIndex, rawModelAt(clientX, clientY), bestDist / pxPerM); + const hit = nearestInDrawings(uIndex, m, bestDist / pxPerM); if (hit) { bestId = hit.drawing.id; bestDist = hit.dist * pxPerM; } } - for (const p of plan.primitives) { - if ((p.kind === "drawingCircle" || p.kind === "drawingArc") && p.drawingId) { - const d = distToDrawingRing(clientX, clientY, p); - if (d < bestDist) { - bestDist = d; - bestId = p.drawingId; - } + // Kreise/Bögen (Ring-Abstand wie früher `distToDrawingRing`), in Plan-Reihenfolge. + for (const { i, dpx } of pick.ringsNear(m, pxPerM, LINE_PICK_PX)) { + if (dpx < bestDist) { + bestDist = dpx; + bestId = (plan.primitives[i] as Extract).drawingId!; } } if (bestId) return bestId; @@ -1519,14 +1498,11 @@ export const PlanView = forwardRef( const maxDist = LINE_PICK_PX / currentPxPerMeter(); let best: { a: Vec2; b: Vec2 } | null = null; let bestDist = maxDist; - const segmentIndex = getSegmentIndex(); - if (segmentIndex) { - const i = nearestSegment(segmentIndex, plan.primitives, m, maxDist); - if (i !== null) { - const p = plan.primitives[i] as Extract; - best = { a: p.a, b: p.b }; - bestDist = pointSegDist(m, p.a, p.b); - } + const seg = getPick().nearestSegment(m, maxDist); + if (seg) { + const p = plan.primitives[seg.i] as Extract; + best = { a: p.a, b: p.b }; + bestDist = seg.dist; } const uIndex = getUnderlayIndex(); if (uIndex) { @@ -1541,7 +1517,8 @@ export const PlanView = forwardRef( // Winkel wird vernachlässigt (meist waagrecht). Liefert die drawingId oder null. const pickDrawingText = (clientX: number, clientY: number): string | null => { const m = rawModelAt(clientX, clientY); - for (const p of plan.primitives) { + for (const i of textImageIdx.texts) { + const p = plan.primitives[i]; if (p.kind !== "drawingText" || !p.drawingId) continue; const singleW = Math.max(1, p.text.length) * p.heightM * 0.6; // Textspalte: Breite = wrapWidth, Höhe = geschätzte Zeilenzahl · Zeilenhöhe. @@ -1566,8 +1543,8 @@ export const PlanView = forwardRef( // oder null. const pickDrawingImage = (clientX: number, clientY: number): string | null => { const m = rawModelAt(clientX, clientY); - for (let i = plan.primitives.length - 1; i >= 0; i--) { - const p = plan.primitives[i]; + for (let k = textImageIdx.images.length - 1; k >= 0; k--) { + const p = plan.primitives[textImageIdx.images[k]]; if (p.kind !== "drawingImage" || !p.drawingId) continue; if (m.x >= p.min.x && m.x <= p.max.x && m.y >= p.min.y && m.y <= p.max.y) { return p.drawingId; @@ -1580,33 +1557,14 @@ export const PlanView = forwardRef( // `openingId` per Bildschirm-Nähe, plus getroffene Fenster-Rahmen (Polygon mit // openingId, per Punkt-in-Polygon). Liefert die openingId oder null. const pickOpening = (clientX: number, clientY: number): string | null => { - let bestId: string | null = null; - let bestDist = LINE_PICK_PX; const v = clientToView(clientX, clientY, view); const m = viewToModel(v.x, v.y); - for (const p of plan.primitives) { - if (p.kind === "line" && p.openingId) { - const a = vbToClient(toScreen(p.a).x, toScreen(p.a).y); - const b = vbToClient(toScreen(p.b).x, toScreen(p.b).y); - const d = pointSegDistPx({ x: clientX, y: clientY }, a, b); - if (d < bestDist) { - bestDist = d; - bestId = p.openingId; - } - } else if (p.kind === "arc" && p.openingId) { - // Bogen: über from→to als Sehne annähern (ausreichend für die Auswahl). - const a = vbToClient(toScreen(p.from).x, toScreen(p.from).y); - const b = vbToClient(toScreen(p.to).x, toScreen(p.to).y); - const d = pointSegDistPx({ x: clientX, y: clientY }, a, b); - if (d < bestDist) { - bestDist = d; - bestId = p.openingId; - } - } else if (p.kind === "polygon" && p.openingId && pointInPolygon(m, p.pts)) { - return p.openingId; - } - } - return bestId; + const pick = getPick(); + // Getroffener Rahmen (das zuerst gezeichnete Polygon) hat Vorrang vor Symbol-Linien. + const hit = pick.bottomPolygon(m, "openingId"); + if (hit !== null) return (plan.primitives[hit] as { openingId?: string }).openingId!; + const i = pick.nearestSymbolPx(["openingId"], ["openingId"], clientMap(), { x: clientX, y: clientY }, LINE_PICK_PX); + return i === null ? null : (plan.primitives[i] as { openingId?: string }).openingId!; }; // Nächstgelegene Treppe zum Cursor: getroffenes Tritt-/Podest-Polygon (per @@ -1614,67 +1572,35 @@ export const PlanView = forwardRef( const pickStair = (clientX: number, clientY: number): string | null => { const v = clientToView(clientX, clientY, view); const m = viewToModel(v.x, v.y); - for (const p of plan.primitives) { - if (p.kind === "polygon" && p.stairId && pointInPolygon(m, p.pts)) { - return p.stairId; - } - } - let bestId: string | null = null; - let bestDist = LINE_PICK_PX; - for (const p of plan.primitives) { - if (p.kind === "line" && p.stairId) { - const a = vbToClient(toScreen(p.a).x, toScreen(p.a).y); - const b = vbToClient(toScreen(p.b).x, toScreen(p.b).y); - const d = pointSegDistPx({ x: clientX, y: clientY }, a, b); - if (d < bestDist) { - bestDist = d; - bestId = p.stairId; - } - } - } - return bestId; + const pick = getPick(); + const hit = pick.bottomPolygon(m, "stairId"); + if (hit !== null) return (plan.primitives[hit] as { stairId?: string }).stairId!; + const i = pick.nearestSymbolPx(["stairId"], [], clientMap(), { x: clientX, y: clientY }, LINE_PICK_PX); + return i === null ? null : (plan.primitives[i] as { stairId?: string }).stairId!; }; // Getroffener Raum: die Raum-Fläche (Polygon mit `roomId`) per Punkt-in-Polygon. // Bei überlappenden Räumen gewinnt der zuletzt gezeichnete (oberste). const pickRoom = (clientX: number, clientY: number): string | null => { const v = clientToView(clientX, clientY, view); - const m = viewToModel(v.x, v.y); - for (let i = plan.primitives.length - 1; i >= 0; i--) { - const p = plan.primitives[i]; - if (p.kind === "polygon" && p.roomId && pointInPolygon(m, p.pts)) { - return p.roomId; - } - } - return null; + const i = getPick().topPolygon(viewToModel(v.x, v.y), "roomId"); + return i === null ? null : (plan.primitives[i] as { roomId?: string }).roomId!; }; // Getroffenes Dach: das unsichtbare Traufe-Pick-Polygon per Punkt-in-Polygon // (die sichtbaren Dachlinien allein wären schwer exakt zu treffen). const pickRoof = (clientX: number, clientY: number): string | null => { const v = clientToView(clientX, clientY, view); - const m = viewToModel(v.x, v.y); - for (let i = plan.primitives.length - 1; i >= 0; i--) { - const p = plan.primitives[i]; - if (p.kind === "polygon" && p.roofId && pointInPolygon(m, p.pts)) { - return p.roofId; - } - } - return null; + const i = getPick().topPolygon(viewToModel(v.x, v.y), "roofId"); + return i === null ? null : (plan.primitives[i] as { roofId?: string }).roofId!; }; // Getroffene Schnitt-/Ansichtslinie: ihr schmales, unsichtbares Pick-Band // (Polygon mit sectionLineId) per Punkt-in-Polygon. const pickSectionLine = (clientX: number, clientY: number): string | null => { const v = clientToView(clientX, clientY, view); - const m = viewToModel(v.x, v.y); - for (let i = plan.primitives.length - 1; i >= 0; i--) { - const p = plan.primitives[i]; - if (p.kind === "polygon" && p.sectionLineId && pointInPolygon(m, p.pts)) { - return p.sectionLineId; - } - } - return null; + const i = getPick().topPolygon(viewToModel(v.x, v.y), "sectionLineId"); + return i === null ? null : (plan.primitives[i] as { sectionLineId?: string }).sectionLineId!; }; // Getroffenes Kontext-Objekt (importiertes Gebäude/Terrain): sein unsichtbares @@ -1683,14 +1609,8 @@ export const PlanView = forwardRef( // dünnen Umrisslinie. const pickContextObject = (clientX: number, clientY: number): string | null => { const v = clientToView(clientX, clientY, view); - const m = viewToModel(v.x, v.y); - for (let i = plan.primitives.length - 1; i >= 0; i--) { - const p = plan.primitives[i]; - if (p.kind === "polygon" && p.contextObjectId && pointInPolygon(m, p.pts)) { - return p.contextObjectId; - } - } - return null; + const i = getPick().topPolygon(viewToModel(v.x, v.y), "contextObjectId"); + return i === null ? null : (plan.primitives[i] as { contextObjectId?: string }).contextObjectId!; }; // Getroffener extrudierter Körper (truck-Integration): der Footprint-Umriss @@ -1698,28 +1618,16 @@ export const PlanView = forwardRef( // trotzdem als FLÄCHE anklickbar (analog Raum, nicht nur auf der Linie). const pickExtrudedSolid = (clientX: number, clientY: number): string | null => { const v = clientToView(clientX, clientY, view); - const m = viewToModel(v.x, v.y); - for (let i = plan.primitives.length - 1; i >= 0; i--) { - const p = plan.primitives[i]; - if (p.kind === "polygon" && p.extrudedSolidId && pointInPolygon(m, p.pts)) { - return p.extrudedSolidId; - } - } - return null; + const i = getPick().topPolygon(viewToModel(v.x, v.y), "extrudedSolidId"); + return i === null ? null : (plan.primitives[i] as { extrudedSolidId?: string }).extrudedSolidId!; }; // Getroffene Stütze (Tragwerk): ihr Querschnitt ist eine gefüllte Poché // (Polygon mit columnId) — per Punkt-in-Polygon als FLÄCHE anklickbar. const pickColumn = (clientX: number, clientY: number): string | null => { const v = clientToView(clientX, clientY, view); - const m = viewToModel(v.x, v.y); - for (let i = plan.primitives.length - 1; i >= 0; i--) { - const p = plan.primitives[i]; - if (p.kind === "polygon" && p.columnId && pointInPolygon(m, p.pts)) { - return p.columnId; - } - } - return null; + const i = getPick().topPolygon(viewToModel(v.x, v.y), "columnId"); + return i === null ? null : (plan.primitives[i] as { columnId?: string }).columnId!; }; // Liegt der Cursor auf dem KÖRPER eines GEWÄHLTEN Elements (Wand-Poché bzw. @@ -2311,16 +2219,7 @@ export const PlanView = forwardRef( }, [pickList]); /** Alle Polygone unter dem Cursor, oberstes zuerst. */ - const hitTestAll = (clientX: number, clientY: number): number[] => { - const m = rawModelAt(clientX, clientY); - const prims = plan.primitives; - const out: number[] = []; - for (let i = prims.length - 1; i >= 0; i--) { - const p = prims[i]; - if (p.kind === "polygon" && pointInPolygon(m, p.pts)) out.push(i); - } - return out; - }; + const hitTestAll = (clientX: number, clientY: number): number[] => getPick().polygonsAt(rawModelAt(clientX, clientY)); /** Bezeichnung eines 2D-Elements nach Form (Linie/Fläche/Text/Kreis/…). */ const drawingLabel = (id: string): string => { @@ -2355,20 +2254,15 @@ export const PlanView = forwardRef( const m = rawModelAt(clientX, clientY); const tol = LINE_PICK_PX / pxPerM; const found: Array<{ id: string; d: number }> = []; - const segIdx = getSegmentIndex(); - if (segIdx) { - for (const { i, dist } of segmentsNear(segIdx, plan.primitives, m, tol)) { - const id = (plan.primitives[i] as Extract).drawingId; - if (id) found.push({ id, d: dist }); - } + const pick = getPick(); + for (const { i, dist } of pick.segmentsNear(m, tol)) { + const id = (plan.primitives[i] as Extract).drawingId; + if (id) found.push({ id, d: dist }); } const uIdx = getUnderlayIndex(); if (uIdx) for (const h of drawingsWithinDistance(uIdx, m, tol)) found.push({ id: h.drawing.id, d: h.dist }); - for (const p of plan.primitives) { - if ((p.kind === "drawingCircle" || p.kind === "drawingArc") && p.drawingId) { - const dpx = distToDrawingRing(clientX, clientY, p); - if (dpx < LINE_PICK_PX) found.push({ id: p.drawingId, d: dpx / pxPerM }); - } + for (const { i, dpx } of pick.ringsNear(m, pxPerM, LINE_PICK_PX)) { + found.push({ id: (plan.primitives[i] as Extract).drawingId!, d: dpx / pxPerM }); } const textId = pickDrawingText(clientX, clientY); if (textId) found.push({ id: textId, d: tol * 2 }); @@ -2779,21 +2673,15 @@ export const PlanView = forwardRef( // gewählten Wand umrandet. Ohne Wand-Auswahl greift die lokale Klick- // Hervorhebung (ein einzelnes Polygon per hitIndex), z. B. für Polygone ohne // Wandbezug. - // Besitzer-Index (s. planView/ownerIndex.ts): EIN Durchgang je Plan, lazy beim - // ersten Bedarf — statt je Elementart ein `plan.primitives.filter`. - const ownerIndexRef = useRef<{ prims: readonly Primitive[]; index: OwnerIndex } | null>(null); + // Besitzer über den Auswahl-Index im Kern (s. planView/planPick.ts) — statt je Elementart ein + // `plan.primitives.filter`. const primsOwnedBy = ( field: OwnerField, ids: ReadonlyArray | undefined, keep: (p: Primitive) => p is K, ): K[] => { if (!ids || ids.length === 0) return []; - let cached = ownerIndexRef.current; - if (!cached || cached.prims !== plan.primitives) { - cached = { prims: plan.primitives, index: buildOwnerIndex(plan.primitives) }; - ownerIndexRef.current = cached; - } - return ownedBy(cached.index, plan.primitives, field, ids).filter(keep); + return getPick().ownedBy(field, ids).filter(keep); }; const highlightPolys = useMemo(() => { From 1fe83d6349e13c8fc6a84d5511df230d60de6cc9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 23:28:22 +0000 Subject: [PATCH 3/5] [K3d] Objektfang auf Strecken im Kern (Lot, Endpunkt, Mitte, Schnitt, Kante, Verweilen) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit core/src/snap.rs (+ web/snap.rs, Fassade src/geometry/snapSegments.ts): die Strecken eines Projekt-Geschosses liegen einmal im Kern (Raster über den Boxen); je Mausbewegung nur Cursor, Toleranz und Entwurfs-/Blattstrecken. Schnittpunkte nur noch zwischen Geraden, die näher als die Fangtoleranz am Cursor vorbeigehen (andere Paare können nichts beitragen; Reihenfolge bleibt) — vorher alle Paare. computeSnap führt die Kern-Blöcke in der alten Reihenfolge mit den eigenen Kandidaten zusammen; Raum-Anker, Kreise, Ellipsen je Projekt/Geschoss gecacht. Gleich zur alten Fassung (2600 Abfragen: Beispielprojekt, mit 2D-Zeichnung, Nahmodus > 2000 Zeichnungen, bigSample(3), Verweilen an/aus, alle Fang-Arten zufällig). Grosses Projekt (20×20 Kacheln): 27,6 s → 0,8 ms je Mausbewegung; bigSample(5): 135 ms → 57 µs. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/plan_pick.rs | 10 +- src-tauri/core/src/snap.rs | 272 ++++++++++++++++++++++++++++++ src-tauri/core/src/web/mod.rs | 1 + src-tauri/core/src/web/snap.rs | 80 +++++++++ src/core/index.ts | 8 + src/geometry/snapSegments.test.ts | 102 +++++++++++ src/geometry/snapSegments.ts | 95 +++++++++++ src/tools/snapping.ts | 212 ++++++++++++++--------- 9 files changed, 692 insertions(+), 89 deletions(-) create mode 100644 src-tauri/core/src/snap.rs create mode 100644 src-tauri/core/src/web/snap.rs create mode 100644 src/geometry/snapSegments.test.ts create mode 100644 src/geometry/snapSegments.ts diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 6a16805c..904f70fa 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -61,6 +61,7 @@ pub mod skeleton; pub mod plan_parts; pub mod plan_scene; pub mod plan_pick; +pub mod snap; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/plan_pick.rs b/src-tauri/core/src/plan_pick.rs index 11d9637b..3f4efd69 100644 --- a/src-tauri/core/src/plan_pick.rs +++ b/src-tauri/core/src/plan_pick.rs @@ -30,7 +30,7 @@ const MAX_CELLS_PER_ITEM: f64 = 1024.0; /// Gleichförmiges Raster (CSR) über Bounding-Boxen; Einträge sind Index-Werte. #[derive(Default)] -struct Grid { +pub(crate) struct Grid { min_x: f64, min_y: f64, cell: f64, @@ -149,13 +149,13 @@ impl Grid { /// Raster über Bounding-Boxen (Einträge mit nicht endlicher Box werden immer geprüft) — nur /// Vorauswahl, die genaue Prüfung macht der Aufrufer in Index-Reihenfolge. #[derive(Default)] -struct BoxIndex { +pub(crate) struct BoxIndex { grid: Option, wild: Vec, } impl BoxIndex { - fn build(boxes: Vec<(u32, f64, f64, f64, f64)>) -> BoxIndex { + pub(crate) fn build(boxes: Vec<(u32, f64, f64, f64, f64)>) -> BoxIndex { let mut wild = Vec::new(); let mut fin = Vec::with_capacity(boxes.len()); let (mut a, mut b, mut c, mut d) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); @@ -176,7 +176,7 @@ impl BoxIndex { } /// Einträge, deren Box den Kreis `(x, y, r)` berühren kann — aufsteigend, ohne Doppel. - fn candidates(&self, x: f64, y: f64, r: f64) -> Vec { + pub(crate) fn candidates(&self, x: f64, y: f64, r: f64) -> Vec { let mut out = self.wild.clone(); if let Some(g) = &self.grid { g.visit(x, y, r, |k| out.push(k)); @@ -188,7 +188,7 @@ impl BoxIndex { } /// Rand für Rundung bei Box-Tests: relativ zur Koordinatengrösse. -fn pad(v: &[f64]) -> f64 { +pub(crate) fn pad(v: &[f64]) -> f64 { 1e-9 * (1.0 + v.iter().fold(0.0f64, |m, x| m.max(x.abs()))) } diff --git a/src-tauri/core/src/snap.rs b/src-tauri/core/src/snap.rs new file mode 100644 index 00000000..6debb824 --- /dev/null +++ b/src-tauri/core/src/snap.rs @@ -0,0 +1,272 @@ +//! Objektfang auf Strecken ([K3d], früher die Schleifen in `src/tools/snapping.ts`): Lotfusspunkt +//! vom letzten Punkt, Endpunkte, Mittelpunkte, Schnittpunkte (unendliche Geraden) und Punkt auf +//! der Kante, dazu die nächste Strecke für die Verweil-Erkennung ("divide"). TS sammelt die +//! Strecken (Wandachsen, Schichtgrenzen, Umrisse, 2D-Zeichnung) einmal je Projekt/Geschoss und +//! legt sie hier ab; je Mausbewegung kommen nur Cursor, Toleranz und die wenigen Zusatzstrecken +//! (Entwurf, Blatt-Geometrie) dazu. +//! +//! Bewertung wie in TS: Kandidat nur bis `tol_m` Abstand, Punktzahl `distPx − Priorität`, der +//! erste mit der kleinsten Punktzahl gewinnt. Ergebnis in zwei Blöcken (die Reihenfolge in TS ist +//! Lot → Endpunkte (Strecken) → [Entwurfspunkte, Raum-Anker in TS] → Mitte → Schnitt → Kante), +//! TS führt sie mit seinen eigenen Kandidaten in derselben Reihenfolge zusammen. +//! +//! Schnittpunkte: nur Geraden, die näher als `tol_m` am Cursor vorbeigehen, können einen +//! Schnittpunkt in Reichweite haben — die übrigen Paare fallen vorab weg (früher alle Paare: +//! beim grossen Projekt ~25k Strecken → Sekunden je Mausbewegung). Die Reihenfolge der +//! verbleibenden Paare bleibt, das Ergebnis ist dasselbe. + +use crate::jsmath::hypot; +use crate::jsnum; +use crate::plan_pick::{pad, BoxIndex}; + +/// Snap-Arten (Code in der Ausgabe). +pub const K_PERPENDICULAR: f64 = 0.0; +pub const K_ENDPOINT: f64 = 1.0; +pub const K_MIDPOINT: f64 = 2.0; +pub const K_INTERSECTION: f64 = 3.0; +pub const K_ON_EDGE: f64 = 4.0; + +/// Prioritäts-Bonus in Pixeln (wie `PRIORITY` in snapping.ts). +fn priority(kind: f64) -> f64 { + match kind as i32 { + 0 => 1.0, + 1 => 7.0, + 2 => 3.0, + 3 => 5.0, + _ => 0.0, + } +} + +/// Welche Arten gefragt sind (Bits). +pub const F_PERPENDICULAR: u32 = 1; +pub const F_ENDPOINT: u32 = 2; +pub const F_MIDPOINT: u32 = 4; +pub const F_INTERSECTION: u32 = 8; +pub const F_ON_EDGE: u32 = 16; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Cand { + pub x: f64, + pub y: f64, + pub kind: f64, + pub dist_px: f64, + pub score: f64, +} + +struct Best { + raw: (f64, f64), + tol_m: f64, + px_per_m: f64, + best: Option, + best_score: f64, +} + +impl Best { + fn new(raw: (f64, f64), tol_m: f64, px_per_m: f64) -> Best { + Best { raw, tol_m, px_per_m, best: None, best_score: f64::INFINITY } + } + + #[inline] + fn consider(&mut self, x: f64, y: f64, kind: f64) { + let dx = x - self.raw.0; + let dy = y - self.raw.1; + // Schnell verwerfen (hypot ≥ max(|dx|, |dy|)); NaN fällt durch wie in TS. + if dx.abs() > self.tol_m || dy.abs() > self.tol_m { + return; + } + let d = hypot(&[dx, dy]); + if d > self.tol_m { + return; + } + let dist_px = d * self.px_per_m; + let score = dist_px - priority(kind); + if score < self.best_score { + self.best_score = score; + self.best = Some(Cand { x, y, kind, dist_px, score }); + } + } +} + +/// Lotfusspunkt von `p` auf die Strecke `a–b`, aufs Segment geklemmt (`perpFoot`). +#[inline] +fn perp_foot(px: f64, py: f64, s: &[f64; 4]) -> (f64, f64) { + let dx = s[2] - s[0]; + let dy = s[3] - s[1]; + let len2 = dx * dx + dy * dy; + if len2 < 1e-12 { + return (s[0], s[1]); + } + let mut t = ((px - s[0]) * dx + (py - s[1]) * dy) / len2; + t = jsnum::max(0.0, jsnum::min(1.0, t)); + (s[0] + dx * t, s[1] + dy * t) +} + +/// Schnittpunkt der Geraden durch `s` und `u` (`lineIntersect`), `None` bei (fast) parallel. +#[inline] +fn line_intersect(s: &[f64; 4], u: &[f64; 4]) -> Option<(f64, f64)> { + let (dax, day) = (s[2] - s[0], s[3] - s[1]); + let (dbx, dby) = (u[2] - u[0], u[3] - u[1]); + let denom = dax * dby - day * dbx; + if denom.abs() < 1e-9 { + return None; + } + let t = ((u[0] - s[0]) * dby - (u[1] - s[1]) * dbx) / denom; + Some((s[0] + dax * t, s[1] + day * t)) +} + +/// Kann die Gerade durch `s` einen Schnittpunkt in `tol_m` um `raw` tragen? (grosszügig; +/// entartete/unendliche Strecken: ja) +fn line_near(s: &[f64; 4], raw: (f64, f64), tol_m: f64) -> bool { + let dx = s[2] - s[0]; + let dy = s[3] - s[1]; + let l = (dx * dx + dy * dy).sqrt(); + if !(l > 0.0) || !l.is_finite() { + return true; + } + let d = ((raw.0 - s[0]) * dy - (raw.1 - s[1]) * dx).abs() / l; + !(d > tol_m * (1.0 + 1e-6) + 1e-9 * (1.0 + raw.0.abs().max(raw.1.abs()))) +} + +/// Abgelegte Strecken mit Raster über ihren Bounding-Boxen. +#[derive(Default)] +pub struct SnapSet { + pub segs: Vec<[f64; 4]>, + ix: BoxIndex, +} + +impl SnapSet { + pub fn new(segs: Vec<[f64; 4]>) -> SnapSet { + let ix = BoxIndex::build( + segs.iter() + .enumerate() + .map(|(k, s)| { + let e = pad(s); + (k as u32, s[0].min(s[2]) - e, s[1].min(s[3]) - e, s[0].max(s[2]) + e, s[1].max(s[3]) + e) + }) + .collect(), + ); + SnapSet { segs, ix } + } + + /// Strecken, die näher als `r` an `(x, y)` liegen können (aufsteigend). Alle Strecken-Fänge + /// (Endpunkt, Mitte, Lot, Kante, Verweilen) liegen auf der Strecke und höchstens `tol_m` vom + /// Cursor — die übrigen tragen nichts bei. + fn near(&self, x: f64, y: f64, r: f64) -> Vec { + if x.is_finite() && y.is_finite() && r.is_finite() && r >= 0.0 { + self.ix.candidates(x, y, r * (1.0 + 1e-6) + pad(&[x, y])) + } else { + (0..self.segs.len() as u32).collect() + } + } +} + +/// Eingabe einer Fang-Abfrage. +pub struct SnapQuery<'a> { + /// Strecken in Fang-Reihenfolge: abgelegte, dann Zusatz. + pub base: &'a SnapSet, + pub extra: &'a [[f64; 4]], + /// Strecken für Schnittpunkte; `None` = dieselben wie `base` + `extra`. + pub int_segs: Option<&'a [[f64; 4]]>, + pub raw: (f64, f64), + pub tol_m: f64, + pub px_per_m: f64, + pub flags: u32, + pub last: Option<(f64, f64)>, +} + +/// Ergebnis: nächste Strecke (Verweilen), Block A (Lot, Endpunkte), Block B (Mitte, Schnitt, Kante). +pub struct SnapOut { + pub dwell: Option, + pub a: Option, + pub b: Option, +} + +pub fn snap_segments(q: &SnapQuery) -> SnapOut { + let (rx, ry) = q.raw; + let near_base = q.base.near(rx, ry, q.tol_m); + let nb = q.base.segs.len(); + // Strecken in Fang-Reihenfolge (Index im Ganzen, Strecke): nahe abgelegte, dann Zusatz. + let segs = || { + near_base.iter().map(|&k| (k as usize, &q.base.segs[k as usize])).chain(q.extra.iter().enumerate().map(move |(k, s)| (nb + k, s))) + }; + // Nächste Strecke für die Verweil-Erkennung (`nearestSegment` in snapping.ts). + let mut dwell = None; + let mut best_d = q.tol_m; + for (i, s) in segs() { + let (fx, fy) = perp_foot(rx, ry, s); + let (dx, dy) = (fx - rx, fy - ry); + if dx.abs() >= best_d || dy.abs() >= best_d { + continue; + } + let d = hypot(&[dx, dy]); + if d < best_d { + best_d = d; + dwell = Some(i); + } + } + let mut a = Best::new(q.raw, q.tol_m, q.px_per_m); + if q.flags & F_PERPENDICULAR != 0 { + if let Some((lx, ly)) = q.last { + for (_, s) in segs() { + let (x, y) = perp_foot(lx, ly, s); + a.consider(x, y, K_PERPENDICULAR); + } + } + } + if q.flags & F_ENDPOINT != 0 { + for (_, s) in segs() { + a.consider(s[0], s[1], K_ENDPOINT); + a.consider(s[2], s[3], K_ENDPOINT); + } + } + let mut b = Best::new(q.raw, q.tol_m, q.px_per_m); + if q.flags & F_MIDPOINT != 0 { + for (_, s) in segs() { + b.consider((s[0] + s[2]) / 2.0, (s[1] + s[3]) / 2.0, K_MIDPOINT); + } + } + if q.flags & F_INTERSECTION != 0 { + let near: Vec<&[f64; 4]> = match q.int_segs { + Some(l) => l.iter().filter(|s| line_near(s, q.raw, q.tol_m)).collect(), + None => q.base.segs.iter().chain(q.extra.iter()).filter(|s| line_near(s, q.raw, q.tol_m)).collect(), + }; + for i in 0..near.len() { + for j in i + 1..near.len() { + if let Some((x, y)) = line_intersect(near[i], near[j]) { + b.consider(x, y, K_INTERSECTION); + } + } + } + } + if q.flags & F_ON_EDGE != 0 { + for (_, s) in segs() { + let (x, y) = perp_foot(rx, ry, s); + b.consider(x, y, K_ON_EDGE); + } + } + SnapOut { dwell, a: a.best, b: b.best } +} + +/// Strecken aus `[ax, ay, bx, by, …]`. +pub fn segs_from(flat: &[f64]) -> Vec<[f64; 4]> { + flat.chunks_exact(4).map(|c| [c[0], c[1], c[2], c[3]]).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn endpunkt_vor_kante_schnitt_nur_nahe_geraden() { + let segs = segs_from(&[0.0, 0.0, 10.0, 0.0, 5.0, -5.0, 5.0, 5.0, 100.0, 50.0, 200.0, 50.0]); + let base = SnapSet::new(segs[..1].to_vec()); + let q = SnapQuery { base: &base, extra: &segs[1..], int_segs: None, raw: (5.05, 0.02), tol_m: 0.2, px_per_m: 100.0, flags: 31, last: None }; + let o = snap_segments(&q); + assert_eq!(o.dwell, Some(0)); + assert_eq!(o.a, None); + let b = o.b.unwrap(); + assert_eq!((b.x, b.y, b.kind), (5.0, 0.0, K_INTERSECTION)); + let q = SnapQuery { raw: (9.95, 0.0), ..q }; + assert_eq!(snap_segments(&q).a.unwrap().kind, K_ENDPOINT); + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 18680fdf..b4fb4d87 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -34,6 +34,7 @@ mod hatch; mod skeleton; mod plan_scene; mod plan_pick; +mod snap; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/snap.rs b/src-tauri/core/src/web/snap.rs new file mode 100644 index 00000000..96353133 --- /dev/null +++ b/src-tauri/core/src/web/snap.rs @@ -0,0 +1,80 @@ +//! Bindungen des Objektfangs (`crate::snap`). Die Fang-Strecken eines Projekt-Geschosses legt TS +//! einmal ab (`snap_segs_hold`) und gibt sie frei, wenn es sie ersetzt (`snap_segs_release`). +//! Je Mausbewegung `snap_eval`; unbekannte Nummer oder kaputte Eingabe → leeres Ergebnis. + +use crate::snap::{segs_from, snap_segments, Cand, SnapQuery, SnapSet}; +use std::cell::RefCell; +use wasm_bindgen::prelude::wasm_bindgen; + +thread_local! { + static SETS: RefCell<(u32, Vec<(u32, SnapSet)>)> = const { RefCell::new((0, Vec::new())) }; +} + +/// Strecken `[ax, ay, bx, by, …]` ablegen; Nummer ≥ 1 (0 = kaputte Eingabe). +#[wasm_bindgen] +pub fn snap_segs_hold(flat: &[f64]) -> u32 { + if flat.len() % 4 != 0 { + return 0; + } + SETS.with(|h| { + let mut h = h.borrow_mut(); + h.0 = h.0.wrapping_add(1).max(1); + let id = h.0; + h.1.push((id, SnapSet::new(segs_from(flat)))); + id + }) +} + +#[wasm_bindgen] +pub fn snap_segs_release(id: u32) { + SETS.with(|h| h.borrow_mut().1.retain(|e| e.0 != id)); +} + +fn push(out: &mut Vec, c: Option) { + match c { + Some(c) => out.extend_from_slice(&[c.x, c.y, c.kind, c.dist_px, c.score]), + None => out.extend_from_slice(&[f64::NAN; 5]), + } +} + +/// Fang über abgelegte (`held`, 0 = keine) + Zusatz-Strecken. `int_mode` 1: Schnittpunkte nur +/// aus `int_segs`, sonst aus denselben Strecken. `flags` s. `snap::F_*`; letzter Punkt NaN = +/// keiner. Ergebnis: `[nächste Strecke (−1), ax, ay, bx, by, Block A (x, y, Art, distPx, +/// Punktzahl), Block B (…)]` (NaN = kein Kandidat); leer = Fehler (Nummer unbekannt). +#[wasm_bindgen] +#[allow(clippy::too_many_arguments)] +pub fn snap_eval(held: u32, extra: &[f64], int_mode: u32, int_segs: &[f64], rx: f64, ry: f64, tol_m: f64, px_per_m: f64, flags: u32, lx: f64, ly: f64) -> Vec { + if extra.len() % 4 != 0 || int_segs.len() % 4 != 0 { + return Vec::new(); + } + let extra = segs_from(extra); + let ints = segs_from(int_segs); + let run = |base: &SnapSet| -> Vec { + let q = SnapQuery { + base, + extra: &extra, + int_segs: (int_mode == 1).then_some(&ints[..]), + raw: (rx, ry), + tol_m, + px_per_m, + flags, + last: (!lx.is_nan() && !ly.is_nan()).then_some((lx, ly)), + }; + let o = snap_segments(&q); + let mut out = Vec::with_capacity(15); + match o.dwell { + Some(i) => { + let s = if i < base.segs.len() { base.segs[i] } else { extra[i - base.segs.len()] }; + out.extend_from_slice(&[i as f64, s[0], s[1], s[2], s[3]]); + } + None => out.extend_from_slice(&[-1.0, f64::NAN, f64::NAN, f64::NAN, f64::NAN]), + } + push(&mut out, o.a); + push(&mut out, o.b); + out + }; + if held == 0 { + return run(&SnapSet::default()); + } + SETS.with(|h| h.borrow().1.iter().find(|e| e.0 == held).map(|e| run(&e.1))).unwrap_or_default() +} diff --git a/src/core/index.ts b/src/core/index.ts index 073e4034..c1e9ab95 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -45,6 +45,14 @@ export { pointSegDist as pointSegDist__geometry_drawingIndex, } from "../geometry/drawingIndex"; +export { + type SegSnapCand, + type SegSnapResult, + holdSnapSegments, + releaseSnapSegments, + snapOnSegments, +} from "../geometry/snapSegments"; + export { mvGeom, reversesOrientation, diff --git a/src/geometry/snapSegments.test.ts b/src/geometry/snapSegments.test.ts new file mode 100644 index 00000000..f2da47dc --- /dev/null +++ b/src/geometry/snapSegments.test.ts @@ -0,0 +1,102 @@ +// Objektfang auf Strecken im Kern ([K3d], `core/src/snap.rs`): gleiche Wahl wie die einfache +// Suche über alle Strecken/Paare (Raster-Vorauswahl und Geraden-Filter für Schnittpunkte dürfen +// nichts ändern). (Gleichheit zur früheren TS-Fassung von computeSnap: 2600 Abfragen, s. TODO [K3d].) + +import { describe, expect, it } from "vitest"; +import { holdSnapSegments, releaseSnapSegments, snapOnSegments, type SnapSeg } from "./snapSegments"; +import type { Vec2 } from "../model/types"; + +const PRIORITY: Record = { perpendicular: 1, endpoint: 7, midpoint: 3, intersection: 5, onEdge: 0 }; + +/** Einfache Fassung (alle Strecken, alle Paare) — Block A (Lot, Endpunkte) und Block B (Mitte, Schnitt, Kante). */ +function brute(segs: SnapSeg[], raw: Vec2, tolM: number, pxPerM: number, last: Vec2 | null) { + const perp = (p: Vec2, a: Vec2, b: Vec2): Vec2 => { + const dx = b.x - a.x, dy = b.y - a.y; + const len2 = dx * dx + dy * dy; + if (len2 < 1e-12) return a; + const t = Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2)); + return { x: a.x + dx * t, y: a.y + dy * t }; + }; + const block = () => { + let best: { point: Vec2; kind: string; distPx: number; score: number } | null = null; + let bestScore = Infinity; + const consider = (point: Vec2, kind: string) => { + const d = Math.hypot(point.x - raw.x, point.y - raw.y); + if (d > tolM) return; + const score = d * pxPerM - PRIORITY[kind]; + if (score < bestScore) { + bestScore = score; + best = { point, kind, distPx: d * pxPerM, score }; + } + }; + return { consider, get: () => best }; + }; + const a = block(); + if (last) for (const [p, q] of segs) a.consider(perp(last, p, q), "perpendicular"); + for (const [p, q] of segs) { + a.consider(p, "endpoint"); + a.consider(q, "endpoint"); + } + const b = block(); + for (const [p, q] of segs) b.consider({ x: (p.x + q.x) / 2, y: (p.y + q.y) / 2 }, "midpoint"); + for (let i = 0; i < segs.length; i++) { + for (let j = i + 1; j < segs.length; j++) { + const [p, q] = segs[i]; + const [r, s] = segs[j]; + const da = { x: q.x - p.x, y: q.y - p.y }; + const db = { x: s.x - r.x, y: s.y - r.y }; + const den = da.x * db.y - da.y * db.x; + if (Math.abs(den) < 1e-9) continue; + const t = ((r.x - p.x) * db.y - (r.y - p.y) * db.x) / den; + b.consider({ x: p.x + da.x * t, y: p.y + da.y * t }, "intersection"); + } + } + for (const [p, q] of segs) b.consider(perp(raw, p, q), "onEdge"); + return { a: a.get(), b: b.get() }; +} + +describe("snapOnSegments (Kern)", () => { + it("gleich wie die Suche über alle Strecken und Paare (Zufallsdaten)", () => { + let seed = 3; + const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647); + for (let run = 0; run < 8; run++) { + const segs: SnapSeg[] = []; + for (let i = 0; i < 300; i++) { + const x = rnd() * 20, y = rnd() * 20; + // Viele achsparallele Strecken (Wände), einige lange schräge (Verlängerungen schneiden weit weg). + const k = rnd(); + segs.push(k < 0.4 ? [{ x, y }, { x: x + rnd() * 5, y }] : k < 0.8 ? [{ x, y }, { x, y: y + rnd() * 5 }] : [{ x, y }, { x: x + rnd() * 30 - 15, y: y + rnd() * 30 - 15 }]); + } + const base = segs.slice(0, 250); + const extra = segs.slice(250); + const h = holdSnapSegments(base); + for (let q = 0; q < 25; q++) { + const raw = { x: rnd() * 20, y: rnd() * 20 }; + const tolM = 0.05 + rnd() * 0.5; + const last = rnd() < 0.5 ? { x: rnd() * 20, y: rnd() * 20 } : null; + const r = snapOnSegments(h, extra, null, { raw, tolM, pxPerMeter: 100, perpendicular: true, endpoint: true, midpoint: true, intersection: true, onEdge: true, lastPoint: last })!; + const e = brute(segs, raw, tolM, 100, last); + expect(r.a).toEqual(e.a); + expect(r.b).toEqual(e.b); + } + releaseSnapSegments(h); + expect(snapOnSegments(h, [], null, { raw: { x: 0, y: 0 }, tolM: 1, pxPerMeter: 1, perpendicular: false, endpoint: true, midpoint: false, intersection: false, onEdge: false, lastPoint: null })).toBeNull(); + } + }, 60_000); + + it("nächste Strecke für das Verweilen", () => { + const r = snapOnSegments(0, [[{ x: 0, y: 0 }, { x: 10, y: 0 }], [{ x: 5, y: -5 }, { x: 5, y: 5 }]], null, { + raw: { x: 5.05, y: 0.02 }, + tolM: 0.2, + pxPerMeter: 100, + perpendicular: false, + endpoint: true, + midpoint: true, + intersection: true, + onEdge: true, + lastPoint: null, + })!; + expect(r.nearest).toEqual([{ x: 0, y: 0 }, { x: 10, y: 0 }]); + expect(r.b?.kind).toBe("intersection"); + }); +}); diff --git a/src/geometry/snapSegments.ts b/src/geometry/snapSegments.ts new file mode 100644 index 00000000..2ce26c87 --- /dev/null +++ b/src/geometry/snapSegments.ts @@ -0,0 +1,95 @@ +// Objektfang auf Strecken über den Kern ([K3d], `src-tauri/core/src/snap.rs`): Lotfusspunkt, +// Endpunkte, Mittelpunkte, Schnittpunkte, Punkt auf der Kante und die nächste Strecke (Verweilen). +// Die Strecken eines Projekt-Geschosses liegen einmal im Kern ({@link holdSnapSegments}); je +// Mausbewegung gehen nur Cursor und Zusatzstrecken über die Grenze. Die Sammlung der Strecken +// und die übrigen Fang-Arten (Raster, Winkel, Kreise, Teilpunkte) bleiben in `tools/snapping.ts`. + +import type { Vec2 } from "../model/types"; +import { core } from "../engine/coreWasm"; + +export type SnapSeg = [Vec2, Vec2]; + +/** Fang-Arten des Kerns (Code → Name wie `SnapKind`). */ +const KINDS = ["perpendicular", "endpoint", "midpoint", "intersection", "onEdge"] as const; +export type SegSnapKind = (typeof KINDS)[number]; + +export interface SegSnapCand { + point: Vec2; + kind: SegSnapKind; + distPx: number; + /** `distPx − Priorität` (kleiner gewinnt). */ + score: number; +} + +export interface SegSnapResult { + /** Nächste Strecke innerhalb der Toleranz (Lotfusspunkt-Abstand) oder null. */ + nearest: SnapSeg | null; + /** Block A: Lot vom letzten Punkt, Endpunkte der Strecken. */ + a: SegSnapCand | null; + /** Block B: Mittelpunkte, Schnittpunkte, Punkt auf der Kante. */ + b: SegSnapCand | null; +} + +export interface SegSnapQuery { + raw: Vec2; + tolM: number; + pxPerMeter: number; + perpendicular: boolean; + endpoint: boolean; + midpoint: boolean; + intersection: boolean; + onEdge: boolean; + lastPoint: Vec2 | null; +} + +function flat(segs: readonly SnapSeg[]): Float64Array { + const out = new Float64Array(segs.length * 4); + for (let i = 0; i < segs.length; i++) { + const [a, b] = segs[i]; + out[4 * i] = a.x; + out[4 * i + 1] = a.y; + out[4 * i + 2] = b.x; + out[4 * i + 3] = b.y; + } + return out; +} + +/** Strecken im Kern ablegen; Nummer für {@link snapOnSegments} (freigeben: {@link releaseSnapSegments}). */ +export function holdSnapSegments(segs: readonly SnapSeg[]): number { + return core().snap_segs_hold(flat(segs)); +} + +export function releaseSnapSegments(id: number): void { + if (id) core().snap_segs_release(id); +} + +const cand = (f: Float64Array, k: number): SegSnapCand | null => + Number.isNaN(f[k + 2]) ? null : { point: { x: f[k], y: f[k + 1] }, kind: KINDS[f[k + 2]], distPx: f[k + 3], score: f[k + 4] }; + +/** + * Fang über die abgelegten Strecken `held` (0 = keine) und `extra` (in dieser Reihenfolge); + * Schnittpunkte aus `intSegs` (null = aus denselben Strecken). null, wenn `held` nicht (mehr) im + * Kern liegt. + */ +export function snapOnSegments(held: number, extra: readonly SnapSeg[], intSegs: readonly SnapSeg[] | null, q: SegSnapQuery): SegSnapResult | null { + const flags = (q.perpendicular ? 1 : 0) | (q.endpoint ? 2 : 0) | (q.midpoint ? 4 : 0) | (q.intersection ? 8 : 0) | (q.onEdge ? 16 : 0); + const f = core().snap_eval( + held, + flat(extra), + intSegs ? 1 : 0, + intSegs ? flat(intSegs) : new Float64Array(0), + q.raw.x, + q.raw.y, + q.tolM, + q.pxPerMeter, + flags, + q.lastPoint ? q.lastPoint.x : NaN, + q.lastPoint ? q.lastPoint.y : NaN, + ); + if (f.length < 15) return null; + return { + nearest: f[0] >= 0 ? [{ x: f[1], y: f[2] }, { x: f[3], y: f[4] }] : null, + a: cand(f, 5), + b: cand(f, 10), + }; +} diff --git a/src/tools/snapping.ts b/src/tools/snapping.ts index cecf35ed..aeb394c4 100644 --- a/src/tools/snapping.ts +++ b/src/tools/snapping.ts @@ -8,7 +8,7 @@ import type { Drawing2D, Project, Vec2, Wall } from "../model/types"; import { getWallType, wallTypeThickness } from "../model/types"; -import { add, leftNormal, lineIntersect, normalize, scale, sub } from "../model/geometry"; +import { add, leftNormal, normalize, scale, sub } from "../model/geometry"; import { wallReferenceOffset } from "../model/wall"; import { centroid as roomCentroid } from "../core"; import { columnFootprint } from "../core"; @@ -17,9 +17,9 @@ import type { SnapKind, SnapResult, SnapSettings } from "./types"; import { sampleBezierChain, sampleCatmullRom, sampleUniformBSpline } from "../core"; import { buildDrawingIndex, drawingsNear, isIndexable, pointSegDist__geometry_drawingIndex as pointSegDist, type DrawingIndex } from "../core"; import { sheetSnapSegments } from "./sheetSnapGeometry"; +import { holdSnapSegments, releaseSnapSegments, snapOnSegments, type SegSnapCand } from "../core"; const dist = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y); -const mid = (a: Vec2, b: Vec2): Vec2 => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }); /** Bildschirm-px-Bonus je Snap-Art: höher = gewinnt knappe Vergleiche. */ const PRIORITY: Record = { @@ -193,8 +193,89 @@ function snapDrawings(input: SnapInput, near?: { at: Vec2; r: number }): Drawing return out; } -/** Sammelt alle sichtbaren Strecken des Geschosses (Wandachsen + 2D-Segmente). */ +/** Sammelt alle sichtbaren Strecken des Geschosses (Wandachsen + 2D-Segmente) samt Entwurf. */ function collectSegments(input: SnapInput, near?: { at: Vec2; r: number }): Seg[] { + const segs = baseSegments(input, near); + for (const seg of draftSegments(input)) segs.push(seg); + return segs; +} + +/** Bereits gesetzte Draft-Segmente (Polylinie/Wand im Bau). */ +function draftSegments(input: SnapInput): Seg[] { + const segs: Seg[] = []; + for (let i = 0; i < input.draftPoints.length - 1; i++) { + segs.push([input.draftPoints[i], input.draftPoints[i + 1]]); + } + return segs; +} + +/** + * Was je Projekt/Geschoss/Sichtbarkeit gleich bleibt, einmal gesammelt (lief sonst bei jeder + * Mausbewegung über alle Wände, Räume, Treppen, Stützen): die Strecken ohne Entwurf (im Kern + * abgelegt, erst bei Bedarf), Raum-Stempel-Anker, Kreise/Bögen, Ellipsen-Mittelpunkte. Die + * letzten paar Einträge bleiben, ältere werden freigegeben. + */ +interface LevelSnap { + project: Project; + levelId: string; + codes: Set; + /** Abgelegte Strecken im Kern (0 = noch nicht). */ + hold: number; + anchors: Vec2[] | null; + circles: CircleGeom[] | null; + ellipses: Vec2[] | null; +} +const levelSnaps: LevelSnap[] = []; +const MAX_LEVEL_SNAPS = 4; +function levelSnap(input: SnapInput): LevelSnap { + let e = levelSnaps.find((h) => h.project === input.project && h.levelId === input.levelId && h.codes === input.visibleCodes); + if (!e) { + e = { project: input.project, levelId: input.levelId, codes: input.visibleCodes, hold: 0, anchors: null, circles: null, ellipses: null }; + levelSnaps.push(e); + while (levelSnaps.length > MAX_LEVEL_SNAPS) releaseSnapSegments(levelSnaps.shift()!.hold); + } + return e; +} +function heldBaseSegments(input: SnapInput, fresh: boolean): number { + const e = levelSnap(input); + if (e.hold && !fresh) return e.hold; + releaseSnapSegments(e.hold); + e.hold = holdSnapSegments(baseSegments(input)); + return e.hold; +} +/** Raum-Stempel-Anker (fixer Anker, sonst Flächenschwerpunkt) des Geschosses. */ +function roomAnchors(input: SnapInput): Vec2[] { + const e = levelSnap(input); + if (!e.anchors) { + e.anchors = []; + for (const room of input.project.rooms ?? []) { + if (room.floorId !== input.levelId) continue; + if (!input.visibleCodes.has(room.categoryCode)) continue; + if (room.boundary.length < 3) continue; + e.anchors.push(room.stampAnchor ?? roomCentroid(room.boundary)); + } + } + return e.anchors; +} +function levelCircles(input: SnapInput): CircleGeom[] { + const e = levelSnap(input); + return (e.circles ??= collectCircles(input)); +} +function ellipseCenters(input: SnapInput): Vec2[] { + const e = levelSnap(input); + if (!e.ellipses) { + e.ellipses = []; + for (const d of nonLineDrawings(input.project.drawings2d)) { + if (d.levelId !== input.levelId) continue; + if (!input.visibleCodes.has(d.categoryCode)) continue; + if (d.geom.shape === "ellipse") e.ellipses.push(d.geom.center); + } + } + return e.ellipses; +} + +/** Sichtbare Strecken des Geschosses ohne Entwurf (Wandachsen, Schichtgrenzen, Umrisse, 2D). */ +function baseSegments(input: SnapInput, near?: { at: Vec2; r: number }): Seg[] { const segs: Seg[] = []; for (const w of input.project.walls) { if (w.floorId !== input.levelId) continue; @@ -235,10 +316,6 @@ function collectSegments(input: SnapInput, near?: { at: Vec2; r: number }): Seg[ // Runde Stützen: s. collectCircles (Zentrum/Quadranten statt Vieleck-Kanten). } for (const d of snapDrawings(input, near)) drawingSegs(d, segs); - // Bereits gesetzte Draft-Segmente (Polylinie/Wand im Bau). - for (let i = 0; i < input.draftPoints.length - 1; i++) { - segs.push([input.draftPoints[i], input.draftPoints[i + 1]]); - } return segs; } @@ -284,16 +361,6 @@ function collectCircles(input: SnapInput): CircleGeom[] { return out; } -/** Lotfußpunkt von p auf die Strecke a-b, auf das Segment geklemmt. */ -function perpFoot(p: Vec2, a: Vec2, b: Vec2): Vec2 { - const dx = b.x - a.x, dy = b.y - a.y; - const len2 = dx * dx + dy * dy; - if (len2 < 1e-12) return a; - let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2; - t = Math.max(0, Math.min(1, t)); - return { x: a.x + dx * t, y: a.y + dy * t }; -} - // ── Verweil-Erkennung fürs Teilpunkte-Snapping ("divide") ─────────────────── // Modul-weiter Zustand (wie `lastCoalesceKey` in projectSlice.ts) statt in // SnapInput/computeSnap-Parametern: computeSnap wird von mehreren, völlig @@ -322,28 +389,14 @@ let acquiredParallelSeg: Seg | null = null; const segKey = (seg: Seg): string => `${seg[0].x},${seg[0].y}|${seg[1].x},${seg[1].y}`; -/** Nächstgelegene Strecke zu `raw` innerhalb der Fangtoleranz (Meter), oder null. */ -function nearestSegment(raw: Vec2, segs: Seg[], tolM: number): Seg | null { - let best: Seg | null = null; - let bestD = tolM; - for (const seg of segs) { - const d = dist(perpFoot(raw, seg[0], seg[1]), raw); - if (d < bestD) { - bestD = d; - best = seg; - } - } - return best; -} - /** * Verankert/verwirft den Verweil-Zustand für den aktuellen Cursor und liefert * die "freigegebene" Strecke (Teilpunkte fangbar), sobald der Cursor lange * genug (`delayMs`) auf DERSELBEN Strecke geblieben ist — sonst `null`. Ein * Streckenwechsel (auch zu "keine Strecke") setzt die Verweildauer zurück. + * `seg` ist die nächste Strecke innerhalb der Fangtoleranz (aus dem Kern) oder null. */ -function updateDwell(raw: Vec2, segs: Seg[], delayMs: number, tolM: number): Seg | null { - const seg = nearestSegment(raw, segs, tolM); +function updateDwell(seg: Seg | null, delayMs: number): Seg | null { const key = seg ? segKey(seg) : null; const now = Date.now(); if (key !== dwellSegKey) { @@ -393,10 +446,14 @@ export function computeSnap(input: SnapInput): SnapResult | null { // Liste gebaut und der Schnittpunkt-Fang prüfte ALLE Paare (O(N²): die Seite // blockierte beim ersten Klick eines Zeichenwerkzeugs). Kleine Projekte bleiben // exakt wie bisher. + // Strecken-Fang (Lot, Endpunkte, Mitte, Schnitt, Kante, nächste Strecke) rechnet der Kern + // (`geometry/snapSegments.ts`): bei normalen Projekten über die dort abgelegten Strecken des + // Geschosses (`held`) plus Entwurf, sonst über die hier vorausgewählten nahen Strecken. const nearMode = input.project.drawings2d.length > LARGE_DRAWINGS; const intRadius = tolM * 6; + let held = 0; let segs: Seg[] = []; - let intSegs: Seg[] = []; + let intSegs: Seg[] | null = null; if (needSegs) { if (nearMode) { const cand = collectSegments(input, { at: raw, r: intRadius }); @@ -408,8 +465,8 @@ export function computeSnap(input: SnapInput): SnapResult | null { // Schnittpunkte nur unter den nächsten Strecken (paarweise → quadratisch). intSegs = withDist.slice(0, 64).map((e) => e.seg); } else { - segs = collectSegments(input); - intSegs = segs; + held = heldBaseSegments(input, false); + segs = draftSegments(input); } // Abgeleitete Blatt-Geometrie (Schnitt/Ansicht, s. sheetSnapGeometry.ts): // nur die Strecken in Cursornähe — eine Ansicht hat schnell Tausende Kanten, @@ -423,17 +480,40 @@ export function computeSnap(input: SnapInput): SnapResult | null { .slice(0, 64) .map((e) => e.seg); if (near.length > 0) { - const shared = intSegs === segs; segs = segs.concat(near); - intSegs = shared ? segs : intSegs.concat(near); + if (intSegs) intSegs = intSegs.concat(near); } } } + let segSnap: ReturnType = null; + if (needSegs) { + const q = { + raw, + tolM, + pxPerMeter, + perpendicular: settings.perpendicular, + endpoint: settings.endpoint, + midpoint: settings.midpoint, + intersection: settings.intersection, + onEdge: settings.onEdge, + lastPoint: settings.perpendicular ? input.lastPoint : null, + }; + segSnap = snapOnSegments(held, segs, intSegs, q); + // Abgelegte Strecken verdrängt/freigegeben: neu ablegen und nochmals. + if (!segSnap && held) segSnap = snapOnSegments(heldBaseSegments(input, true), segs, intSegs, q); + } + // Kern-Kandidat übernehmen, wenn er besser ist (gleiche Regel wie `consider`). + const offer = (c: SegSnapCand | null | undefined) => { + if (c && c.score < bestScore) { + bestScore = c.score; + best = { point: c.point, kind: c.kind, distPx: c.distPx, refA: c.kind === "perpendicular" ? input.lastPoint ?? undefined : undefined }; + } + }; // Teilpunkt-Verweilerkennung: braucht dieselben Strecken wie oben. Ohne sie // (alle Objekt-Snap-Arten aus) bleiben "divide"/"parallel" ebenfalls inaktiv // — konsistent dazu, dass dann ohnehin keine Linien-bezogenen Snaps gelten. - const revealed = updateDwell(raw, segs, settings.hoverDivideDelayMs, tolM); + const revealed = updateDwell(segSnap?.nearest ?? null, settings.hoverDivideDelayMs); if (revealed) { const [a, b] = revealed; const n = Math.max(2, Math.round(settings.hoverDivideCount)); @@ -474,50 +554,18 @@ export function computeSnap(input: SnapInput): SnapResult | null { // perpendicular: Lotfusspunkt VOM LETZTEN PUNKT (nicht vom Cursor wie // "onEdge") auf nahe Strecken — die Strecke lastPoint→Fangpunkt steht im - // rechten Winkel zur Referenz-Strecke. - if (settings.perpendicular && input.lastPoint) { - for (const [a, b] of segs) { - consider(perpFoot(input.lastPoint, a, b), "perpendicular", input.lastPoint); - } - } + // rechten Winkel zur Referenz-Strecke; dann die Strecken-Endpunkte (Kern, Block A). + offer(segSnap?.a); - // endpoint (Strecken-Endpunkte + Draft-Knoten + Raum-Stempel-Anker). + // endpoint (Draft-Knoten + Raum-Stempel-Anker). if (settings.endpoint) { - for (const [a, b] of segs) { - consider(a, "endpoint"); - consider(b, "endpoint"); - } for (const p of input.draftPoints) consider(p, "endpoint"); // Raum-Stempel-Anker (fixer Anker, sonst Flächenschwerpunkt) des Geschosses. - for (const room of input.project.rooms ?? []) { - if (room.floorId !== input.levelId) continue; - if (!input.visibleCodes.has(room.categoryCode)) continue; - if (room.boundary.length < 3) continue; - consider(room.stampAnchor ?? roomCentroid(room.boundary), "endpoint"); - } - } - // midpoint. - if (settings.midpoint) { - for (const [a, b] of segs) consider(mid(a, b), "midpoint"); - } - // intersection (paarweise Geraden-Schnitt der Strecken, nahe am Cursor). - if (settings.intersection) { - for (let i = 0; i < intSegs.length; i++) { - for (let j = i + 1; j < intSegs.length; j++) { - const [a, b] = intSegs[i]; - const [c, d] = intSegs[j]; - const x = lineIntersect(a, { x: b.x - a.x, y: b.y - a.y }, c, { - x: d.x - c.x, - y: d.y - c.y, - }); - if (x) consider(x, "intersection"); - } - } - } - // onEdge (Lotfußpunkt auf nahe Strecken; niedrige Priorität). - if (settings.onEdge) { - for (const [a, b] of segs) consider(perpFoot(raw, a, b), "onEdge"); + for (const p of roomAnchors(input)) consider(p, "endpoint"); } + // midpoint, intersection (paarweise Geraden-Schnitt der Strecken, nahe am Cursor), onEdge + // (Lotfußpunkt auf nahe Strecken; niedrige Priorität) — Kern, Block B. + offer(segSnap?.b); // Kreis-/Bogen-Snaps: Mittelpunkt + Quadranten (Ost/Nord/West/Süd); bei Bögen // nur die Quadranten IM Bogen-Bereich, plus die beiden Bogen-Endpunkte. Center/ @@ -535,7 +583,7 @@ export function computeSnap(input: SnapInput): SnapResult | null { const sweep = norm(c.arc.a1 - c.arc.a0) || TAU; return norm(ang - c.arc.a0) <= sweep + 1e-9; }; - for (const c of collectCircles(input)) { + for (const c of levelCircles(input)) { if (settings.center) { consider(c.center, "center"); // Volle CCW-Spanne (0 ⇒ Vollkreis); Quadrant nur, wenn im Bogen liegt. @@ -570,11 +618,7 @@ export function computeSnap(input: SnapInput): SnapResult | null { // Ellipse: nur der Mittelpunkt (keine Quadranten — bei gedrehter Ellipse // wären die "Achsenpunkte" ohnehin keine Kreis-Quadranten mehr). if (settings.center) { - for (const d of nonLineDrawings(input.project.drawings2d)) { - if (d.levelId !== input.levelId) continue; - if (!input.visibleCodes.has(d.categoryCode)) continue; - if (d.geom.shape === "ellipse") consider(d.geom.center, "center"); - } + for (const p of ellipseCenters(input)) consider(p, "center"); } } From 126e419efa3eeda57083c50dfbe0e123429fdb93 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 23:32:53 +0000 Subject: [PATCH 4/5] [K3d] SVG-Text-Export aus dem Plan-Puffer im Kern MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit core/src/plan_svg.rs (+ web/plan_svg.rs): planToSvgString (dossier-cli plan/section/elevation, MCP, Golden-Tests) schreibt der Kern direkt aus den Abschnitten der Plan-Puffer; Texte aus dem Text-JSON des Puffers (planParts im Text-Modus). TS-Datei ist nur noch Fassade. Byte-gleich zur alten Fassung (328 SVGs: Beispielprojekt alle Ebenen × Detailgrade, Massstab/Rand, Überlagerung, Schnitt, Ansicht, 300 Zufallspläne, grosses Projekt; Goldens unverändert). CLI-Ausgaben (plan EG/OG svg+json, section, elevation, dxf) md5-gleich zur CLI des Hauptstands. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/plan_svg.rs | 278 +++++++++++++++++++++++++++++ src-tauri/core/src/web/mod.rs | 1 + src-tauri/core/src/web/plan_svg.rs | 18 ++ src/export/planToSvgString.ts | 98 +--------- 5 files changed, 305 insertions(+), 91 deletions(-) create mode 100644 src-tauri/core/src/plan_svg.rs create mode 100644 src-tauri/core/src/web/plan_svg.rs diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 904f70fa..49737a2c 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -62,6 +62,7 @@ pub mod plan_parts; pub mod plan_scene; pub mod plan_pick; pub mod snap; +pub mod plan_svg; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/plan_svg.rs b/src-tauri/core/src/plan_svg.rs new file mode 100644 index 00000000..9253f27d --- /dev/null +++ b/src-tauri/core/src/plan_svg.rs @@ -0,0 +1,278 @@ +//! Plan → SVG-Text ohne DOM ([K3d], früher `src/export/planToSvgString.ts`): für `dossier-cli plan`, +//! MCP und Referenzbild-Tests, direkt aus den Abschnitten eines zusammengesetzten Plans +//! ([`crate::plan_parts`]). Koordinaten in Metern (Y nach oben → SVG gespiegelt), Strichstärken +//! aus Papier-mm über den Massstab; Schraffur-Muster werden nicht ausgebreitet (nur Grundfüllung), +//! Bilder und Textpfade fehlen — gedacht für Kontrolle und Diffs, nicht für Druck. Byte-gleich zur +//! TS-Fassung (Zahlen wie `String(Math.round(v·1e5)/1e5)`, Texte aus dem Text-JSON des Puffers). + +use crate::js_fmt::js_number; +use crate::jsnum; +use crate::plan_buf::{whole, F_COLOR, F_DASH_LIST, F_GREYED, F_OPACITY, T_ARC, T_CIRCLE, T_DRAWING_ARC, T_DRAWING_TEXT, T_LINE, T_POLYGON, T_TEXT}; +use crate::plan_parts::Part; +use serde_json::Value; +use std::f64::consts::PI; + +/// `num()`: gerundet auf 1e-5, nicht endlich → "0". +fn num(v: f64) -> String { + if v.is_finite() { + js_number(jsnum::round(v * 1e5) / 1e5) + } else { + "0".into() + } +} + +/// `esc()` für Attribut- und Textinhalt. +fn esc(s: &str) -> String { + let mut o = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => o.push_str("&"), + '<' => o.push_str("<"), + '>' => o.push_str(">"), + '"' => o.push_str("""), + _ => o.push(c), + } + } + o +} + +/// Optionen und Ausmass (wie `SvgStringOptions` + `plan.bounds`). +pub struct SvgOptions { + pub scale_denominator: f64, + pub margin_m: f64, + pub min_x: f64, + pub min_y: f64, + pub max_x: f64, + pub max_y: f64, +} + +/// Zahl aus JSON (null/fehlend → NaN wie `undefined`/`NaN` in JS-Rechnungen). +fn jnum(v: &Value, k: &str) -> f64 { + v.get(k).and_then(Value::as_f64).unwrap_or(f64::NAN) +} + +fn jstr<'a>(v: &'a Value, k: &str) -> Option<&'a str> { + v.get(k).and_then(Value::as_str) +} + +/// `op(p)` aus JSON-Feldern: greyed (wahr) bzw. opacity < 1. +fn op_json(v: &Value) -> String { + let greyed = match v.get("greyed") { + Some(Value::Bool(b)) => *b, + _ => false, + }; + op(greyed, v.get("opacity").map(|o| o.as_f64().unwrap_or(f64::NAN))) +} + +fn op(greyed: bool, opacity: Option) -> String { + if greyed { + " opacity=\"0.35\"".into() + } else { + match opacity { + Some(o) if o < 1.0 => format!(" opacity=\"{}\"", num(o)), + _ => String::new(), + } + } +} + +/// SVG-Text des Plans; `None` bei kaputtem Puffer. +pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option { + let n = o.scale_denominator; + let margin = o.margin_m; + let mm_to_m = n / 1000.0; + let x0 = o.min_x - margin; + let w = o.max_x - o.min_x + 2.0 * margin; + let h = o.max_y - o.min_y + 2.0 * margin; + let top = o.max_y + margin; + let xs = |x: f64| num(x); + let ys = |y: f64| num(top - y); + let mut out: Vec = Vec::new(); + for part in parts.iter_mut() { + for i in part.from..part.to { + let rec = part.view.rec(i)?; + let f = rec.f.clone(); + let fl = rec.flags; + let greyed = fl & F_GREYED != 0; + let opacity = |k: usize| (fl & F_OPACITY != 0).then_some(f[k]); + let dash_attr = |part: &Part| -> Option { + if fl & F_DASH_LIST == 0 { + return Some(String::new()); + } + let (o, len) = rec.dash?; + let d = part.view.pool(o, len)?; + if d.is_empty() { + return Some(String::new()); + } + Some(format!(" stroke-dasharray=\"{}\"", d.iter().map(|v| num(v * mm_to_m)).collect::>().join(" "))) + }; + match rec.tag { + T_POLYGON => { + let pts = part.view.pool_pts(whole(f[5])?, whole(f[6])?)?; + if pts.len() < 3 { + continue; + } + let pl = pts.iter().map(|q| format!("{},{}", xs(q.x), ys(q.y))).collect::>().join(" "); + let fill = esc(part.str(f[0]).unwrap_or("")); + let stroke = esc(part.str(f[1]).unwrap_or("")); + out.push(format!( + "", + num(f[2] * mm_to_m), + op(greyed, opacity(4)) + )); + } + T_LINE => { + let color = if fl & F_COLOR != 0 { esc(part.str(f[1]).unwrap_or("")) } else { "#000".into() }; + let dash = dash_attr(part)?; + out.push(format!( + "", + xs(f[4]), + ys(f[5]), + xs(f[6]), + ys(f[7]), + num(f[2] * mm_to_m), + op(greyed, opacity(3)) + )); + } + T_ARC => { + let (cx, cy, fx, fy, tx, ty, r) = (f[4], f[5], f[6], f[7], f[8], f[9], f[10]); + let a0 = jsnum::atan2(fy - cy, fx - cx); + let mut sweep = jsnum::atan2(ty - cy, tx - cx) - a0; + while sweep < 0.0 && sweep.is_finite() { + sweep += PI * 2.0; + } + let dash = dash_attr(part)?; + out.push(format!( + "", + xs(fx), + ys(fy), + num(r), + num(r), + if sweep > PI { 1 } else { 0 }, + xs(tx), + ys(ty), + num(f[2] * mm_to_m), + op(greyed, opacity(3)) + )); + } + T_CIRCLE => { + let fill = esc(part.str(f[0]).unwrap_or("")); + let stroke = esc(part.str(f[1]).unwrap_or("")); + let dash = dash_attr(part)?; + out.push(format!( + "", + xs(f[4]), + ys(f[5]), + num(f[6]), + num(f[2] * mm_to_m), + op(greyed, opacity(3)) + )); + } + T_DRAWING_ARC => { + let (cx, cy, r, a0, a1) = (f[3], f[4], f[5], f[6], f[7]); + let sx = cx + r * jsnum::cos(a0); + let sy = cy + r * jsnum::sin(a0); + let ex = cx + r * jsnum::cos(a1); + let ey = cy + r * jsnum::sin(a1); + let mut sweep = a1 - a0; + while sweep < 0.0 && sweep.is_finite() { + sweep += PI * 2.0; + } + let stroke = esc(part.str(f[0]).unwrap_or("")); + let dash = dash_attr(part)?; + out.push(format!( + "", + xs(sx), + ys(sy), + num(r), + num(r), + if sweep > PI { 1 } else { 0 }, + xs(ex), + ys(ey), + num(f[1] * mm_to_m), + op(greyed, opacity(2)) + )); + } + T_DRAWING_TEXT | T_TEXT => { + // Texte reisen als JSON (nur im Text-Modus der Abschnitte; sonst fehlen sie). + let Some(js) = part.str(f[0]).map(str::to_owned) else { continue }; + let Ok(v) = serde_json::from_str::(&js) else { continue }; + let at = v.get("at").cloned().unwrap_or(Value::Null); + let (ax, ay) = (jnum(&at, "x"), jnum(&at, "y")); + if rec.tag == T_DRAWING_TEXT { + let angle = jnum(&v, "angle"); + out.push(format!( + "{}", + xs(ax), + ys(ay), + num(jnum(&v, "heightM")), + esc(jstr(&v, "color").unwrap_or("")), + num(-(angle * 180.0) / PI), + xs(ax), + ys(ay), + op_json(&v), + esc(jstr(&v, "text").unwrap_or("")) + )); + } else { + let size = (jnum(&v, "basePt") * 0.3528) * mm_to_m; + // plainText(doc): Absätze (Runs verkettet) mit "\n". + let doc = v.get("doc").and_then(|d| d.get("paragraphs")).and_then(Value::as_array); + let plain = doc + .map(|ps| { + ps.iter() + .map(|p| p.get("runs").and_then(Value::as_array).map(|rs| rs.iter().map(|r| jstr(r, "text").unwrap_or("")).collect::()).unwrap_or_default()) + .collect::>() + .join("\n") + }) + .unwrap_or_default(); + let mut lines = vec![plain]; + if let Some(ex) = v.get("extraLines").and_then(Value::as_array) { + for l in ex { + lines.push(jstr(l, "text").unwrap_or("").to_owned()); + } + } + let color = esc(jstr(&v, "color").unwrap_or("")); + let o = op_json(&v); + for (k, ln) in lines.iter().filter(|s| !s.is_empty()).enumerate() { + out.push(format!( + "{}", + xs(ax), + num(top - ay + k as f64 * size * 1.2), + num(size), + esc(ln) + )); + } + } + } + _ => {} + } + } + } + Some(format!( + "\n\n\n{}\n\n", + num(x0), + num(w), + num(h), + num(w * 1000.0 / n), + num(h * 1000.0 / n), + num(x0), + num(w), + num(h), + out.join("\n") + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn zahlen_und_escapes() { + assert_eq!(num(1.234567), "1.23457"); + assert_eq!(num(f64::NAN), "0"); + assert_eq!(num(-0.000001), "0"); + assert_eq!(esc("a"), "a<b & "c">"); + assert_eq!(op(false, Some(0.5)), " opacity=\"0.5\""); + assert_eq!(op(true, Some(0.5)), " opacity=\"0.35\""); + assert_eq!(op(false, Some(1.0)), ""); + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index b4fb4d87..a4d1f583 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -35,6 +35,7 @@ mod skeleton; mod plan_scene; mod plan_pick; mod snap; +mod plan_svg; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/plan_svg.rs b/src-tauri/core/src/web/plan_svg.rs new file mode 100644 index 00000000..42026394 --- /dev/null +++ b/src-tauri/core/src/web/plan_svg.rs @@ -0,0 +1,18 @@ +//! Bindung des SVG-Text-Exports (`crate::plan_svg`) auf gehaltenen Plan-Puffern (Abschnitte wie +//! `plan_parts`). Leerer Text = Puffer fehlt oder kaputt (TS legt neu ab und fragt nochmals). + +use crate::plan_parts::parts_from; +use crate::plan_svg::{plan_svg, SvgOptions}; +use wasm_bindgen::prelude::wasm_bindgen; + +/// `opts` = `[Massstab-Nenner, Rand m, minX, minY, maxX, maxY]`. +#[wasm_bindgen] +pub fn plan_svg_string(segs: &[f64], opts: &[f64]) -> String { + let [n, margin, min_x, min_y, max_x, max_y] = match <[f64; 6]>::try_from(opts) { + Ok(a) => a, + Err(_) => return String::new(), + }; + let Some(held) = super::plan_buf::held_for_segs(segs) else { return String::new() }; + let Some(mut parts) = parts_from(segs, |nr| held.iter().find(|e| e.0 == nr).map(|e| &*e.1)) else { return String::new() }; + plan_svg(&mut parts, &SvgOptions { scale_denominator: n, margin_m: margin, min_x, min_y, max_x, max_y }).unwrap_or_default() +} diff --git a/src/export/planToSvgString.ts b/src/export/planToSvgString.ts index 89c9e316..411b0a2b 100644 --- a/src/export/planToSvgString.ts +++ b/src/export/planToSvgString.ts @@ -1,11 +1,13 @@ // Plan → SVG-TEXT ohne DOM (für `dossier-cli` und Referenzbild-Tests, lessons-bimcraft [4]/[17]). -// Der Druck-Export (`planToPrintSvg`) baut ein DOM-Element für svg2pdf; dieser Serializer ist +// Der Druck-Export (`sceneToPrintSvg`) baut ein DOM-Element für svg2pdf; dieser Serializer ist // die schlanke, headless Variante: Koordinaten in Metern (Y nach oben → SVG gespiegelt), // Strichstärken aus Papier-mm über den Massstab umgerechnet. Schraffur-Muster werden nicht // ausgebreitet (nur Grundfüllung), Bilder fehlen — gedacht für Kontrolle und Diffs, nicht für Druck. +// Geschrieben vom Kern direkt aus dem Plan-Puffer ([K3d], `src-tauri/core/src/plan_svg.rs`). -import type { Plan, Primitive } from "../plan/generatePlan"; -import { plainText } from "../text/richText"; +import type { Plan } from "../plan/generatePlan"; +import { planParts, withPlanParts } from "../plan/planParts"; +import { core } from "../engine/coreWasm"; export interface SvgStringOptions { /** Massstab-Nenner N (1:N) — bestimmt die Umrechnung Papier-mm → Meter. Default 100. */ @@ -14,94 +16,8 @@ export interface SvgStringOptions { marginM?: number; } -const esc = (s: string): string => - s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); -const num = (v: number): string => (Number.isFinite(v) ? String(Math.round(v * 1e5) / 1e5) : "0"); - export function planToSvgString(plan: Plan, opts: SvgStringOptions = {}): string { - const n = opts.scaleDenominator ?? 100; - const margin = opts.marginM ?? 0.5; - const mmToM = n / 1000; // 1 mm Papier = n/1000 m Modell const b = plan.bounds; - const x0 = b.minX - margin; - const w = b.maxX - b.minX + 2 * margin; - const h = b.maxY - b.minY + 2 * margin; - // Y spiegeln: svgY = (maxY + margin) − y - const top = b.maxY + margin; - const X = (x: number): string => num(x); - const Y = (y: number): string => num(top - y); - const dashAttr = (d: number[] | null | undefined): string => - d && d.length ? ` stroke-dasharray="${d.map((v) => num(v * mmToM)).join(" ")}"` : ""; - const op = (p: { opacity?: number; greyed?: boolean }): string => - p.greyed ? ' opacity="0.35"' : p.opacity !== undefined && p.opacity < 1 ? ` opacity="${num(p.opacity)}"` : ""; - - const out: string[] = []; - for (const p of plan.primitives as Primitive[]) { - switch (p.kind) { - case "polygon": { - if (p.pts.length < 3) break; - const pts = p.pts.map((q) => `${X(q.x)},${Y(q.y)}`).join(" "); - out.push( - ``, - ); - break; - } - case "line": - out.push( - ``, - ); - break; - case "arc": { - // Bogen von `from` nach `to` um `center`, gegen den Uhrzeigersinn im Modell. - const a0 = Math.atan2(p.from.y - p.center.y, p.from.x - p.center.x); - let sweep = Math.atan2(p.to.y - p.center.y, p.to.x - p.center.x) - a0; - while (sweep < 0) sweep += Math.PI * 2; - out.push( - ``, - ); - break; - } - case "drawingCircle": - out.push( - ``, - ); - break; - case "drawingArc": { - const sx = p.center.x + p.r * Math.cos(p.a0); - const sy = p.center.y + p.r * Math.sin(p.a0); - const ex = p.center.x + p.r * Math.cos(p.a1); - const ey = p.center.y + p.r * Math.sin(p.a1); - let sweep = p.a1 - p.a0; - while (sweep < 0) sweep += Math.PI * 2; - out.push( - ``, - ); - break; - } - case "drawingText": - out.push( - `${esc(p.text)}`, - ); - break; - case "text": { - const size = (p.basePt * 0.3528) * mmToM; // pt → mm Papier → m Modell - const lines = [plainText(p.doc), ...p.extraLines.map((l) => l.text)].filter((s) => s); - lines.forEach((ln, i) => - out.push( - `${esc(ln)}`, - ), - ); - break; - } - default: - break; // Bilder, Textpfade: im headless SVG nicht dargestellt - } - } - return ( - `\n` + - `\n` + - `\n` + - out.join("\n") + - `\n\n` - ); + const o = Float64Array.from([opts.scaleDenominator ?? 100, opts.marginM ?? 0.5, b.minX, b.minY, b.maxX, b.maxY]); + return withPlanParts(planParts(plan, true), (segs) => core().plan_svg_string(segs, o)); } From 82eccb2e5f5d13b154349565fde009b6f381765e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 23:41:20 +0000 Subject: [PATCH 5/5] [K3d] TODO: Verbraucher lesen den Plan-Puffer (Szene, Auswahl, Fang, SVG), Messung, Rest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stand 28.10.: render2d-Szene, Auswahl/Picken, Objektfang und SVG-Text-Export laufen im Kern auf den gehaltenen Plan-Puffern; Gleichheit, Messung und was über Primitive[] bleibt (Overlay/Texte, Culling, Marquee, DXF, Layout-PDF) nachgeführt. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- TODO.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/TODO.md b/TODO.md index c1b00fc8..aca9b0a6 100644 --- a/TODO.md +++ b/TODO.md @@ -173,6 +173,38 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern unverändert). Offen: diese Verbraucher auf den Puffer umstellen (Picken über Pick-Art/Id je Eintrag; render2d-Szene direkt aus dem Puffer), TS-Anteile (2D-Zeichnungen, Schatten/Baurecht) in den Puffer schreiben. Nicht in der Tauri-App angesehen (der direkte GPU-Weg läuft nur im nativen macOS-Renderer; geprüft über die hochgeladenen Puffer in Vitest). + ✅ (28.10.) **Verbraucher lesen den Puffer** (Szene, Auswahl, Fang, SVG-Export). Grundlage `core/src/plan_parts.rs` ↔ + `src/plan/planParts.ts`: ein Plan als Abschnitte gehaltener Plan-Puffer in Zeichenreihenfolge — Kern-Abschnitte aus `Plan.bufRuns` + (Objekt-Identität geprüft) ohne Umweg, der Rest (2D-Zeichnungen, Schatten, Baurecht, zerlegte Polygone, gedimmte Klone) einmal in + einen eigenen Puffer (ohne Schraffur-JSON; Texte nur mit JSON für den SVG-Export); `greyedRanges` gehen als Bereiche mit (kein + Klonen). Gehaltene Puffer sind geteilt (`Rc`), bis 64; verdrängt → TS legt neu ab und fragt nochmals. + - Render-Szene: `core/src/plan_scene.rs` (Farben wie `toRgba`, CSS-Klassen, Dimmen, `z`, Verkettung, Kantennaht mit Raster statt + O(n²)-Suche, Schraffur-Läufe, Zickzack/Motiv, Kreis-Tessellierung) schreibt die render2d-Szene v1 direkt (`planSceneBin` → + `set_scene_bin`, `push_native_scene`) bzw. eine verlustfreie f64-Szene (`planToRenderScene` für `sceneToPrintSvg`/PDF/SVG-Dialog, + CLI `--format json`). Text-Layout bleibt TS (`planSceneTexts`). `renderSceneBin.ts` gelöscht, Fixture-Test nach Rust. + - Auswahl: `core/src/plan_pick.rs` ↔ `src/plan/planView/planPick.ts` (Index je Plan, lazy): 2D-Zeichenlinien im Raster (wie + `segmentIndex`), Polygone unter dem Punkt (oberstes/unterstes, Pick-Feld-Filter), Symbol-Linien/-Bögen in Client-Pixeln, Kreis-/ + Bogen-Ringe, Besitzer. PlanView fragt nur ab (hitTest, pickRoom/Roof/Stair/Opening/Column/…, pickDrawing, nearDrawingIds, + Hervorhebung); `segmentIndex.ts`, `ownerIndex.ts` und die Schleifen über alle Primitive je Mausbewegung gelöscht. + - Fang: `core/src/snap.rs` ↔ `src/geometry/snapSegments.ts`: Strecken eines Projekt-Geschosses einmal im Kern (Raster), je + Mausbewegung Lot/Endpunkt/Mitte/Schnitt/Kante/Verweilen; Schnittpunkte nur zwischen Geraden, die näher als die Toleranz am Cursor + vorbeigehen (vorher alle Paare). Die Sammlung der Strecken (Modell) bleibt in `tools/snapping.ts` (bis [K4]), gecacht je + Projekt/Geschoss/Sichtbarkeit samt Raum-Ankern, Kreisen, Ellipsen. + - SVG-Text-Export: `core/src/plan_svg.rs` (`planToSvgString` für CLI/MCP/Goldens), Texte aus dem Text-JSON des Puffers. + Gleichheit (temporäre Paritätstests gegen die alten TS-Fassungen, danach entfernt): Szene JSON + Binär bitgleich (Beispielprojekt + alle Ebenen × Detailgrade × mono, Überlagerung mit gedimmten Ebenen, Schnitt, Ansicht, 400 Zufallslisten aller Primitiv-Arten, + grosses Projekt); Auswahl 25 000 Abfragen gleich (Beispiel + Überlagerung, 150 Zufallspläne, grosses Projekt); Fang 2600 Abfragen + gleich (Beispiel, mit 2D-Zeichnung, Nahmodus > 2000 Zeichnungen, bigSample(3), Verweilen an/aus, alle Fang-Arten zufällig); SVG + 328 Pläne byte-gleich, Goldens unverändert; CLI plan EG/OG (svg, json), section, elevation, dxf md5-gleich zur CLI des Hauptstands. + Messung (Node, Linux-Container, `--no-opt`-WASM): Szene grosses Projekt 3125 → 133 ms (Beispiel-EG 1,8 → 0,7 ms); Auswahl grosses + Projekt + 100k 2D-Linien alle Hover-Abfragen zusammen 90 ms → 30 µs je Mausbewegung (Aufbau ~100 ms lazy); Fang grosses Projekt + 27,6 s → 0,8 ms je Mausbewegung, bigSample(5) 135 ms → 57 µs. Kodieren des eigenen Puffers in TS ~1 µs je Linie (bei 100k + gemischten Primitiven ~200 ms, einmal je Plan). Nicht in der Tauri-App angesehen; `push_native_scene` nur über die Bytes geprüft. + Bleibt über `Primitive[]`: Text-Overlay und SVG-Rückfall der PlanView (`nativeText`, `primitives.tsx`, Culling `cullPrimitives`), + Marquee (`marqueeHit*`, nur beim Loslassen), `drawingLabel`/Text-/Bild-Treffer (Bbox, je Plan vorsortiert), DXF-Sammler + (`exportDxf.ts`, 1000 Zeilen Stil/Layer-Logik) und `planToPrintSvg.ts` (Layout-PDF/LayoutSheet; nicht auf `sceneToPrintSvg` + umgestellt, weil die Ausgabe dann nicht mehr byte-gleich wäre). `generatePlan` dekodiert den Kern-Puffer weiter vollständig + (für diese Verbraucher); fällt, wenn sie den Puffer lesen bzw. das Modell nach Rust zieht [K4]. Nachteile (bewusst): Übergang mit doppelter Datenhaltung, Format muss TS/Rust gleich bleiben (Versionsnummer + Hin-und-zurück-Tests), Text-Layout bleibt bis [K4] in TS. - ◐ **[K4] Modell und Ops in Rust** [2]; TS bekommt die Typen generiert (z. B. `ts-rs`). · XL @@ -206,6 +238,8 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern ([K3d] hängt hier dran: Plan-Puffer v2 mit Pick-IDs und vollem Primitive-Umfang). Stand 28.10.: Plan-Puffer v2 steht ([K3d]) — `planDomains` liefert binär, GPU liest ihn direkt; Export/Auswahl/Overlay lesen noch die dekodierten `Primitive[]`. + Nachtrag 28.10.: render2d-Szene, Auswahl, Fang und SVG-Text-Export lesen den Puffer im Kern ([K3d]); Overlay/Texte, DXF und + Layout-PDF noch über `Primitive[]`. - ◐ **S3 Änderungen kommen aus Rust**: Befehle (Zustandsautomaten, Werkzeuge) erzeugen Ops im Kern; Undo/Redo, Validierung (`validateOps`) und Gruppen/Ebenen-Logik wandern nach Rust; `diffToOps` entfällt, TS hält nur noch eine Leseansicht. **Erste Etappe (28.10.): Ops, Prüfung, Undo/Redo im Kern.** `core/src/ops.rs` (Op, Prüfung bitgleich zur TS-Fassung — gleiche