From 54a7d270eab2b905f889778fff758432f53a87e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 21:57:01 +0000 Subject: [PATCH 1/4] [K3d] Plan-Puffer v2: Format, Schreiber/Leser in Rust und TS, GPU-Kompilierung liest v2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Format im Kopf von plan_buf.rs (Gegenstück src/plan/planBuf.ts): Bytes mit f64-Teil und UTF-16-Texten, Kopf mit Magie PLB2/Version 2, Tabellen für Strings und Schraffuren (JSON für TS + numerischer Hatch-Datensatz), Gruppen, Offsets, Inhalts-Hashes, Einträge mit Pick-Art/-Id und Punkt-Pool, voller Primitive-Umfang (Texte/Bild als JSON). v1 und TS-parseColor gelöscht (Farben parst plan_buf::parse_color bitgleich). GPU-Kompilierung liest Bereiche direkt (gpu_compile_flat/gpu_compile_held, plan_buf_hold); gemischte Listen kodiert TS schlank. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src-tauri/core/src/gpu_compile.rs | 37 +- src-tauri/core/src/plan/prim.rs | 88 +- src-tauri/core/src/plan_buf.rs | 2001 ++++++++++++++++++++----- src-tauri/core/src/web/gpu_compile.rs | 15 +- src-tauri/core/src/web/plan_buf.rs | 45 +- src/plan/glPlan/glPlanCompile.ts | 29 +- src/plan/planBuf.test.ts | 179 ++- src/plan/planBuf.ts | 678 ++++++--- 8 files changed, 2391 insertions(+), 681 deletions(-) diff --git a/src-tauri/core/src/gpu_compile.rs b/src-tauri/core/src/gpu_compile.rs index 91a9fc52..59ac4733 100644 --- a/src-tauri/core/src/gpu_compile.rs +++ b/src-tauri/core/src/gpu_compile.rs @@ -779,9 +779,10 @@ fn draw_circle_like( c.stroke_polyline(&pts, fill.is_some(), stroke_col, stroke_mm, false); } -/// Flache Ausgabe (s. Modulkopf); leer bei unlesbarem Plan-Puffer. -pub fn compile_flat(buf: &[f64], px_per_meter: f64, packed: bool) -> Vec { - let Some(plan) = plan_buf::decode(buf) else { return Vec::new() }; +/// Flache Ausgabe (s. Modulkopf) für die Primitive `[from, to)` eines Plan-Puffers (v2); leer bei +/// unlesbarem Puffer oder ungültigem Bereich. +pub fn compile_flat(bytes: &[u8], from: usize, to: usize, px_per_meter: f64, packed: bool) -> Vec { + let Some(plan) = plan_buf::View::parse(bytes).and_then(|v| v.gpu(from, to)) else { return Vec::new() }; let o = compile(&plan, px_per_meter, packed); let mut meta: Vec = vec![ o.origin.0, @@ -843,7 +844,6 @@ mod tests { weight_mm: 0.18, a: v2(ax, 0.0), b: v2(bx, 0.0), - dash: vec![], chain, zigzag: None, motif: None, @@ -926,8 +926,8 @@ mod tests { #[test] fn kreis_und_bogen() { let p = plan(vec![ - Prim::Circle { style: st(), fill: 1, stroke: 0, weight_mm: 0.0, center: v2(1.0, 1.0), r: 1.0, dash: vec![] }, - Prim::DrawingArc { style: st(), stroke: 0, weight_mm: 0.5, center: v2(0.0, 0.0), r: 1.0, a0: 0.0, a1: 0.0, dash: vec![] }, + Prim::Circle { style: st(), fill: 1, stroke: 0, weight_mm: 0.0, center: v2(1.0, 1.0), r: 1.0 }, + Prim::DrawingArc { style: st(), stroke: 0, weight_mm: 0.5, center: v2(0.0, 0.0), r: 1.0, a0: 0.0, a1: 0.0 }, Prim::Placeholder, ]); let o = compile(&p, 0.0, false); @@ -938,9 +938,26 @@ mod tests { #[test] fn kaputter_puffer_leer() { - assert!(compile_flat(&[1.0, 2.0, 3.0], 90.0, true).is_empty()); - let enc = plan_buf::encode(&plan(vec![line(0.0, f64::NAN, false)])); - let out = compile_flat(&enc, 90.0, true); - assert!(!out.is_empty()); + assert!(compile_flat(&[1, 2, 3], 0, 0, 90.0, true).is_empty()); + let mut w = plan_buf::Writer::new(false); + w.push(&crate::plan::prim::Primitive::Line { + a: crate::model::Vec2 { x: 0.0, y: 0.0 }, + b: crate::model::Vec2 { x: f64::NAN, y: 0.0 }, + cls: "c".into(), + weight_mm: 0.18, + dash: None, + zigzag: None, + motif: None, + color: None, + drawing_id: None, + opening_id: None, + stair_id: None, + greyed: None, + opacity: None, + }); + let enc = w.finish(); + assert!(!compile_flat(&enc, 0, 1, 90.0, true).is_empty()); + assert!(compile_flat(&enc, 0, 2, 90.0, true).is_empty(), "Bereich ausserhalb"); + assert!(!compile_flat(&enc, 1, 1, 90.0, true).is_empty(), "leerer Bereich = leere Geometrie"); } } diff --git a/src-tauri/core/src/plan/prim.rs b/src-tauri/core/src/plan/prim.rs index 3d2172b3..c14db0a9 100644 --- a/src-tauri/core/src/plan/prim.rs +++ b/src-tauri/core/src/plan/prim.rs @@ -3,10 +3,10 @@ //! Zeichen für Zeichen die der TS-Objekte (camelCase, fehlende Felder fehlen). use crate::model::*; -use serde::Serialize; +use serde::{Deserialize, Deserializer, Serialize}; /// Aufgelöste Schraffur eines Polygons (`HatchRender`). -#[derive(Debug, Clone, PartialEq, Serialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct HatchRender { pub pattern: HatchPattern, @@ -38,7 +38,7 @@ pub struct HatchRender { } /// Zeile unter dem Raum-Stempel. -#[derive(Debug, Clone, PartialEq, Serialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct StampLine { pub text: String, pub align: Align, @@ -47,7 +47,12 @@ pub struct StampLine { /// `dash?: number[] | null`: fehlt (`None`), `null` (`Some(None)`) oder Muster. pub type Dash = Option>>; -#[derive(Debug, Clone, PartialEq, Serialize)] +/// Liest `dash` so, dass `null` (`Some(None)`) und fehlend (`None`, über `default`) verschieden bleiben. +fn de_dash<'de, D: Deserializer<'de>>(d: D) -> Result { + Option::>::deserialize(d).map(Some) +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(tag = "kind")] pub enum Primitive { #[serde(rename = "polygon", rename_all = "camelCase")] @@ -92,7 +97,7 @@ pub enum Primitive { b: Vec2, cls: String, weight_mm: f64, - #[serde(skip_serializing_if = "Option::is_none")] + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_dash")] dash: Dash, #[serde(skip_serializing_if = "Option::is_none")] zigzag: Option, @@ -119,7 +124,7 @@ pub enum Primitive { r: f64, cls: String, weight_mm: f64, - #[serde(skip_serializing_if = "Option::is_none")] + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_dash")] dash: Dash, #[serde(skip_serializing_if = "Option::is_none")] opening_id: Option, @@ -164,13 +169,82 @@ pub enum Primitive { #[serde(skip_serializing_if = "Option::is_none")] opacity: Option, }, + /// Text entlang eines Pfads (2D-Zeichnung); erzeugt heute nur TS, s. Plan-Puffer v2. + #[serde(rename = "drawingTextPath", rename_all = "camelCase")] + DrawingTextPath { + path_pts: Vec, + text: String, + height_m: f64, + color: String, + #[serde(skip_serializing_if = "Option::is_none")] + drawing_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + greyed: Option, + #[serde(skip_serializing_if = "Option::is_none")] + opacity: Option, + }, + /// Eingebettetes Rasterbild (2D-Zeichnung). + #[serde(rename = "drawingImage", rename_all = "camelCase")] + DrawingImage { + min: Vec2, + max: Vec2, + src: String, + opacity: f64, + #[serde(skip_serializing_if = "Option::is_none")] + drawing_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + greyed: Option, + }, + /// Glatter Kreis (2D-Zeichnung). + #[serde(rename = "drawingCircle", rename_all = "camelCase")] + DrawingCircle { + center: Vec2, + r: f64, + fill: String, + stroke: String, + weight_mm: f64, + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_dash")] + dash: Dash, + #[serde(skip_serializing_if = "Option::is_none")] + drawing_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + greyed: Option, + #[serde(skip_serializing_if = "Option::is_none")] + opacity: Option, + }, + /// Glatter Bogen (2D-Zeichnung), Winkel im Bogenmass (CCW). + #[serde(rename = "drawingArc", rename_all = "camelCase")] + DrawingArc { + center: Vec2, + r: f64, + a0: f64, + a1: f64, + stroke: String, + weight_mm: f64, + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_dash")] + dash: Dash, + #[serde(skip_serializing_if = "Option::is_none")] + drawing_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + greyed: Option, + #[serde(skip_serializing_if = "Option::is_none")] + opacity: Option, + }, } impl Primitive { /// Setzt `greyed` (für Gruppen, deren Darstellungsmodus gedimmt ist). pub fn with_greyed(mut self, g: bool) -> Self { match &mut self { - Primitive::Polygon { greyed, .. } | Primitive::Line { greyed, .. } | Primitive::Arc { greyed, .. } | Primitive::Text { greyed, .. } | Primitive::DrawingText { greyed, .. } => *greyed = Some(g), + Primitive::Polygon { greyed, .. } + | Primitive::Line { greyed, .. } + | Primitive::Arc { greyed, .. } + | Primitive::Text { greyed, .. } + | Primitive::DrawingText { greyed, .. } + | Primitive::DrawingTextPath { greyed, .. } + | Primitive::DrawingImage { greyed, .. } + | Primitive::DrawingCircle { greyed, .. } + | Primitive::DrawingArc { greyed, .. } => *greyed = Some(g), } self } diff --git a/src-tauri/core/src/plan_buf.rs b/src-tauri/core/src/plan_buf.rs index 61027b6d..496b6567 100644 --- a/src-tauri/core/src/plan_buf.rs +++ b/src-tauri/core/src/plan_buf.rs @@ -1,51 +1,119 @@ -//! Plan-Puffer ([K3b]): kompakte Binärkodierung der zeichnungsrelevanten Plan-Primitive als -//! flacher `f64`-Puffer (TS schreibt ihn heute in `src/plan/planBuf.ts`, später erzeugt Rust ihn -//! direkt, [K3a]). Pick-IDs gehören nicht hinein (Picken bleibt vorerst TS); dafür hat jedes -//! Primitiv genau einen Eintrag, damit Indizes und Bereiche (`greyedRanges`, Chunks) gleich bleiben. +//! Plan-Puffer v2 ([K3d]): binäre Übergabe der Plan-Primitive zwischen Kern und Verbrauchern — +//! Gegenstück in TS ist `src/plan/planBuf.ts` (dort dieselbe Formatbeschreibung). Der Kern schreibt +//! ihn direkt aus der Plan-Erzeugung (`planDomains`, [`Writer`]); TS liest ihn zu `Primitive[]` +//! (Auswahl, Overlay, SVG/PDF/DXF) und schreibt ihn für GPU-Chunks aus gemischten Listen. Die +//! GPU-Kompilierung (`gpu_compile.rs`) liest beliebige Bereiche direkt ([`View::gpu`]). //! +//! Ein Puffer sind Bytes (little-endian): erst ein `f64`-Teil, dann die Text-Einheiten (UTF-16). //! ```text -//! Kopf [MAGIC, VERSION, nColors, nHatches, nPrims] -//! MAGIC = 0x504C4231 ("PLB1"), VERSION = 1 — fremde Werte → Puffer abgelehnt -//! Farben nColors × [r, g, b, a] (0..1, aus dem Farbtext in TS geparst) -//! Schraffuren nHatches × Hatch -//! Primitive nPrims × Prim -//! -//! Hatch [pattern, kind, flags, scale, angle, colorIdx, lineWeight, originX, originY, -//! seed, density, lengthMin, lengthMax, nDash, dash…, (Motiv: length, nPts, x,y…)] -//! pattern 0 none · 1 solid · 2 diagonal · 3 crosshatch · 4 insulation · 5 custom -//! kind 0 vector · 1 image · 2 gradient (Bild/Verlauf: GPU fällt auf die Füllung zurück) -//! flags 1 random · 2 origin · 4 seed · 8 density · 16 lengthMin · 32 lengthMax · 64 Motiv -//! (Felder ohne Flag stehen auf 0 und gelten als „nicht gesetzt“) -//! -//! Prim [tag, flags, …] flags 1 greyed · 2 opacity gesetzt · 4 setzt den Linienzug der -//! vorigen Linie fort · 8 Zickzack · 16 Motiv -//! 0 Platzhalter [0] (Text, Bild … — zeichnet die GPU nicht) -//! 1 polygon [1, flags, fillIdx, strokeIdx, strokeWidthMm, hatchIdx, opacity, -//! nPts, x,y…, nNoStroke, kante…] -//! 2 line [2, flags, colorIdx, weightMm, opacity, ax, ay, bx, by, nDash, dash…, -//! (Zickzack: amplitude, wavelength), (Motiv: length, nPts, x,y…)] -//! 3 arc [3, flags, colorIdx, weightMm, opacity, cx, cy, fromX, fromY, toX, toY, r, -//! nDash, dash…] -//! 4 drawingCircle [4, flags, fillIdx, strokeIdx, weightMm, opacity, cx, cy, r, nDash, dash…] -//! 5 drawingArc [5, flags, strokeIdx, weightMm, opacity, cx, cy, r, a0, a1, nDash, dash…] +//! Kopf (16 × f64) [MAGIC, VERSION, flags, nStrings, nHatches, nHatchWords, nGroups, nPrims, +//! nRecWords, nPool, nUnits, 0, minX, minY, maxX, maxY] +//! MAGIC = 0x504C4232 ("PLB2"), VERSION = 2 — fremde Werte → Puffer abgelehnt +//! flags 1 = Inhalts-Hashes vorhanden · 2 = Ausmass (minX…maxY) gesetzt +//! Strings nStrings × [unitOff, unitLen] (Abschnitt der UTF-16-Einheiten am Ende) +//! Schraffuren nHatchWords Wörter, nHatches Einträge: [jsonStr, Hatch] +//! jsonStr = die volle `HatchRender` als JSON (TS liest sie einmal je Eintrag); +//! Hatch = [pattern, kind, flags, scale, angle, colorStr, lineWeight, originX, originY, +//! seed, density, lengthMin, lengthMax, nDash, dash…, (Motiv: length, nPts, x,y…)] +//! pattern 0 none · 1 solid · 2 diagonal (auch unbekannt) · 3 crosshatch · 4 insulation · +//! 5 custom; kind 0 vector · 1 image · 2 gradient; flags 1 random · 2 origin · 4 seed · +//! 8 density · 16 lengthMin · 32 lengthMax · 64 Motiv (Felder ohne Flag stehen auf 0). +//! Dasselbe Hatch-Format (Farbe −1) nehmen die Einzel-Bindungen der Schraffur ([`decode_hatch`]). +//! Gruppen nGroups × [start, end) (Primitiv-Bereiche, bei `planDomains` die Domänen +//! Decken, Dächer, Räume, Wände, Treppen, Stützen, +//! Körper, Kontext, Schnittlinien) +//! Offsets nPrims × Wortindex des Eintrags im Primitiv-Abschnitt (wahlfreier Zugriff) +//! Hashes nPrims × Inhalts-Hash (52 Bit, nur mit flags & 1) — Schlüssel des GPU-Chunk-Caches +//! Primitive nRecWords Wörter, je Primitiv ein Eintrag (Reihenfolge = Zeichenreihenfolge) +//! Pool nPool f64 (Punkte x,y…, Strichmuster, Kantenlisten, Motive, weitere Ids) +//! Einheiten nUnits × u16 (alle Texte hintereinander, UTF-16 wie JS-Strings) //! ``` -//! Farb-/Schraffur-Index −1 = keine (Farbtext ungültig, "none", fehlende Schraffur). Längen in -//! Metern, Strichstärken/Strichmuster/Zickzack/Motiv in Papier-mm, Winkel von drawingArc in -//! Bogenmass, Schraffur-Winkel in Grad (SVG-Drehsinn). Ohne opacity-Flag steht 1 im Feld. -//! Fehlende Strichstärke (`undefined`) wird NaN (der Verbraucher nimmt dann seinen Standard). -//! Flag 4 (Linienzug): TS prüft gleiches Element (`drawingId`), gleiche Farbe/Stärke/greyed/ -//! opacity/Strichmuster und Anfang = Ende der vorigen Linie; der Verbraucher prüft die Lage nach. +//! Eintrag `[tag, flags, pickKind, pickStr, …]`; danach je Typ (Liste = `off, n` im Pool): +//! ```text +//! 1 polygon fill, stroke, strokeWidthMm, hatch, opacity, pts(off, nPts) [, noStrokeEdges(off, n)] +//! 2 line cls, color, weightMm, opacity, ax, ay, bx, by [, dash(off, n)] [, zigzag amp, wav] +//! [, motif length, pts(off, nPts)] +//! 3 arc cls, color, weightMm, opacity, cx, cy, fromX, fromY, toX, toY, r [, dash(off, n)] +//! 4 drawingCircle fill, stroke, weightMm, opacity, cx, cy, r [, dash(off, n)] +//! 5 drawingArc stroke, weightMm, opacity, cx, cy, r, a0, a1 [, dash(off, n)] +//! 6 text · 7 drawingText · 8 drawingTextPath · 9 drawingImage jsonStr (das ganze Primitiv als JSON, +//! „Daten wie heute“; die GPU zeichnet sie nicht) +//! 0 Platzhalter (nur GPU-Puffer aus TS, s. `lean`) +//! zuletzt [, ids(off, n)] mit Flag 1024: weitere Pick-Ids als Paare (kind, str) im Pool +//! ``` +//! Flags: 1 greyed gesetzt · 2 greyed = true · 4 opacity gesetzt · 8 setzt den Linienzug der +//! vorigen Linie fort · 16 Zickzack · 32 Motiv · 64 dash = null · 128 dash = Liste · 256 +//! noStrokeEdges · 512 Farbe gesetzt (line/arc) · 1024 weitere Ids. +//! Pick-Arten: 0 keine · 1 wall · 2 drawing · 3 ceiling · 4 opening · 5 stair · 6 room · +//! 7 extrudedSolid · 8 contextObject · 9 column · 10 roof · 11 sectionLine (= `Id`). +//! String-/Schraffur-Index −1 = fehlt. Ohne opacity-Flag steht 1 im Feld. Längen in Metern, +//! Strichstärken/Strichmuster/Zickzack/Motiv in Papier-mm, Bögen von drawingArc im Bogenmass, +//! Schraffur-Winkel in Grad (SVG-Drehsinn). Fehlende Zahlen (TS `undefined`) werden NaN. +//! Flag 8 (Linienzug) setzt der Schreiber: gleiches Element (`drawingId`), gleiche Farbe/Stärke/ +//! greyed/opacity, gleiches Strichmuster (TS: dieselbe Referenz; Kern: beide fehlend oder beide +//! null) und Anfang = Ende der vorigen Linie. Der Leser ignoriert es am Anfang eines Bereichs. +//! Unbekannte Zusatzfelder von Zickzack/Motiv (Modell-`extra`) reisen nicht mit. +//! Fehler einer Abfrage: `[ERR_MAGIC, nUnits]` + Meldung als UTF-16 ([`encode_error`]). use crate::hatch::{Hatch, HatchKind, Motif, Pattern, V2}; +use crate::model::{HatchPattern, HatchStyleKind, HatchStyleLines, LineStyleMotif, LineStyleZigzag, Vec2}; +use crate::plan::overrides::js_trim; +use crate::plan::prim::{Dash, HatchRender, Primitive}; +use std::collections::HashMap; +use std::hash::{BuildHasherDefault, Hasher}; -pub const MAGIC: f64 = 1_347_174_961.0; // 0x504C4231 -pub const VERSION: f64 = 1.0; +/// Schneller Hasher für die Tabellen des Schreibers (FNV-1a über die Bytes; kein Schutz gegen +/// gezielte Kollisionen nötig). +#[derive(Default)] +struct FnvHasher(u64); -pub const FLAG_GREYED: u32 = 1; -pub const FLAG_OPACITY: u32 = 2; -pub const FLAG_CHAIN: u32 = 4; -pub const FLAG_ZIGZAG: u32 = 8; -pub const FLAG_MOTIF: u32 = 16; +impl Hasher for FnvHasher { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + let mut h = if self.0 == 0 { FNV_OFFSET } else { self.0 }; + for b in bytes { + h ^= *b as u64; + h = h.wrapping_mul(FNV_PRIME); + } + self.0 = h; + } +} + +type FastMap = HashMap>; + +pub const MAGIC: f64 = 1_347_174_962.0; // 0x504C4232 "PLB2" +pub const VERSION: f64 = 2.0; +/// Fehlerpuffer einer Abfrage ("PLBe"). +pub const ERR_MAGIC: f64 = 1_347_175_013.0; +const HEAD: usize = 16; + +const HEAD_HASHES: u32 = 1; +const HEAD_BOUNDS: u32 = 2; + +pub const F_GREYED_SET: u32 = 1; +pub const F_GREYED: u32 = 2; +pub const F_OPACITY: u32 = 4; +pub const F_CHAIN: u32 = 8; +pub const F_ZIGZAG: u32 = 16; +pub const F_MOTIF: u32 = 32; +pub const F_DASH_NULL: u32 = 64; +pub const F_DASH_LIST: u32 = 128; +pub const F_NSE: u32 = 256; +pub const F_COLOR: u32 = 512; +pub const F_IDS: u32 = 1024; + +pub const T_PLACEHOLDER: u32 = 0; +pub const T_POLYGON: u32 = 1; +pub const T_LINE: u32 = 2; +pub const T_ARC: u32 = 3; +pub const T_CIRCLE: u32 = 4; +pub const T_DRAWING_ARC: u32 = 5; +pub const T_TEXT: u32 = 6; +pub const T_DRAWING_TEXT: u32 = 7; +pub const T_TEXT_PATH: u32 = 8; +pub const T_IMAGE: u32 = 9; const HF_RANDOM: u32 = 1; const HF_ORIGIN: u32 = 2; @@ -55,6 +123,8 @@ const HF_LEN_MIN: u32 = 16; const HF_LEN_MAX: u32 = 32; const HF_MOTIF: u32 = 64; +// ── GPU-Sicht: was die Kompilierung braucht (Farben geparst, Indizes in `colors`) ────────────── + /// Gemeinsame Darstellungs-Attribute. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Style { @@ -88,7 +158,6 @@ pub enum Prim { weight_mm: f64, a: V2, b: V2, - dash: Vec, /// Setzt den Linienzug der vorigen Linie fort (gleiches Element und gleicher Stil). chain: bool, zigzag: Option<(f64, f64)>, @@ -102,7 +171,6 @@ pub enum Prim { from: V2, to: V2, r: f64, - dash: Vec, }, Circle { style: Style, @@ -111,7 +179,6 @@ pub enum Prim { weight_mm: f64, center: V2, r: f64, - dash: Vec, }, DrawingArc { style: Style, @@ -121,10 +188,10 @@ pub enum Prim { r: f64, a0: f64, a1: f64, - dash: Vec, }, } +/// Ein Bereich des Puffers in der GPU-Sicht. #[derive(Clone, Debug, Default, PartialEq)] pub struct PlanBuf { pub colors: Vec<[f64; 4]>, @@ -142,27 +209,148 @@ impl PlanBuf { } } -// ── Lesen ─────────────────────────────────────────────────────────────────── +// ── 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 { + 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() { + Some(b'-') => (true, &t[1..]), + Some(b'+') => (false, &t[1..]), + _ => (false, t), + }; + let t = if t.len() >= 2 && (t.starts_with("0x") || t.starts_with("0X")) { &t[2..] } else { t }; + let mut v = 0.0; + let mut any = false; + for c in t.chars() { + let Some(d) = c.to_digit(16) else { break }; + v = v * 16.0 + d as f64; + any = true; + } + if !any { + return f64::NAN; + } + if neg { + -v + } else { + v + } +} + +/// JS `parseFloat` auf einer Folge aus Ziffern und Punkten (längster gültiger Präfix). +fn js_parse_float_digits(s: &str) -> f64 { + let b = s.as_bytes(); + let mut i = 0; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + let int_end = i; + if i < b.len() && b[i] == b'.' { + let mut j = i + 1; + while j < b.len() && b[j].is_ascii_digit() { + j += 1; + } + if j > i + 1 || int_end > 0 { + i = j; + } + } + let p = &s[..i]; + if p.is_empty() || p == "." { + return f64::NAN; + } + p.parse::().unwrap_or(f64::NAN) +} + +/// JS `Number(s)` auf einer Folge aus Ziffern und Punkten. +fn js_number_digits(s: &str) -> f64 { + s.parse::().unwrap_or(f64::NAN) +} + +/// Farbtext → RGBA in [0, 1]; ungültig/"none"/"transparent" → `None`. Bitgleich zur früheren +/// TS-Fassung (`parseColor`): "#rgb", "#rrggbb", "#rrggbbaa", "rgb()/rgba()". +pub fn parse_color(text: &str) -> Option<[f64; 4]> { + if text.is_empty() { + return None; + } + let s = js_trim(text).to_lowercase(); + if s == "none" || s == "transparent" { + return None; + } + if s.starts_with("rgb") { + let mut m: Vec<&str> = Vec::new(); + let b = s.as_bytes(); + let mut i = 0; + while i < b.len() { + if b[i].is_ascii_digit() || b[i] == b'.' { + let st = i; + while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.') { + i += 1; + } + m.push(&s[st..i]); + } else { + i += 1; + } + } + if m.len() < 3 { + return None; + } + let a = if m.len() >= 4 { js_parse_float_digits(m[3]) } else { 1.0 }; + return Some([js_number_digits(m[0]) / 255.0, js_number_digits(m[1]) / 255.0, js_number_digits(m[2]) / 255.0, if a > 1.0 { a / 255.0 } else { a }]); + } + let u: Vec = s.encode_utf16().collect(); + let mut h: Vec = if u.first() == Some(&(b'#' as u16)) { u[1..].to_vec() } else { u }; + if h.len() == 3 { + h = vec![h[0], h[0], h[1], h[1], h[2], h[2]]; + } + if h.len() != 6 && h.len() != 8 { + return None; + } + let r = js_parse_hex(&h[0..2]); + let g = js_parse_hex(&h[2..4]); + let bl = js_parse_hex(&h[4..6]); + let a = if h.len() == 8 { js_parse_hex(&h[6..8]) / 255.0 } else { 1.0 }; + if r.is_nan() || g.is_nan() || bl.is_nan() { + return None; + } + Some([r / 255.0, g / 255.0, bl / 255.0, a]) +} + +// ── Lesen ──────────────────────────────────────────────────────────────────────────────────────── + +/// Wort-Leser über einem `f64`-Ausschnitt (Bytes, little-endian) — ohne Kopie. +#[derive(Clone, Copy)] +struct Words<'a> { + bytes: &'a [u8], +} + +impl<'a> Words<'a> { + fn get(&self, i: usize) -> Option { + let b = self.bytes.get(i.checked_mul(8)?..i.checked_mul(8)?.checked_add(8)?)?; + Some(f64::from_le_bytes(b.try_into().ok()?)) + } +} struct Reader<'a> { - buf: &'a [f64], + w: Words<'a>, pos: usize, + end: usize, } impl<'a> Reader<'a> { fn f(&mut self) -> Option { - let v = *self.buf.get(self.pos)?; + if self.pos >= self.end { + return None; + } + let v = self.w.get(self.pos)?; self.pos += 1; Some(v) } - /// Nicht-negative ganze Anzahl, höchstens so gross wie der Rest des Puffers × `per`. + /// Nicht-negative ganze Anzahl, höchstens so gross wie der Rest × `per`. fn count(&mut self, per: usize) -> Option { let v = self.f()?; - if !(v >= 0.0) || v.fract() != 0.0 { - return None; - } - let n = v as usize; - if n.checked_mul(per)? > self.buf.len() - self.pos { + let n = whole(v)?; + if n.checked_mul(per)? > self.end - self.pos { return None; } Some(n) @@ -186,9 +374,11 @@ impl<'a> Reader<'a> { } fn list(&mut self) -> Option> { let n = self.count(1)?; - let s = self.buf[self.pos..self.pos + n].to_vec(); - self.pos += n; - Some(s) + let mut out = Vec::with_capacity(n); + for _ in 0..n { + out.push(self.f()?); + } + Some(out) } fn pts(&mut self) -> Option> { let n = self.count(2)?; @@ -198,25 +388,22 @@ impl<'a> Reader<'a> { } Some(out) } - fn motif(&mut self) -> Option { - let length = self.f()?; - Some(Motif { length, points: self.pts()? }) - } - fn style(flags: u32, opacity: f64) -> Style { - Style { greyed: flags & FLAG_GREYED != 0, opacity: if flags & FLAG_OPACITY != 0 { Some(opacity) } else { None } } +} + +/// Nicht-negative ganze Zahl als Index/Anzahl. +fn whole(v: f64) -> Option { + if !(v >= 0.0) || v.fract() != 0.0 || v > (u32::MAX as f64) { + return None; } + Some(v as usize) } fn opt(flags: u32, bit: u32, v: f64) -> Option { - if flags & bit != 0 { - Some(v) - } else { - None - } + (flags & bit != 0).then_some(v) } -/// Einen Schraffur-Eintrag lesen (auch für die Einzel-Bindungen der Schraffur-Fassade). -fn read_hatch(r: &mut Reader) -> Option { +/// Einen Hatch-Datensatz lesen; `color` ist der Farb-Eintrag (−1 = keine, sonst String-Index). +fn read_hatch(r: &mut Reader) -> Option<(Hatch, i32)> { let pattern = Pattern::from_code(r.f()?); let kind = HatchKind::from_code(r.f()?); let flags = r.flags()?; @@ -230,16 +417,21 @@ fn read_hatch(r: &mut Reader) -> Option { let length_min = r.f()?; let length_max = r.f()?; let dash = r.list()?; - let motif = if flags & HF_MOTIF != 0 { Some(r.motif()?) } else { None }; - Some(HatchEntry { - hatch: Hatch { + let motif = if flags & HF_MOTIF != 0 { + let length = r.f()?; + Some(Motif { length, points: r.pts()? }) + } else { + None + }; + Some(( + Hatch { pattern, kind, random: flags & HF_RANDOM != 0, scale, angle, line_weight, - origin: if flags & HF_ORIGIN != 0 { Some(origin) } else { None }, + origin: (flags & HF_ORIGIN != 0).then_some(origin), seed: opt(flags, HF_SEED, seed), density: opt(flags, HF_DENSITY, density), length_min: opt(flags, HF_LEN_MIN, length_min), @@ -248,130 +440,1041 @@ fn read_hatch(r: &mut Reader) -> Option { motif, }, color, - }) + )) } -/// Einzelne Schraffur (Format wie ein Hatch-Eintrag des Plan-Puffers) ab `buf[0]`. +/// Einzelne Schraffur (Hatch-Format, s. Kopf) ab `buf[0]` — Eingabe der Schraffur-Bindungen. pub fn decode_hatch(buf: &[f64]) -> Option<(Hatch, usize)> { - let mut r = Reader { buf, pos: 0 }; - let h = read_hatch(&mut r)?; - Some((h.hatch, r.pos)) + let bytes: Vec = buf.iter().flat_map(|v| v.to_le_bytes()).collect(); + let mut r = Reader { w: Words { bytes: &bytes }, pos: 0, end: buf.len() }; + let (h, _) = read_hatch(&mut r)?; + Some((h, r.pos)) } -fn read_prim(r: &mut Reader) -> Option { - let tag = r.f()?; - if tag == 0.0 { - return Some(Prim::Placeholder); - } - let flags = r.flags()?; - Some(match tag as i64 { - 1 => { - let fill = r.idx()?; - let stroke = r.idx()?; - let stroke_width_mm = r.f()?; - let hatch = r.idx()?; - let opacity = r.f()?; - let pts = r.pts()?; - let no_stroke_edges = r.list()?; - Prim::Polygon { style: Reader::style(flags, opacity), fill, stroke, stroke_width_mm, hatch, pts, no_stroke_edges } - } - 2 => { - let color = r.idx()?; - let weight_mm = r.f()?; - let opacity = r.f()?; - let a = r.v2()?; - let b = r.v2()?; - let dash = r.list()?; - let zigzag = if flags & FLAG_ZIGZAG != 0 { Some((r.f()?, r.f()?)) } else { None }; - let motif = if flags & FLAG_MOTIF != 0 { Some(r.motif()?) } else { None }; - Prim::Line { style: Reader::style(flags, opacity), color, weight_mm, a, b, dash, chain: flags & FLAG_CHAIN != 0, zigzag, motif } - } - 3 => { - let color = r.idx()?; - let weight_mm = r.f()?; - let opacity = r.f()?; - let center = r.v2()?; - let from = r.v2()?; - let to = r.v2()?; - let rad = r.f()?; - let dash = r.list()?; - Prim::Arc { style: Reader::style(flags, opacity), color, weight_mm, center, from, to, r: rad, dash } - } - 4 => { - let fill = r.idx()?; - let stroke = r.idx()?; - let weight_mm = r.f()?; - let opacity = r.f()?; - let center = r.v2()?; - let rad = r.f()?; - let dash = r.list()?; - Prim::Circle { style: Reader::style(flags, opacity), fill, stroke, weight_mm, center, r: rad, dash } - } - 5 => { - let stroke = r.idx()?; - let weight_mm = r.f()?; - let opacity = r.f()?; - let center = r.v2()?; - let rad = r.f()?; - let a0 = r.f()?; - let a1 = r.f()?; - let dash = r.list()?; - Prim::DrawingArc { style: Reader::style(flags, opacity), stroke, weight_mm, center, r: rad, a0, a1, dash } - } +/// Gelesener Kopf und Abschnitte eines Puffers (ohne Kopie). +pub struct View<'a> { + w: Words<'a>, + units: &'a [u8], + n_strings: usize, + n_hatches: usize, + n_groups: usize, + n_prims: usize, + n_pool: usize, + strings_at: usize, + hatches_at: usize, + hatches_end: usize, + groups_at: usize, + offsets_at: usize, + hashes_at: Option, + recs_at: usize, + recs_end: usize, + pool_at: usize, + bounds: Option<[f64; 4]>, +} + +/// Ein Primitiv-Eintrag, roh gelesen (Indizes noch nicht aufgelöst). +struct Rec { + tag: u32, + flags: u32, + 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)>, +} + +fn fixed_len(tag: u32) -> Option { + Some(match tag { + T_PLACEHOLDER => 0, + T_POLYGON => 7, + T_LINE => 8, + T_ARC => 11, + T_CIRCLE => 7, + T_DRAWING_ARC => 8, + T_TEXT | T_DRAWING_TEXT | T_TEXT_PATH | T_IMAGE => 1, _ => return None, }) } -/// Puffer lesen; `None` bei fremder Magie/Version oder kaputtem Puffer (nie ein Panic). -pub fn decode(buf: &[f64]) -> Option { - let mut r = Reader { buf, pos: 0 }; - if r.f()? != MAGIC || r.f()? != VERSION { - return None; +impl<'a> View<'a> { + /// Kopf und Abschnittsgrenzen prüfen; `None` bei fremder Magie/Version oder kaputtem Puffer. + pub fn parse(bytes: &'a [u8]) -> Option> { + if bytes.len() < HEAD * 8 { + return None; + } + let head = Words { bytes: &bytes[..HEAD * 8] }; + let h = |i: usize| head.get(i).unwrap_or(f64::NAN); + if h(0) != MAGIC || h(1) != VERSION { + return None; + } + let flags = whole(h(2))? as u32; + let n_strings = whole(h(3))?; + let n_hatches = whole(h(4))?; + let n_hatch_words = whole(h(5))?; + let n_groups = whole(h(6))?; + let n_prims = whole(h(7))?; + let n_rec = whole(h(8))?; + let n_pool = whole(h(9))?; + let n_units = whole(h(10))?; + let hashes = flags & HEAD_HASHES != 0; + let strings_at = HEAD; + let hatches_at = strings_at.checked_add(n_strings.checked_mul(2)?)?; + let groups_at = hatches_at.checked_add(n_hatch_words)?; + let offsets_at = groups_at.checked_add(n_groups.checked_mul(2)?)?; + let hashes_end = offsets_at.checked_add(n_prims.checked_mul(if hashes { 2 } else { 1 })?)?; + let recs_at = hashes_end; + let pool_at = recs_at.checked_add(n_rec)?; + let n_f64 = pool_at.checked_add(n_pool)?; + if bytes.len() != n_f64.checked_mul(8)?.checked_add(n_units.checked_mul(2)?)? { + return None; + } + let bounds = (flags & HEAD_BOUNDS != 0).then(|| [h(12), h(13), h(14), h(15)]); + Some(View { + w: Words { bytes: &bytes[..n_f64 * 8] }, + units: &bytes[n_f64 * 8..], + n_strings, + n_hatches, + n_groups, + n_prims, + n_pool, + strings_at, + hatches_at, + hatches_end: groups_at, + groups_at, + offsets_at, + hashes_at: hashes.then_some(offsets_at + n_prims), + recs_at, + recs_end: pool_at, + pool_at, + bounds, + }) } - let n_colors = r.count(4)?; - let n_hatches = r.count(1)?; - let n_prims = r.count(1)?; - let mut colors = Vec::with_capacity(n_colors); - for _ in 0..n_colors { - colors.push([r.f()?, r.f()?, r.f()?, r.f()?]); - } - let mut hatches = Vec::with_capacity(n_hatches); - for _ in 0..n_hatches { - hatches.push(read_hatch(&mut r)?); - } - let mut prims = Vec::with_capacity(n_prims); - for _ in 0..n_prims { - prims.push(read_prim(&mut r)?); - } - if r.pos != buf.len() { - return None; - } - Some(PlanBuf { colors, hatches, prims }) -} -// ── Schreiben (Rust-Erzeuger ab [K3a]; heute für Hin-und-zurück-Tests) ────── + pub fn len(&self) -> usize { + self.n_prims + } -fn put_list(out: &mut Vec, l: &[f64]) { - out.push(l.len() as f64); - out.extend_from_slice(l); -} + pub fn is_empty(&self) -> bool { + self.n_prims == 0 + } -fn put_pts(out: &mut Vec, pts: &[V2]) { - out.push(pts.len() as f64); - for p in pts { - out.push(p.x); - out.push(p.y); + pub fn bounds(&self) -> Option<[f64; 4]> { + self.bounds + } + + /// Gruppen `[start, end)`; `None` bei ungültigen Bereichen. + pub fn groups(&self) -> Option> { + let mut out = Vec::with_capacity(self.n_groups); + for g in 0..self.n_groups { + let a = whole(self.w.get(self.groups_at + 2 * g)?)?; + let b = whole(self.w.get(self.groups_at + 2 * g + 1)?)?; + if a > b || b > self.n_prims { + return None; + } + out.push((a, b)); + } + Some(out) + } + + /// Inhalts-Hash des Primitivs `i` (nur, wenn der Schreiber Hashes abgelegt hat). + pub fn hash(&self, i: usize) -> Option { + if i >= self.n_prims { + return None; + } + self.w.get(self.hashes_at? + i) + } + + fn units_of(&self, idx: usize) -> Option> { + if idx >= self.n_strings { + return None; + } + let off = whole(self.w.get(self.strings_at + 2 * idx)?)?; + let len = whole(self.w.get(self.strings_at + 2 * idx + 1)?)?; + let b = self.units.get(off.checked_mul(2)?..off.checked_add(len)?.checked_mul(2)?)?; + Some(b.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect()) + } + + /// String `idx` (ungültiges UTF-16 wird ersetzt). + pub fn string(&self, idx: usize) -> Option { + Some(String::from_utf16_lossy(&self.units_of(idx)?)) + } + + fn opt_string(&self, idx: f64) -> Option> { + if idx == -1.0 { + return Some(None); + } + Some(Some(self.string(whole(idx)?)?)) + } + + fn pool(&self, off: usize, n: usize) -> Option> { + if off.checked_add(n)? > self.n_pool { + return None; + } + let mut out = Vec::with_capacity(n); + for k in 0..n { + out.push(self.w.get(self.pool_at + off + k)?); + } + Some(out) + } + + 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> { + 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 { + let json = r.idx()?; + let (h, color) = read_hatch(&mut r)?; + if json >= self.n_strings as i32 || color >= self.n_strings as i32 { + return None; + } + out.push((json, h, color)); + } + if r.pos != self.hatches_end { + return None; + } + Some(out) + } + + fn rec(&self, i: usize) -> Option { + if i >= self.n_prims { + return None; + } + let off = whole(self.w.get(self.offsets_at + i)?)?; + let mut r = Reader { w: self.w, pos: self.recs_at.checked_add(off)?, end: self.recs_end }; + let tag = whole(r.f()?)? as u32; + let flags = r.flags()?; + let pk = whole(r.f()?)? as u32; + let ps = r.idx()?; + if pk > 11 || ps >= self.n_strings as i32 { + return None; + } + let n = fixed_len(tag)?; + let mut f = Vec::with_capacity(n); + for _ in 0..n { + f.push(r.f()?); + } + let list = |r: &mut Reader| -> Option<(usize, usize)> { Some((whole(r.f()?)?, whole(r.f()?)?)) }; + let mut rec = Rec { tag, flags, pick: (pk, ps), f, dash: None, nse: None, zigzag: None, motif: None, ids: None }; + match tag { + T_POLYGON => { + if flags & F_NSE != 0 { + rec.nse = Some(list(&mut r)?); + } + } + T_LINE | T_ARC | T_CIRCLE | T_DRAWING_ARC => { + if flags & F_DASH_LIST != 0 { + rec.dash = Some(list(&mut r)?); + } + if tag == T_LINE { + if flags & F_ZIGZAG != 0 { + rec.zigzag = Some((r.f()?, r.f()?)); + } + if flags & F_MOTIF != 0 { + let len = r.f()?; + let (o, n) = list(&mut r)?; + rec.motif = Some((len, o, n)); + } + } + } + _ => {} + } + if flags & F_IDS != 0 { + rec.ids = Some(list(&mut r)?); + } + Some(rec) + } + + /// Bereich `[from, to)` in der GPU-Sicht (Farben geparst). Flag „Linienzug“ des ersten + /// Primitivs gilt nicht (er setzt nichts innerhalb des Bereichs fort). + pub fn gpu(&self, from: usize, to: usize) -> Option { + if from > to || to > self.n_prims { + return None; + } + let mut out = PlanBuf::default(); + let mut color_of: HashMap = HashMap::new(); + let mut color = |out: &mut PlanBuf, s: f64| -> Option { + if s == -1.0 { + return Some(-1); + } + let k = whole(s)? as i32; + if let Some(&c) = color_of.get(&k) { + return Some(c); + } + let c = match parse_color(&self.string(k as usize)?) { + Some(rgba) => { + out.colors.push(rgba); + out.colors.len() as i32 - 1 + } + None => -1, + }; + color_of.insert(k, c); + Some(c) + }; + // Schraffuren nur lesen, wenn ein Polygon sie braucht. + let mut hatches: Option> = None; + let mut hatch_map: HashMap = HashMap::new(); + for i in from..to { + let rec = self.rec(i)?; + let greyed = rec.flags & F_GREYED != 0; + let f = &rec.f; + let p = match rec.tag { + T_POLYGON => { + let style = Style { greyed, opacity: opt(rec.flags, F_OPACITY, f[4]) }; + let fill = color(&mut out, f[0])?; + let stroke = color(&mut out, f[1])?; + let hatch = if f[3] == -1.0 { + -1 + } else { + let k = whole(f[3])?; + if let Some(&h) = hatch_map.get(&k) { + h + } else { + if hatches.is_none() { + hatches = Some(self.hatch_table()?); + } + let (_, h, c) = hatches.as_ref()?.get(k)?.clone(); + let hc = color(&mut out, c as f64)?; + out.hatches.push(HatchEntry { hatch: h, color: hc }); + let idx = out.hatches.len() as i32 - 1; + hatch_map.insert(k, idx); + idx + } + }; + let pts = self.pool_pts(whole(f[5])?, whole(f[6])?)?; + let no_stroke_edges = match rec.nse { + Some((o, n)) => self.pool(o, n)?, + None => Vec::new(), + }; + Prim::Polygon { style, fill, stroke, stroke_width_mm: f[2], hatch, pts, no_stroke_edges } + } + T_LINE => { + let style = Style { greyed, opacity: opt(rec.flags, F_OPACITY, f[3]) }; + let c = color(&mut out, f[1])?; + let motif = match rec.motif { + Some((length, o, n)) => Some(Motif { length, points: self.pool_pts(o, n)? }), + None => None, + }; + Prim::Line { + style, + color: c, + weight_mm: f[2], + a: V2 { x: f[4], y: f[5] }, + b: V2 { x: f[6], y: f[7] }, + chain: i > from && rec.flags & F_CHAIN != 0, + zigzag: rec.zigzag, + motif, + } + } + T_ARC => { + let style = Style { greyed, opacity: opt(rec.flags, F_OPACITY, f[3]) }; + let c = color(&mut out, f[1])?; + Prim::Arc { style, color: c, weight_mm: f[2], center: V2 { x: f[4], y: f[5] }, from: V2 { x: f[6], y: f[7] }, to: V2 { x: f[8], y: f[9] }, r: f[10] } + } + T_CIRCLE => { + let style = Style { greyed, opacity: opt(rec.flags, F_OPACITY, f[3]) }; + let fill = color(&mut out, f[0])?; + let stroke = color(&mut out, f[1])?; + Prim::Circle { style, fill, stroke, weight_mm: f[2], center: V2 { x: f[4], y: f[5] }, r: f[6] } + } + T_DRAWING_ARC => { + let style = Style { greyed, opacity: opt(rec.flags, F_OPACITY, f[2]) }; + let stroke = color(&mut out, f[0])?; + Prim::DrawingArc { style, stroke, weight_mm: f[1], center: V2 { x: f[3], y: f[4] }, r: f[5], a0: f[6], a1: f[7] } + } + _ => Prim::Placeholder, + }; + out.prims.push(p); + } + Some(out) + } + + /// Alle Primitive voll gelesen (Hin-und-zurück, künftige Rust-Verbraucher). Platzhalter (tag 0) + /// haben keinen Inhalt → `None`. + pub fn prims(&self) -> Option> { + let hatches: Vec = { + let t = self.hatch_table()?; + let mut v = Vec::with_capacity(t.len()); + for (json, _, _) in t { + v.push(serde_json::from_str(&self.string(whole(json as f64)?)?).ok()?); + } + v + }; + let mut out = Vec::with_capacity(self.n_prims); + for i in 0..self.n_prims { + out.push(self.prim(i, &hatches)?); + } + Some(out) + } + + fn prim(&self, i: usize, hatches: &[HatchRender]) -> Option { + let rec = self.rec(i)?; + let f = &rec.f; + let fl = rec.flags; + let greyed = (fl & F_GREYED_SET != 0).then_some(fl & F_GREYED != 0); + let v = |x: f64, y: f64| Vec2 { x, y }; + let dash: Dash = if fl & F_DASH_NULL != 0 { + Some(None) + } else if let Some((o, n)) = rec.dash { + Some(Some(self.pool(o, n)?)) + } else { + None + }; + let to_vec2 = |p: Vec| p.into_iter().map(|q| Vec2 { x: q.x, y: q.y }).collect::>(); + // Pick-Ids: erste im Eintrag, weitere im Pool. + let mut ids: [Option; 12] = Default::default(); + if rec.pick.0 > 0 { + ids[rec.pick.0 as usize] = Some(self.string(whole(rec.pick.1 as f64)?)?); + } + if let Some((o, n)) = rec.ids { + let l = self.pool(o, n.checked_mul(2)?)?; + for c in l.chunks_exact(2) { + let k = whole(c[0])?; + if k == 0 || k > 11 { + return None; + } + ids[k] = Some(self.string(whole(c[1])?)?); + } + } + let [_, wall_id, drawing_id, ceiling_id, opening_id, stair_id, room_id, extruded_solid_id, context_object_id, column_id, roof_id, section_line_id] = ids; + Some(match rec.tag { + T_POLYGON => Primitive::Polygon { + pts: to_vec2(self.pool_pts(whole(f[5])?, whole(f[6])?)?), + fill: self.opt_string(f[0])?.unwrap_or_default(), + stroke: self.opt_string(f[1])?.unwrap_or_default(), + stroke_width_mm: f[2], + hatch: if f[3] == -1.0 { crate::plan::style::no_hatch() } else { hatches.get(whole(f[3])?)?.clone() }, + greyed, + opacity: opt(fl, F_OPACITY, f[4]), + no_stroke_edges: match rec.nse { + Some((o, n)) => Some(self.pool(o, n)?), + None => None, + }, + wall_id, + drawing_id, + ceiling_id, + opening_id, + stair_id, + room_id, + extruded_solid_id, + context_object_id, + column_id, + roof_id, + section_line_id, + }, + T_LINE => Primitive::Line { + a: v(f[4], f[5]), + b: v(f[6], f[7]), + cls: self.opt_string(f[0])?.unwrap_or_default(), + weight_mm: f[2], + dash, + zigzag: rec.zigzag.map(|(amplitude, wavelength)| LineStyleZigzag { amplitude, wavelength, ..Default::default() }), + motif: match rec.motif { + Some((length, o, n)) => Some(LineStyleMotif { points: to_vec2(self.pool_pts(o, n)?), length, ..Default::default() }), + None => None, + }, + color: if fl & F_COLOR != 0 { self.opt_string(f[1])? } else { None }, + drawing_id, + opening_id, + stair_id, + greyed, + opacity: opt(fl, F_OPACITY, f[3]), + }, + T_ARC => Primitive::Arc { + center: v(f[4], f[5]), + from: v(f[6], f[7]), + to: v(f[8], f[9]), + r: f[10], + cls: self.opt_string(f[0])?.unwrap_or_default(), + weight_mm: f[2], + dash, + opening_id, + stair_id, + greyed, + opacity: opt(fl, F_OPACITY, f[3]), + }, + T_CIRCLE => Primitive::DrawingCircle { + center: v(f[4], f[5]), + r: f[6], + fill: self.opt_string(f[0])?.unwrap_or_default(), + stroke: self.opt_string(f[1])?.unwrap_or_default(), + weight_mm: f[2], + dash, + drawing_id, + greyed, + opacity: opt(fl, F_OPACITY, f[3]), + }, + T_DRAWING_ARC => Primitive::DrawingArc { + center: v(f[3], f[4]), + r: f[5], + a0: f[6], + a1: f[7], + stroke: self.opt_string(f[0])?.unwrap_or_default(), + weight_mm: f[1], + dash, + drawing_id, + greyed, + opacity: opt(fl, F_OPACITY, f[2]), + }, + T_TEXT | T_DRAWING_TEXT | T_TEXT_PATH | T_IMAGE => serde_json::from_str(&self.string(whole(f[0])?)?).ok()?, + _ => return None, + }) } } -fn style_flags(s: &Style) -> u32 { - (if s.greyed { FLAG_GREYED } else { 0 }) | (if s.opacity.is_some() { FLAG_OPACITY } else { 0 }) +/// Puffer → Primitive, Gruppen und Ausmass (`None` bei kaputtem Puffer). +pub fn decode(bytes: &[u8]) -> Option<(Vec, Vec<(usize, usize)>, Option<[f64; 4]>)> { + let v = View::parse(bytes)?; + Some((v.prims()?, v.groups()?, v.bounds())) } -fn write_hatch(out: &mut Vec, e: &HatchEntry) { - let h = &e.hatch; +/// Lesen und neu schreiben (Hin-und-zurück-Prüfung der TS-Kodierung); leer bei kaputtem Puffer. +pub fn recode(bytes: &[u8]) -> Vec { + let Some((prims, groups, bounds)) = decode(bytes) else { return Vec::new() }; + let mut w = Writer::new(false); + for p in &prims { + w.push(p); + } + for (a, b) in groups { + w.groups.push((a, b)); + } + w.bounds = bounds; + w.finish() +} + +// ── Schreiben ──────────────────────────────────────────────────────────────────────────────────── + +const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325; +const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; + +/// Mischt ein Wort in den Inhalts-Hash (wortweise statt byteweise: ein Multiplizieren je Zahl; die +/// Güte reicht für Cache-Schlüssel, die der Cache zusätzlich Wort für Wort vergleicht). +#[inline] +fn fnv(h: u64, v: u64) -> u64 { + let x = (h ^ v).wrapping_mul(0x9E37_79B9_7F4A_7C15); + x ^ (x >> 29) +} + +/// Schlüssel der Linienzug-Prüfung (vorige einfache Linie). +struct ChainKey { + drawing: Option, + color: Option, + weight: f64, + greyed: Option, + opacity: Option, + /// 0 fehlt, 1 null, 2 Liste (Listen sind im Kern nie „dieselbe Referenz“). + dash: u8, + b: Vec2, +} + +fn dash_state(d: &Dash) -> u8 { + match d { + None => 0, + Some(None) => 1, + Some(Some(_)) => 2, + } +} + +/// Schreiber des Plan-Puffers aus Kern-Primitiven. +pub struct Writer { + units: Vec, + strings: Vec<(usize, usize)>, + str_map: FastMap, + str_hash: Vec, + hatch_words: Vec, + hatch_map: FastMap, + /// Schnellweg vor dem JSON-Vergleich: Bit-Schlüssel → (Schraffur, Index, Hash). + hatch_fast: FastMap>, + n_hatches: usize, + pub groups: Vec<(usize, usize)>, + offsets: Vec, + hashes: Option>, + recs: Vec, + pool: Vec, + prev: Option, + h: u64, + pub bounds: Option<[f64; 4]>, +} + +impl Writer { + /// `hashes`: Inhalts-Hash je Primitiv ablegen (Schlüssel des GPU-Chunk-Caches). + pub fn new(hashes: bool) -> Writer { + Writer { + units: Vec::new(), + strings: Vec::new(), + str_map: FastMap::default(), + str_hash: Vec::new(), + hatch_words: Vec::new(), + hatch_map: FastMap::default(), + hatch_fast: FastMap::default(), + n_hatches: 0, + groups: Vec::new(), + offsets: Vec::new(), + hashes: hashes.then(Vec::new), + recs: Vec::new(), + pool: Vec::new(), + prev: None, + h: FNV_OFFSET, + bounds: None, + } + } + + fn intern(&mut self, s: &str) -> (usize, u64) { + if let Some(&i) = self.str_map.get(s) { + return (i, self.str_hash[i]); + } + let off = self.units.len(); + let mut h = FNV_OFFSET; + for u in s.encode_utf16() { + self.units.push(u); + h = fnv(h, u as u64); + } + let i = self.strings.len(); + self.strings.push((off, self.units.len() - off)); + self.str_hash.push(h); + self.str_map.insert(s.to_string(), i); + (i, h) + } + + #[inline] + fn num(&mut self, v: f64) { + self.recs.push(v); + self.h = fnv(self.h, v.to_bits()); + } + + fn str(&mut self, s: Option<&str>) { + match s { + Some(s) => { + let (i, h) = self.intern(s); + self.recs.push(i as f64); + self.h = fnv(self.h, h); + } + None => self.num(-1.0), + } + } + + /// Liste in den Pool (Hash über den Inhalt, nicht über die Lage). + fn list(&mut self, l: &[f64]) { + let off = self.pool.len(); + self.pool.extend_from_slice(l); + self.recs.push(off as f64); + self.recs.push(l.len() as f64); + self.h = fnv(self.h, l.len() as u64); + for v in l { + self.h = fnv(self.h, v.to_bits()); + } + } + + fn pts(&mut self, p: &[Vec2]) { + let off = self.pool.len(); + for q in p { + self.pool.push(q.x); + self.pool.push(q.y); + } + self.recs.push(off as f64); + self.recs.push(p.len() as f64); + self.h = fnv(self.h, p.len() as u64); + for q in p { + self.h = fnv(self.h, q.x.to_bits()); + self.h = fnv(self.h, q.y.to_bits()); + } + } + + fn hatch(&mut self, h: &HatchRender) -> (usize, u64) { + // Schnellweg: gleiche Schraffur (Bit für Bit) schon geschrieben? Erspart das JSON je Polygon. + let simple = h.image.is_none() && h.gradient.is_none() && h.motif.is_none(); + let key = if simple { hatch_bits_key(h) } else { 0 }; + if simple { + if let Some(c) = self.hatch_fast.get(&key) { + if let Some(e) = c.iter().find(|e| hatch_bits_eq(&e.0, h)) { + return (e.1, e.2); + } + } + } + let json = serde_json::to_string(h).unwrap_or_default(); + if let Some(&e) = self.hatch_map.get(&json) { + if simple { + self.hatch_fast.entry(key).or_default().push((h.clone(), e.0, e.1)); + } + return e; + } + let (js, jh) = self.intern(&json); + let (cs, _) = self.intern(&h.color); + let idx = self.n_hatches; + self.n_hatches += 1; + self.hatch_words.push(js as f64); + write_hatch_words(&mut self.hatch_words, h, cs as f64); + self.hatch_map.insert(json, (idx, jh)); + if simple { + self.hatch_fast.entry(key).or_default().push((h.clone(), idx, jh)); + } + (idx, jh) + } + + fn head(&mut self, tag: u32, flags: u32, ids: &[(u32, &Option)]) -> Vec<(u32, String)> { + self.offsets.push(self.recs.len() as f64); + self.h = FNV_OFFSET; + let mut it = ids.iter().filter_map(|(k, s)| s.as_deref().map(|s| (*k, s))); + let first = it.next(); + // Weitere Ids (selten) erst hier sammeln. + let rest: Vec<(u32, String)> = it.map(|(k, s)| (k, s.to_string())).collect(); + self.num(tag as f64); + self.num((flags | if rest.is_empty() { 0 } else { F_IDS }) as f64); + match first { + None => { + self.num(0.0); + self.num(-1.0); + } + Some((k, s)) => { + self.num(k as f64); + self.str(Some(s)); + } + } + rest + } + + fn tail_ids(&mut self, rest: Vec<(u32, String)>) { + if rest.is_empty() { + return; + } + let mut l = Vec::with_capacity(rest.len() * 2); + let mut hs = Vec::with_capacity(rest.len()); + for (k, s) in &rest { + let (i, h) = self.intern(s); + l.push(*k as f64); + l.push(i as f64); + hs.push(h); + } + let off = self.pool.len(); + self.pool.extend_from_slice(&l); + self.recs.push(off as f64); + self.recs.push(rest.len() as f64); + for (k, h) in rest.iter().map(|r| r.0).zip(hs) { + self.h = fnv(self.h, k as u64); + self.h = fnv(self.h, h); + } + } + + fn end_prim(&mut self) { + if let Some(hs) = self.hashes.as_mut() { + hs.push((self.h >> 12) as f64); + } + } + + fn style_flags(greyed: Option, opacity: Option) -> u32 { + (match greyed { + Some(true) => F_GREYED_SET | F_GREYED, + Some(false) => F_GREYED_SET, + None => 0, + }) | if opacity.is_some() { F_OPACITY } else { 0 } + } + + fn dash_flags(d: &Dash) -> u32 { + match d { + None => 0, + Some(None) => F_DASH_NULL, + Some(Some(_)) => F_DASH_LIST, + } + } + + fn dash_tail(&mut self, d: &Dash) { + if let Some(Some(l)) = d { + self.list(l); + } + } + + fn json(&mut self, tag: u32, p: &Primitive, ids: &[(u32, &Option)]) { + let rest = self.head(tag, 0, ids); + let json = serde_json::to_string(p).unwrap_or_default(); + self.str(Some(&json)); + self.tail_ids(rest); + } + + /// Ein Primitiv anhängen. + pub fn push(&mut self, p: &Primitive) { + let mut next_prev: Option = None; + match p { + Primitive::Polygon { + pts, + fill, + stroke, + stroke_width_mm, + hatch, + greyed, + opacity, + no_stroke_edges, + wall_id, + drawing_id, + ceiling_id, + opening_id, + stair_id, + room_id, + extruded_solid_id, + context_object_id, + column_id, + roof_id, + section_line_id, + } => { + let flags = Self::style_flags(*greyed, *opacity) | if no_stroke_edges.is_some() { F_NSE } else { 0 }; + let ids = [ + (1, wall_id), + (2, drawing_id), + (3, ceiling_id), + (4, opening_id), + (5, stair_id), + (6, room_id), + (7, extruded_solid_id), + (8, context_object_id), + (9, column_id), + (10, roof_id), + (11, section_line_id), + ]; + let rest = self.head(T_POLYGON, flags, &ids); + self.str(Some(fill)); + self.str(Some(stroke)); + self.num(*stroke_width_mm); + let (hi, hh) = self.hatch(hatch); + self.recs.push(hi as f64); + self.h = fnv(self.h, hh); + self.num(opacity.unwrap_or(1.0)); + self.pts(pts); + if let Some(l) = no_stroke_edges { + self.list(l); + } + self.tail_ids(rest); + } + Primitive::Line { a, b, cls, weight_mm, dash, zigzag, motif, color, drawing_id, opening_id, stair_id, greyed, opacity } => { + let plain = zigzag.is_none() && motif.is_none(); + let di = drawing_id.as_deref().map(|s| self.intern(s).0); + let ci = color.as_deref().map(|s| self.intern(s).0); + let chain = plain + && self.prev.as_ref().is_some_and(|q| { + q.drawing == di + && q.color == ci + && q.weight == *weight_mm + && q.greyed == *greyed + && q.opacity == *opacity + && q.dash == dash_state(dash) + && q.dash != 2 + && a.x == q.b.x + && a.y == q.b.y + }); + let flags = Self::style_flags(*greyed, *opacity) + | Self::dash_flags(dash) + | if chain { F_CHAIN } else { 0 } + | if zigzag.is_some() { F_ZIGZAG } else { 0 } + | if motif.is_some() { F_MOTIF } else { 0 } + | if color.is_some() { F_COLOR } else { 0 }; + let rest = self.head(T_LINE, flags, &[(2, drawing_id), (4, opening_id), (5, stair_id)]); + self.str(Some(cls)); + self.str(color.as_deref()); + self.num(*weight_mm); + self.num(opacity.unwrap_or(1.0)); + self.num(a.x); + self.num(a.y); + self.num(b.x); + self.num(b.y); + self.dash_tail(dash); + if let Some(z) = zigzag { + self.num(z.amplitude); + self.num(z.wavelength); + } + if let Some(m) = motif { + self.num(m.length); + self.pts(&m.points); + } + self.tail_ids(rest); + if plain { + next_prev = Some(ChainKey { drawing: di, color: ci, weight: *weight_mm, greyed: *greyed, opacity: *opacity, dash: dash_state(dash), b: b.clone() }); + } + } + Primitive::Arc { center, from, to, r, cls, weight_mm, dash, opening_id, stair_id, greyed, opacity } => { + let flags = Self::style_flags(*greyed, *opacity) | Self::dash_flags(dash); + let rest = self.head(T_ARC, flags, &[(4, opening_id), (5, stair_id)]); + self.str(Some(cls)); + self.str(None); + self.num(*weight_mm); + self.num(opacity.unwrap_or(1.0)); + for v in [center.x, center.y, from.x, from.y, to.x, to.y, *r] { + self.num(v); + } + self.dash_tail(dash); + self.tail_ids(rest); + } + Primitive::DrawingCircle { center, r, fill, stroke, weight_mm, dash, drawing_id, greyed, opacity } => { + let flags = Self::style_flags(*greyed, *opacity) | Self::dash_flags(dash); + let rest = self.head(T_CIRCLE, flags, &[(2, drawing_id)]); + self.str(Some(fill)); + self.str(Some(stroke)); + self.num(*weight_mm); + self.num(opacity.unwrap_or(1.0)); + for v in [center.x, center.y, *r] { + self.num(v); + } + self.dash_tail(dash); + self.tail_ids(rest); + } + Primitive::DrawingArc { center, r, a0, a1, stroke, weight_mm, dash, drawing_id, greyed, opacity } => { + let flags = Self::style_flags(*greyed, *opacity) | Self::dash_flags(dash); + let rest = self.head(T_DRAWING_ARC, flags, &[(2, drawing_id)]); + self.str(Some(stroke)); + self.num(*weight_mm); + self.num(opacity.unwrap_or(1.0)); + for v in [center.x, center.y, *r, *a0, *a1] { + self.num(v); + } + self.dash_tail(dash); + self.tail_ids(rest); + } + Primitive::Text { room_id, .. } => self.json(T_TEXT, p, &[(6, room_id)]), + Primitive::DrawingText { drawing_id, .. } => self.json(T_DRAWING_TEXT, p, &[(2, drawing_id)]), + Primitive::DrawingTextPath { drawing_id, .. } => self.json(T_TEXT_PATH, p, &[(2, drawing_id)]), + Primitive::DrawingImage { drawing_id, .. } => self.json(T_IMAGE, p, &[(2, drawing_id)]), + } + self.end_prim(); + self.prev = next_prev; + } + + /// Eine Gruppe (Domäne) anhängen. + pub fn group(&mut self, prims: &[Primitive]) { + let start = self.offsets.len(); + for p in prims { + self.push(p); + } + self.groups.push((start, self.offsets.len())); + } + + pub fn finish(self) -> Vec { + let n_prims = self.offsets.len(); + let mut flags = 0; + if self.hashes.is_some() { + flags |= HEAD_HASHES; + } + let b = self.bounds.unwrap_or([0.0; 4]); + if self.bounds.is_some() { + flags |= HEAD_BOUNDS; + } + let head = [ + MAGIC, + VERSION, + flags as f64, + self.strings.len() as f64, + self.n_hatches as f64, + self.hatch_words.len() as f64, + self.groups.len() as f64, + n_prims as f64, + self.recs.len() as f64, + self.pool.len() as f64, + self.units.len() as f64, + 0.0, + b[0], + b[1], + b[2], + b[3], + ]; + let n_f64 = HEAD + 2 * self.strings.len() + self.hatch_words.len() + 2 * self.groups.len() + n_prims * if self.hashes.is_some() { 2 } else { 1 } + self.recs.len() + self.pool.len(); + let mut out = Vec::with_capacity(n_f64 * 8 + self.units.len() * 2); + let mut put = |v: f64| out.extend_from_slice(&v.to_le_bytes()); + for v in head { + put(v); + } + for (o, n) in &self.strings { + put(*o as f64); + put(*n as f64); + } + for v in &self.hatch_words { + put(*v); + } + for (a, b) in &self.groups { + put(*a as f64); + put(*b as f64); + } + for v in &self.offsets { + put(*v); + } + if let Some(hs) = &self.hashes { + for v in hs { + put(*v); + } + } + for v in &self.recs { + put(*v); + } + for v in &self.pool { + put(*v); + } + for u in &self.units { + out.extend_from_slice(&u.to_le_bytes()); + } + out + } +} + +/// Bit-Schlüssel einer Schraffur ohne Bild/Verlauf/Motiv (für den Schnellweg des Schreibers). +fn hatch_bits_key(h: &HatchRender) -> u64 { + let mut k = FNV_OFFSET; + for v in [h.scale, h.angle, h.line_weight, h.seed.unwrap_or(f64::NAN), h.density.unwrap_or(f64::NAN), h.length_min.unwrap_or(f64::NAN), h.length_max.unwrap_or(f64::NAN)] { + k = fnv(k, v.to_bits()); + } + for b in h.color.bytes() { + k = fnv(k, b as u64); + } + k +} + +fn opt_bits_eq(a: Option, b: Option) -> bool { + match (a, b) { + (None, None) => true, + (Some(x), Some(y)) => x.to_bits() == y.to_bits(), + _ => false, + } +} + +/// Bitgleich (gleiche JSON-Form) — nur für Schraffuren ohne Bild/Verlauf/Motiv. +fn hatch_bits_eq(a: &HatchRender, b: &HatchRender) -> bool { + let bits = |x: f64, y: f64| x.to_bits() == y.to_bits(); + let vbits = |x: &Option>, y: &Option>| match (x, y) { + (None, None) => true, + (Some(x), Some(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| p.to_bits() == q.to_bits()), + _ => false, + }; + let obits = |x: &Option, y: &Option| match (x, y) { + (None, None) => true, + (Some(x), Some(y)) => bits(x.x, y.x) && bits(x.y, y.y), + _ => false, + }; + a.pattern == b.pattern + && bits(a.scale, b.scale) + && bits(a.angle, b.angle) + && obits(&a.origin, &b.origin) + && a.color == b.color + && bits(a.line_weight, b.line_weight) + && vbits(&a.dash, &b.dash) + && a.kind == b.kind + && a.lines == b.lines + && a.image.is_none() + && b.image.is_none() + && a.gradient.is_none() + && b.gradient.is_none() + && a.motif.is_none() + && b.motif.is_none() + && opt_bits_eq(a.seed, b.seed) + && opt_bits_eq(a.density, b.density) + && opt_bits_eq(a.length_min, b.length_min) + && opt_bits_eq(a.length_max, b.length_max) +} + +/// Hatch-Datensatz aus einer `HatchRender` (Farbe = String-Index). +fn write_hatch_words(out: &mut Vec, h: &HatchRender, color: f64) { let mut flags = 0; - if h.random { + if h.lines == Some(HatchStyleLines::Random) { flags |= HF_RANDOM; } if h.origin.is_some() { @@ -392,14 +1495,27 @@ fn write_hatch(out: &mut Vec, e: &HatchEntry) { if h.motif.is_some() { flags |= HF_MOTIF; } - let o = h.origin.unwrap_or(V2 { x: 0.0, y: 0.0 }); + let pattern = match h.pattern { + HatchPattern::None => 0.0, + HatchPattern::Solid => 1.0, + HatchPattern::Crosshatch => 3.0, + HatchPattern::Insulation => 4.0, + HatchPattern::Custom => 5.0, + _ => 2.0, + }; + let kind = match h.kind { + Some(HatchStyleKind::Image) => 1.0, + Some(HatchStyleKind::Gradient) => 2.0, + _ => 0.0, + }; + let o = h.origin.clone().unwrap_or(Vec2 { x: 0.0, y: 0.0 }); out.extend_from_slice(&[ - h.pattern as u8 as f64, - h.kind as u8 as f64, + pattern, + kind, flags as f64, h.scale, h.angle, - e.color as f64, + color, h.line_weight, o.x, o.y, @@ -408,259 +1524,322 @@ fn write_hatch(out: &mut Vec, e: &HatchEntry) { h.length_min.unwrap_or(0.0), h.length_max.unwrap_or(0.0), ]); - put_list(out, &h.dash); + let dash = h.dash.as_deref().unwrap_or(&[]); + out.push(dash.len() as f64); + out.extend_from_slice(dash); if let Some(m) = &h.motif { out.push(m.length); - put_pts(out, &m.points); - } -} - -pub fn encode(p: &PlanBuf) -> Vec { - let mut out = vec![MAGIC, VERSION, p.colors.len() as f64, p.hatches.len() as f64, p.prims.len() as f64]; - for c in &p.colors { - out.extend_from_slice(c); - } - for h in &p.hatches { - write_hatch(&mut out, h); - } - for prim in &p.prims { - match prim { - Prim::Placeholder => out.push(0.0), - Prim::Polygon { style, fill, stroke, stroke_width_mm, hatch, pts, no_stroke_edges } => { - out.extend_from_slice(&[ - 1.0, - style_flags(style) as f64, - *fill as f64, - *stroke as f64, - *stroke_width_mm, - *hatch as f64, - style.opacity.unwrap_or(1.0), - ]); - put_pts(&mut out, pts); - put_list(&mut out, no_stroke_edges); - } - Prim::Line { style, color, weight_mm, a, b, dash, chain, zigzag, motif } => { - let mut flags = style_flags(style); - if *chain { - flags |= FLAG_CHAIN; - } - if zigzag.is_some() { - flags |= FLAG_ZIGZAG; - } - if motif.is_some() { - flags |= FLAG_MOTIF; - } - out.extend_from_slice(&[2.0, flags as f64, *color as f64, *weight_mm, style.opacity.unwrap_or(1.0), a.x, a.y, b.x, b.y]); - put_list(&mut out, dash); - if let Some((amp, wav)) = zigzag { - out.push(*amp); - out.push(*wav); - } - if let Some(m) = motif { - out.push(m.length); - put_pts(&mut out, &m.points); - } - } - Prim::Arc { style, color, weight_mm, center, from, to, r, dash } => { - out.extend_from_slice(&[ - 3.0, - style_flags(style) as f64, - *color as f64, - *weight_mm, - style.opacity.unwrap_or(1.0), - center.x, - center.y, - from.x, - from.y, - to.x, - to.y, - *r, - ]); - put_list(&mut out, dash); - } - Prim::Circle { style, fill, stroke, weight_mm, center, r, dash } => { - out.extend_from_slice(&[ - 4.0, - style_flags(style) as f64, - *fill as f64, - *stroke as f64, - *weight_mm, - style.opacity.unwrap_or(1.0), - center.x, - center.y, - *r, - ]); - put_list(&mut out, dash); - } - Prim::DrawingArc { style, stroke, weight_mm, center, r, a0, a1, dash } => { - out.extend_from_slice(&[ - 5.0, - style_flags(style) as f64, - *stroke as f64, - *weight_mm, - style.opacity.unwrap_or(1.0), - center.x, - center.y, - *r, - *a0, - *a1, - ]); - put_list(&mut out, dash); - } + out.push(m.points.len() as f64); + for p in &m.points { + out.push(p.x); + out.push(p.y); } } - out } -/// Lesen und neu schreiben (Hin-und-zurück-Prüfung der TS-Kodierung); leer bei kaputtem Puffer. -pub fn recode(buf: &[f64]) -> Vec { - decode(buf).map(|p| encode(&p)).unwrap_or_default() +/// Fehlerpuffer einer Abfrage (TS wirft die Meldung). +pub fn encode_error(msg: &str) -> Vec { + let units: Vec = msg.encode_utf16().collect(); + let mut out = Vec::with_capacity(16 + units.len() * 2); + out.extend_from_slice(&ERR_MAGIC.to_le_bytes()); + out.extend_from_slice(&(units.len() as f64).to_le_bytes()); + for u in units { + out.extend_from_slice(&u.to_le_bytes()); + } + out } #[cfg(test)] mod tests { use super::*; - use crate::hatch::v2; + use crate::model::{Marks, RichTextDoc}; + use crate::plan::prim::StampLine; + use crate::plan::style::no_hatch; - fn style() -> Style { - Style { greyed: true, opacity: Some(0.5) } + fn v(x: f64, y: f64) -> Vec2 { + Vec2 { x, y } } - fn sample() -> PlanBuf { - PlanBuf { - colors: vec![[0.1, 0.2, 0.3, 1.0], [1.0, 1.0, 1.0, 0.25]], - hatches: vec![ - HatchEntry { - hatch: Hatch { - pattern: Pattern::Custom, - kind: HatchKind::Vector, - random: true, - scale: 2.0, - angle: 30.0, - line_weight: 0.13, - origin: Some(v2(1.0, 2.0)), - seed: Some(7.0), - density: Some(1.5), - length_min: Some(0.5), - length_max: Some(2.0), - dash: vec![1.0, 0.5], - motif: Some(Motif { points: vec![v2(0.0, 0.0), v2(1.0, 1.0)], length: 2.0 }), - }, - color: 0, - }, - HatchEntry { - hatch: Hatch { - pattern: Pattern::Insulation, - kind: HatchKind::Gradient, - random: false, - scale: 1.0, - angle: 0.0, - line_weight: 0.0, - origin: None, - seed: None, - density: None, - length_min: None, - length_max: None, - dash: vec![], - motif: None, - }, - color: -1, - }, - ], - prims: vec![ - Prim::Placeholder, - Prim::Polygon { - style: style(), - fill: 1, - stroke: 0, - stroke_width_mm: 0.35, - hatch: 0, - pts: vec![v2(0.0, 0.0), v2(1.0, 0.0), v2(0.0, 1.0)], - no_stroke_edges: vec![1.0, 2.0], - }, - Prim::Line { - style: Style { greyed: false, opacity: None }, - color: -1, - weight_mm: f64::NAN, - a: v2(0.0, 0.0), - b: v2(3.0, 4.0), - dash: vec![2.0], - chain: true, - zigzag: Some((1.0, 4.0)), - motif: Some(Motif { points: vec![v2(0.0, 0.0), v2(2.0, 1.0)], length: 4.0 }), - }, - Prim::Arc { - style: style(), - color: 0, - weight_mm: 0.25, - center: v2(0.0, 0.0), - from: v2(1.0, 0.0), - to: v2(0.0, 1.0), - r: 1.0, - dash: vec![], - }, - Prim::Circle { style: style(), fill: -1, stroke: 1, weight_mm: 0.18, center: v2(5.0, 5.0), r: 2.0, dash: vec![] }, - Prim::DrawingArc { - style: style(), - stroke: 0, - weight_mm: 0.18, - center: v2(5.0, 5.0), - r: 2.0, - a0: 0.0, - a1: 3.0, - dash: vec![0.5, 0.5], - }, - ], + fn hatch() -> HatchRender { + HatchRender { + pattern: HatchPattern::Custom, + scale: 2.0, + angle: 30.0, + origin: Some(v(1.0, 2.0)), + color: "#123456".into(), + line_weight: 0.13, + dash: Some(vec![1.0, 0.5]), + kind: Some(HatchStyleKind::Vector), + lines: Some(HatchStyleLines::Random), + image: None, + gradient: None, + seed: Some(7.0), + density: Some(1.5), + length_min: Some(0.5), + length_max: Some(2.0), + motif: None, } } - /// NaN-feste Gleichheit über die Bits der Kodierung. - fn bits(v: &[f64]) -> Vec { - v.iter().map(|x| x.to_bits()).collect() + fn line(ax: f64, bx: f64, dash: Dash) -> Primitive { + Primitive::Line { + a: v(ax, 0.0), + b: v(bx, 0.0), + cls: "wall".into(), + weight_mm: 0.18, + dash, + zigzag: None, + motif: None, + color: Some("#000".into()), + drawing_id: None, + opening_id: None, + stair_id: None, + greyed: None, + opacity: None, + } + } + + fn sample() -> Vec { + vec![ + Primitive::Polygon { + pts: vec![v(0.0, 0.0), v(1.0, 0.0), v(0.0, 1.0)], + fill: "#fff".into(), + stroke: "none".into(), + stroke_width_mm: 0.35, + hatch: hatch(), + greyed: Some(true), + opacity: Some(0.5), + no_stroke_edges: Some(vec![1.0, 2.0]), + wall_id: Some("W1".into()), + drawing_id: None, + ceiling_id: None, + opening_id: Some("D1".into()), + stair_id: None, + room_id: None, + extruded_solid_id: None, + context_object_id: None, + column_id: None, + roof_id: None, + section_line_id: Some("S".into()), + }, + Primitive::Polygon { + pts: vec![], + fill: "#fff".into(), + stroke: "#000".into(), + stroke_width_mm: f64::NAN, + hatch: no_hatch(), + greyed: Some(false), + opacity: None, + no_stroke_edges: None, + wall_id: None, + drawing_id: None, + ceiling_id: Some("C1".into()), + opening_id: None, + stair_id: None, + room_id: None, + extruded_solid_id: None, + context_object_id: None, + column_id: None, + roof_id: None, + section_line_id: None, + }, + line(0.0, 1.0, None), + line(1.0, 2.0, None), + line(2.0, 3.0, Some(None)), + line(3.0, 4.0, Some(Some(vec![0.4, 0.2]))), + Primitive::Line { + a: v(0.0, 0.0), + b: v(3.0, 4.0), + cls: "c".into(), + weight_mm: 0.25, + dash: Some(Some(vec![2.0])), + zigzag: Some(LineStyleZigzag { amplitude: 1.0, wavelength: 4.0, ..Default::default() }), + motif: Some(LineStyleMotif { points: vec![v(0.0, 0.0), v(2.0, 1.0)], length: 4.0, ..Default::default() }), + color: None, + drawing_id: Some("d".into()), + opening_id: None, + stair_id: Some("st".into()), + greyed: Some(true), + opacity: Some(0.3), + }, + Primitive::Arc { + center: v(0.0, 0.0), + from: v(1.0, 0.0), + to: v(0.0, 1.0), + r: 1.0, + cls: "door-swing".into(), + weight_mm: 0.13, + dash: Some(Some(vec![0.5])), + opening_id: Some("D1".into()), + stair_id: None, + greyed: None, + opacity: None, + }, + Primitive::Text { + at: v(2.0, 2.0), + doc: RichTextDoc::default(), + extra_lines: vec![StampLine { text: "17.01 m²".into(), align: Default::default() }], + base_pt: 10.0, + color: "#6b7280".into(), + room_id: Some("R1".into()), + greyed: None, + opacity: None, + }, + Primitive::DrawingText { + at: v(1.0, 1.0), + text: "Hallo 𝄞".into(), + height_m: 0.25, + angle: 0.5, + color: "#000".into(), + marks: Some(Marks::default()), + wrap_width: None, + doc: None, + drawing_id: Some("t".into()), + greyed: None, + opacity: Some(0.5), + }, + Primitive::DrawingTextPath { path_pts: vec![v(0.0, 0.0), v(1.0, 1.0)], text: "Pfad".into(), height_m: 0.2, color: "#f00".into(), drawing_id: None, greyed: Some(true), opacity: None }, + Primitive::DrawingImage { min: v(0.0, 0.0), max: v(1.0, 1.0), src: "data:image/png;base64,AAAA".into(), opacity: 0.8, drawing_id: Some("img".into()), greyed: None }, + Primitive::DrawingCircle { center: v(5.0, 5.0), r: 2.0, fill: "none".into(), stroke: "#0f0".into(), weight_mm: 0.18, dash: Some(None), drawing_id: Some("c".into()), greyed: None, opacity: None }, + Primitive::DrawingArc { center: v(5.0, 5.0), r: 2.0, a0: 0.0, a1: 3.0, stroke: "#0f0".into(), weight_mm: 0.18, dash: Some(Some(vec![0.5, 0.5])), drawing_id: None, greyed: None, opacity: Some(1.0) }, + ] + } + + fn encode(prims: &[Primitive], hashes: bool) -> Vec { + let mut w = Writer::new(hashes); + w.group(&prims[..2]); + w.group(&prims[2..]); + w.bounds = Some([0.0, -1.0, 5.0, 7.0]); + w.finish() + } + + /// JSON-Form (NaN wird `null` wie in JS). + fn json(p: &[Primitive]) -> String { + serde_json::to_string(p).unwrap() } #[test] fn hin_und_zurueck_je_typ() { let p = sample(); - let enc = encode(&p); - let back = decode(&enc).expect("lesbar"); - assert_eq!(bits(&encode(&back)), bits(&enc)); - assert_eq!(back.prims.len(), 6); - assert_eq!(back.colors, p.colors); - assert_eq!(back.hatches, p.hatches); - // Je Typ einzeln (NaN-Stärke der Linie über die Bits). - for (i, prim) in p.prims.iter().enumerate() { - if i == 2 { - continue; - } - assert_eq!(&back.prims[i], prim); - } - if let Prim::Line { weight_mm, chain, zigzag, .. } = &back.prims[2] { - assert!(weight_mm.is_nan()); - assert!(*chain); - assert_eq!(*zigzag, Some((1.0, 4.0))); - } else { - panic!("Linie erwartet"); - } + let enc = encode(&p, true); + let (back, groups, bounds) = decode(&enc).expect("lesbar"); + assert_eq!(json(&back), json(&p)); + assert_eq!(groups, vec![(0, 2), (2, p.len())]); + assert_eq!(bounds, Some([0.0, -1.0, 5.0, 7.0])); + // Neu schreiben ergibt dieselben Bytes (ohne Hashes). + let plain = encode(&p, false); + assert_eq!(recode(&plain), plain); + assert_eq!(recode(&enc), plain); } #[test] - fn fremde_version_und_kaputte_puffer() { - let mut enc = encode(&sample()); - assert!(decode(&enc[..enc.len() - 1]).is_none()); + fn linienzug_flag_nach_js_referenz_semantik() { + let p = sample(); + let enc = encode(&p, false); + let v = View::parse(&enc).unwrap(); + let chain = |i: usize| v.rec(i).unwrap().flags & F_CHAIN != 0; + // 2 → 3: beide ohne Muster → Zug; 3 → 4: fehlend vs. null → nein; 4 → 5: Liste nie. + assert!(!chain(2)); + assert!(chain(3)); + assert!(!chain(4)); + assert!(!chain(5)); + // GPU-Sicht: am Bereichsanfang gilt das Flag nicht. + let g = v.gpu(3, 5).unwrap(); + assert!(matches!(g.prims[0], Prim::Line { chain: false, .. })); + let g = v.gpu(2, 5).unwrap(); + assert!(matches!(g.prims[1], Prim::Line { chain: true, .. })); + } + + #[test] + fn gpu_sicht_farben_und_schraffur() { + let p = sample(); + let enc = encode(&p, false); + let g = View::parse(&enc).unwrap().gpu(0, p.len()).unwrap(); + let Prim::Polygon { fill, stroke, hatch, style, pts, no_stroke_edges, .. } = &g.prims[0] else { panic!() }; + assert_eq!(g.color(*fill), Some([1.0, 1.0, 1.0, 1.0])); + assert_eq!(*stroke, -1, "none = keine Farbe"); + assert_eq!(style.opacity, Some(0.5)); + assert!(style.greyed); + assert_eq!(pts.len(), 3); + assert_eq!(no_stroke_edges, &vec![1.0, 2.0]); + let h = &g.hatches[*hatch as usize]; + assert!(h.hatch.random && h.hatch.pattern == Pattern::Custom && h.hatch.dash == vec![1.0, 0.5]); + assert_eq!(g.color(h.color), Some([0x12 as f64 / 255.0, 0x34 as f64 / 255.0, 0x56 as f64 / 255.0, 1.0])); + assert!(matches!(g.prims[1], Prim::Polygon { hatch: 1, .. }), "no_hatch wird ein eigener Eintrag"); + assert!(matches!(g.prims[8], Prim::Placeholder)); + assert!(matches!(g.prims[13], Prim::DrawingArc { .. })); + } + + #[test] + fn hashes_folgen_dem_inhalt() { + let p = sample(); + let a = encode(&p, true); + let mut q = p.clone(); + // Ein weiteres Primitiv vorn verschiebt Indizes/Pool, die Hashes der übrigen bleiben. + q.insert(0, line(9.0, 10.0, None)); + let mut w = Writer::new(true); + for x in &q { + w.push(x); + } + let b = w.finish(); + let (va, vb) = (View::parse(&a).unwrap(), View::parse(&b).unwrap()); + for i in 0..p.len() { + if i == 2 { + continue; // Linienzug-Flag hängt vom Vorgänger ab + } + assert_eq!(va.hash(i), vb.hash(i + 1), "Primitiv {i}"); + } + assert_ne!(va.hash(0), va.hash(1)); + let h = va.hash(0).unwrap(); + assert!(h >= 0.0 && h < 2f64.powi(52) && h.fract() == 0.0); + } + + #[test] + fn kaputte_puffer_werden_abgelehnt() { + let enc = encode(&sample(), true); + assert!(View::parse(&enc[..enc.len() - 1]).is_none()); let mut extra = enc.clone(); - extra.push(0.0); - assert!(decode(&extra).is_none()); - enc[1] = 2.0; - assert!(decode(&enc).is_none()); - enc[1] = VERSION; - enc[0] = 0.0; - assert!(decode(&enc).is_none()); - assert!(decode(&[]).is_none()); - // Riesige Anzahl ohne Daten: kein Speicher-Absturz. - assert!(decode(&[MAGIC, VERSION, 1e15, 0.0, 0.0]).is_none()); - assert!(decode(&[MAGIC, VERSION, 0.0, 0.0, 1.0, 9.0, 0.0]).is_none()); - assert!(decode(&[MAGIC, VERSION, 0.0, 0.0, f64::NAN]).is_none()); - assert_eq!(recode(&[1.0, 2.0]), Vec::::new()); + extra.push(0); + assert!(View::parse(&extra).is_none()); + let mut wrong = enc.clone(); + wrong[8..16].copy_from_slice(&3.0f64.to_le_bytes()); + assert!(View::parse(&wrong).is_none()); + assert!(View::parse(&[]).is_none()); + assert!(View::parse(&encode_error("x")).is_none()); + // Jede einzelne verfälschte Zahl: nie ein Panic. + for i in 0..enc.len() / 8 { + for bad in [f64::NAN, -2.0, 1e12, 3.5] { + let mut b = enc.clone(); + b[i * 8..i * 8 + 8].copy_from_slice(&bad.to_le_bytes()); + if let Some(v) = View::parse(&b) { + let _ = v.prims(); + let _ = v.gpu(0, v.len()); + let _ = v.groups(); + } + } + } + assert!(recode(&[1, 2, 3]).is_empty()); + } + + #[test] + fn farben_wie_js() { + let c = |s: &str| parse_color(s); + assert_eq!(c("#ff0000"), Some([1.0, 0.0, 0.0, 1.0])); + assert_eq!(c(" #F00 "), Some([1.0, 0.0, 0.0, 1.0])); + assert_eq!(c("#00000080"), Some([0.0, 0.0, 0.0, 128.0 / 255.0])); + assert_eq!(c("rgba(255, 0, 0, 0.5)"), Some([1.0, 0.0, 0.0, 0.5])); + assert_eq!(c("rgb(255,128,0,128)"), Some([1.0, 128.0 / 255.0, 0.0, 128.0 / 255.0])); + assert_eq!(c("none"), None); + assert_eq!(c("transparent"), None); + assert_eq!(c(""), None); + assert_eq!(c("#ggg"), None); + assert_eq!(c("rgb(1,2)"), None); + // parseInt-Eigenheiten: Präfix, Vorzeichen; Alpha darf NaN sein. + assert_eq!(c("#1g2h3i"), Some([1.0 / 255.0, 2.0 / 255.0, 3.0 / 255.0, 1.0])); + assert_eq!(c("-1ffff"), Some([-1.0 / 255.0, 1.0, 1.0, 1.0])); + assert!(c("#000000zz").unwrap()[3].is_nan()); + let r = c("rgb(1.2.3, 4, 5, 1.5.5)").unwrap(); + assert!(r[0].is_nan()); + assert_eq!(r[3], 1.5 / 255.0); } } diff --git a/src-tauri/core/src/web/gpu_compile.rs b/src-tauri/core/src/web/gpu_compile.rs index 99216b83..ca772c3e 100644 --- a/src-tauri/core/src/web/gpu_compile.rs +++ b/src-tauri/core/src/web/gpu_compile.rs @@ -2,11 +2,18 @@ use wasm_bindgen::prelude::wasm_bindgen; -/// Plan-Puffer (ein Chunk) → Vertex-/Index-/Batch-Daten als ein `u32`-Puffer; leer bei -/// unlesbarem Puffer. +/// Primitive `[from, to)` eines Plan-Puffers (v2) → Vertex-/Index-/Batch-Daten als ein +/// `u32`-Puffer; leer bei unlesbarem Puffer oder ungültigem Bereich. #[wasm_bindgen] -pub fn gpu_compile_flat(buf: &[f64], px_per_meter: f64, packed_lines: bool) -> Vec { - crate::gpu_compile::compile_flat(buf, px_per_meter, packed_lines) +pub fn gpu_compile_flat(buf: &[u8], from: u32, to: u32, px_per_meter: f64, packed_lines: bool) -> Vec { + crate::gpu_compile::compile_flat(buf, from as usize, to as usize, px_per_meter, packed_lines) +} + +/// Wie [`gpu_compile_flat`] auf einem gehaltenen Puffer (`plan_buf_hold`); leer, wenn er nicht +/// mehr gehalten wird. +#[wasm_bindgen] +pub fn gpu_compile_held(id: u32, from: u32, to: u32, px_per_meter: f64, packed_lines: bool) -> Vec { + super::plan_buf::with_held(id, |b| crate::gpu_compile::compile_flat(b, from as usize, to as usize, px_per_meter, packed_lines)).unwrap_or_default() } /// Ear-Clipping eines Rings `[x, y, …]` → Dreiecks-Indizes. diff --git a/src-tauri/core/src/web/plan_buf.rs b/src-tauri/core/src/web/plan_buf.rs index f421c499..7ed99649 100644 --- a/src-tauri/core/src/web/plan_buf.rs +++ b/src-tauri/core/src/web/plan_buf.rs @@ -1,10 +1,53 @@ //! Bindungen des Plan-Puffers (`crate::plan_buf`). Format s. dort. +//! +//! Gehaltene Puffer: TS übergibt einen Plan-Puffer einmal (`plan_buf_hold`) und kompiliert danach +//! beliebig viele GPU-Chunks daraus (`gpu_compile_held`), ohne ihn je Chunk erneut zu kopieren. +//! Höchstens `MAX_HELD` Puffer bzw. `MAX_HELD_BYTES` bleiben liegen (ältester fällt weg); +//! ein verdrängter Puffer liefert leere Ergebnisse, TS übergibt ihn dann neu. +use std::cell::RefCell; use wasm_bindgen::prelude::wasm_bindgen; +const MAX_HELD: usize = 8; +const MAX_HELD_BYTES: usize = 96 << 20; + +thread_local! { + static HELD: RefCell<(u32, Vec<(u32, Vec)>)> = const { RefCell::new((0, Vec::new())) }; +} + /// Plan-Puffer lesen und neu schreiben (Hin-und-zurück-Prüfung der TS-Kodierung); leer bei /// fremder Version oder kaputtem Puffer. #[wasm_bindgen] -pub fn plan_buf_recode(buf: &[f64]) -> Vec { +pub fn plan_buf_recode(buf: &[u8]) -> Vec { crate::plan_buf::recode(buf) } + +/// Puffer im Kern halten; Ergebnis ist die Nummer (≥ 1), 0 bei unlesbarem Puffer. +#[wasm_bindgen] +pub fn plan_buf_hold(buf: &[u8]) -> u32 { + if crate::plan_buf::View::parse(buf).is_none() { + return 0; + } + HELD.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, buf.to_vec())); + 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(); + } + id + }) +} + +/// Gehaltenen Puffer freigeben (unbekannte Nummer: nichts). +#[wasm_bindgen] +pub fn plan_buf_release(id: u32) { + HELD.with(|h| h.borrow_mut().1.retain(|e| e.0 != id)); +} + +/// Mit dem gehaltenen Puffer `id` rechnen; `None`, wenn er nicht (mehr) da ist. +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))) +} diff --git a/src/plan/glPlan/glPlanCompile.ts b/src/plan/glPlan/glPlanCompile.ts index e171cb04..d158d2c1 100644 --- a/src/plan/glPlan/glPlanCompile.ts +++ b/src/plan/glPlan/glPlanCompile.ts @@ -1,9 +1,10 @@ /** * Tessellierung: wandelt Plan-`Primitive` in GPU-fertige Puffer — Fassade über den Rust-Kern - * ([K3b], `src-tauri/core/src/gpu_compile.rs`). TS kodiert die Primitive eines Chunks in den - * Plan-Puffer (`../planBuf.ts`), Rust tesselliert (Ear-Clipping, Striche mit runden Kappen/Ecken, - * Schraffur, Zickzack, Motive, Bögen, Kreise) und liefert Vertex-/Index-/Batch-Daten flach zurück; - * hier werden sie nur noch hochgeladen. + * ([K3b], `src-tauri/core/src/gpu_compile.rs`). Rust tesselliert (Ear-Clipping, Striche mit runden + * Kappen/Ecken, Schraffur, Zickzack, Motive, Bögen, Kreise) und liefert Vertex-/Index-/Batch-Daten + * flach zurück; hier werden sie nur noch hochgeladen. Eingabe ist der Plan-Puffer v2 + * (`../planBuf.ts`): Bereiche eines Kern-Puffers (`planDomains`) gehen direkt in die Kompilierung + * ({@link compilePlanBufRange}, [K3d]), gemischte Listen kodiert TS schlank ({@link compilePrimitivesToGpu}). * * Koordinaten: alles in BILDSCHIRM-Raum (wie `toScreen`): sx = mx·PX_PER_M, sy = -my·PX_PER_M, * relativ zum lokalen Ursprung (`origin`, erster abgelegter Punkt). @@ -12,7 +13,7 @@ import type { Primitive } from '../generatePlan'; import type { Vec2 } from '../../model/types'; import type { BufferGl, GpuGeometry, Rgba } from './glPlanTypes'; -import { encodePlanBuf } from '../planBuf'; +import { encodePlanBuf, type DecodedPlanBuf } from '../planBuf'; import { core } from '../../engine/coreWasm'; /** @@ -41,7 +42,23 @@ export function compilePrimitivesToGpu( pxPerMeter = 0, ): GpuGeometry { const packed = gl.packedLineVertices === true; - const out = core().gpu_compile_flat(encodePlanBuf(primitives), pxPerMeter, packed); + const out = core().gpu_compile_flat(encodePlanBuf(primitives, { lean: true }), 0, primitives.length, pxPerMeter, packed); + return uploadCompiled(gl, out); +} + +/** + * Wie {@link compilePrimitivesToGpu} für die Primitive `[from, to)` eines Kern-Puffers — ohne + * Umweg über Objekte: der Puffer wird einmal im Kern abgelegt (`plan_buf_hold`) und für alle + * Chunks wiederverwendet. Ist er dort verdrängt, wird er neu abgelegt. + */ +export function compilePlanBufRange(gl: BufferGl, src: DecodedPlanBuf, from: number, to: number, pxPerMeter = 0): GpuGeometry { + const packed = gl.packedLineVertices === true; + const c = core(); + let out = src.hold ? c.gpu_compile_held(src.hold, from, to, pxPerMeter, packed) : new Uint32Array(0); + if (out.length === 0) { + src.hold = c.plan_buf_hold(src.bytes); + out = src.hold ? c.gpu_compile_held(src.hold, from, to, pxPerMeter, packed) : c.gpu_compile_flat(src.bytes, from, to, pxPerMeter, packed); + } return uploadCompiled(gl, out); } diff --git a/src/plan/planBuf.test.ts b/src/plan/planBuf.test.ts index fce7a0d3..3c739fc4 100644 --- a/src/plan/planBuf.test.ts +++ b/src/plan/planBuf.test.ts @@ -1,8 +1,10 @@ -// Plan-Puffer [K3b]: TS kodiert, Rust liest und schreibt neu — Hin und zurück muss jede Zahl -// erhalten (je Primitiv-Typ), fremde Versionen werden sauber abgelehnt. +// Plan-Puffer v2 [K3d]: TS kodiert und liest, Rust liest und schreibt neu — hin und zurück bleibt +// jedes Primitiv gleich (je Typ, gemischt, über den Kern), fremde Versionen werden sauber abgelehnt. import { describe, it, expect } from "vitest"; -import { encodePlanBuf, encodeHatch, parseColor, PLAN_BUF_MAGIC, PLAN_BUF_VERSION } from "./planBuf"; +import { decodePlanBuf, encodeHatch, encodePlanBuf, PLAN_BUF_MAGIC, PLAN_BUF_VERSION } from "./planBuf"; +import { documentFor } from "../core/document"; +import { sampleProject } from "../model/sampleProject"; import { core } from "../engine/coreWasm"; import type { HatchRender, Primitive } from "./generatePlan"; @@ -51,88 +53,159 @@ const PRIMS: Record = { arc: { kind: "arc", center: { x: 0, y: 0 }, from: { x: 1, y: 0 }, to: { x: 0, y: 1 }, r: 1, cls: "c", weightMm: 0.18, opacity: 0.5 }, drawingCircle: { kind: "drawingCircle", center: { x: 5, y: 5 }, r: 2, fill: "none", stroke: "#123", weightMm: 0.18, dash: [2] }, drawingArc: { kind: "drawingArc", center: { x: 5, y: 5 }, r: 2, a0: 0, a1: 3, stroke: "#123", weightMm: 0.5, greyed: true }, - text: { kind: "drawingText", at: { x: 0, y: 0 }, text: "x", heightM: 1, angle: 0, color: "#000" }, - image: { kind: "drawingImage", min: { x: 0, y: 0 }, max: { x: 1, y: 1 }, src: "", opacity: 1 }, + text: { kind: "drawingText", at: { x: 0, y: 0 }, text: "x 𝄞 ü", heightM: 1, angle: 0, color: "#000", drawingId: "t" }, + textPath: { kind: "drawingTextPath", pathPts: [{ x: 0, y: 0 }, { x: 1, y: 2 }], text: "Pfad", heightM: 0.2, color: "#f00", greyed: false }, + image: { kind: "drawingImage", min: { x: 0, y: 0 }, max: { x: 1, y: 1 }, src: "data:image/png;base64,AA", opacity: 1 }, + stamp: { + kind: "text", + at: { x: 1, y: 1 }, + doc: { version: 1, paragraphs: [{ align: "center", runs: [{ text: "Bad", marks: { bold: true } }] }] }, + extraLines: [{ text: "4.20 m²", align: "center" }], + basePt: 10, + color: "#333", + roomId: "R1", + } as unknown as Primitive, + dashNull: { kind: "arc", center: { x: 0, y: 0 }, from: { x: 1, y: 0 }, to: { x: 0, y: 1 }, r: 1, cls: "c", weightMm: 0.18, dash: null, openingId: "o", stairId: "s", greyed: false }, + manyIds: { + kind: "polygon", + pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], + fill: "none", + stroke: "#000", + strokeWidthMm: 0.1, + hatch, + sectionLineId: "sl", + wallId: "w", + stairId: "st", + }, }; -/** Gleichheit Zahl für Zahl (NaN = NaN, −0 ≠ +0). */ -function sameBits(a: Float64Array, b: Float64Array): boolean { - if (a.length !== b.length) return false; - for (let i = 0; i < a.length; i++) if (!Object.is(a[i], b[i])) return false; - return true; +/** + * JSON mit sortierten Schlüsseln. Fehlende Zahlen (TS `undefined`) reisen als NaN — beide fallen + * hier weg; Kern-Ausgaben vergleichen die Paritätstests mit dem früheren JSON (NaN → null). + */ +function canon(v: unknown): string { + return JSON.stringify(v, (_k, x) => + typeof x === "number" && Number.isNaN(x) + ? undefined + : x && typeof x === "object" && !Array.isArray(x) + ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, (x as Record)[k]])) + : x, + ); } -describe("Plan-Puffer", () => { +/** Flags der Einträge (Kopf und Offsets gelesen wie im Format beschrieben). */ +function recFlags(bytes: Uint8Array): number[] { + const f = new Float64Array(bytes.buffer, bytes.byteOffset, bytes.byteLength >> 3); + const [nStrings, , nHatchWords, nGroups, nPrims] = [f[3], f[4], f[5], f[6], f[7]]; + const offAt = 16 + 2 * nStrings + nHatchWords + 2 * nGroups; + const recAt = offAt + nPrims * (f[2] & 1 ? 2 : 1); + return Array.from({ length: nPrims }, (_, i) => f[recAt + f[offAt + i] + 1]); +} + +describe("Plan-Puffer v2", () => { for (const [name, prim] of Object.entries(PRIMS)) { it(`Hin und zurück: ${name}`, () => { const buf = encodePlanBuf([prim]); - expect(buf[0]).toBe(PLAN_BUF_MAGIC); - expect(buf[1]).toBe(PLAN_BUF_VERSION); - expect(buf[4]).toBe(1); - expect(sameBits(core().plan_buf_recode(buf), buf)).toBe(true); + const head = new Float64Array(buf.buffer, 0, 8); + expect(head[0]).toBe(PLAN_BUF_MAGIC); + expect(head[1]).toBe(PLAN_BUF_VERSION); + expect(head[7]).toBe(1); + expect(canon(decodePlanBuf(buf).prims)).toBe(canon([prim])); + // Über den Kern (lesen + neu schreiben) bleibt der Inhalt gleich. + expect(canon(decodePlanBuf(core().plan_buf_recode(buf)).prims)).toBe(canon([prim])); }); } - it("Hin und zurück: alle Typen gemischt, ein Eintrag je Primitiv", () => { + it("Hin und zurück: alle Typen gemischt, mit Gruppen und Ausmass", () => { const prims = Object.values(PRIMS); - const buf = encodePlanBuf(prims); - expect(buf[4]).toBe(prims.length); - expect(sameBits(core().plan_buf_recode(buf), buf)).toBe(true); + const buf = encodePlanBuf(prims, { groups: [[0, 2], [2, prims.length]], bounds: [-1, -2, 3, 4] }); + const d = decodePlanBuf(buf); + expect(canon(d.prims)).toBe(canon(prims)); + expect(d.groups).toEqual([[0, 2], [2, prims.length]]); + expect(d.bounds).toEqual([-1, -2, 3, 4]); + expect(d.hashes).toBeNull(); + const back = decodePlanBuf(core().plan_buf_recode(buf)); + expect(canon(back.prims)).toBe(canon(prims)); + expect(back.groups).toEqual(d.groups); + // Schraffuren werden einmal gelesen und geteilt. + expect((d.prims[0] as { hatch: unknown }).hatch).toBe((d.prims[prims.length - 1] as { hatch: unknown }).hatch); }); - it("Texte und Bilder sind Platzhalter (nur der Typ-Eintrag 0)", () => { - expect(Array.from(encodePlanBuf([PRIMS.text, PRIMS.image]))).toEqual([PLAN_BUF_MAGIC, PLAN_BUF_VERSION, 0, 0, 2, 0, 0]); + it("Texte mit einzelnen Surrogaten bleiben in TS exakt", () => { + const t = { ...PRIMS.text, text: "a\ud800b\udfff" } as Primitive; + expect(decodePlanBuf(encodePlanBuf([t])).prims[0]).toEqual(t); }); - it("Farben werden einmal geparst und geteilt, ungültige ergeben −1", () => { - const a = { ...PRIMS.line, color: "#ff0000" } as Primitive; - const b = { ...PRIMS.line, color: "nonsense" } as Primitive; - const buf = encodePlanBuf([a, a, b]); - expect(buf[2]).toBe(1); - expect(Array.from(buf.subarray(5, 9))).toEqual(parseColor("#ff0000")); + it("schlank (nur GPU): Texte/Bilder als Platzhalter, ohne Ids und Klassen", () => { + const prims = Object.values(PRIMS); + const lean = encodePlanBuf(prims, { lean: true }); + expect(lean.byteLength).toBeLessThan(encodePlanBuf(prims).byteLength); + expect(() => decodePlanBuf(lean)).toThrow(); + // Die GPU-Kompilierung liest beide gleich. + const a = core().gpu_compile_flat(lean, 0, prims.length, 90, true); + const b = core().gpu_compile_flat(encodePlanBuf(prims), 0, prims.length, 90, true); + expect(a.length).toBeGreaterThan(30); + expect(Array.from(a)).toEqual(Array.from(b)); }); it("Linienzug-Flag: nur gleiches Element, gleicher Stil und lückenlos", () => { const seg = (ax: number, bx: number, extra: object = {}): Primitive => ({ kind: "line", a: { x: ax, y: 0 }, b: { x: bx, y: 0 }, cls: "c", weightMm: 0.18, color: "#000", drawingId: "d", ...extra }) as Primitive; - const flagsOf = (prims: Primitive[]) => { - const buf = encodePlanBuf(prims); - const out: number[] = []; - let i = 5 + buf[2] * 4; - for (let k = 0; k < prims.length; k++) { - out.push(buf[i + 1] & 4); - i += 9 + 1 + buf[i + 9]; - } - return out; - }; - expect(flagsOf([seg(0, 1), seg(1, 2), seg(2, 3)])).toEqual([0, 4, 4]); - expect(flagsOf([seg(0, 1), seg(1.5, 2)])).toEqual([0, 0]); - expect(flagsOf([seg(0, 1), seg(1, 2, { drawingId: "e" })])).toEqual([0, 0]); - expect(flagsOf([seg(0, 1), seg(1, 2, { weightMm: 0.5 })])).toEqual([0, 0]); - expect(flagsOf([seg(0, 1), seg(1, 2, { greyed: false })])).toEqual([0, 0]); - expect(flagsOf([seg(0, 1, { dash: [1] }), seg(1, 2, { dash: [1] })])).toEqual([0, 0]); + const chain = (prims: Primitive[]) => recFlags(encodePlanBuf(prims)).map((fl) => fl & 8); + expect(chain([seg(0, 1), seg(1, 2), seg(2, 3)])).toEqual([0, 8, 8]); + expect(chain([seg(0, 1), seg(1.5, 2)])).toEqual([0, 0]); + expect(chain([seg(0, 1), seg(1, 2, { drawingId: "e" })])).toEqual([0, 0]); + expect(chain([seg(0, 1), seg(1, 2, { weightMm: 0.5 })])).toEqual([0, 0]); + expect(chain([seg(0, 1), seg(1, 2, { greyed: false })])).toEqual([0, 0]); + // Strichmuster: dieselbe Referenz verbindet, gleiche Werte in neuen Listen nicht. + expect(chain([seg(0, 1, { dash: [1] }), seg(1, 2, { dash: [1] })])).toEqual([0, 0]); + const d = [1]; + expect(chain([seg(0, 1, { dash: d }), seg(1, 2, { dash: d })])).toEqual([0, 8]); + expect(chain([seg(0, 1, { dash: null }), seg(1, 2, { dash: null })])).toEqual([0, 8]); }); - it("fremde Version oder kaputter Puffer → leeres Ergebnis, kein Absturz", () => { - const buf = encodePlanBuf(Object.values(PRIMS)); + it("fremde Version oder kaputter Puffer → leeres Ergebnis bzw. Fehler, kein Absturz", () => { + const prims = Object.values(PRIMS); + const buf = encodePlanBuf(prims); const wrong = buf.slice(); - wrong[1] = PLAN_BUF_VERSION + 1; + new Float64Array(wrong.buffer, 0, 2)[1] = PLAN_BUF_VERSION + 1; expect(core().plan_buf_recode(wrong).length).toBe(0); - expect(core().gpu_compile_flat(wrong, 90, true).length).toBe(0); + expect(core().gpu_compile_flat(wrong, 0, 1, 90, true).length).toBe(0); + expect(() => decodePlanBuf(wrong)).toThrow(/Version/); expect(core().plan_buf_recode(buf.subarray(0, buf.length - 3)).length).toBe(0); - expect(core().gpu_compile_flat(new Float64Array([1, 2, 3]), 90, false).length).toBe(0); + expect(() => decodePlanBuf(buf.subarray(0, buf.length - 2))).toThrow(); + expect(core().gpu_compile_flat(new Uint8Array([1, 2, 3]), 0, 0, 90, false).length).toBe(0); + expect(core().gpu_compile_flat(buf, 0, prims.length + 1, 90, false).length).toBe(0); + expect(core().gpu_compile_held(424242, 0, 1, 90, false).length).toBe(0); + expect(core().plan_buf_hold(wrong)).toBe(0); // Danach arbeitet der Kern normal weiter. - expect(sameBits(core().plan_buf_recode(buf), buf)).toBe(true); + expect(canon(decodePlanBuf(core().plan_buf_recode(buf)).prims)).toBe(canon(prims)); + }); + + it("gehaltener Puffer kompiliert wie der übergebene", () => { + const prims = Object.values(PRIMS); + const buf = encodePlanBuf(prims); + const id = core().plan_buf_hold(buf); + expect(id).toBeGreaterThan(0); + expect(Array.from(core().gpu_compile_held(id, 1, 5, 90, true))).toEqual(Array.from(core().gpu_compile_flat(buf, 1, 5, 90, true))); + core().plan_buf_release(id); + expect(core().gpu_compile_held(id, 1, 5, 90, true).length).toBe(0); + }); + + it("Fehler einer Kern-Abfrage kommen als Meldung", () => { + const doc = documentFor(sampleProject); + expect(() => decodePlanBuf(doc.queryBin("planDomains", [1], "kein json"))).toThrow(/Plan-Argumente/); }); it("Einzel-Schraffur hat dasselbe Format wie ein Hatch-Eintrag", () => { const h = encodeHatch(hatch); const buf = encodePlanBuf([PRIMS.polygon]); - const colors = buf[2]; - // Im Plan-Puffer steht der Farbindex statt −1. - const inPlan = buf.slice(5 + colors * 4, 5 + colors * 4 + h.length); + const f = new Float64Array(buf.buffer, 0, buf.byteLength >> 3); + const at = 16 + 2 * f[3] + 1; // nach dem JSON-String-Index des ersten Eintrags + const inPlan = f.slice(at, at + h.length); + // Im Plan-Puffer steht der Farb-String statt −1. expect(inPlan[5]).toBeGreaterThanOrEqual(0); inPlan[5] = -1; - expect(sameBits(inPlan, h)).toBe(true); + expect(Array.from(inPlan)).toEqual(Array.from(h)); }); }); diff --git a/src/plan/planBuf.ts b/src/plan/planBuf.ts index be336b59..4c6ccea4 100644 --- a/src/plan/planBuf.ts +++ b/src/plan/planBuf.ts @@ -1,91 +1,73 @@ /** - * Plan-Puffer ([K3b]): kompakte Binärkodierung der zeichnungsrelevanten Plan-Primitive als - * flacher `Float64Array`. TS schreibt ihn vorerst aus `Plan.primitives`, der Rust-Kern liest ihn - * (`src-tauri/core/src/plan_buf.rs`, dort dieselbe Formatbeschreibung) — heute für die GPU- - * Kompilierung (`glPlan/glPlanCompile.ts`), ab [K3a] erzeugt Rust ihn direkt. + * Plan-Puffer v2 ([K3d]): binäre Übergabe der Plan-Primitive zwischen Rust-Kern und TS — Format + * und Bedeutung aller Felder stehen im Kopf von `src-tauri/core/src/plan_buf.rs` (hier gekürzt). + * Der Kern schreibt ihn direkt aus der Plan-Erzeugung (Abfrage `planDomains`); TS liest ihn zu + * `Primitive[]` ({@link decodePlanBuf}: Auswahl, Overlay, SVG/PDF/DXF) und schreibt ihn für + * GPU-Chunks aus gemischten Listen ({@link encodePlanBuf}, `glPlanCompile.ts`). Die GPU-Kompilierung + * liest Bereiche eines Kern-Puffers direkt (`compilePlanBufRange`), ohne Umweg über Objekte. * * ```text - * Kopf [MAGIC, VERSION, nColors, nHatches, nPrims] - * MAGIC = 0x504C4231 ("PLB1"), VERSION = 1 — Rust lehnt fremde Werte ab (leeres Ergebnis) - * Farben nColors × [r, g, b, a] (0..1, hier aus dem Farbtext geparst) - * Schraffuren nHatches × Hatch - * Primitive nPrims × Prim (genau ein Eintrag je Primitiv → Indizes bleiben gleich) - * - * Hatch [pattern, kind, flags, scale, angle, colorIdx, lineWeight, originX, originY, - * seed, density, lengthMin, lengthMax, nDash, dash…, (Motiv: length, nPts, x,y…)] - * pattern 0 none · 1 solid · 2 diagonal (auch unbekannt) · 3 crosshatch · 4 insulation · 5 custom - * kind 0 vector · 1 image · 2 gradient (Bild/Verlauf: GPU fällt auf die Füllung zurück) - * flags 1 random · 2 origin · 4 seed · 8 density · 16 lengthMin · 32 lengthMax · 64 Motiv - * (Felder ohne Flag stehen auf 0 und gelten als „nicht gesetzt") - * - * Prim [tag, flags, …] flags 1 greyed · 2 opacity gesetzt · 4 setzt den Linienzug der - * vorigen Linie fort · 8 Zickzack · 16 Motiv - * 0 Platzhalter [0] (Text, Bild … — zeichnet die GPU nicht) - * 1 polygon [1, flags, fillIdx, strokeIdx, strokeWidthMm, hatchIdx, opacity, - * nPts, x,y…, nNoStroke, kante…] - * 2 line [2, flags, colorIdx, weightMm, opacity, ax, ay, bx, by, nDash, dash…, - * (Zickzack: amplitude, wavelength), (Motiv: length, nPts, x,y…)] - * 3 arc [3, flags, colorIdx, weightMm, opacity, cx, cy, fromX, fromY, toX, toY, r, - * nDash, dash…] - * 4 drawingCircle [4, flags, fillIdx, strokeIdx, weightMm, opacity, cx, cy, r, nDash, dash…] - * 5 drawingArc [5, flags, strokeIdx, weightMm, opacity, cx, cy, r, a0, a1, nDash, dash…] + * Bytes: f64-Teil, dann UTF-16-Einheiten aller Texte + * Kopf (16) [MAGIC "PLB2", VERSION 2, flags (1 Hashes, 2 Ausmass), nStrings, nHatches, nHatchWords, + * nGroups, nPrims, nRecWords, nPool, nUnits, 0, minX, minY, maxX, maxY] + * Strings nStrings × [unitOff, unitLen] + * Schraffur nHatches × [jsonStr, Hatch] (Hatch wie encodeHatch, Farbe = String-Index) + * Gruppen nGroups × [start, end) + * Offsets nPrims × Wortindex des Eintrags + * Hashes nPrims × Inhalts-Hash (nur Kern) + * Primitive [tag, flags, pickKind, pickStr, …] 1 polygon · 2 line · 3 arc · 4 drawingCircle · + * 5 drawingArc · 6 text · 7 drawingText · 8 drawingTextPath · 9 drawingImage (JSON) · + * 0 Platzhalter (nur `lean`) + * Pool Punkte, Strichmuster, Kantenlisten, Motive, weitere Ids * ``` - * Farb-/Schraffur-Index −1 = keine (Farbtext ungültig, "none", fehlende Schraffur). Längen in - * Metern, Strichstärken/Strichmuster/Zickzack/Motiv in Papier-mm, Winkel von drawingArc in - * Bogenmass, Schraffur-Winkel in Grad (SVG-Drehsinn). Ohne opacity-Flag steht 1 im Feld; fehlende - * Zahlen (`undefined`) werden NaN, der Verbraucher nimmt dann wie bisher seinen Standard. - * Flag 4 (Linienzug): gleiches Element (`drawingId`), gleiche Farbe/Stärke/greyed/opacity/ - * Strichmuster (Referenz) und Anfang = Ende der vorigen Linie — dann zeichnet die GPU die - * Einzelsegmente als EINEN Zug (zwei echte Kappen statt 2N). Pick-IDs stehen NICHT im Puffer - * (Picken bleibt vorerst TS). + * Flags: 1 greyed gesetzt · 2 greyed · 4 opacity · 8 Linienzug · 16 Zickzack · 32 Motiv · + * 64 dash null · 128 dash Liste · 256 noStrokeEdges · 512 Farbe (line/arc) · 1024 weitere Ids. */ import type { HatchRender, Primitive } from "./generatePlan"; import type { Vec2 } from "../model/types"; -export const PLAN_BUF_MAGIC = 0x504c4231; -export const PLAN_BUF_VERSION = 1; +export const PLAN_BUF_MAGIC = 0x504c4232; +export const PLAN_BUF_VERSION = 2; +/** Fehlerpuffer einer Kern-Abfrage ("PLBe"): `[ERR_MAGIC, nUnits]` + Meldung (UTF-16). */ +export const PLAN_BUF_ERR_MAGIC = 0x504c4265; +const HEAD = 16; -/** RGBA-Farbe, Komponenten in [0,1]. */ -export type PlanRgba = [number, number, number, number]; +const F_GREYED_SET = 1; +const F_GREYED = 2; +const F_OPACITY = 4; +const F_CHAIN = 8; +const F_ZIGZAG = 16; +const F_MOTIF = 32; +const F_DASH_NULL = 64; +const F_DASH_LIST = 128; +const F_NSE = 256; +const F_COLOR = 512; +const F_IDS = 1024; -const FLAG_GREYED = 1; -const FLAG_OPACITY = 2; -const FLAG_CHAIN = 4; -const FLAG_ZIGZAG = 8; -const FLAG_MOTIF = 16; - -/** - * Farbe → RGBA[0..1]; ungültig/"none"/"transparent" → null. - * Unterstützt "#rgb", "#rrggbb", "#rrggbbaa" und "rgb()/rgba()". - */ -export function parseColor(hex: string | undefined): PlanRgba | null { - if (!hex) return null; - const s = hex.trim().toLowerCase(); - if (s === "none" || s === "transparent") return null; - - if (s.startsWith("rgb")) { - const m = s.match(/[\d.]+/g); - if (!m || m.length < 3) return null; - const a = m.length >= 4 ? parseFloat(m[3]) : 1; - return [+m[0] / 255, +m[1] / 255, +m[2] / 255, a > 1 ? a / 255 : a]; - } - - let h = s[0] === "#" ? s.slice(1) : s; - if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2]; - if (h.length !== 6 && h.length !== 8) return null; - const r = parseInt(h.slice(0, 2), 16); - const g = parseInt(h.slice(2, 4), 16); - const b = parseInt(h.slice(4, 6), 16); - const a = h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1; - if (isNaN(r) || isNaN(g) || isNaN(b)) return null; - return [r / 255, g / 255, b / 255, a]; -} +/** Pick-Arten (Index + 1) = Feldname am Primitiv. */ +const PICK_KEYS = [ + "wallId", + "drawingId", + "ceilingId", + "openingId", + "stairId", + "roomId", + "extrudedSolidId", + "contextObjectId", + "columnId", + "roofId", + "sectionLineId", +] as const; +type PickKey = (typeof PICK_KEYS)[number]; /** Wachsender `Float64Array`-Schreiber. */ class F64Writer { - buf = new Float64Array(1024); + buf: Float64Array; length = 0; + constructor(cap = 256) { + this.buf = new Float64Array(cap); + } private grow(need: number): void { let cap = this.buf.length * 2; while (cap < need) cap *= 2; @@ -131,7 +113,7 @@ const PATTERN_CODE: Record = { custom: 5, }; -/** Eine Schraffur im Hatch-Format (auch Eingabe der Einzel-Bindungen in `glPlanHatch.ts`). */ +/** Ein Hatch-Datensatz (auch Eingabe der Einzel-Bindungen in `glPlanHatch.ts`). */ function writeHatch(w: F64Writer, h: HatchRender, colorIdx: number): void { let flags = 0; if (h.lines === "random") flags |= 1; @@ -165,14 +147,11 @@ function writeHatch(w: F64Writer, h: HatchRender, colorIdx: number): void { /** Einzelne Schraffur kodieren (Farbe −1) — Eingabe der Schraffur-Bindungen des Kerns. */ export function encodeHatch(h: HatchRender): Float64Array { - const w = new F64Writer(); + const w = new F64Writer(32); writeHatch(w, h, -1); return w.buf.subarray(0, w.length); } -/** Zwischenspeicher Farbtext → Farbindex-Eintrag (geparste Farbe oder null). */ -const colorCache = new Map(); - type LinePrim = Extract; const isPlainLine = (p: Primitive | undefined): p is LinePrim => @@ -193,164 +172,485 @@ function chainsPrev(prev: Primitive | undefined, p: LinePrim): boolean { ); } -/** Primitive → Plan-Puffer (Format s. Dateikopf). */ -export function encodePlanBuf(prims: readonly Primitive[]): Float64Array { - const colors: PlanRgba[] = []; - const colorIdx = new Map(); - let lastColor: string | undefined; - let lastColorIdx = -1; - const color = (s: string | undefined): number => { - if (!s) return -1; - if (s === lastColor) return lastColorIdx; - let i = colorIdx.get(s); - if (i !== undefined) { - lastColor = s; - lastColorIdx = i; - return i; +export interface EncodeOptions { + /** + * Nur für die GPU: ohne Pick-Ids, Linienklassen und Schraffur-JSON, Texte/Bilder als Platzhalter + * (tag 0). Schneller; {@link decodePlanBuf} kann so einen Puffer nicht vollständig lesen. + */ + lean?: boolean; + /** Gruppen `[start, end)` in den Kopf schreiben. */ + groups?: ReadonlyArray; + bounds?: readonly [number, number, number, number]; +} + +/** Primitive → Plan-Puffer v2 (Format s. Dateikopf). */ +export function encodePlanBuf(prims: readonly Primitive[], opts: EncodeOptions = {}): Uint8Array { + const lean = opts.lean === true; + const strParts: string[] = []; + const strTab = new F64Writer(64); + const strIdx = new Map(); + let units = 0; + const str = (s: string | undefined): number => { + if (s === undefined) return -1; + let i = strIdx.get(s); + if (i === undefined) { + i = strTab.length >> 1; + strTab.push(units); + strTab.push(s.length); + units += s.length; + strParts.push(s); + strIdx.set(s, i); } - let c = colorCache.get(s); - if (c === undefined) { - c = parseColor(s); - if (colorCache.size > 4096) colorCache.clear(); - colorCache.set(s, c); - } - i = c ? colors.push(c) - 1 : -1; - colorIdx.set(s, i); return i; }; - const hatchW = new F64Writer(); + const hatchW = new F64Writer(64); const hatchIdx = new Map(); const hatch = (h: HatchRender | undefined): number => { if (!h) return -1; let i = hatchIdx.get(h); if (i === undefined) { i = hatchIdx.size; - writeHatch(hatchW, h, color(h.color)); + hatchW.push(lean ? -1 : str(JSON.stringify(h))); + writeHatch(hatchW, h, str(h.color)); hatchIdx.set(h, i); } return i; }; - const style = (greyed: boolean | undefined, opacity: number | undefined): number => - (greyed ? FLAG_GREYED : 0) | (opacity !== undefined ? FLAG_OPACITY : 0); + const offsets = new Float64Array(prims.length); + const w = new F64Writer(Math.max(256, prims.length * 14)); + const pool = new F64Writer(Math.max(256, prims.length * 4)); + const poolList = (l: readonly number[]): void => { + w.push(pool.length); + w.push(l.length); + const o = pool.reserve(l.length); + for (let i = 0; i < l.length; i++) pool.buf[o + i] = l[i]; + }; + const poolPts = (p: readonly Vec2[]): void => { + w.push(pool.length); + w.push(p.length); + const o = pool.reserve(2 * p.length); + const b = pool.buf; + for (let i = 0; i < p.length; i++) { + b[o + 2 * i] = p[i].x; + b[o + 2 * i + 1] = p[i].y; + } + }; + const styleFlags = (greyed: boolean | undefined, opacity: number | undefined): number => + (greyed === undefined ? 0 : greyed ? F_GREYED_SET | F_GREYED : F_GREYED_SET) | (opacity !== undefined ? F_OPACITY : 0); + const dashFlags = (d: number[] | null | undefined): number => (d === null ? F_DASH_NULL : d ? F_DASH_LIST : 0); const op = (opacity: number | undefined): number => (opacity !== undefined ? opacity : 1); + /** Kopf [tag, flags, pickKind, pickStr]; liefert die weiteren Ids. */ + const head = (tag: number, flags: number, p: Primitive): number[] | null => { + let pk = 0; + let ps = -1; + let more: number[] | null = null; + if (!lean) { + const r = p as Partial>; + for (let k = 0; k < PICK_KEYS.length; k++) { + const id = r[PICK_KEYS[k]]; + if (id === undefined) continue; + if (pk === 0) { + pk = k + 1; + ps = str(id); + } else (more ??= []).push(k + 1, str(id)); + } + } + const o = w.reserve(4); + const b = w.buf; + b[o] = tag; + b[o + 1] = flags | (more ? F_IDS : 0); + b[o + 2] = pk; + b[o + 3] = ps; + return more; + }; + const tail = (more: number[] | null): void => { + if (!more) return; + w.push(pool.length); + w.push(more.length / 2); + for (const v of more) pool.push(v); + }; - const w = new F64Writer(); for (let i = 0; i < prims.length; i++) { const p = prims[i]; + offsets[i] = w.length; switch (p.kind) { case "polygon": { - const fill = color(p.fill); - const stroke = color(p.stroke); + const more = head(1, styleFlags(p.greyed, p.opacity) | (p.noStrokeEdges ? F_NSE : 0), p); + const fill = str(p.fill); + const stroke = str(p.stroke); const h = hatch(p.hatch); - const o = w.reserve(7); + const o = w.reserve(5); const b = w.buf; - b[o] = 1; - b[o + 1] = style(p.greyed, p.opacity); - b[o + 2] = fill; - b[o + 3] = stroke; - b[o + 4] = p.strokeWidthMm; - b[o + 5] = h; - b[o + 6] = op(p.opacity); - w.pts(p.pts); - w.list(p.noStrokeEdges); + b[o] = fill; + b[o + 1] = stroke; + b[o + 2] = p.strokeWidthMm; + b[o + 3] = h; + b[o + 4] = op(p.opacity); + poolPts(p.pts); + if (p.noStrokeEdges) poolList(p.noStrokeEdges); + tail(more); break; } case "line": { - let flags = style(p.greyed, p.opacity); - if (isPlainLine(p) && chainsPrev(prims[i - 1], p)) flags |= FLAG_CHAIN; - if (p.zigzag) flags |= FLAG_ZIGZAG; - if (p.motif) flags |= FLAG_MOTIF; - const c = color(p.color); - const o = w.reserve(9); + let flags = styleFlags(p.greyed, p.opacity) | dashFlags(p.dash); + if (isPlainLine(p) && chainsPrev(prims[i - 1], p)) flags |= F_CHAIN; + if (p.zigzag) flags |= F_ZIGZAG; + if (p.motif) flags |= F_MOTIF; + if (p.color !== undefined) flags |= F_COLOR; + const more = head(2, flags, p); + const cls = lean ? -1 : str(p.cls); + const c = str(p.color); + const o = w.reserve(8); const b = w.buf; - b[o] = 2; - b[o + 1] = flags; - b[o + 2] = c; - b[o + 3] = p.weightMm; - b[o + 4] = op(p.opacity); - b[o + 5] = p.a.x; - b[o + 6] = p.a.y; - b[o + 7] = p.b.x; - b[o + 8] = p.b.y; - w.list(p.dash); + b[o] = cls; + b[o + 1] = c; + b[o + 2] = p.weightMm; + b[o + 3] = op(p.opacity); + b[o + 4] = p.a.x; + b[o + 5] = p.a.y; + b[o + 6] = p.b.x; + b[o + 7] = p.b.y; + if (p.dash) poolList(p.dash); if (p.zigzag) { w.push(p.zigzag.amplitude); w.push(p.zigzag.wavelength); } if (p.motif) { w.push(p.motif.length); - w.pts(p.motif.points); + poolPts(p.motif.points); } + tail(more); break; } case "arc": { - const c = color((p as { color?: string }).color); - const o = w.reserve(12); + const color = (p as { color?: string }).color; + const more = head(3, styleFlags(p.greyed, p.opacity) | dashFlags(p.dash) | (color !== undefined ? F_COLOR : 0), p); + const cls = lean ? -1 : str(p.cls); + const c = str(color); + const o = w.reserve(11); const b = w.buf; - b[o] = 3; - b[o + 1] = style(p.greyed, p.opacity); - b[o + 2] = c; - b[o + 3] = p.weightMm; - b[o + 4] = op(p.opacity); - b[o + 5] = p.center.x; - b[o + 6] = p.center.y; - b[o + 7] = p.from.x; - b[o + 8] = p.from.y; - b[o + 9] = p.to.x; - b[o + 10] = p.to.y; - b[o + 11] = p.r; - w.list(p.dash); + b[o] = cls; + b[o + 1] = c; + b[o + 2] = p.weightMm; + b[o + 3] = op(p.opacity); + b[o + 4] = p.center.x; + b[o + 5] = p.center.y; + b[o + 6] = p.from.x; + b[o + 7] = p.from.y; + b[o + 8] = p.to.x; + b[o + 9] = p.to.y; + b[o + 10] = p.r; + if (p.dash) poolList(p.dash); + tail(more); break; } case "drawingCircle": { - const fill = color(p.fill); - const stroke = color(p.stroke); - const o = w.reserve(9); + const more = head(4, styleFlags(p.greyed, p.opacity) | dashFlags(p.dash), p); + const fill = str(p.fill); + const stroke = str(p.stroke); + const o = w.reserve(7); const b = w.buf; - b[o] = 4; - b[o + 1] = style(p.greyed, p.opacity); - b[o + 2] = fill; - b[o + 3] = stroke; - b[o + 4] = p.weightMm; - b[o + 5] = op(p.opacity); - b[o + 6] = p.center.x; - b[o + 7] = p.center.y; - b[o + 8] = p.r; - w.list(p.dash); + b[o] = fill; + b[o + 1] = stroke; + b[o + 2] = p.weightMm; + b[o + 3] = op(p.opacity); + b[o + 4] = p.center.x; + b[o + 5] = p.center.y; + b[o + 6] = p.r; + if (p.dash) poolList(p.dash); + tail(more); break; } case "drawingArc": { - const stroke = color(p.stroke); - const o = w.reserve(10); + const more = head(5, styleFlags(p.greyed, p.opacity) | dashFlags(p.dash), p); + const stroke = str(p.stroke); + const o = w.reserve(8); const b = w.buf; - b[o] = 5; - b[o + 1] = style(p.greyed, p.opacity); - b[o + 2] = stroke; - b[o + 3] = p.weightMm; - b[o + 4] = op(p.opacity); - b[o + 5] = p.center.x; - b[o + 6] = p.center.y; - b[o + 7] = p.r; - b[o + 8] = p.a0; - b[o + 9] = p.a1; - w.list(p.dash); + b[o] = stroke; + b[o + 1] = p.weightMm; + b[o + 2] = op(p.opacity); + b[o + 3] = p.center.x; + b[o + 4] = p.center.y; + b[o + 5] = p.r; + b[o + 6] = p.a0; + b[o + 7] = p.a1; + if (p.dash) poolList(p.dash); + tail(more); break; } - default: - // Text, Bild …: Platzhalter, damit Indizes/Bereiche gleich bleiben. - w.push(0); + default: { + if (lean) { + head(0, 0, p); + break; + } + 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))); + } } } - const head = 5 + colors.length * 4; - const out = new Float64Array(head + hatchW.length + w.length); - out[0] = PLAN_BUF_MAGIC; - out[1] = PLAN_BUF_VERSION; - out[2] = colors.length; - out[3] = hatchIdx.size; - out[4] = prims.length; - for (let i = 0; i < colors.length; i++) out.set(colors[i], 5 + i * 4); - out.set(hatchW.buf.subarray(0, hatchW.length), head); - out.set(w.buf.subarray(0, w.length), head + hatchW.length); - return out; + const groups = opts.groups ?? []; + const nStrings = strTab.length >> 1; + const nF64 = HEAD + strTab.length + hatchW.length + 2 * groups.length + prims.length + w.length + pool.length; + const out = new ArrayBuffer(nF64 * 8 + units * 2); + const f = new Float64Array(out, 0, nF64); + const bounds = opts.bounds; + f.set([ + PLAN_BUF_MAGIC, + PLAN_BUF_VERSION, + bounds ? 2 : 0, + nStrings, + hatchIdx.size, + hatchW.length, + groups.length, + prims.length, + w.length, + pool.length, + units, + 0, + bounds ? bounds[0] : 0, + bounds ? bounds[1] : 0, + bounds ? bounds[2] : 0, + bounds ? bounds[3] : 0, + ]); + let k = HEAD; + f.set(strTab.buf.subarray(0, strTab.length), k); + k += strTab.length; + f.set(hatchW.buf.subarray(0, hatchW.length), k); + k += hatchW.length; + for (const [a, b] of groups) { + f[k++] = a; + f[k++] = b; + } + f.set(offsets, k); + k += prims.length; + f.set(w.buf.subarray(0, w.length), k); + k += w.length; + f.set(pool.buf.subarray(0, pool.length), k); + if (units > 0) { + const u = new Uint16Array(out, nF64 * 8, units); + let j = 0; + for (const s of strParts) for (let c = 0; c < s.length; c++) u[j++] = s.charCodeAt(c); + } + return new Uint8Array(out); +} + +/** Gelesener Plan-Puffer (Kern-Ergebnis); `bytes` bleibt für die GPU-Kompilierung erhalten. */ +export interface DecodedPlanBuf { + bytes: Uint8Array; + prims: Primitive[]; + groups: Array<[number, number]>; + bounds?: [number, number, number, number]; + /** Inhalts-Hash je Primitiv (vom Kern; Schlüssel des GPU-Chunk-Caches) oder null. */ + hashes: Float64Array | null; + /** Nummer des im Kern gehaltenen Puffers (0 = keiner), s. `compilePlanBufRange`. */ + hold: number; +} + +/** UTF-16-Einheiten → ein String (exakt, auch einzelne Surrogate). */ +function unitsToString(u: Uint16Array): string { + let s = ""; + for (let i = 0; i < u.length; i += 8192) { + s += String.fromCharCode.apply(null, u.subarray(i, Math.min(u.length, i + 8192)) as unknown as number[]); + } + return s; +} + +function bad(why: string): never { + throw new Error(`Plan-Puffer unlesbar: ${why}`); +} + +/** + * Plan-Puffer → Primitive (in der JSON-Form, die der Kern früher lieferte: gleiche Felder, gleiche + * Reihenfolge). Wirft bei einem Fehlerpuffer des Kerns (mit dessen Meldung) oder kaputtem Puffer. + */ +export function decodePlanBuf(input: Uint8Array): DecodedPlanBuf { + const bytes = input.byteOffset % 8 === 0 ? input : input.slice(); + if (bytes.byteLength >= 16) { + const h = new Float64Array(bytes.buffer, bytes.byteOffset, 2); + if (h[0] === PLAN_BUF_ERR_MAGIC) { + const n = h[1]; + throw new Error(unitsToString(new Uint16Array(bytes.buffer, bytes.byteOffset + 16, Math.min(n, (bytes.byteLength - 16) >> 1)))); + } + } + if (bytes.byteLength < HEAD * 8) bad("zu kurz"); + const hd = new Float64Array(bytes.buffer, bytes.byteOffset, HEAD); + if (hd[0] !== PLAN_BUF_MAGIC || hd[1] !== PLAN_BUF_VERSION) bad("fremde Version"); + const [, , flags, nStrings, nHatches, nHatchWords, nGroups, nPrims, nRec, nPool, nUnits] = hd; + const hashes = (flags & 1) !== 0; + const strAt = HEAD; + const hatchAt = strAt + 2 * nStrings; + const groupAt = hatchAt + nHatchWords; + const offAt = groupAt + 2 * nGroups; + const hashAt = offAt + nPrims; + const recAt = hashAt + (hashes ? nPrims : 0); + const poolAt = recAt + nRec; + const nF64 = poolAt + nPool; + if (!Number.isInteger(nF64) || bytes.byteLength !== nF64 * 8 + nUnits * 2) bad("Länge"); + const f = new Float64Array(bytes.buffer, bytes.byteOffset, nF64); + const all = unitsToString(new Uint16Array(bytes.buffer, bytes.byteOffset + nF64 * 8, nUnits)); + const strs: Array = new Array(nStrings); + const S = (i: number): string => { + let s = strs[i]; + if (s === undefined) { + const o = f[strAt + 2 * i]; + s = all.slice(o, o + f[strAt + 2 * i + 1]); + strs[i] = s; + } + return s; + }; + // Schraffuren: einmal je Eintrag aus dem JSON (geteilt von allen Polygonen). + const hatchList: HatchRender[] = []; + let k = hatchAt; + for (let i = 0; i < nHatches; i++) { + // [jsonStr, pattern, kind, flags, scale, angle, color, lineWeight, ox, oy, seed, density, + // lengthMin, lengthMax, nDash, dash…, (Motiv: length, nPts, x,y…)] + const js = f[k]; + hatchList.push(js >= 0 ? (JSON.parse(S(js)) as HatchRender) : (undefined as unknown as HatchRender)); + const hf = f[k + 3]; + k += 15 + f[k + 14]; + if (hf & 64) k += 2 + 2 * f[k + 1]; + if (!(k <= groupAt)) bad("Schraffuren"); + } + if (k !== groupAt) bad("Schraffuren"); + const groups: Array<[number, number]> = []; + for (let g = 0; g < nGroups; g++) groups.push([f[groupAt + 2 * g], f[groupAt + 2 * g + 1]]); + const pts = (o: number, n: number): Vec2[] => { + const out: Vec2[] = new Array(n); + const b = poolAt + o; + for (let i = 0; i < n; i++) out[i] = { x: f[b + 2 * i], y: f[b + 2 * i + 1] }; + return out; + }; + const list = (o: number, n: number): number[] => { + const out: number[] = new Array(n); + const b = poolAt + o; + for (let i = 0; i < n; i++) out[i] = f[b + i]; + return out; + }; + /** Pick-Ids in Art-Reihenfolge (= Feldreihenfolge der Kern-JSON-Form). */ + const setIds = (o: Record, pk: number, ps: number, fl: number, tailAt: number): void => { + if (!(fl & F_IDS)) { + o[PICK_KEYS[pk - 1]] = S(ps); + return; + } + const found: Array<[number, string]> = [[pk, S(ps)]]; + const po = poolAt + f[tailAt]; + const n = f[tailAt + 1]; + for (let j = 0; j < n; j++) found.push([f[po + 2 * j], S(f[po + 2 * j + 1])]); + found.sort((a, b) => a[0] - b[0]); + for (const [kk, id] of found) o[PICK_KEYS[kk - 1]] = id; + }; + const prims: Primitive[] = new Array(nPrims); + for (let i = 0; i < nPrims; i++) { + let r = recAt + f[offAt + i]; + const tag = f[r]; + const fl = f[r + 1]; + const pk = f[r + 2]; + const ps = f[r + 3]; + r += 4; + let o: Record; + switch (tag) { + case 1: { + o = { kind: "polygon", pts: pts(f[r + 5], f[r + 6]), fill: S(f[r]), stroke: S(f[r + 1]), strokeWidthMm: f[r + 2] }; + if (f[r + 3] >= 0) o.hatch = hatchList[f[r + 3]]; + if (fl & F_GREYED_SET) o.greyed = (fl & F_GREYED) !== 0; + if (fl & F_OPACITY) o.opacity = f[r + 4]; + let t = r + 7; + if (fl & F_NSE) { + o.noStrokeEdges = list(f[t], f[t + 1]); + t += 2; + } + if (pk > 0 || fl & F_IDS) setIds(o, pk, ps, fl, t); + break; + } + case 2: { + o = { kind: "line", a: { x: f[r + 4], y: f[r + 5] }, b: { x: f[r + 6], y: f[r + 7] }, cls: S(f[r]), weightMm: f[r + 2] }; + let t = r + 8; + if (fl & F_DASH_NULL) o.dash = null; + else if (fl & F_DASH_LIST) { + o.dash = list(f[t], f[t + 1]); + t += 2; + } + if (fl & F_ZIGZAG) { + o.zigzag = { amplitude: f[t], wavelength: f[t + 1] }; + t += 2; + } + if (fl & F_MOTIF) { + o.motif = { points: pts(f[t + 1], f[t + 2]), length: f[t] }; + t += 3; + } + if (fl & F_COLOR) o.color = S(f[r + 1]); + if (pk > 0 || fl & F_IDS) setIds(o, pk, ps, fl, t); + if (fl & F_GREYED_SET) o.greyed = (fl & F_GREYED) !== 0; + if (fl & F_OPACITY) o.opacity = f[r + 3]; + break; + } + case 3: { + o = { + kind: "arc", + center: { x: f[r + 4], y: f[r + 5] }, + from: { x: f[r + 6], y: f[r + 7] }, + to: { x: f[r + 8], y: f[r + 9] }, + r: f[r + 10], + cls: S(f[r]), + weightMm: f[r + 2], + }; + let t = r + 11; + if (fl & F_DASH_NULL) o.dash = null; + else if (fl & F_DASH_LIST) { + o.dash = list(f[t], f[t + 1]); + t += 2; + } + if (fl & F_COLOR) o.color = S(f[r + 1]); + if (pk > 0 || fl & F_IDS) setIds(o, pk, ps, fl, t); + if (fl & F_GREYED_SET) o.greyed = (fl & F_GREYED) !== 0; + if (fl & F_OPACITY) o.opacity = f[r + 3]; + break; + } + case 4: { + o = { kind: "drawingCircle", center: { x: f[r + 4], y: f[r + 5] }, r: f[r + 6], fill: S(f[r]), stroke: S(f[r + 1]), weightMm: f[r + 2] }; + let t = r + 7; + if (fl & F_DASH_NULL) o.dash = null; + else if (fl & F_DASH_LIST) { + o.dash = list(f[t], f[t + 1]); + t += 2; + } + if (pk > 0 || fl & F_IDS) setIds(o, pk, ps, fl, t); + if (fl & F_GREYED_SET) o.greyed = (fl & F_GREYED) !== 0; + if (fl & F_OPACITY) o.opacity = f[r + 3]; + break; + } + case 5: { + o = { kind: "drawingArc", center: { x: f[r + 3], y: f[r + 4] }, r: f[r + 5], a0: f[r + 6], a1: f[r + 7], stroke: S(f[r]), weightMm: f[r + 1] }; + let t = r + 8; + if (fl & F_DASH_NULL) o.dash = null; + else if (fl & F_DASH_LIST) { + o.dash = list(f[t], f[t + 1]); + t += 2; + } + if (pk > 0 || fl & F_IDS) setIds(o, pk, ps, fl, t); + if (fl & F_GREYED_SET) o.greyed = (fl & F_GREYED) !== 0; + if (fl & F_OPACITY) o.opacity = f[r + 2]; + break; + } + case 6: + case 7: + case 8: + case 9: + o = JSON.parse(S(f[r])) as Record; + break; + default: + bad(`Primitiv-Typ ${tag}`); + } + prims[i] = o as unknown as Primitive; + } + return { + bytes, + prims, + groups, + bounds: flags & 2 ? [hd[12], hd[13], hd[14], hd[15]] : undefined, + hashes: hashes ? new Float64Array(bytes.buffer, bytes.byteOffset + hashAt * 8, nPrims) : null, + hold: 0, + }; } From e2210201b72dd980dda61f9846866e5c3bee9bfa Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 21:57:13 +0000 Subject: [PATCH 2/4] [K3d][K4] planDomains liefert den Plan-Puffer v2 statt JSON MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Abfrage über doc_query_bin/queries::run_bin (plan_domains_buf: neun Gruppen, Ausmass, Hashes); generatePlan liest den Puffer (decodePlanBuf) und merkt sich die Kern-Abschnitte als Plan.bufRuns (über Abzugskörper, Geschoss-Überlagerung und kompakte Unterlage nachgeführt). Grosses Projekt (Beispielhaus 20x20) generatePlan 386 → 171 ms, Beispiel-EG 0,63 → 0,32 ms. Primitive-JSON nach Dekodierung gleich zum alten planDomains (Beispiel, 120 Zufallsprojekte, grosses Projekt), CLI-SVG byte-gleich. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src-tauri/core/src/plan/domains.rs | 73 ++++++++++++++- src-tauri/core/src/queries.rs | 9 +- src-tauri/core/src/web/document.rs | 12 +++ src/core/document.ts | 9 ++ src/plan/bigSampleProject.testing.ts | 56 +++++++++++ src/plan/generatePlan.bufRuns.test.ts | 68 ++++++++++++++ src/plan/generatePlan.ts | 129 +++++++++++++++++++------- src/plan/voids.ts | 8 +- 8 files changed, 321 insertions(+), 43 deletions(-) create mode 100644 src/plan/bigSampleProject.testing.ts create mode 100644 src/plan/generatePlan.bufRuns.test.ts diff --git a/src-tauri/core/src/plan/domains.rs b/src-tauri/core/src/plan/domains.rs index 6b2131fd..fa0187f7 100644 --- a/src-tauri/core/src/plan/domains.rs +++ b/src-tauri/core/src/plan/domains.rs @@ -13,7 +13,6 @@ use crate::js_fmt::{js_number, to_fixed}; use crate::jsnum::{max, min, round}; use crate::model::*; use crate::plan_walls::{ceiling_outline_lines, wall_footprint, WallFootprint}; -use serde::Serialize; use std::collections::{HashMap, HashSet}; /// Footprint-Farbe der Extrusionen (wie das 3D-Orange). @@ -96,9 +95,10 @@ impl<'a> Ctx<'a> { } } -/// Ergebnis der Abfrage `planDomains`: Primitive je Domäne (TS setzt sie an ihre Stelle in der -/// Zeichenreihenfolge) und das Ausmass der Decken, Räume und Dach-Traufen. -#[derive(Serialize, Default)] +/// Ergebnis der Plan-Erzeugung: Primitive je Domäne (TS setzt sie an ihre Stelle in der +/// Zeichenreihenfolge) und das Ausmass der Decken, Räume und Dach-Traufen. Über die Grenze geht es +/// als Plan-Puffer v2 ([`plan_domains_buf`]). +#[derive(Default)] pub struct DomainPrims { pub ceilings: Vec, /// Wände (Poché, Referenzlinie) mit ihren Öffnungs-Symbolen, je Wand nacheinander. @@ -517,6 +517,21 @@ pub fn plan_domains(p: &Project, a: &PlanArgs) -> Result { Ok(out) } +/// Reihenfolge der Gruppen im Plan-Puffer der Abfrage `planDomains`. +pub const GROUPS: [&str; 9] = ["ceilings", "roofs", "rooms", "walls", "stairs", "columns", "solids", "context", "sections"]; + +/// Abfrage `planDomains` als Plan-Puffer v2 (s. `plan_buf.rs`): eine Gruppe je Domäne in der +/// Reihenfolge [`GROUPS`], Ausmass im Kopf, Inhalts-Hashes für den GPU-Chunk-Cache. +pub fn plan_domains_buf(p: &Project, a: &PlanArgs) -> Result, String> { + let d = plan_domains(p, a)?; + let mut w = crate::plan_buf::Writer::new(true); + for g in [&d.ceilings, &d.roofs, &d.rooms, &d.walls, &d.stairs, &d.columns, &d.solids, &d.context, &d.sections] { + w.group(g); + } + w.bounds = d.bounds; + Ok(w.finish()) +} + #[cfg(test)] mod tests { use super::*; @@ -545,6 +560,22 @@ mod tests { assert!(r.bounds.is_some()); } + #[test] + fn puffer_gruppen_wie_domaenen() { + let p = sample(); + let a = args("eg", 1.0, &["20", "21", "30", "40", "60"]); + let d = plan_domains(&p, &a).unwrap(); + let buf = plan_domains_buf(&p, &a).unwrap(); + let (prims, groups, bounds) = crate::plan_buf::decode(&buf).unwrap(); + assert_eq!(groups.len(), GROUPS.len()); + let lists = [&d.ceilings, &d.roofs, &d.rooms, &d.walls, &d.stairs, &d.columns, &d.solids, &d.context, &d.sections]; + for ((a, b), l) in groups.iter().zip(lists) { + assert_eq!(serde_json::to_string(&prims[*a..*b]).unwrap(), serde_json::to_string(l).unwrap()); + } + assert!(!d.walls.is_empty() && !d.rooms.is_empty()); + assert_eq!(bounds, d.bounds); + } + #[test] fn unsichtbare_codes_fehlen() { let p = sample(); @@ -605,4 +636,38 @@ mod tests { let col = Column { profile: ColumnProfile::Round { radius: 0.125 }, ..Default::default() }; assert_eq!(column_label(&col), "Stütze Ø25"); } + + /// Messung (von Hand): `PLAN_BIG=projekt.obp cargo test --release --lib messung_plan_puffer -- --ignored --nocapture`. + #[test] + #[ignore] + fn messung_plan_puffer() { + let Ok(path) = std::env::var("PLAN_BIG") else { return }; + let mut doc = crate::document::Document::from_json(&std::fs::read_to_string(path).unwrap()).unwrap(); + let p = doc.project().unwrap().clone(); + let codes: Vec = p.flat_categories().iter().map(|c| c.code.clone()).collect(); + let t = serde_json::json!({ "floor": "eg", "show": codes, "grey": [], "global": true }).to_string(); + let a = PlanArgs::parse(1.0, &t).unwrap(); + let time = |name: &str, f: &mut dyn FnMut()| { + f(); + let t0 = std::time::Instant::now(); + for _ in 0..5 { + f(); + } + println!("{name}: {:.1} ms", t0.elapsed().as_secs_f64() * 1000.0 / 5.0); + }; + time("plan_domains", &mut || { + plan_domains(&p, &a).unwrap(); + }); + let d = plan_domains(&p, &a).unwrap(); + time("Puffer schreiben", &mut || { + let mut w = crate::plan_buf::Writer::new(true); + for g in [&d.ceilings, &d.roofs, &d.rooms, &d.walls, &d.stairs, &d.columns, &d.solids, &d.context, &d.sections] { + w.group(g); + } + w.finish(); + }); + time("JSON (früher)", &mut || { + serde_json::to_string(&(&d.ceilings, &d.roofs, &d.rooms, &d.walls, &d.stairs, &d.columns, &d.solids, &d.context, &d.sections)).unwrap(); + }); + } } diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs index 00ca4cd4..65e9229c 100644 --- a/src-tauri/core/src/queries.rs +++ b/src-tauri/core/src/queries.rs @@ -34,8 +34,15 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result json(&export_schedule::schedule_rows(p)), ("scheduleCsv", 1) => Ok(export_schedule::export_schedule_csv(p, text, args[0] != 0.0)), ("pickGeometry", _) => json(&model3d::pick_geometry(p)?), - ("planDomains", 1) => json(&crate::plan::domains::plan_domains(p, &crate::plan::domains::PlanArgs::parse(args[0], text)?)?), ("model3dParts", 3) => json(&model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?), _ => Err(format!("Unbekannte Abfrage: {name}")), } } + +/// Abfragen mit binärer Antwort (Plan-Puffer v2, s. `plan_buf.rs`). +pub fn run_bin(p: &Project, name: &str, args: &[f64], text: &str) -> Result, String> { + match (name, args.len()) { + ("planDomains", 1) => crate::plan::domains::plan_domains_buf(p, &crate::plan::domains::PlanArgs::parse(args[0], text)?), + _ => Err(format!("Unbekannte Abfrage: {name}")), + } +} diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index 49f5a268..4c132a69 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -177,3 +177,15 @@ pub fn doc_drawing_line_verts(h: u32) -> Vec { pub fn doc_serialize(h: u32) -> String { with_doc(h, |d| d.serialize()).unwrap_or_default() } + +/// Abfrage mit binärer Antwort (`crate::queries::run_bin`, z. B. `planDomains` als Plan-Puffer v2). +/// Fehler kommen als Fehlerpuffer (`plan_buf::encode_error`). +#[wasm_bindgen] +pub fn doc_query_bin(h: u32, name: &str, args: &[f64], text: &str) -> Vec { + let result = with_doc(h, |d| { + let p = d.project().map_err(|e| format!("Projekt passt nicht zum Kern-Modell: {e}"))?; + crate::queries::run_bin(&p, name, args, text) + }) + .unwrap_or_else(|| Err("Dokument nicht offen".to_string())); + result.unwrap_or_else(|e| crate::plan_buf::encode_error(&e)) +} diff --git a/src/core/document.ts b/src/core/document.ts index 5348a77e..50e94338 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -92,6 +92,15 @@ export class ProjectDocument { return out; } + /** + * Abfrage mit binärer Antwort (`queries.rs::run_bin`, z. B. `planDomains` als Plan-Puffer v2, + * s. `plan/planBuf.ts`). Fehler kommen als Fehlerpuffer (`decodePlanBuf` wirft die Meldung). + */ + queryBin(name: QueryName, args: number[] = [], text = ""): Uint8Array { + if (!this.handle) throw new Error(`Kern-Abfrage „${name}": Dokument nicht offen`); + return core().doc_query_bin(this.handle, name, Float64Array.from(args), text); + } + /** Datei-Text des Projekts (Formatversion vorn, Einrückung 2). */ serialize(): string { return this.handle ? core().doc_serialize(this.handle) : ""; diff --git a/src/plan/bigSampleProject.testing.ts b/src/plan/bigSampleProject.testing.ts new file mode 100644 index 00000000..8e7596d3 --- /dev/null +++ b/src/plan/bigSampleProject.testing.ts @@ -0,0 +1,56 @@ +// Testhilfe ([K3d]): grosses Projekt für Messungen — das Beispielhaus n × n Mal gekachelt +// (n = 20: 3600 Wände, 1200 Öffnungen, 400 Decken/Räume/Treppen/Dächer, 1600 Stützen). +// Ids bekommen ein Kachel-Suffix, Verweise (Öffnung → Wand) werden mitgeführt. + +import type { Column, Project, Vec2 } from "../model/types"; +import { sampleProject } from "../model/sampleProject"; + +const shift = (p: Vec2, dx: number, dy: number): Vec2 => ({ x: p.x + dx, y: p.y + dy }); + +export function bigSampleProject(n = 20, pitch = 8): Project { + const s = sampleProject; + const out: Project = { + ...s, + walls: [], + openings: [], + ceilings: [], + roofs: [], + stairs: [], + rooms: [], + columns: [], + }; + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + const dx = i * pitch; + const dy = j * pitch; + const sfx = `_${i}_${j}`; + for (const w of s.walls) out.walls.push({ ...w, id: w.id + sfx, start: shift(w.start, dx, dy), end: shift(w.end, dx, dy) }); + for (const o of s.openings ?? []) out.openings!.push({ ...o, id: o.id + sfx, hostWallId: o.hostWallId + sfx }); + for (const c of s.ceilings ?? []) out.ceilings!.push({ ...c, id: c.id + sfx, outline: c.outline.map((p) => shift(p, dx, dy)) }); + for (const r of s.roofs ?? []) out.roofs!.push({ ...r, id: r.id + sfx, outline: r.outline.map((p) => shift(p, dx, dy)) }); + for (const st of s.stairs ?? []) out.stairs!.push({ ...st, id: st.id + sfx, start: shift(st.start, dx, dy) }); + for (const r of s.rooms ?? []) { + out.rooms!.push({ + ...r, + id: r.id + sfx, + boundary: r.boundary.map((p) => shift(p, dx, dy)), + ...(r.stampAnchor ? { stampAnchor: shift(r.stampAnchor, dx, dy) } : {}), + }); + } + for (let k = 0; k < 4; k++) { + const col: Column = { + id: `COL${k}${sfx}`, + type: "column", + floorId: "eg", + categoryCode: "50", + position: { x: dx + 1 + k, y: dy + 2 }, + profile: k % 2 ? { kind: "round", radius: 0.12 } : { kind: "rect", width: 0.25, depth: 0.25 }, + rotation: k * 0.3, + height: 2.6, + }; + out.columns!.push(col); + } + } + } + return out; +} diff --git a/src/plan/generatePlan.bufRuns.test.ts b/src/plan/generatePlan.bufRuns.test.ts new file mode 100644 index 00000000..97a405ec --- /dev/null +++ b/src/plan/generatePlan.bufRuns.test.ts @@ -0,0 +1,68 @@ +// Kern-Abschnitte im Plan ([K3d], Plan-Puffer v2): `Plan.bufRuns` zeigt auf unveränderte Primitive +// aus dem Puffer des Kerns — auch nach Abzugskörpern, beim Überlagern mehrerer Geschosse und mit +// der kompakten Unterlage; Mono und Strichstärken-Massstab lassen sie weg. + +import { describe, expect, it } from "vitest"; +import { generatePlan, generateVisibleLevelsPlan, materializeUnderlay } from "./generatePlan"; +import type { Plan } from "./generatePlan"; +import { sampleProject } from "../model/sampleProject"; +import { flattenCategories } from "../model/types"; +import type { ExtrudedSolid, Project } from "../model/types"; + +const codes = (p: Project) => new Set(flattenCategories(p.layers).map((c) => c.code)); + +/** Jede Stelle eines Abschnitts trägt genau das Objekt aus dem Puffer. */ +function checkRuns(plan: Plan): number { + let n = 0; + for (const r of plan.bufRuns ?? []) { + expect(r.to).toBeGreaterThan(r.from); + for (let k = 0; k < r.to - r.from; k++) expect(plan.primitives[r.at + k]).toBe(r.buf.prims[r.from + k]); + n += r.to - r.from; + } + return n; +} + +describe("Plan.bufRuns", () => { + it("Beispiel-EG: zwei Abschnitte, alle Kern-Primitive abgedeckt", () => { + const plan = generatePlan(sampleProject, "eg", codes(sampleProject)); + expect(plan.bufRuns?.length).toBe(2); + const covered = checkRuns(plan); + expect(covered).toBe(plan.bufRuns![0].buf.prims.length); + }); + + it("Abzugskörper zerlegen Polygone: Abschnitte werden neu ausgerichtet", () => { + const solid: ExtrudedSolid = { + id: "void1", + type: "extrudedSolid", + levelId: "eg", + operation: "subtract", + height: 3, + points: [ + { x: 1, y: -0.5 }, + { x: 1.4, y: -0.5 }, + { x: 1.4, y: 0.5 }, + { x: 1, y: 0.5 }, + ], + } as ExtrudedSolid; + const p: Project = { ...sampleProject, extrudedSolids: [solid] }; + const plan = generatePlan(p, "eg", codes(p)); + const total = plan.bufRuns![0].buf.prims.length; + const covered = checkRuns(plan); + expect(covered).toBeGreaterThan(total / 2); + expect(covered).toBeLessThan(total); + }); + + it("Überlagerung mehrerer Geschosse und kompakte Unterlage verschieben die Abschnitte mit", () => { + const plan = generateVisibleLevelsPlan(sampleProject, "og", codes(sampleProject), undefined, "mittel", false, false, undefined, 100, true); + expect((plan.bufRuns ?? []).length).toBeGreaterThanOrEqual(3); + checkRuns(plan); + checkRuns(materializeUnderlay(plan)); + }); + + it("Mono und Strichstärken-Massstab: keine Abschnitte", () => { + expect(generatePlan(sampleProject, "eg", codes(sampleProject), undefined, "mittel", false, true).bufRuns).toBeUndefined(); + const scaled: Project = { ...sampleProject, scaleLineWeights: true }; + expect(generatePlan(scaled, "eg", codes(scaled), undefined, "mittel", false, false, true, 50).bufRuns).toBeUndefined(); + expect(generatePlan(scaled, "eg", codes(scaled), undefined, "mittel", false, false, true, 100).bufRuns?.length).toBe(2); + }); +}); diff --git a/src/plan/generatePlan.ts b/src/plan/generatePlan.ts index 9c894e50..8b7bd202 100644 --- a/src/plan/generatePlan.ts +++ b/src/plan/generatePlan.ts @@ -36,6 +36,7 @@ import { getWallType, } from "../model/types"; import { documentFor } from "../core/document"; +import { decodePlanBuf, type DecodedPlanBuf } from "./planBuf"; import { effectiveOverrides, hasOverrides } from "../overrides/engine"; import type { SectionOutput } from "./toSection"; import { @@ -193,6 +194,26 @@ export interface Plan { * {@link materializeUnderlay}. */ underlay?: UnderlayGroup[]; + /** + * Abschnitte, die unverändert aus einem Plan-Puffer des Kerns stammen ([K3d]): der GPU-Pfad + * kompiliert sie direkt aus dem Puffer und erkennt Unverändertes am Inhalts-Hash + * (`glPlanChunks.ts`). Wer Primitive ersetzt oder verschiebt, muss nichts nachführen — der + * Verbraucher prüft die Objekt-Identität und fällt sonst auf die Objekte zurück. + */ + bufRuns?: PlanBufRun[]; +} + +/** `primitives[at + k]` ist (solange nicht ersetzt) `buf.prims[from + k]`, `k < to − from`. */ +export interface PlanBufRun { + at: number; + buf: DecodedPlanBuf; + from: number; + to: number; +} + +/** Kern-Abschnitte um `shift` verschieben (beim Zusammensetzen mehrerer Pläne). */ +function shiftRuns(runs: readonly PlanBufRun[] | undefined, shift: number, into: PlanBufRun[]): void { + for (const r of runs ?? []) into.push({ ...r, at: r.at + shift }); } /** @@ -244,11 +265,14 @@ export function materializeUnderlay(plan: Plan): Plan { ...shifted, ...aboveGreyed.map(([a, b]): [number, number] => [a + aboveShift, b + aboveShift]), ]; + const bufRuns: PlanBufRun[] = []; + shiftRuns(plan.bufRuns, below.length, bufRuns); return { ...plan, primitives, underlay: undefined, greyedRanges: ranges.length ? ranges : undefined, + bufRuns: bufRuns.length ? bufRuns : undefined, }; } @@ -385,20 +409,23 @@ export function generatePlan( // Kern auf dem Dokument ([K3d], `plan/{domains,walls,stairs}.rs`): Filter, Override-Regeln, // Verschneidung, Stil und Raumstempel-Daten. Decken, Dächer und Räume liegen unter der Wand-Poché; Stützen folgen // nach den Treppen, Extrusionen nach den 2D-Zeichnungen. + // Der Kern liefert alles in EINEM Plan-Puffer (Gruppen in dieser Reihenfolge); die Abschnitte + // merkt sich der Plan (`bufRuns`), damit die GPU sie direkt aus dem Puffer kompiliert. const dom = planDomains(project, floorId, visibleCodes, categoryDisplay, detail, showReferenceLines, includeGlobal); - for (const pr of dom.ceilings) primitives.push(pr); - for (const pr of dom.roofs) primitives.push(pr); - for (const pr of dom.rooms) primitives.push(pr); - - // Wände (Poché, Referenzlinie) mit ihren Öffnungs-Symbolen, je Wand nacheinander. - for (const pr of dom.walls) primitives.push(pr); - - // Treppen: Tritte + Lauflinie + Auf-/Abpfeil mit dem Grundriss-Schnitt (unter der Schnitthöhe - // durchgezogen, darüber gestrichelt + SIA-Bruchlinie), über der Wand-Poché. - for (const pr of dom.stairs) primitives.push(pr); - - // Stützen (Tragwerk): Querschnitt-Poché, über der Wand-Poché. - for (const pr of dom.columns) primitives.push(pr); + const runs: PlanBufRun[] = []; + const pushGroups = (first: number, last: number): void => { + if (!dom.buf) return; + const from = dom.buf.groups[first][0]; + const to = dom.buf.groups[last][1]; + const at = primitives.length; + const src = dom.buf.prims; + for (let i = from; i < to; i++) primitives.push(src[i]); + if (to > from) runs.push({ at, buf: dom.buf, from, to }); + }; + // Decken, Dächer, Räume; Wände (Poché, Referenzlinie) mit ihren Öffnungs-Symbolen, je Wand + // nacheinander; Treppen (Tritte + Lauflinie + Auf-/Abpfeil mit dem Grundriss-Schnitt, über der + // Wand-Poché); Stützen (Querschnitt-Poché). + pushGroups(G_CEILINGS, G_COLUMNS); // 2D-Zeichengeometrie zuletzt (über der Poché). const compact = compactUnderlay && !mono && !forPrint; @@ -439,22 +466,21 @@ export function generatePlan( for (const grp of underGroups.values()) underlay.push(mkGroup(grp.ds, grp.greyed)); // Extrudierte Körper: Footprint-Umriss (Quell-Profil wurde beim Extrudieren entfernt). - for (const pr of dom.solids) primitives.push(pr); - // Kontext-Konturen (Höhenlinien) als dezente Linien zeichnen — UNTER der // Wand-Poché wäre ideal, aber da sie eine eigene gedämpfte Farbe tragen, ist // die Reihenfolge unkritisch; wir hängen sie als Referenz an. Projektglobal // (nicht je Geschoss) → nur beim aktiven Aufruf einer Mehrfach-Überlagerung. - for (const pr of dom.context) primitives.push(pr); // Schnittführungs-Symbole aller Schnitt-/Ansichtsebenen mit Linie — ebenfalls projektglobal, // Sichtbarkeit über die Kategorie "90" (Referenzen). - for (const pr of dom.sections) primitives.push(pr); + pushGroups(G_SOLIDS, G_SECTIONS); // Schwarz-Weiss (mono): nachträglich alle Farben auf reine Tinte zwingen. // Element-/Kategorie-/Hatch-Farben werden ignoriert, Füllungen werden weiss, // Musterlinien/Striche schwarz — so entsteht ein reiner S/W-Plan. // Abzugskörper (Aussparungen/Durchbrüche): von Wand-/Stützen-/Decken-Poché abziehen. - subtractVoidsInPlan(primitives, project, (floor?.baseElevation ?? 0) + (floor?.cutHeight ?? 1.0)); + // Ersetzte Primitive erkennt der GPU-Pfad selbst (Identität); verschiebt das Zerlegen die + // Indizes, werden die Kern-Abschnitte neu ausgerichtet. + if (subtractVoidsInPlan(primitives, project, (floor?.baseElevation ?? 0) + (floor?.cutHeight ?? 1.0))) realignRuns(primitives, runs); // Baurechts-Verstösse über allem (Signal, soll nicht unter der Wand-Poché verschwinden). if (includeGlobal) addSiteViolations(primitives, project, floorId); @@ -488,14 +514,40 @@ export function generatePlan( ctx: [...g.ctx, lwf], build: (ds: Drawing2D[]) => g.build(ds).map((p) => scalePrimitiveWeights(p, lwf)), })); + // Mono färbt die Objekte um, der Massstab ersetzt sie: dann gilt der Puffer nicht mehr. + const keepRuns = !mono && lwf === 1 && runs.length > 0; return { primitives: lwf === 1 ? primitives : primitives.map((p) => scalePrimitiveWeights(p, lwf)), - bounds: computeBounds(project, drawings, dom.bounds, primitives.slice(0, underlayCount)), + bounds: computeBounds(project, drawings, dom.buf?.bounds, primitives.slice(0, underlayCount)), backgroundImages, ...(scaledUnderlay.length ? { underlay: scaledUnderlay } : {}), + ...(keepRuns ? { bufRuns: runs } : {}), }; } +/** + * Kern-Abschnitte nach einem Umbau der Liste (Abzugskörper zerlegen Polygone) neu ausrichten: + * jede noch vorhandene Folge unveränderter Puffer-Objekte wird ein eigener Abschnitt. + */ +function realignRuns(primitives: readonly Primitive[], runs: PlanBufRun[]): void { + if (runs.length === 0) return; + const where = new Map(); + for (const r of runs) for (let i = r.from; i < r.to; i++) where.set(r.buf.prims[i], [r, i]); + const out: PlanBufRun[] = []; + let cur: PlanBufRun | null = null; + for (let i = 0; i < primitives.length; i++) { + const w = where.get(primitives[i]); + if (w && cur && w[0].buf === cur.buf && w[1] === cur.to && i === cur.at + (cur.to - cur.from)) { + cur.to++; + continue; + } + cur = w ? { at: i, buf: w[0].buf, from: w[1], to: w[1] + 1 } : null; + if (cur) out.push(cur); + } + runs.length = 0; + for (const r of out) runs.push(r); +} + /** * Wie `generatePlan`, überlagert aber ZUSÄTZLICH alle sichtbaren Geschoss- * oder Zeichnungs-Ebenen DERSELBEN Art wie `activeLevelId` in EINEM Plan — @@ -544,6 +596,7 @@ export function generateVisibleLevelsPlan( const primitives: Primitive[] = []; const greyedRanges: Array<[number, number]> = []; const underlay: UnderlayGroup[] = []; + const bufRuns: PlanBufRun[] = []; const bounds = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }; const extend = (b: Plan["bounds"]) => { bounds.minX = Math.min(bounds.minX, b.minX); @@ -579,6 +632,7 @@ export function generateVisibleLevelsPlan( // `dwgParser.ts`. Reine `for`-Schleife ist unbegrenzt sicher. const from = primitives.length; for (const pr of p.primitives) primitives.push(pr); + shiftRuns(p.bufRuns, from, bufRuns); if (d.greyed && primitives.length > from) greyedRanges.push([from, primitives.length]); // Leere Ebenen melden als Platzhalter (0,0)–(1,1) — NICHT mitzählen: sonst zog // jede leere Nachbar-Ebene den Ausschnitt bis zum Ursprung (bei Landes- @@ -599,6 +653,7 @@ export function generateVisibleLevelsPlan( false, compactUnderlay, ); + shiftRuns(activePlan.bufRuns, primitives.length, bufRuns); for (const pr of activePlan.primitives) primitives.push(pr); for (const g of activePlan.underlay ?? []) underlay.push(g); // Aktive Ebene leer UND keine Nachbar-Ebene mit Inhalt → Platzhalter-Ausmass. @@ -610,6 +665,7 @@ export function generateVisibleLevelsPlan( backgroundImages: activePlan.backgroundImages, ...(greyedRanges.length ? { greyedRanges } : {}), ...(underlay.length ? { underlay } : {}), + ...(bufRuns.length ? { bufRuns } : {}), }; } @@ -863,21 +919,20 @@ function categoryMap(layers: LayerCategory[]): Map { return map; } -/** Primitive der Kern-Domänen (`planDomains` in `queries.rs`). */ +/** Primitive der Kern-Domänen (`planDomains` in `queries.rs`) als gelesener Plan-Puffer v2. */ interface DomainPrims { - ceilings: Primitive[]; - walls: Primitive[]; - stairs: Primitive[]; - context: Primitive[]; - sections: Primitive[]; - roofs: Primitive[]; - rooms: Primitive[]; - columns: Primitive[]; - solids: Primitive[]; - bounds?: [number, number, number, number]; + /** Fehlt, wenn das Geschoss nichts für den Kern enthält. */ + buf?: DecodedPlanBuf; } -const NO_DOMAINS: DomainPrims = { ceilings: [], walls: [], stairs: [], context: [], sections: [], roofs: [], rooms: [], columns: [], solids: [] }; +/** Gruppen des Puffers (`plan/domains.rs::GROUPS`). */ +const G_CEILINGS = 0; +const G_COLUMNS = 5; +const G_SOLIDS = 6; +const G_SECTIONS = 8; +const N_GROUPS = 9; + +const NO_DOMAINS: DomainPrims = {}; const DETAIL_CODE: Record = { grob: 0, mittel: 1, fein: 2 }; /** @@ -932,11 +987,15 @@ function planDomains( show.push(c); if (d.greyed) grey.push(c); } - return documentFor(project).query( - "planDomains", - [DETAIL_CODE[detail] ?? 1], - JSON.stringify({ floor: floorId, show, grey, referenceLines, global }), + const buf = decodePlanBuf( + documentFor(project).queryBin( + "planDomains", + [DETAIL_CODE[detail] ?? 1], + JSON.stringify({ floor: floorId, show, grey, referenceLines, global }), + ), ); + if (buf.groups.length !== N_GROUPS) throw new Error("planDomains: unerwartete Gruppen im Plan-Puffer"); + return { buf }; } function computeBounds( diff --git a/src/plan/voids.ts b/src/plan/voids.ts index 940eec1a..88b0995f 100644 --- a/src/plan/voids.ts +++ b/src/plan/voids.ts @@ -137,11 +137,12 @@ const WALL_LINE_CLS = new Set(["wall-outline", "layer-joint", "layer-joint-l"]); /** * Zieht die Abzugskörper von den Bauteil-Polygonen eines Grundrisses ab (in place). * Wände: wenn der Körper die Schnitthöhe `cutZ` durchdringt. Stützen: ebenso, über ihren - * Höhenbereich. Decken: wenn der Körper die Platte durchdringt (Deckendurchbruch). + * Höhenbereich. Decken: wenn der Körper die Platte durchdringt (Deckendurchbruch). Liefert, ob + * Abzugskörper da waren (dann kann sich die Liste verändert haben). */ -export function subtractVoidsInPlan(prims: Primitive[], project: Project, cutZ: number): void { +export function subtractVoidsInPlan(prims: Primitive[], project: Project, cutZ: number): boolean { const voids = voidPrisms(project); - if (voids.length === 0) return; + if (voids.length === 0) return false; const ceilings = new Map((project.ceilings ?? []).map((c) => [c.id, c])); const columns = new Map((project.columns ?? []).map((c) => [c.id, c])); const cuttersFor = (z0: number, z1: number): Pair[][] => @@ -198,6 +199,7 @@ export function subtractVoidsInPlan(prims: Primitive[], project: Project, cutZ: } prims.length = 0; for (const p of out) prims.push(p); + return true; } // ── Schnitt ────────────────────────────────────────────────────────────────── From 896601d77902ceb7ba069ee6a686434c894f2932 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 21:57:13 +0000 Subject: [PATCH 3/4] =?UTF-8?q?[K3d]=20GPU-Chunk-Cache:=20Inhalts-Hash=20f?= =?UTF-8?q?=C3=BCr=20Kern-Abschnitte,=20direkt=20aus=20dem=20Puffer=20komp?= =?UTF-8?q?iliert?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Chunks innerhalb von Plan.bufRuns (Identität je Stelle geprüft) werden am Inhalts-Hash des Kerns wiedererkannt statt an der Objekt-Identität und direkt aus dem Puffer kompiliert; Chunk-Grenzen auch an Bauteil-Ids. Neu erzeugter Plan mit gleichem Inhalt: 0 Chunks neu (vorher alle), eine verschobene Wand: 1 von 69. Nativer Renderer reicht bufRuns durch (nicht auf macOS getestet). Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src/plan/glPlan/glPlanChunks.test.ts | 86 +++++++++++++- src/plan/glPlan/glPlanChunks.ts | 148 +++++++++++++++++++++--- src/views/plan/useNativePlanRenderer.ts | 1 + 3 files changed, 219 insertions(+), 16 deletions(-) diff --git a/src/plan/glPlan/glPlanChunks.test.ts b/src/plan/glPlan/glPlanChunks.test.ts index 453bcee8..becb3c9e 100644 --- a/src/plan/glPlan/glPlanChunks.test.ts +++ b/src/plan/glPlan/glPlanChunks.test.ts @@ -1,7 +1,11 @@ import { describe, it, expect } from 'vitest'; import type { Primitive, UnderlayGroup } from '../generatePlan'; -import type { Drawing2D } from '../../model/types'; +import { generatePlan } from '../generatePlan'; +import type { Drawing2D, Project } from '../../model/types'; +import { flattenCategories } from '../../model/types'; +import { bigSampleProject } from '../bigSampleProject.testing'; import { GpuChunkCache, splitIntoChunks } from './glPlanChunks'; +import { compilePlanBufRange, compilePrimitivesToGpu } from './glPlanCompile'; const line = (x: number, drawingId: string): Primitive => ({ kind: 'line', @@ -213,3 +217,83 @@ describe('GpuChunkCache: kompakte Unterlage', () => { expect(g.length).toBe(3); // 1 unten + 1 Primitiv-Chunk + 1 oben }); }); + +describe('GpuChunkCache: Kern-Abschnitte (Plan-Puffer v2, Inhalts-Hash)', () => { + const codes = (p: Project) => new Set(flattenCategories(p.layers).map((c) => c.code)); + /** GL, das die hochgeladenen Daten mitschreibt. */ + function recordingGl() { + const uploads: number[][] = []; + const gl = { + createBuffer: () => ({}), + bindBuffer: () => {}, + bufferData: (_t: number, d: ArrayBufferView) => uploads.push(Array.from(new Uint8Array(d.buffer, d.byteOffset, d.byteLength))), + deleteBuffer: () => {}, + ARRAY_BUFFER: 1, + ELEMENT_ARRAY_BUFFER: 2, + STATIC_DRAW: 3, + } as unknown as WebGL2RenderingContext; + return { gl, uploads }; + } + + it('neu erzeugter Plan (neue Objekte, gleicher Inhalt) kompiliert nichts neu', () => { + const p = bigSampleProject(4); + const { gl } = makeGl(); + const cache = new GpuChunkCache(gl); + const a = generatePlan(p, 'eg', codes(p)); + expect(a.bufRuns?.length).toBe(2); + cache.update(a.primitives, 90, 6, a.greyedRanges, a.underlay, a.bufRuns); + expect(cache.lastStats.recompiled).toBe(cache.lastStats.chunks); + const b = generatePlan(p, 'eg', codes(p)); + expect(b.primitives[0]).not.toBe(a.primitives[0]); + cache.update(b.primitives, 90, 6, b.greyedRanges, b.underlay, b.bufRuns); + expect(cache.lastStats.recompiled).toBe(0); + // Ohne Abschnitte (Objekt-Identität) wäre alles neu. + const c = generatePlan(p, 'eg', codes(p)); + cache.update(c.primitives, 90, 6, c.greyedRanges, c.underlay); + expect(cache.lastStats.recompiled).toBe(cache.lastStats.chunks); + }); + + it('eine verschobene Wand kompiliert nur wenige Chunks neu', () => { + const p = bigSampleProject(8); + const { gl } = makeGl(); + const cache = new GpuChunkCache(gl); + const a = generatePlan(p, 'eg', codes(p)); + cache.update(a.primitives, 90, 6, a.greyedRanges, a.underlay, a.bufRuns); + const total = cache.lastStats.chunks; + expect(total).toBeGreaterThan(8); + const walls = p.walls.slice(); + walls[200] = { ...walls[200], end: { x: walls[200].end.x + 0.05, y: walls[200].end.y } }; + const b = generatePlan({ ...p, walls }, 'eg', codes(p)); + cache.update(b.primitives, 90, 6, b.greyedRanges, b.underlay, b.bufRuns); + expect(cache.lastStats.recompiled).toBeGreaterThan(0); + expect(cache.lastStats.recompiled).toBeLessThanOrEqual(3); + }); + + it('ersetzte Primitive (gedimmt geklont) fallen auf den Objekt-Weg zurück', () => { + const p = bigSampleProject(2); + const { gl } = makeGl(); + const cache = new GpuChunkCache(gl); + const a = generatePlan(p, 'eg', codes(p)); + const prims = a.primitives.slice(); + prims[10] = { ...prims[10], greyed: true } as Primitive; + cache.update(prims, 90, 6, a.greyedRanges, a.underlay, a.bufRuns); + const n = cache.lastStats.chunks; + cache.update(prims, 90, 6, a.greyedRanges, a.underlay, a.bufRuns); + expect(cache.lastStats.recompiled).toBe(0); + expect(cache.lastStats.chunks).toBe(n); + }); + + it('direkt aus dem Puffer = über die Objekte (gleiche hochgeladene Daten)', () => { + const p = bigSampleProject(2); + const plan = generatePlan(p, 'eg', codes(p)); + const run = plan.bufRuns![0]; + for (const [from, to] of [[run.from, run.to], [run.from + 3, run.to - 5]]) { + const x = recordingGl(); + const y = recordingGl(); + compilePlanBufRange(x.gl, run.buf, from, to, 120); + compilePrimitivesToGpu(y.gl, run.buf.prims.slice(from, to), 120); + expect(x.uploads.length).toBeGreaterThan(2); + expect(x.uploads).toEqual(y.uploads); + } + }); +}); diff --git a/src/plan/glPlan/glPlanChunks.ts b/src/plan/glPlan/glPlanChunks.ts index 5db179c1..5adb4d29 100644 --- a/src/plan/glPlan/glPlanChunks.ts +++ b/src/plan/glPlan/glPlanChunks.ts @@ -10,21 +10,28 @@ * Füllungen ebenfalls vor Linien kamen und innerhalb beider die Primitiv- * Reihenfolge galt. * - * Chunk-Grenzen sind INHALTSBASIERT (Hash der `drawingId`), nicht - * positionsbasiert: wird vorn ein Element eingefügt, verschieben sich alle - * Indizes dahinter, die Grenzen bleiben aber an denselben Elementen — nur der - * betroffene Chunk ändert sich. + * Chunk-Grenzen sind INHALTSBASIERT (Hash der Element-Id: `drawingId`, sonst + * die Pick-Id wie `wallId`), nicht positionsbasiert: wird vorn ein Element + * eingefügt, verschieben sich alle Indizes dahinter, die Grenzen bleiben aber + * an denselben Elementen — nur der betroffene Chunk ändert sich. * * Wiederverwendung: ein Chunk gilt als unverändert, wenn jede seiner * Primitive dasselbe OBJEKT ist wie beim letzten Lauf (Referenzvergleich) und, * falls er zoomabhängige Primitive (Bögen/Kreise) enthält, der LOD-Bucket * gleich ist. Beim blossen Zoomen werden dadurch nur die (wenigen) Chunks mit * Bögen neu tesselliert. + * + * Kern-Primitive ([K3d]): Abschnitte, die unverändert aus einem Plan-Puffer des + * Kerns stammen (`Plan.bufRuns`), sind bei jeder Plan-Erzeugung neue Objekte — + * dort gilt statt der Objekt-Identität der INHALTS-HASH je Primitiv (vom Kern + * mitgeliefert), und kompiliert wird direkt aus dem Puffer + * (`compilePlanBufRange`), ohne die Objekte erneut zu kodieren. */ -import type { Primitive, UnderlayGroup } from '../generatePlan'; +import type { PlanBufRun, Primitive, UnderlayGroup } from '../generatePlan'; import type { Drawing2D } from '../../model/types'; -import { compilePrimitivesToGpu } from './glPlanCompile'; +import type { DecodedPlanBuf } from '../planBuf'; +import { compilePlanBufRange, compilePrimitivesToGpu } from './glPlanCompile'; import type { BufferGl, GpuGeometry } from './glPlanTypes'; /** Ziel: im Mittel so viele Elemente (drawingIds) je Chunk = 2^BITS. */ @@ -45,10 +52,42 @@ function hashId(id: string): number { return h >>> 0; } +type Ids = { + drawingId?: string; + wallId?: string; + openingId?: string; + stairId?: string; + ceilingId?: string; + roomId?: string; + columnId?: string; + roofId?: string; + extrudedSolidId?: string; + contextObjectId?: string; + sectionLineId?: string; +}; + +/** Element eines Primitivs für die Chunk-Grenzen: `drawingId`, sonst die Pick-Id des Bauteils. */ +function elemId(p: Primitive): string | undefined { + const q = p as Ids; + return ( + q.drawingId ?? + q.wallId ?? + q.openingId ?? + q.stairId ?? + q.ceilingId ?? + q.roomId ?? + q.columnId ?? + q.roofId ?? + q.extrudedSolidId ?? + q.contextObjectId ?? + q.sectionLineId + ); +} + /** * Index-Bereiche [start, end) der Chunks. `cuts` sind Indizes, an denen IMMER * geschnitten wird (Grenzen gedimmter Bereiche, damit ein Chunk entweder ganz - * gedimmt ist oder gar nicht). + * gedimmt ist oder gar nicht; Grenzen der Kern-Abschnitte). */ export function splitIntoChunks( prims: readonly Primitive[], @@ -57,9 +96,9 @@ export function splitIntoChunks( const out: Array<[number, number]> = []; const mask = (1 << BOUNDARY_BITS) - 1; let start = 0; - let prevId: string | undefined = prims.length ? (prims[0] as { drawingId?: string }).drawingId : undefined; + let prevId: string | undefined = prims.length ? elemId(prims[0]) : undefined; for (let i = 1; i < prims.length; i++) { - const id = (prims[i] as { drawingId?: string }).drawingId; + const id = elemId(prims[i]); if (cuts.has(i)) { out.push([start, i]); start = i; @@ -79,12 +118,48 @@ export function splitIntoChunks( } interface Chunk { + /** Primitive (Referenzvergleich) — leer bei Kern-Chunks, die `keys` tragen. */ prims: Primitive[]; + /** Inhalts-Hashes der Primitive eines Kern-Chunks (sonst null). */ + keys: Float64Array | null; dynamic: boolean; bucket: number; geometry: GpuGeometry; } +/** Ein geprüfter Kern-Abschnitt: `primitives[start..end)` = `buf.prims[from..]`. */ +interface Segment { + start: number; + end: number; + buf: DecodedPlanBuf; + from: number; +} + +/** + * Kern-Abschnitte auf Objekt-Identität prüfen: nur Stellen, an denen noch genau das dekodierte + * Objekt steht (nicht ersetzt durch Abzugskörper, Dimmen, Strichstärken-Massstab), gelten. + */ +function verifiedSegments(primitives: readonly Primitive[], runs: readonly PlanBufRun[] | undefined): Segment[] { + const out: Segment[] = []; + for (const r of runs ?? []) { + if (!r.buf.hashes) continue; + 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 }); + } + } + return out.sort((a, b) => a.start - b.start); +} + +function sameKeys(a: Float64Array, b: Float64Array, offset: number): boolean { + for (let i = 0; i < a.length; i++) if (a[i] !== b[offset + i]) return false; + return true; +} + function disposeGeometry(gl: BufferGl, g: GpuGeometry): void { gl.deleteBuffer(g.fill.positionBuffer); gl.deleteBuffer(g.fill.indexBuffer); @@ -229,35 +304,77 @@ export class GpuChunkCache { lodBucket: number, greyedRanges?: ReadonlyArray<[number, number]>, underlay?: readonly UnderlayGroup[], + /** Abschnitte aus Kern-Puffern (`Plan.bufRuns`): Inhalts-Hash statt Objekt-Identität. */ + runs?: readonly PlanBufRun[], ): void { const cuts = new Set(); for (const [a, b] of greyedRanges ?? []) { cuts.add(a); cuts.add(b); } - // Aktuelle + vorherige Generation nach erstem Primitiv indizieren (Referenz-Identität). + const segs = verifiedSegments(primitives, runs); + for (const g of segs) { + cuts.add(g.start); + cuts.add(g.end); + } + // Aktuelle + vorherige Generation nach erstem Primitiv (Referenz) bzw. erstem Hash indizieren. const pool = [...this.chunks, ...this.previous]; - const old = new Map(); + const old = new Map(); for (const c of pool) { - if (!c.prims.length) continue; - const list = old.get(c.prims[0]); + const first = c.keys ? (c.keys.length ? c.keys[0] : undefined) : c.prims[0]; + if (first === undefined) continue; + const list = old.get(first); if (list) list.push(c); - else old.set(c.prims[0], [c]); + else old.set(first, [c]); } const next: Chunk[] = []; const chunkStarts: number[] = []; const reused = new Set(); let recompiled = 0; + let si = 0; for (const [start, end] of splitIntoChunks(primitives, cuts)) { + chunkStarts.push(start); + while (si < segs.length && segs[si].end <= start) si++; + const seg = si < segs.length && segs[si].start <= start && end <= segs[si].end ? segs[si] : null; + if (seg) { + // Kern-Chunk: Inhalts-Hashes vergleichen, direkt aus dem Puffer kompilieren. + const hashes = seg.buf.hashes!; + const from = seg.from + (start - seg.start); + const n = end - start; + const hit = old.get(hashes[from])?.find( + (c) => + !reused.has(c) && + c.keys !== null && + c.keys.length === n && + (!c.dynamic || c.bucket === lodBucket) && + sameKeys(c.keys, hashes, from), + ); + if (hit) { + reused.add(hit); + next.push(hit); + continue; + } + let dynamic = false; + for (let i = start; i < end && !dynamic; i++) dynamic = isLodDependent(primitives[i]); + next.push({ + prims: [], + keys: hashes.slice(from, from + n), + dynamic, + bucket: lodBucket, + geometry: compilePlanBufRange(this.gl, seg.buf, from, from + n, pxPerMeter), + }); + recompiled++; + continue; + } const hit = old.get(primitives[start])?.find( (c) => !reused.has(c) && + c.keys === null && c.prims.length === end - start && (!c.dynamic || c.bucket === lodBucket) && sameRefs(c.prims, primitives, start), ); - chunkStarts.push(start); if (hit) { reused.add(hit); next.push(hit); @@ -266,6 +383,7 @@ export class GpuChunkCache { const slice = primitives.slice(start, end); next.push({ prims: slice, + keys: null, dynamic: slice.some(isLodDependent), bucket: lodBucket, geometry: compilePrimitivesToGpu(this.gl, slice, pxPerMeter), diff --git a/src/views/plan/useNativePlanRenderer.ts b/src/views/plan/useNativePlanRenderer.ts index aee806d3..0e835a5b 100644 --- a/src/views/plan/useNativePlanRenderer.ts +++ b/src/views/plan/useNativePlanRenderer.ts @@ -275,6 +275,7 @@ export function useNativePlanRenderer( pxPerMeter > 0 ? Math.round(Math.log2(pxPerMeter)) : -Infinity, plan.greyedRanges, plan.underlay, + plan.bufRuns, ); } catch (e) { console.warn('Tessellierung fehlgeschlagen:', e); From 8590a1c42c0500b0da164e2f87a878a8aa623c8e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 21:57:13 +0000 Subject: [PATCH 4/4] =?UTF-8?q?[K3d][K4]=20TODO:=20Plan-Puffer=20v2=20erle?= =?UTF-8?q?digt,=20Gleichheit,=20Messung,=20was=20noch=20=C3=BCber=20Primi?= =?UTF-8?q?tive[]=20l=C3=A4uft?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- TODO.md | 36 +++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/TODO.md b/TODO.md index 3c207db6..53bc1b24 100644 --- a/TODO.md +++ b/TODO.md @@ -142,9 +142,37 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern aber die Antwort ist ~14 MB JSON (Wände 9,3 MB, Treppen 3,7 MB): Abfrage inkl. Serialisierung ~160–210 ms, `JSON.parse` ~145–225 ms. Die JSON-Form ist damit der Engpass → Plan-Puffer v2. Offen: `drawing2d.ts` (Verteiler), Schatten/Baurecht (dünner Stil-Glue um `analysis/`, Datum/Sonnenstand in TS), Abzugskörper - (`voids.ts`), Mono, Strichstärken-Massstab und `generateVisibleLevelsPlan` bleiben TS; die Override-Engine in TS bedient nur noch 2D-Zeichnungen. Plan-Puffer v2 (Primitive binär mit Pick-IDs und vollem - Umfang statt JSON, gemeinsame Tabellen für Schraffuren/Farben, damit nicht jedes Polygon seine `HatchRender` wiederholt) ist nicht - begonnen; erst sinnvoll, wenn die Verbraucher (SVG/PDF/DXF, Auswahl, Overlay) den Puffer lesen statt `Primitive[]`. + (`voids.ts`), Mono, Strichstärken-Massstab und `generateVisibleLevelsPlan` bleiben TS; die Override-Engine in TS bedient nur noch 2D-Zeichnungen. Plan-Puffer v2 + s. nächster Punkt (28.10. erledigt). + ✅ (28.10.) **Plan-Puffer v2**: `planDomains` antwortet binär statt mit ~15 MB JSON (`doc_query_bin` → `queries.rs::run_bin` → + `plan/domains.rs::plan_domains_buf`). Format im Kopf von `plan_buf.rs` (Gegenstück `src/plan/planBuf.ts`): Bytes mit f64-Teil + + UTF-16-Texten; Kopf mit Magie "PLB2"/Version 2, Ausmass und Flags; gemeinsame Tabellen für Strings (Farben, Klassen, Ids, + Text-JSON) und Schraffuren (je Eintrag einmal als JSON für TS + numerischer Hatch-Datensatz für die GPU); Gruppen (die neun + Domänen); Offset-Tabelle (wahlfreier Zugriff); Inhalts-Hash je Primitiv; Einträge `[tag, flags, Pick-Art, Pick-Id, …]` mit + Punkt-/Listen-Pool; voller `Primitive`-Umfang (Polygon mit Löchern/noStrokeEdges, Linie mit Strichmuster null/Liste, Zickzack, + Motiv, Bogen, Kreis/Bogen der 2D-Zeichnung; Raumstempel, Texte, Textpfad, Bild als JSON „wie heute“). v1 und die TS-`parseColor` + sind gelöscht (Farben parst jetzt `plan_buf::parse_color`, bitgleich); `prim.rs` kennt auch `drawingTextPath/Image/Circle/Arc`. + TS liest den Puffer zu `Primitive[]` (gleiche Felder und Reihenfolge wie das alte JSON, Schraffur-Objekte geteilt); + die GPU-Kompilierung liest Bereiche direkt aus dem Kern-Puffer (`compilePlanBufRange`: Puffer einmal im Kern gehalten, + `plan_buf_hold`/`gpu_compile_held`, höchstens 8 Puffer/96 MB), gemischte Listen kodiert TS schlank (`lean`). + GPU-Chunk-Cache: `Plan.bufRuns` merkt sich die Kern-Abschnitte (auch über Abzugskörper, Geschoss-Überlagerung, kompakte + Unterlage hinweg; Mono/Strichstärken-Massstab lassen sie weg); dort zählt der Inhalts-Hash statt der Objekt-Identität, Chunk- + Grenzen auch an Bauteil-Ids. Neu erzeugter Plan mit gleichem Inhalt → 0 Chunks neu (vorher alle), eine Wand verschoben → 1 von 69. + Gleichheit (temporärer Paritätstest gegen den alten Kern, danach entfernt): planDomains-JSON nach Dekodierung Zeichen für Zeichen + gleich (ohne Sortieren) über Beispiel + 120 Zufallsprojekte (Zickzack/Motiv-Fugen, Random-Schraffur, Override-Regeln, + Zusatzwände/-öffnungen/-stützen/-treppen, kaputte Schraffuren/Deckentypen → gleiche Fehlermeldungen) × 2 Geschosse × 3 Detailgrade + mit zufälliger Sichtbarkeit/Graustufe/Referenzlinien/global (726 Abfragen) und das grosse Projekt; GPU-Vertex-/Index-/Batch-Puffer + byte-gleich zur v1-Kompilierung (2988 Puffer: Kern-Puffer direkt, ganzer Plan schlank kodiert, gepackt/ungepackt, LOD); + CLI-SVG Beispiel-EG/OG und grosses Projekt byte-gleich; `npm run e2e` grün. + Messung (Node, Linux-Container unter Last, Min/Median): `generatePlan` Beispiel-EG 0,63/0,76 → 0,32/0,51 ms; grosses Projekt + (Beispielhaus 20×20, `plan/bigSampleProject.testing.ts`: 3600 Wände, 56 824 Primitive) 386/442 → 171/210 ms. Davon Abfrage + 122–130 ms (Rechnung ~130 ms nativ, Puffer schreiben 21 ms statt JSON 38 ms), Lesen in TS 39 ms (vorher `JSON.parse` 148 ms); + Puffer 9,2 MB statt 15,5 MB JSON. GPU-Kompilierung des ganzen grossen Plans unverändert ~0,5 s (Rechnung, nicht Übergabe). + Noch über `Primitive[]` (dekodiert): SVG/PDF/DXF-Export, Auswahl/Picken (`ownerIndex`, `segmentIndex`), Overlay/Texte + (`nativeText`, PlanView), Culling, Fang, `toRenderScene` → render2d (`scene_bin.rs`, Browser-Ansicht und `push_native_scene`, + 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). 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 @@ -176,6 +204,8 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern kommen über `planDomains` aus dem Dokument ([K3d]); übrig in `generatePlan`: 2D-Zeichnungen, Schatten/Baurecht, Abzugskörper. Ziel: Plan/Schnitt/Ansicht, 3D, Export rechnen mit `doc`-Handle statt flach gesammelter Arrays; TS-Sammler/-Adapter werden gelöscht ([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[]`. - ◐ **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