From 63f653d1c29f1ef46ec09b971eb6c4493745db85 Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 00:47:12 +0100 Subject: [PATCH 01/31] [K3a] Treppen-Symbol im Grundriss in Rust (plan_stairs.rs); generatePlan/stairs.ts nur noch Uebersetzung --- TODO.md | 7 +- src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/plan_stairs.rs | 177 +++++++++++++++++++++ src-tauri/core/src/web/mod.rs | 1 + src-tauri/core/src/web/plan_stairs.rs | 10 ++ src/plan/generatePlan/stairs.ts | 219 ++++++++------------------ 6 files changed, 262 insertions(+), 153 deletions(-) create mode 100644 src-tauri/core/src/plan_stairs.rs create mode 100644 src-tauri/core/src/web/plan_stairs.rs diff --git a/TODO.md b/TODO.md index 3c13cd61..9b7bf803 100644 --- a/TODO.md +++ b/TODO.md @@ -80,8 +80,13 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern über `Math` der JS-Engine (musl-libm wich ab, auch in der Topologie). Leistung (Node, Min. über Wiederholungen): Beispiel-EG 1,5 → 0,8 ms, 100k Linien + 3000 Schraffurflächen 3,9 → 1,8 s, nur Schraffur ~2×, nur Linien 104 → 81 ms (davon Kodieren in TS 7–29 ms). Mac-Test bestanden. - - ○ **[K3a] Plan-Erzeugung in Rust** (Wand-Poché, Öffnungssymbole, Decken, Treppen, Dächer, Räume, + - ◐ **[K3a] Plan-Erzeugung in Rust** (Wand-Poché, Öffnungssymbole, Decken, Treppen, Dächer, Räume, 2D-Zeichnung, Kontext, Schnittlinien) direkt in den Plan-Puffer; JS-Objekte nur noch für Export/Overlay. + Vorgehen (28.10.): je Domäne ein Rust-Modul mit flacher Primitivliste, TS nur als dünne Übersetzung + (Farbe, Graustufen, Pick-ID) — kein Format-v2, bis [K3d] den Puffer direkt liefert. + ✅ Treppen: `plan_stairs.rs` (`plan_stair_flat`), `generatePlan/stairs.ts` nur noch Übersetzung; bitgleich zur + alten TS-Fassung (49 Fälle: gerade/L/Wendel, Pfeilstil, Schnitthöhen). Nicht in der Tauri-App angesehen. + Offen: Decken, Räume, Dächer, Stützen, 2D-Zeichnung, Kontext, Schnittlinien, Wände, Öffnungen. - ○ **[K3c] Schnitt und Ansicht** (`toSection`, `toElevation`, `meshSection`) im selben Puffer-Format. - ○ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. Nachteile (bewusst): Übergang mit doppelter Datenhaltung, Format muss TS/Rust gleich bleiben diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index a349b5f0..7a79ee87 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -33,6 +33,7 @@ pub mod hatch; pub mod hatch_flat; pub mod plan_buf; pub mod gpu_compile; +pub mod plan_stairs; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/plan_stairs.rs b/src-tauri/core/src/plan_stairs.rs new file mode 100644 index 00000000..7f2ca50d --- /dev/null +++ b/src-tauri/core/src/plan_stairs.rs @@ -0,0 +1,177 @@ +//! Treppen-Symbol im Grundriss ([K3a]): Tritte, Lauflinie, Pfeil, Podest, SIA-Bruchlinie und +//! Aussenlinie als flache Primitivliste. Port von `src/plan/generatePlan/stairs.ts`; die Geometrie +//! kommt aus `kernel2d` (`stair_geometry`, `stair_cut`, `stair_outline`), Farbe, Pick-ID und +//! Graustufen setzt der Aufrufer. +//! +//! Eingabe: Treppen-Parameter (16 Zahlen, s. `stair.rs`), Gesamt-Steighöhe, Schnitthöhe über der +//! Treppen-UK, Strichstärke `lw_mm` (Papier-mm), `filled_arrow` (0/1). +//! +//! Ausgabe `[n, Eintrag × n]`, Reihenfolge = Zeichenreihenfolge: +//! ```text +//! 1 polygon [1, strokeMm, gefüllt (0 = nur Umriss, 1 = Füllung in Strichfarbe), nPts, x, y …] +//! 2 line [2, cls, weightMm, gestrichelt (0|1), ax, ay, bx, by] +//! 3 arc [3, weightMm, cx, cy, fromX, fromY, toX, toY, r] (cls immer stair-outline) +//! cls 0 stair-outline · 1 stair-tread · 2 stair-break · 3 stair-run · 4 stair-arrow +//! ``` +//! Gestrichelte Linien tragen das Strichmuster `[0.12, 0.08]` (Meter, `DASH`). + +use crate::jsnum; +use crate::stair::decode_params; +use kernel2d::{stair_cut, stair_geometry, stair_outline, Vec2}; +use std::collections::HashSet; + +pub const DASH: [f64; 2] = [0.12, 0.08]; + +const CLS_OUTLINE: f64 = 0.0; +const CLS_TREAD: f64 = 1.0; +const CLS_BREAK: f64 = 2.0; +const CLS_RUN: f64 = 3.0; +const CLS_ARROW: f64 = 4.0; + +#[derive(Default)] +struct Out { + buf: Vec, + n: usize, +} + +impl Out { + fn polygon(&mut self, pts: &[Vec2], stroke_mm: f64, filled: bool) { + self.n += 1; + self.buf.extend([1.0, stroke_mm, if filled { 1.0 } else { 0.0 }, pts.len() as f64]); + for p in pts { + self.buf.extend([p.x, p.y]); + } + } + fn line(&mut self, cls: f64, a: Vec2, b: Vec2, weight_mm: f64, dashed: bool) { + self.n += 1; + self.buf.extend([2.0, cls, weight_mm, if dashed { 1.0 } else { 0.0 }, a.x, a.y, b.x, b.y]); + } + fn arc(&mut self, weight_mm: f64, c: Vec2, from: Vec2, to: Vec2, r: f64) { + self.n += 1; + self.buf.extend([3.0, weight_mm, c.x, c.y, from.x, from.y, to.x, to.y, r]); + } +} + +pub fn plan_stair(params: &[f64], total_rise: f64, cut_rise: f64, lw_mm: f64, filled_arrow: bool) -> Vec { + let Some(p) = decode_params(params) else { return Vec::new() }; + if !(total_rise.is_finite() && cut_rise.is_finite() && lw_mm.is_finite()) { + return Vec::new(); + } + let geo = stair_geometry(&p, total_rise); + let cut = stair_cut(&geo, cut_rise); + let below: HashSet = cut.below_indices.iter().copied().collect(); + let mut o = Out::default(); + + for tr in &geo.treads { + let is_below = below.contains(&tr.index); + o.polygon(&tr.pts, lw_mm * 0.7, false); + if tr.pts.len() >= 3 { + o.line(CLS_TREAD, tr.pts[1], tr.pts[2], lw_mm * if is_below { 1.0 } else { 0.6 }, !is_below); + } + } + if let Some(l) = &geo.landing { + if l.len() >= 3 { + o.polygon(l, lw_mm * 0.7, false); + } + } + if let Some(lines) = &cut.break_line { + for (a, b) in lines { + o.line(CLS_BREAK, *a, *b, lw_mm, false); + } + } + for w in geo.run_line.windows(2) { + o.line(CLS_RUN, w[0], w[1], lw_mm, false); + } + let (h1, tip, h2) = geo.arrow.head; + if filled_arrow { + o.polygon(&[h1, tip, h2], lw_mm, true); + } else { + o.line(CLS_ARROW, h1, tip, lw_mm, false); + o.line(CLS_ARROW, h2, tip, lw_mm, false); + } + + let outline = stair_outline(&p); + if let Some(poly) = &outline.polygon { + if poly.len() >= 3 { + o.polygon(poly, lw_mm, false); + } + } + if let Some(s) = &outline.spiral { + for (a, b) in &s.lines { + o.line(CLS_OUTLINE, *a, *b, lw_mm, false); + } + for (c, r, a0, a1) in &s.arcs { + let from = Vec2::new(c.x + r * jsnum::cos(*a0), c.y + r * jsnum::sin(*a0)); + let to = Vec2::new(c.x + r * jsnum::cos(*a1), c.y + r * jsnum::sin(*a1)); + o.arc(lw_mm, *c, from, to, *r); + } + } + + let mut out = Vec::with_capacity(o.buf.len() + 1); + out.push(o.n as f64); + out.extend(o.buf); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const NAN: f64 = f64::NAN; + + fn straight() -> Vec { + vec![0.0, 0.0, 0.0, 1.0, 0.0, 3.0, NAN, NAN, NAN, NAN, NAN, NAN, 1.2, 16.0, NAN, 0.0] + } + + /// Zählt Einträge je Tag und prüft, dass der Puffer genau aufgeht. + fn tags(buf: &[f64]) -> Vec { + let n = buf[0] as usize; + let mut i = 1; + let mut t = Vec::new(); + for _ in 0..n { + t.push(buf[i]); + i += match buf[i] as i64 { + 1 => 4 + 2 * buf[i + 3] as usize, + 2 => 8, + 3 => 9, + _ => panic!("unbekannter Tag"), + }; + } + assert_eq!(i, buf.len()); + t + } + + #[test] + fn gerade_treppe_hat_tritte_lauflinie_pfeil_und_aussenlinie() { + let b = plan_stair(&straight(), 2.8, 1.0, 0.25, false); + let t = tags(&b); + // 16 Tritte × (Polygon + Kante) + 2 Bruchstriche + Lauflinie + 2 Pfeilflügel + Aussenlinie + assert_eq!(t.iter().filter(|x| **x == 1.0).count(), 16 + 1); + assert!(t.iter().filter(|x| **x == 2.0).count() >= 16 + 2 + 2); + // erster Tritt liegt unter der Schnittebene: durchgezogen, volle Stärke + assert_eq!(&b[1 + 4 + 8 + 1..][..3], &[1.0, 0.25, 0.0]); + } + + #[test] + fn gefuellter_pfeil_ist_ein_dreieck() { + let offen = tags(&plan_stair(&straight(), 2.8, 1.0, 0.25, false)); + let voll = tags(&plan_stair(&straight(), 2.8, 1.0, 0.25, true)); + assert_eq!(voll.len() + 1, offen.len()); + } + + #[test] + fn wendel_liefert_boegen() { + let p = vec![2.0, 0.0, 0.0, 1.0, 0.0, 3.0, NAN, NAN, 0.0, 0.0, 1.5, 270.0, 1.0, 14.0, NAN, 0.0]; + let t = tags(&plan_stair(&p, 2.8, 1.0, 0.25, false)); + assert_eq!(t.iter().filter(|x| **x == 3.0).count(), 2); + } + + #[test] + fn unsinn_ergibt_leeres_ergebnis() { + assert!(plan_stair(&[1.0, 2.0], 2.8, 1.0, 0.25, false).is_empty()); + assert!(plan_stair(&straight(), NAN, 1.0, 0.25, false).is_empty()); + let mut kaputt = straight(); + kaputt[1] = NAN; + assert!(plan_stair(&kaputt, 2.8, 1.0, 0.25, false).is_empty()); + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 574f5710..78d14dcb 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -25,6 +25,7 @@ mod openings3d; mod wall_mesh_cut; mod plan_buf; mod gpu_compile; +mod plan_stairs; mod hatch; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/plan_stairs.rs b/src-tauri/core/src/web/plan_stairs.rs new file mode 100644 index 00000000..b15a30e6 --- /dev/null +++ b/src-tauri/core/src/web/plan_stairs.rs @@ -0,0 +1,10 @@ +//! Bindung des Treppen-Symbols im Grundriss (`crate::plan_stairs`). Ausgabe-Layout s. dort. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Treppen-Parameter (16 Zahlen), Gesamt-Steighöhe, Schnitthöhe über der UK, Strichstärke (mm), +/// gefüllter Pfeil (0/1) → Primitivliste; Unsinn → leer. +#[wasm_bindgen] +pub fn plan_stair_flat(params: &[f64], total_rise: f64, cut_rise: f64, lw_mm: f64, filled_arrow: f64) -> Vec { + crate::plan_stairs::plan_stair(params, total_rise, cut_rise, lw_mm, filled_arrow != 0.0) +} diff --git a/src/plan/generatePlan/stairs.ts b/src/plan/generatePlan/stairs.ts index 49dbf88f..32f499d1 100644 --- a/src/plan/generatePlan/stairs.ts +++ b/src/plan/generatePlan/stairs.ts @@ -2,46 +2,21 @@ // Auf-/Abpfeil, Zwischenpodest und Aussenlinie — mit dem Grundriss-Schnitt // (Tritte unter der Schnitthöhe durchgezogen, darüber gestrichelt/verdeckt + // SIA-Bruchlinie). +// +// Die Primitive entstehen im Rust-Kern (`src-tauri/core/src/plan_stairs.rs`, [K3a]); hier nur die +// Übersetzung der flachen Liste in `Primitive`-Objekte (Farbe, Graustufen, `stairId`). +// Fällt mit [K3d] weg, wenn der Plan-Puffer direkt aus Rust kommt. -import type { Project, Stair, Vec2 } from "../../model/types"; +import type { Project, Stair } from "../../model/types"; import { stairVerticalExtent } from "../../model/wall"; -import { stairCut, stairGeometry, stairOutline } from "../../geometry/stair"; -import type { SpiralOutlineSegments } from "../../geometry/stair"; +import { encodeStair } from "../../geometry/stair"; +import { core } from "../../engine/coreWasm"; import { NO_HATCH, POCHE_STROKE, type Primitive } from "./shared"; -/** - * Zeichnet die Wendel-Aussenlinie: Innen-/Aussenbogen als Arc-Primitive plus zwei - * radiale Schliesslinien. Wird von `addStairSymbol` aufgerufen wenn `shape === "spiral"`. - */ -function _addSpiralOutline( - out: Primitive[], - seg: SpiralOutlineSegments, - stroke: string, - lwMm: number, - greyed: boolean, - stairId: string, -): void { - // Radiale Schliesslinien (Startwinkel + Endwinkel). - for (const [a, b] of seg.lines) { - out.push({ kind: "line", a, b, cls: "stair-outline", weightMm: lwMm, color: stroke, greyed, stairId }); - } - // Innen- und Aussenbogen. - for (const arc of seg.arcs) { - const from: Vec2 = { x: arc.cx + arc.r * Math.cos(arc.a0), y: arc.cy + arc.r * Math.sin(arc.a0) }; - const to: Vec2 = { x: arc.cx + arc.r * Math.cos(arc.a1), y: arc.cy + arc.r * Math.sin(arc.a1) }; - out.push({ - kind: "arc", - center: { x: arc.cx, y: arc.cy }, - from, - to, - r: arc.r, - cls: "stair-outline", - weightMm: lwMm, - greyed, - stairId, - }); - } -} +/** Linienklassen in der Reihenfolge der Kern-Kodierung (`plan_stairs.rs`). */ +const LINE_CLS = ["stair-outline", "stair-tread", "stair-break", "stair-run", "stair-arrow"] as const; +/** Strichmuster der verdeckten Tritte (Meter). */ +const TREAD_DASH = [0.12, 0.08]; /** * Treppen-Symbol im Grundriss (DOSSIER/SIA): @@ -62,124 +37,64 @@ export function addStairSymbol( cutHeight: number, ): void { const { zBottom, zTop } = stairVerticalExtent(project, stair); - const totalRise = zTop - zBottom; - const geo = stairGeometry(stair, totalRise); - const cut = stairCut(geo, cutHeight); - const below = new Set(cut.belowIndices); + const f = core().plan_stair_flat( + encodeStair(stair), + zTop - zBottom, + cutHeight, + lwMm, + stair.arrowStyle === "filled" ? 1 : 0, + ); + if (f.length === 0) return; const stroke = stair.color ?? POCHE_STROKE; const stairId = stair.id; - - // Umriss + Tritt-Trennlinien je Stufe. Der letzte Punkt jedes Tritt-Rechtecks - // liefert die vordere Kante (Auftritt); wir zeichnen jede Tritt-Kante. - for (const tr of geo.treads) { - const isBelow = below.has(tr.index); - // Tritt-Rechteck als reine Umrisslinie (keine Füllung), durchgezogen wenn - // unter der Schnittebene, sonst gestrichelt (verdeckt). - out.push({ - kind: "polygon", - pts: tr.pts, - fill: "none", - stroke, - strokeWidthMm: lwMm * 0.7, - hatch: NO_HATCH, - greyed, - stairId, - }); - // Zusätzliche Auftrittskante (vordere Kante der Stufe) etwas kräftiger. - const front: [Vec2, Vec2] = [tr.pts[1], tr.pts[2]]; - out.push({ - kind: "line", - a: front[0], - b: front[1], - cls: "stair-tread", - weightMm: lwMm * (isBelow ? 1.0 : 0.6), - dash: isBelow ? null : [0.12, 0.08], - color: stroke, - greyed, - stairId, - }); - } - - // Zwischenpodest (L/Wendel-Auge): Umriss-Polygon. - if (geo.landing && geo.landing.length >= 3) { - out.push({ - kind: "polygon", - pts: geo.landing, - fill: "none", - stroke, - strokeWidthMm: lwMm * 0.7, - hatch: NO_HATCH, - greyed, - stairId, - }); - } - - // SIA-Bruchlinie (Doppelstrich diagonal über den Schnitt-Tritt). - if (cut.breakLine) { - for (const [a, b] of cut.breakLine) { - out.push({ - kind: "line", - a, - b, - cls: "stair-break", - weightMm: lwMm, - color: stroke, - greyed, - stairId, - }); + const n = f[0]; + let i = 1; + for (let k = 0; k < n; k++) { + switch (f[i]) { + case 1: { + const count = f[i + 3]; + const pts = new Array<{ x: number; y: number }>(count); + for (let j = 0; j < count; j++) pts[j] = { x: f[i + 4 + 2 * j], y: f[i + 5 + 2 * j] }; + out.push({ + kind: "polygon", + pts, + fill: f[i + 2] ? stroke : "none", + stroke, + strokeWidthMm: f[i + 1], + hatch: NO_HATCH, + greyed, + stairId, + }); + i += 4 + 2 * count; + break; + } + case 2: + out.push({ + kind: "line", + a: { x: f[i + 4], y: f[i + 5] }, + b: { x: f[i + 6], y: f[i + 7] }, + cls: LINE_CLS[f[i + 1]], + weightMm: f[i + 2], + ...(LINE_CLS[f[i + 1]] === "stair-tread" ? { dash: f[i + 3] ? TREAD_DASH : null } : {}), + color: stroke, + greyed, + stairId, + }); + i += 8; + break; + default: + out.push({ + kind: "arc", + center: { x: f[i + 2], y: f[i + 3] }, + from: { x: f[i + 4], y: f[i + 5] }, + to: { x: f[i + 6], y: f[i + 7] }, + r: f[i + 8], + cls: "stair-outline", + weightMm: f[i + 1], + greyed, + stairId, + }); + i += 9; } } - - // Lauflinie (Lauflinie) — kräftig, durchgezogen. - for (let i = 0; i < geo.runLine.length - 1; i++) { - out.push({ - kind: "line", - a: geo.runLine[i], - b: geo.runLine[i + 1], - cls: "stair-run", - weightMm: lwMm, - color: stroke, - greyed, - stairId, - }); - } - // Auf-/Abpfeil an der Spitze der Lauflinie. "filled" = gefülltes Dreieck - // (SIA-Vollpfeil), sonst der offene Winkelpfeil (zwei Linien, Default). - const [h1, tip, h2] = geo.arrow.head; - if (stair.arrowStyle === "filled") { - out.push({ - kind: "polygon", - pts: [h1, tip, h2], - fill: stroke, - stroke, - strokeWidthMm: lwMm, - hatch: NO_HATCH, - greyed, - stairId, - }); - } else { - out.push({ kind: "line", a: h1, b: tip, cls: "stair-arrow", weightMm: lwMm, color: stroke, greyed, stairId }); - out.push({ kind: "line", a: h2, b: tip, cls: "stair-arrow", weightMm: lwMm, color: stroke, greyed, stairId }); - } - - // Aussenlinie (Outline) der Treppe — schliessendes Umriss-Polygon (gerade/L) - // bzw. Innen-/Aussenbogen + radiale Schliesslinien (Wendel). - // Entspricht `_aussen_gerade` / `_aussen_l_polygon` / `_aussen_wendel` im - // Rhino-Plugin. Stets durchgezogen, volle Strichstärke. - const outline = stairOutline(stair, totalRise); - if (outline.polygon && outline.polygon.length >= 3) { - out.push({ - kind: "polygon", - pts: outline.polygon, - fill: "none", - stroke, - strokeWidthMm: lwMm, - hatch: NO_HATCH, - greyed, - stairId, - }); - } - if (outline.spiral) { - _addSpiralOutline(out, outline.spiral, stroke, lwMm, greyed, stairId); - } } From 8c112b2bc55113fc83a25a9834cfce3a279149d4 Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 00:52:09 +0100 Subject: [PATCH 02/31] [K3a] Wand-Poche und Decken-Umriss im Grundriss in Rust (plan_walls.rs); TS nur noch Stil und Uebersetzung --- TODO.md | 7 +- src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/plan_walls.rs | 527 +++++++++++++++++++++++++++ src-tauri/core/src/web/mod.rs | 1 + src-tauri/core/src/web/plan_walls.rs | 15 + src/plan/generatePlan/ceilings.ts | 51 ++- src/plan/generatePlan/walls.ts | 478 ++++++------------------ 7 files changed, 690 insertions(+), 390 deletions(-) create mode 100644 src-tauri/core/src/plan_walls.rs create mode 100644 src-tauri/core/src/web/plan_walls.rs diff --git a/TODO.md b/TODO.md index 9b7bf803..2dc700cd 100644 --- a/TODO.md +++ b/TODO.md @@ -86,7 +86,12 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern (Farbe, Graustufen, Pick-ID) — kein Format-v2, bis [K3d] den Puffer direkt liefert. ✅ Treppen: `plan_stairs.rs` (`plan_stair_flat`), `generatePlan/stairs.ts` nur noch Übersetzung; bitgleich zur alten TS-Fassung (49 Fälle: gerade/L/Wendel, Pfeilstil, Schnitthöhen). Nicht in der Tauri-App angesehen. - Offen: Decken, Räume, Dächer, Stützen, 2D-Zeichnung, Kontext, Schnittlinien, Wände, Öffnungen. + ✅ Wand-Poché und Decken-Umriss: `plan_walls.rs` (Segmente zwischen Öffnungen, Gehrungsbänder, Schichtfugen, + L-Anschlüsse, Durchgangswand-Aussparungen, Verdeckung durch Wand-Footprints). Stil (Bauteil, Schraffur, Farbe, + Fugen-Linienstil) bleibt in TS, bis das Modell in Rust liegt [K4]; Zuordnung über den Schichtindex. Bitgleich zur + alten Fassung (60 Zufallspläne × 3 Detailgrade, Öffnungen, Beispielprojekt, Decken mit/ohne Loch); `subtractIntervals`/ + `segmentInsideWallBand` aus TS gelöscht. Nicht in der Tauri-App angesehen. + Offen: Öffnungssymbole, Räume, Dächer, Stützen, 2D-Zeichnung, Kontext, Schnittlinien. - ○ **[K3c] Schnitt und Ansicht** (`toSection`, `toElevation`, `meshSection`) im selben Puffer-Format. - ○ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. Nachteile (bewusst): Übergang mit doppelter Datenhaltung, Format muss TS/Rust gleich bleiben diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 7a79ee87..fd767c28 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -34,6 +34,7 @@ pub mod hatch_flat; pub mod plan_buf; pub mod gpu_compile; pub mod plan_stairs; +pub mod plan_walls; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/plan_walls.rs b/src-tauri/core/src/plan_walls.rs new file mode 100644 index 00000000..2c2f8c70 --- /dev/null +++ b/src-tauri/core/src/plan_walls.rs @@ -0,0 +1,527 @@ +//! Wand-Poché und Decken-Umriss im Grundriss ([K3a]): die Geometrie von `generatePlan/walls.ts` +//! und `ceilings.ts` (Segmente zwischen Öffnungen, Gehrungsbänder, Schichtfugen, Durchgangswand- +//! Aussparungen, Verdeckung von Decken-Umrissen durch Wand-Footprints). Stil (Bauteil, Schraffur, +//! Farbe, Strichstärke, Linienstil der Fuge) löst TS aus dem Modell auf und ordnet ihn über den +//! Schichtindex zu — das Modell bleibt bis [K4] in TS. +//! +//! Rechenreihenfolge und Zahlsemantik wie in TS (`Math.hypot` über `jsmath`, `Math.min/max` über +//! `jsnum`), damit die Ausgabe bitgleich bleibt. +//! +//! ## Wand-Poché +//! Eingabe (alles `f64`): `[sx, sy, ex, ey, dicke, refOff, grob (0|1), nurAnsicht (0|1), nSchichten, +//! dicke × n, startCut, endCut, hatLayerCuts, (je Schicht: start, end, startSide, endSide)×n, +//! nAussparungen, (from, to, offA, offB)×m, nLuecken, (from, to)×k]` mit einer Linie als +//! `[vorhanden (0|1), px, py, dx, dy]`. +//! +//! Ausgabe `[n, Eintrag × n]` in Zeichenreihenfolge: +//! ```text +//! 1 polygon [1, art, schicht, nOhneStrich, kante…, x0,y0 … x3,y3] +//! art 0 Ansichts-Umriss · 1 Sammelfläche (grob) · 2 Schichtband · 3 Wand-Umriss +//! 2 line [2, art, schicht, ax, ay, bx, by] +//! art 0 layer-joint-l · 1 layer-joint · 2 wall-outline +//! ``` +//! +//! ## Decken-Umriss +//! Eingabe `[nRing, x, y …, nBruecken, kante…, nFootprints, (ax, ay, ux, uy, mx, my, len, half, +//! refOff)×n]`; Ausgabe `[n, ax, ay, bx, by …]` (freie Teilstücke der Umrisskanten). + +use crate::flat_read::Reader; +use crate::jsmath::hypot2; +use crate::jsnum::{max, min}; + +pub const CUTOUT_EPS: f64 = 1e-9; + +#[derive(Clone, Copy, Debug, PartialEq)] +struct V { + x: f64, + y: f64, +} + +fn v(x: f64, y: f64) -> V { + V { x, y } +} +fn sub(a: V, b: V) -> V { + v(a.x - b.x, a.y - b.y) +} +fn add(a: V, b: V) -> V { + v(a.x + b.x, a.y + b.y) +} +fn scale(a: V, s: f64) -> V { + v(a.x * s, a.y * s) +} +fn dot(p: V, q: V) -> f64 { + p.x * q.x + p.y * q.y +} +fn cross(p: V, q: V) -> f64 { + p.x * q.y - p.y * q.x +} +fn normalize(a: V) -> V { + let l = hypot2(a.x, a.y); + let l = if l == 0.0 || l.is_nan() { 1.0 } else { l }; + v(a.x / l, a.y / l) +} +fn left_normal(a: V) -> V { + v(-a.y, a.x) +} +fn along(p1: V, p2: V, d: f64) -> V { + add(p1, scale(normalize(sub(p2, p1)), d)) +} +fn line_intersect(a: V, da: V, b: V, db: V) -> Option { + let denom = cross(da, db); + if denom.abs() < 1e-9 { + return None; + } + let t = cross(sub(b, a), db) / denom; + Some(add(a, scale(da, t))) +} + +#[derive(Clone, Copy, Debug)] +struct Line { + point: V, + dir: V, +} + +fn clipped_band(start: V, end: V, off_a: f64, off_b: f64, sc: Option, ec: Option) -> [V; 4] { + let u = normalize(sub(end, start)); + let n = left_normal(u); + let edge_start = |off: f64| { + let base = add(start, scale(n, off)); + match sc { + None => base, + Some(c) => line_intersect(base, u, c.point, c.dir).unwrap_or(base), + } + }; + let edge_end = |off: f64| { + let base = add(end, scale(n, off)); + match ec { + None => base, + Some(c) => line_intersect(base, u, c.point, c.dir).unwrap_or(base), + } + }; + [edge_start(off_a), edge_end(off_a), edge_end(off_b), edge_start(off_b)] +} + +/// Loch-Intervalle vom Segment `[s,e]` abziehen (wie `subtractIntervals` in TS). +pub fn subtract_intervals(s: f64, e: f64, holes: &[(f64, f64)]) -> Vec<(f64, f64)> { + let mut clipped: Vec<(f64, f64)> = holes + .iter() + .map(|&(a, b)| (max(s, min(a, b)), min(e, max(a, b)))) + .filter(|&(a, b)| b > a + CUTOUT_EPS) + .collect(); + clipped.sort_by(|p, q| p.0.partial_cmp(&q.0).unwrap_or(std::cmp::Ordering::Equal)); + let mut parts = Vec::new(); + let mut cursor = s; + for (a, b) in clipped { + if a > cursor + CUTOUT_EPS { + parts.push((cursor, a)); + } + if b > cursor { + cursor = b; + } + } + if cursor < e - CUTOUT_EPS { + parts.push((cursor, e)); + } + parts +} + +#[derive(Clone, Copy, Debug)] +struct Footprint { + a: V, + u: V, + m: V, + len: f64, + half: f64, + ref_off: f64, +} + +fn clip_slab(f0: f64, fd: f64, lo: f64, hi: f64) -> Option<(f64, f64)> { + if fd.abs() < 1e-12 { + return if f0 >= lo - CUTOUT_EPS && f0 <= hi + CUTOUT_EPS { Some((0.0, 1.0)) } else { None }; + } + let mut ta = (lo - f0) / fd; + let mut tb = (hi - f0) / fd; + if ta > tb { + std::mem::swap(&mut ta, &mut tb); + } + Some((ta, tb)) +} + +/// Intervall `[t0,t1] ⊆ [0,1]`, über das `pa→pb` im Wand-Footprint liegt. +fn segment_inside(pa: V, pb: V, fp: &Footprint) -> Option<(f64, f64)> { + let d = sub(pb, pa); + let rel = sub(pa, fp.a); + let su = clip_slab(dot(rel, fp.u), dot(d, fp.u), -fp.half, fp.len + fp.half)?; + let sm = clip_slab(dot(rel, fp.m), dot(d, fp.m), fp.ref_off - fp.half, fp.ref_off + fp.half)?; + let t0 = max(max(0.0, su.0), sm.0); + let t1 = min(min(1.0, su.1), sm.1); + if t1 > t0 + CUTOUT_EPS { + Some((t0, t1)) + } else { + None + } +} + +// ── Decken-Umriss ─────────────────────────────────────────────────────────── + +pub fn ceiling_outline(buf: &[f64]) -> Vec { + (|| { + let mut r = Reader::new(buf); + let ring: Vec = r.ring()?.into_iter().map(|p| v(p[0], p[1])).collect(); + let n_bridge = r.count()?; + let mut bridge = Vec::with_capacity(n_bridge); + for _ in 0..n_bridge { + bridge.push(r.num()?); + } + let n_fp = r.count()?; + let mut fps = Vec::with_capacity(n_fp); + for _ in 0..n_fp { + let a = [r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?]; + fps.push(Footprint { a: v(a[0], a[1]), u: v(a[2], a[3]), m: v(a[4], a[5]), len: a[6], half: a[7], ref_off: a[8] }); + } + let n = ring.len(); + let mut lines: Vec = Vec::new(); + let mut count = 0usize; + for i in 0..n { + if bridge.contains(&(i as f64)) { + continue; + } + let a = ring[i]; + let b = ring[(i + 1) % n]; + let holes: Vec<(f64, f64)> = fps.iter().filter_map(|fp| segment_inside(a, b, fp)).collect(); + let d = sub(b, a); + for (t0, t1) in subtract_intervals(0.0, 1.0, &holes) { + let p = add(a, scale(d, t0)); + let q = add(a, scale(d, t1)); + lines.extend([p.x, p.y, q.x, q.y]); + count += 1; + } + } + let mut out = vec![count as f64]; + out.extend(lines); + Some(out) + })() + .unwrap_or_default() +} + +// ── Wand-Poché ────────────────────────────────────────────────────────────── + +struct LayerCuts { + start: Vec>, + end: Vec>, + start_side: Vec>, + end_side: Vec>, +} + +#[derive(Clone, Copy)] +struct Cutout { + from: f64, + to: f64, + off_a: f64, + off_b: f64, +} + +fn read_line(r: &mut Reader) -> Option> { + let has = r.num()?; + let (px, py, dx, dy) = (r.num()?, r.num()?, r.num()?, r.num()?); + Some(if has != 0.0 { Some(Line { point: v(px, py), dir: v(dx, dy) }) } else { None }) +} + +#[derive(Default)] +struct Out { + buf: Vec, + n: usize, +} + +impl Out { + fn polygon(&mut self, art: f64, layer: usize, no_stroke: &[f64], pts: &[V; 4]) { + self.n += 1; + self.buf.extend([1.0, art, layer as f64, no_stroke.len() as f64]); + self.buf.extend_from_slice(no_stroke); + for p in pts { + self.buf.extend([p.x, p.y]); + } + } + fn line(&mut self, art: f64, layer: usize, a: V, b: V) { + self.n += 1; + self.buf.extend([2.0, art, layer as f64, a.x, a.y, b.x, b.y]); + } +} + +const ART_VIEW: f64 = 0.0; +const ART_GROB: f64 = 1.0; +const ART_BAND: f64 = 2.0; +const ART_OUTLINE: f64 = 3.0; +const LINE_JOINT_L: f64 = 0.0; +const LINE_JOINT: f64 = 1.0; +const LINE_OUTLINE: f64 = 2.0; + +fn join_edges(sc: Option, ec: Option) -> Vec { + let mut e = Vec::new(); + if ec.is_some() { + e.push(1.0); + } + if sc.is_some() { + e.push(3.0); + } + e +} + +pub fn wall_poche(buf: &[f64]) -> Vec { + wall_poche_inner(buf).unwrap_or_default() +} + +fn wall_poche_inner(buf: &[f64]) -> Option> { + let mut r = Reader::new(buf); + let (sx, sy, ex, ey) = (r.num()?, r.num()?, r.num()?, r.num()?); + let (total, ref_off) = (r.num()?, r.num()?); + let grob = r.num()? != 0.0; + let view_only = r.num()? != 0.0; + let n_layers = r.count()?; + let mut thick = Vec::with_capacity(n_layers); + for _ in 0..n_layers { + thick.push(r.num()?); + } + let start_cut = read_line(&mut r)?; + let end_cut = read_line(&mut r)?; + let has_layer_cuts = r.num()? != 0.0; + let mut layer_cuts = None; + if has_layer_cuts { + let mut lc = LayerCuts { start: vec![], end: vec![], start_side: vec![], end_side: vec![] }; + for _ in 0..n_layers { + lc.start.push(read_line(&mut r)?); + lc.end.push(read_line(&mut r)?); + lc.start_side.push(read_line(&mut r)?); + lc.end_side.push(read_line(&mut r)?); + } + layer_cuts = Some(lc); + } + let n_cut = r.count()?; + let mut span_cutouts = Vec::with_capacity(n_cut); + for _ in 0..n_cut { + span_cutouts.push(Cutout { from: r.num()?, to: r.num()?, off_a: r.num()?, off_b: r.num()? }); + } + let n_gap = r.count()?; + let mut gaps = Vec::with_capacity(n_gap); + for _ in 0..n_gap { + gaps.push((r.num()?, r.num()?)); + } + if !(sx.is_finite() && sy.is_finite() && ex.is_finite() && ey.is_finite() && total.is_finite() && ref_off.is_finite()) { + return None; + } + + let wstart = v(sx, sy); + let wend = v(ex, ey); + let axis_len = hypot2(ex - sx, ey - sy); + let mut segments: Vec<(f64, f64)> = Vec::new(); + let mut cursor = 0.0; + for &(from, to) in &gaps { + if from > cursor { + segments.push((cursor, from)); + } + cursor = max(cursor, to); + } + if cursor < axis_len { + segments.push((cursor, axis_len)); + } + + let mut o = Out::default(); + for &(s, e) in &segments { + let p1 = along(wstart, wend, s); + let p2 = along(wstart, wend, e); + let sc = if s <= 1e-6 { start_cut } else { None }; + let ec = if e >= axis_len - 1e-6 { end_cut } else { None }; + + if view_only { + o.polygon(ART_VIEW, 0, &join_edges(sc, ec), &clipped_band(p1, p2, ref_off - total / 2.0, ref_off + total / 2.0, sc, ec)); + continue; + } + if grob { + o.polygon(ART_GROB, 0, &join_edges(sc, ec), &clipped_band(p1, p2, ref_off - total / 2.0, ref_off + total / 2.0, sc, ec)); + continue; + } + + let band_join_edges = join_edges(sc, ec); + let seg_cutouts: Vec = span_cutouts + .iter() + .filter(|c| min(c.from, c.to) < e - CUTOUT_EPS && max(c.from, c.to) > s + CUTOUT_EPS) + .copied() + .collect(); + let axis_pt = |d: f64| if d == s { p1 } else if d == e { p2 } else { along(wstart, wend, d) }; + let mut off = ref_off - total / 2.0; + for li in 0..n_layers { + let layer_start_cut = if s <= 1e-6 { + match &layer_cuts { + Some(lc) => lc.start[li], + None => sc, + } + } else { + None + }; + let layer_end_cut = if e >= axis_len - 1e-6 { + match &layer_cuts { + Some(lc) => lc.end[li], + None => ec, + } + } else { + None + }; + let band_lo = off; + let band_hi = off + thick[li]; + let mut band_holes: Vec<(f64, f64)> = Vec::new(); + for c in &seg_cutouts { + let c_lo = min(c.off_a, c.off_b); + let c_hi = max(c.off_a, c.off_b); + if band_lo < c_hi - CUTOUT_EPS && band_hi > c_lo + CUTOUT_EPS { + band_holes.push((c.from, c.to)); + } + } + for (a, b) in subtract_intervals(s, e, &band_holes) { + let bsc = if a <= s + CUTOUT_EPS { layer_start_cut } else { None }; + let bec = if b >= e - CUTOUT_EPS { layer_end_cut } else { None }; + o.polygon(ART_BAND, li, &band_join_edges, &clipped_band(axis_pt(a), axis_pt(b), off, off + thick[li], bsc, bec)); + } + let side_start = if s <= 1e-6 { layer_cuts.as_ref().and_then(|lc| lc.start_side[li]) } else { None }; + let side_end = if e >= axis_len - 1e-6 { layer_cuts.as_ref().and_then(|lc| lc.end_side[li]) } else { None }; + if side_start.is_some() || side_end.is_some() { + let u_seg = normalize(sub(p2, p1)); + let n_seg = left_normal(u_seg); + let side_point = |base: V, layer_off: f64, cut: Line| { + let pt = add(base, scale(n_seg, layer_off)); + line_intersect(pt, u_seg, cut.point, cut.dir).unwrap_or(pt) + }; + if let Some(c) = side_start { + o.line(LINE_JOINT_L, li, side_point(p1, off, c), side_point(p1, off + thick[li], c)); + } + if let Some(c) = side_end { + o.line(LINE_JOINT_L, li, side_point(p2, off, c), side_point(p2, off + thick[li], c)); + } + } + off += thick[li]; + if li + 1 < n_layers { + let mut fuge_holes: Vec<(f64, f64)> = Vec::new(); + for c in &seg_cutouts { + let c_lo = min(c.off_a, c.off_b); + let c_hi = max(c.off_a, c.off_b); + if off >= c_lo - CUTOUT_EPS && off <= c_hi + CUTOUT_EPS { + fuge_holes.push((c.from, c.to)); + } + } + for (a, b) in subtract_intervals(s, e, &fuge_holes) { + let jsc = if a <= s + CUTOUT_EPS { sc } else { None }; + let jec = if b >= e - CUTOUT_EPS { ec } else { None }; + let jq = clipped_band(axis_pt(a), axis_pt(b), off, off, jsc, jec); + o.line(LINE_JOINT, li, jq[0], jq[1]); + } + } + } + + let off_lo = ref_off - total / 2.0; + let off_hi = ref_off + total / 2.0; + let mut holes_hi: Vec<(f64, f64)> = Vec::new(); + let mut holes_lo: Vec<(f64, f64)> = Vec::new(); + for c in &seg_cutouts { + if (c.off_a - off_hi).abs() < 1e-6 { + holes_hi.push((c.from, c.to)); + } else if (c.off_a - off_lo).abs() < 1e-6 { + holes_lo.push((c.from, c.to)); + } + } + let mut outline_no_stroke = band_join_edges.clone(); + if !holes_hi.is_empty() { + outline_no_stroke.push(2.0); + } + if !holes_lo.is_empty() { + outline_no_stroke.push(0.0); + } + o.polygon(ART_OUTLINE, 0, &outline_no_stroke, &clipped_band(p1, p2, off_lo, off_hi, sc, ec)); + let mut near_edge = |edge_off: f64, holes: &[(f64, f64)]| { + for (a, b) in subtract_intervals(s, e, holes) { + let nsc = if a <= s + CUTOUT_EPS { sc } else { None }; + let nec = if b >= e - CUTOUT_EPS { ec } else { None }; + let jq = clipped_band(axis_pt(a), axis_pt(b), edge_off, edge_off, nsc, nec); + o.line(LINE_OUTLINE, 0, jq[0], jq[1]); + } + }; + if !holes_hi.is_empty() { + near_edge(off_hi, &holes_hi); + } + if !holes_lo.is_empty() { + near_edge(off_lo, &holes_lo); + } + } + let mut out = Vec::with_capacity(o.buf.len() + 1); + out.push(o.n as f64); + out.extend(o.buf); + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + const NO_LINE: [f64; 5] = [0.0; 5]; + + fn wall(len: f64, grob: bool, gaps: &[(f64, f64)]) -> Vec { + let mut b = vec![0.0, 0.0, len, 0.0, 0.3, 0.0, grob as u8 as f64, 0.0, 2.0, 0.1, 0.2]; + b.extend(NO_LINE); + b.extend(NO_LINE); + b.extend([0.0, 0.0, gaps.len() as f64]); + for g in gaps { + b.extend([g.0, g.1]); + } + b + } + + fn count(out: &[f64], tag: f64) -> usize { + let (mut i, mut n) = (1, 0); + for _ in 0..out[0] as usize { + let t = out[i]; + if t == tag { + n += 1; + } + i += if t == 1.0 { 4 + out[i + 3] as usize + 8 } else { 7 }; + } + assert_eq!(i, out.len()); + n + } + + #[test] + fn intervalle_abziehen() { + assert_eq!(subtract_intervals(0.0, 5.0, &[]), vec![(0.0, 5.0)]); + assert_eq!(subtract_intervals(0.0, 5.0, &[(1.0, 2.0), (1.5, 3.0)]), vec![(0.0, 1.0), (3.0, 5.0)]); + assert!(subtract_intervals(0.0, 5.0, &[(-1.0, 9.0)]).is_empty()); + } + + #[test] + fn wand_ohne_luecke_hat_zwei_baender_fuge_und_umriss() { + let o = wall_poche(&wall(4.0, false, &[])); + assert_eq!(count(&o, 1.0), 3); // 2 Bänder + Umriss + assert_eq!(count(&o, 2.0), 1); // 1 Fuge + } + + #[test] + fn luecke_teilt_die_wand_in_zwei_segmente() { + let o = wall_poche(&wall(4.0, false, &[(1.0, 2.0)])); + assert_eq!(count(&o, 1.0), 6); + assert_eq!(count(&wall_poche(&wall(4.0, true, &[(1.0, 2.0)])), 1.0), 2); + } + + #[test] + fn unsinn_ohne_panic() { + assert!(wall_poche(&[1.0, 2.0]).is_empty()); + let mut b = wall(4.0, false, &[]); + b[0] = f64::NAN; + assert!(wall_poche(&b).is_empty()); + assert!(ceiling_outline(&[3.0, 0.0]).is_empty()); + } + + #[test] + fn decken_umriss_wird_von_wand_verdeckt() { + // Quadrat 4×4, Wand entlang der unteren Kante (Mitte y=0, Dicke 0.4) + let mut b = vec![4.0, 0.0, 0.0, 4.0, 0.0, 4.0, 4.0, 0.0, 4.0, 0.0, 1.0]; + b.extend([0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 4.0, 0.2, 0.0]); + let o = ceiling_outline(&b); + assert_eq!(o[0], 3.0); // untere Kante entfällt, drei freie Kanten + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 78d14dcb..2cea7b21 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -26,6 +26,7 @@ mod wall_mesh_cut; mod plan_buf; mod gpu_compile; mod plan_stairs; +mod plan_walls; mod hatch; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/plan_walls.rs b/src-tauri/core/src/web/plan_walls.rs new file mode 100644 index 00000000..5642663f --- /dev/null +++ b/src-tauri/core/src/web/plan_walls.rs @@ -0,0 +1,15 @@ +//! Bindungen von Wand-Poché und Decken-Umriss im Grundriss (`crate::plan_walls`). Layout s. dort. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Wand-Poché-Geometrie einer Wand; Unsinn → leer. +#[wasm_bindgen] +pub fn plan_wall_poche_flat(buf: &[f64]) -> Vec { + crate::plan_walls::wall_poche(buf) +} + +/// Freie Teilstücke eines Decken-Umrisses gegen Wand-Footprints; Unsinn → leer. +#[wasm_bindgen] +pub fn plan_ceiling_outline_flat(buf: &[f64]) -> Vec { + crate::plan_walls::ceiling_outline(buf) +} diff --git a/src/plan/generatePlan/ceilings.ts b/src/plan/generatePlan/ceilings.ts index 6e5dfeba..beefb215 100644 --- a/src/plan/generatePlan/ceilings.ts +++ b/src/plan/generatePlan/ceilings.ts @@ -7,7 +7,7 @@ import type { Ceiling, LayerCategory, Project } from "../../model/types"; import { getCeilingType, getComponent } from "../../model/types"; import { mergeHoles } from "../../geometry/polygonHoles"; -import { add, scale, sub } from "../../model/geometry"; +import { core } from "../../engine/coreWasm"; import { NO_HATCH, OVERHEAD_DASH, @@ -21,7 +21,7 @@ import { type DetailLevel, type Primitive, } from "./shared"; -import { segmentInsideWallBand, subtractIntervals, type WallFootprint } from "./walls"; +import type { WallFootprint } from "./walls"; /** * Decken-Poché im Grundriss: die Decke liegt als Slab ÜBER der Schnittebene und @@ -116,32 +116,25 @@ export function addCeilingPoche( // der Umriss ganz; nur Überstände (Vordach/Balkon jenseits der Wand) // bleiben sichtbar. Brückenkanten (künstliche Verbindung Aussenring↔Loch) // werden NICHT gestrichen. - const n = ring.length; - const bridgeSet = new Set(bridgeEdges); - for (let i = 0; i < n; i++) { - if (bridgeSet.has(i)) continue; - const a = ring[i]; - const b = ring[(i + 1) % n]; - const holes: Array<[number, number]> = []; - for (const fp of wallFootprints) { - const iv = segmentInsideWallBand(a, b, fp); - if (iv) holes.push(iv); - } - const d = sub(b, a); - for (const [t0, t1] of subtractIntervals(0, 1, holes)) { - out.push({ - kind: "line", - a: add(a, scale(d, t0)), - b: add(a, scale(d, t1)), - cls: "ceiling-outline", - // Überkopf-Ansichtslinie (Decke liegt als Slab über der Schnittebene) → - // gestrichelt statt durchgezogen (BIM-Konvention) — die DICKE folgt - // aber ceiling.strokeWeight/-Source wie bei der Wand (s. Aufrufer). - weightMm: lwMm * LAYER_DETAIL_FACTOR[detail], - dash: OVERHEAD_DASH, - color: stroke, - greyed, - }); - } + // Die freien Teilstücke berechnet der Kern (`plan_walls.rs`, [K3a]). + const buf: number[] = [ring.length]; + for (const p of ring) buf.push(p.x, p.y); + buf.push(bridgeEdges.length, ...bridgeEdges, wallFootprints.length); + for (const fp of wallFootprints) buf.push(fp.a.x, fp.a.y, fp.u.x, fp.u.y, fp.m.x, fp.m.y, fp.len, fp.half, fp.refOff); + const f = core().plan_ceiling_outline_flat(Float64Array.from(buf)); + for (let i = 0; i < f[0]; i++) { + out.push({ + kind: "line", + a: { x: f[1 + 4 * i], y: f[2 + 4 * i] }, + b: { x: f[3 + 4 * i], y: f[4 + 4 * i] }, + cls: "ceiling-outline", + // Überkopf-Ansichtslinie (Decke liegt als Slab über der Schnittebene) → + // gestrichelt statt durchgezogen (BIM-Konvention) — die DICKE folgt + // aber ceiling.strokeWeight/-Source wie bei der Wand (s. Aufrufer). + weightMm: lwMm * LAYER_DETAIL_FACTOR[detail], + dash: OVERHEAD_DASH, + color: stroke, + greyed, + }); } } diff --git a/src/plan/generatePlan/walls.ts b/src/plan/generatePlan/walls.ts index 06f82a64..df9dd850 100644 --- a/src/plan/generatePlan/walls.ts +++ b/src/plan/generatePlan/walls.ts @@ -2,24 +2,19 @@ // die Wand-Footprints (für das Verdecken darunterliegender Decken-Umrisse, s. // {@link ../ceilings}) und die eigentliche Wand-Poché (Schichten + Umriss + // Öffnungsaussparungen + T-Stoss-/Gehrungs-Behandlung). +// +// Die Geometrie der Poché entsteht im Rust-Kern (`src-tauri/core/src/plan_walls.rs`, [K3a]); hier +// bleibt die Stilauflösung aus dem Modell (Bauteil, Schraffur, Farbe, Fugen-Linienstil) und die +// Übersetzung in `Primitive`-Objekte. Fällt mit [K3d] weg. import type { LayerCategory, Opening, Project, Vec2, Wall } from "../../model/types"; import { getComponent, getWallType, wallTypeThickness } from "../../model/types"; import { wallReferenceOffset } from "../../model/wall"; import { openingInterval } from "../../geometry/opening"; -import { - add, - along, - clippedBand, - dot, - leftNormal, - lineIntersect, - normalize, - scale, - sub, -} from "../../model/geometry"; +import { leftNormal, normalize, sub } from "../../model/geometry"; import type { Line } from "../../model/geometry"; import type { WallCuts } from "../../model/joins"; +import { core } from "../../engine/coreWasm"; import { HATCH_INK, HATCH_PAPER, @@ -33,6 +28,7 @@ import { resolveHatch, resolveHatchId, type DetailLevel, + type HatchRender, type Primitive, } from "./shared"; @@ -61,38 +57,6 @@ export function wallGaps( return gaps.sort((a, b) => a.from - b.from); } -/** Toleranz für die Achsen-Intervall-Arithmetik der Durchgangswand-Aussparungen. */ -export const CUTOUT_EPS = 1e-9; - -/** - * Zieht die Loch-Intervalle `holes` vom Segment `[s,e]` ab und liefert die - * verbleibenden (gezeichneten) Teil-Intervalle in Achsen-Metern. Löcher werden - * auf `[s,e]` geklemmt, sortiert und vereinigt; leeres Ergebnis heisst „ganz - * ausgespart". Ist `holes` leer, kommt exakt `[[s,e]]` zurück (unverändertes - * Verhalten für Wände ohne Aussparung). - */ -export function subtractIntervals( - s: number, - e: number, - holes: Array<[number, number]>, -): Array<[number, number]> { - const clipped = holes - .map(([a, b]): [number, number] => [ - Math.max(s, Math.min(a, b)), - Math.min(e, Math.max(a, b)), - ]) - .filter(([a, b]) => b > a + CUTOUT_EPS) - .sort((p, q) => p[0] - q[0]); - const parts: Array<[number, number]> = []; - let cursor = s; - for (const [a, b] of clipped) { - if (a > cursor + CUTOUT_EPS) parts.push([cursor, a]); - if (b > cursor) cursor = b; - } - if (cursor < e - CUTOUT_EPS) parts.push([cursor, e]); - return parts; -} - /** * Wand-Footprint als orientiertes Rechteck (OBB) für das Verdecken der * darunterliegenden Decke im Grundriss: Achs-Startpunkt + Einheits-Richtung `u` @@ -133,49 +97,37 @@ export function buildWallFootprints(project: Project, walls: Wall[]): WallFootpr return out; } -/** - * Parametrisches Intervall [t0,t1] ⊆ [0,1], über das die Strecke `pa→pb` - * INNERHALB des Wand-Footprints liegt (also von der Wand verdeckt). `null`, wenn - * die Strecke den Footprint nicht schneidet. OBB-Test über zwei Slabs: Projektion - * auf die Achse `u` (Bereich [−half, len+half]) und auf die Normale `m` (Bereich - * [refOff−half, refOff+half]); das Schnitt-Intervall beider Slabs ∩ [0,1] ist die - * verdeckte Strecke. - */ -export function segmentInsideWallBand( - pa: Vec2, - pb: Vec2, - fp: WallFootprint, -): [number, number] | null { - const d = sub(pb, pa); - const rel = sub(pa, fp.a); - const clipSlab = ( - f0: number, - fd: number, - lo: number, - hi: number, - ): [number, number] | null => { - if (Math.abs(fd) < 1e-12) - return f0 >= lo - CUTOUT_EPS && f0 <= hi + CUTOUT_EPS ? [0, 1] : null; - let ta = (lo - f0) / fd; - let tb = (hi - f0) / fd; - if (ta > tb) [ta, tb] = [tb, ta]; - return [ta, tb]; - }; - const su = clipSlab(dot(rel, fp.u), dot(d, fp.u), -fp.half, fp.len + fp.half); - if (!su) return null; - const sm = clipSlab( - dot(rel, fp.m), - dot(d, fp.m), - fp.refOff - fp.half, - fp.refOff + fp.half, - ); - if (!sm) return null; - const t0 = Math.max(0, su[0], sm[0]); - const t1 = Math.min(1, su[1], sm[1]); - return t1 > t0 + CUTOUT_EPS ? [t0, t1] : null; -} +const lineBuf = (l: Line | null | undefined): number[] => + l ? [1, l.point.x, l.point.y, l.dir.x, l.dir.y] : [0, 0, 0, 0, 0]; -const length = (w: Wall): number => Math.hypot(w.end.x - w.start.x, w.end.y - w.start.y); +/** Eingabe der Kern-Funktion `plan_wall_poche_flat` (Aufbau: `plan_walls.rs`). */ +function encodeWallPoche( + wall: Wall, + layerThickness: number[], + total: number, + refOff: number, + gaps: WallGap[], + cuts: WallCuts, + grob: boolean, + viewOnly: boolean, +): Float64Array { + const b: number[] = [wall.start.x, wall.start.y, wall.end.x, wall.end.y, total, refOff, grob ? 1 : 0, viewOnly ? 1 : 0]; + b.push(layerThickness.length, ...layerThickness); + b.push(...lineBuf(cuts.startCut), ...lineBuf(cuts.endCut)); + const lc = cuts.layerCuts; + b.push(lc ? 1 : 0); + if (lc) { + for (let i = 0; i < layerThickness.length; i++) { + b.push(...lineBuf(lc.start[i]), ...lineBuf(lc.end[i]), ...lineBuf(lc.startSide[i]), ...lineBuf(lc.endSide[i])); + } + } + const sc = cuts.spanCutouts ?? []; + b.push(sc.length); + for (const c of sc) b.push(c.from, c.to, c.offA, c.offB); + b.push(gaps.length); + for (const g of gaps) b.push(g.from, g.to); + return Float64Array.from(b); +} /** * Wand als gefüllte Schnittfläche (Poché), um Öffnungen ausgespart. @@ -188,6 +140,9 @@ const length = (w: Wall): number => Math.hypot(w.end.x - w.start.x, w.end.y - w. * volle Wanddicke (Füllung = Farbe des „Backbone"-Bauteils mit höchster * joinPriority) mit dicker Umrisslinie. Bewusst vereinfacht (≙ DOSSIER * „Einfach"). + * + * Segmente, Gehrungsbänder, Schichtfugen und Durchgangswand-Aussparungen berechnet der Kern; + * hier kommen nur Stil und Pick-ID (`wallId`) dazu. */ export function addWallPoche( out: Primitive[], @@ -206,311 +161,114 @@ export function addWallPoche( ): void { const wt = getWallType(project, wall); const total = wallTypeThickness(wt); - // Versatz der Schichtstapelung über die Dicke gemäß Referenzlinie (center=0, - // left=+T/2, right=−T/2). Alle Band-Offsets unten werden hierum verschoben, - // sodass die Achse bei „außen"/„innen" auf der jeweiligen Wandfläche liegt. const refOff = wallReferenceOffset(wall, total); - // Jede Schicht-/Umrissfläche trägt die Wand-ID, damit ein Links-Klick die - // GANZE Wand (alle Bänder) markiert und die PlanView die wallId nach oben - // melden kann. const wallId = wall.id; - // Achswinkel der Wand (Modell, Grad) — treibt wandbezogene Schraffuren - // ({@link resolveHatch}), damit z. B. eine Diagonale oder die Dämmungsstriche - // mit der Wandorientierung mitdrehen. + // Achswinkel der Wand (Modell, Grad) — treibt wandbezogene Schraffuren ({@link resolveHatch}). const wallAngleDeg = (Math.atan2(wall.end.y - wall.start.y, wall.end.x - wall.start.x) * 180) / Math.PI; - // Strich-/Umrandungsfarbe der Wand: optionale Übersteuerung (wall.color), - // sonst der Default-Poché-Strich. Betrifft NUR die Linienfarbe (Umriss + - // Schichtfugen), nicht die Schicht-Füllfarben/Schraffuren. + // Strich-/Umrandungsfarbe der Wand: optionale Übersteuerung (wall.color), sonst der + // Default-Poché-Strich. Betrifft NUR die Linienfarbe, nicht die Schicht-Füllfarben/Schraffuren. const stroke = wall.color ?? POCHE_STROKE; - - // Öffnungs-Intervalle entlang der Wandachse, sortiert (bereits vereint). - const openings = gaps; - - // Wand in Segmente zwischen den Öffnungen zerlegen. - let cursor = 0; - const segments: Array<[number, number]> = []; - for (const op of openings) { - if (op.from > cursor) segments.push([cursor, op.from]); - cursor = Math.max(cursor, op.to); - } - const axisLen = length(wall); - if (cursor < axisLen) segments.push([cursor, axisLen]); - const outlineMm = wallLwMm * OUTLINE_DETAIL_FACTOR[detail]; const layerLineMm = LAYER_LINE_MM * LAYER_DETAIL_FACTOR[detail]; - // Vereinfachte Füllung (grob): immer schwarze Vollfüllung, keine Schraffur - // Durchgangswand-Aussparungen (Phase 1c): über diese Achsen-Intervalle × Quer- - // Offsetbereiche wird die Nah-Putz-Zone der Durchgangswand echt ausgeschnitten - // (der Abzweig-Kern sticht durch). `offA` ist stets die Nahfläche, `offB` die - // Rückgrat-Nahfläche (siehe SpanCutout in model/joins.ts). Leer ⇒ heutiges - // Verhalten (Wand ohne T-Durchstoss). - const spanCutouts = cuts.spanCutouts ?? []; + const f = core().plan_wall_poche_flat( + encodeWallPoche(wall, wt.layers.map((l) => l.thickness), total, refOff, gaps, cuts, detail === "grob", viewOnly), + ); + if (f.length === 0) return; - // Kanten-Indizes der inneren Gehrungs-Stirnflächen (die Diagonalen am Knoten). - // clippedBand liefert [A.start, A.end, B.end, B.start] → Kante 1 (A.end→B.end) - // ist die endCut-Stirnfläche, Kante 3 (B.start→A.start) die startCut-Stirnfläche. - // Diese werden NICHT umrissen: sonst 45°-Naht zwischen gleichfarbigen Schichten - // + überschießende Gehrungs-Barbe am Eck-Apex. Freie Enden (kein Cut) bleiben - // rechtwinklig gestrichen. Die Längskanten (Schichtfugen) bleiben stets sichtbar. - const joinEdges = (startCut: Line | null, endCut: Line | null): number[] => { - const e: number[] = []; - if (endCut) e.push(1); - if (startCut) e.push(3); - return e; - }; - - for (const [s, e] of segments) { - const p1 = along(wall.start, wall.end, s); - const p2 = along(wall.start, wall.end, e); - // Nur die echten Wandenden bekommen die Gehrung. Türnahe Segmentenden - // bleiben rechtwinklig (kein Schnitt). - const startCut = s <= 1e-6 ? cuts.startCut : null; - const endCut = e >= axisLen - 1e-6 ? cuts.endCut : null; - - if (viewOnly) { - // Ansichts-Wand (unter der Schnittebene): ein Umriss über die volle Dicke - // als Haarlinie, ohne Füllung/Schraffur. Segment-/Gehrungs-/Öffnungs-Logik - // bleibt dieselbe wie im Schnittfall (nur eben ohne Poché). - out.push({ - kind: "polygon", - pts: clippedBand(p1, p2, refOff - total / 2, refOff + total / 2, startCut, endCut), - fill: "none", - stroke, - strokeWidthMm: layerLineMm, - hatch: NO_HATCH, - greyed, - noStrokeEdges: joinEdges(startCut, endCut), - wallId, - }); - continue; - } - - if (detail === "grob") { - // Eine Sammelfläche über die volle Dicke, ohne Schraffur, dicker Umriss. - // Bei grob: immer Vollschwarz-Füllung gemäß SIA 400 Anhang B.9, Figur 36 - out.push({ - kind: "polygon", - pts: clippedBand(p1, p2, refOff - total / 2, refOff + total / 2, startCut, endCut), - fill: HATCH_INK, - stroke, - strokeWidthMm: outlineMm, - hatch: NO_HATCH, - greyed, - noStrokeEdges: joinEdges(startCut, endCut), - wallId, - }); - continue; - } - - // mittel/fein: Schichten von außen (-T/2) nach innen (+T/2) stapeln. Jede - // Schicht löst Bauteil (Füllfarbe) + Schraffur (Muster/Maßstab/Winkel/Farbe) - // auf. Die Bänder tragen NUR Füllung + Schraffur (kein eigener Umriss); jede - // innere Schichtfuge wird als EIGENSTÄNDIGE, stilisierbare Linie gezeichnet. - const bandJoinEdges = joinEdges(startCut, endCut); - // Nur die Aussparungen, die dieses Segment [s,e] entlang der Achse berühren. - const segCutouts = spanCutouts.filter( - (c) => - Math.min(c.from, c.to) < e - CUTOUT_EPS && - Math.max(c.from, c.to) > s + CUTOUT_EPS, - ); - // Punkt entlang der Wandachse bei Achsen-Meter `d` (p1/p2 an den Rändern). - const axisPt = (d: number): Vec2 => - d === s ? p1 : d === e ? p2 : along(wall.start, wall.end, d); - // Materialbewusster T-Stoss (siehe resolveJoinPriority in model/joins.ts): - // liegt eine Pro-Schicht-Cut-Überschreibung vor, ersetzt sie PRO SCHICHT den - // einheitlichen startCut/endCut — nur an den echten Wandenden (dieselbe - // Maskierung wie oben für startCut/endCut, s <= 1e-6 / e >= axisLen-1e-6). - // Fehlt sie, bleibt alles wie zuvor (startCut/endCut für jede Schicht). - const layerCuts = cuts.layerCuts; - let off = refOff - total / 2; - for (let li = 0; li < wt.layers.length; li++) { - const layer = wt.layers[li]; - const comp = getComponent(project, layer.componentId); + // Stil je Schicht erst beim ersten Band lösen (wie zuvor: nur wenn die Wand Segmente hat). + const layerStyle = new Map(); + const styleOf = (li: number) => { + let st = layerStyle.get(li); + if (!st) { + const comp = getComponent(project, wt.layers[li].componentId); const layerHatchId = resolveHatchId(wall.hatchId, wall.hatchSource, category, comp.hatchId) ?? comp.hatchId; - const layerHatch = resolveHatch( + const hatch = resolveHatch( project, layerHatchId, wallAngleDeg, resolveForeground(comp, wall.foreground, category, wall.foregroundSource), ); - // SIA-Poché: neutraler Hintergrund (Papier) statt Bauteil-Albedo, die - // Schichtschraffur (fest in HATCH_INK, siehe resolveHatch) liegt darüber; - // Vollmuster ("solid") = Tinten-Poché. - const layerSolid = layerHatch.pattern === "solid"; + // SIA-Poché: neutraler Hintergrund (Papier) statt Bauteil-Albedo, die Schichtschraffur + // (fest in HATCH_INK, siehe resolveHatch) liegt darüber; Vollmuster ("solid") = Tinten-Poché. const bgOverride = resolveBackground(comp, wall.background, category, wall.backgroundSource); - const layerStartCut = s <= 1e-6 ? (layerCuts ? layerCuts.start[li] : startCut) : null; - const layerEndCut = e >= axisLen - 1e-6 ? (layerCuts ? layerCuts.end[li] : endCut) : null; - // Durchgangswand-Aussparung: liegt der Quer-Offsetbereich dieses Bandes - // [off, off+thickness] im Nah-Putz-Bereich einer Aussparung, wird das Band - // entlang der Achse in Teil-Bänder VOR/NACH dem Intervall zerlegt (das - // Durchstoss-Stück entfällt). Ohne Überlappung bleibt genau ein Band - // [s,e] (unverändertes Verhalten). - const bandLo = off; - const bandHi = off + layer.thickness; - const bandHoles: Array<[number, number]> = []; - for (const c of segCutouts) { - const cLo = Math.min(c.offA, c.offB); - const cHi = Math.max(c.offA, c.offB); - if (bandLo < cHi - CUTOUT_EPS && bandHi > cLo + CUTOUT_EPS) - bandHoles.push([c.from, c.to]); - } - for (const [a, b] of subtractIntervals(s, e, bandHoles)) { - const sc = a <= s + CUTOUT_EPS ? layerStartCut : null; - const ec = b >= e - CUTOUT_EPS ? layerEndCut : null; + st = { hatch, fill: bgOverride ?? (hatch.pattern === "solid" ? HATCH_INK : HATCH_PAPER) }; + layerStyle.set(li, st); + } + return st; + }; + + const n = f[0]; + let i = 1; + for (let k = 0; k < n; k++) { + if (f[i] === 1) { + const art = f[i + 1]; + const li = f[i + 2]; + const nNo = f[i + 3]; + const noStrokeEdges = Array.from(f.subarray(i + 4, i + 4 + nNo)); + const q = i + 4 + nNo; + const pts = [0, 1, 2, 3].map((j) => ({ x: f[q + 2 * j], y: f[q + 2 * j + 1] })); + i = q + 8; + if (art === 2) { + const st = styleOf(li); out.push({ kind: "polygon", - pts: clippedBand(axisPt(a), axisPt(b), off, off + layer.thickness, sc, ec), - fill: bgOverride ?? (layerSolid ? HATCH_INK : HATCH_PAPER), - // Band ohne Umriss: keine Schichtfuge über die Bandkante, keine 45°-Naht - // am Knoten. Die Fugen kommen als separate `line`-Primitive (siehe unten). + pts, + fill: st.fill, + // Band ohne Umriss: keine Schichtfuge über die Bandkante, keine 45°-Naht am Knoten. + // Die Fugen kommen als separate `line`-Primitive. stroke: "none", strokeWidthMm: 0, - hatch: layerHatch, + hatch: st.hatch, greyed, - // Für die Ecktests/Konsistenz beibehalten (bei stroke:"none" wirkungslos). - noStrokeEdges: bandJoinEdges, + noStrokeEdges, + wallId, + }); + } else { + out.push({ + kind: "polygon", + pts, + // Grob: immer Vollschwarz-Füllung gemäss SIA 400 Anhang B.9, Figur 36. + fill: art === 1 ? HATCH_INK : "none", + stroke, + strokeWidthMm: art === 0 ? layerLineMm : outlineMm, + hatch: NO_HATCH, + greyed, + noStrokeEdges, wallId, }); } - // L-Anschluss: eine getrimmte Schicht (z. B. Putz), die an eine - // verschmelzende Nachbarschicht (durchlaufender Kern) grenzt, bekommt - // zusätzlich eine seitliche Cut-Linie entlang der Durchgangsachse — sie - // begrenzt die Schichtbreite dort, wo der Kern sie unterbricht (L-Form). - const sideStart = s <= 1e-6 ? layerCuts?.startSide[li] : null; - const sideEnd = e >= axisLen - 1e-6 ? layerCuts?.endSide[li] : null; - if (sideStart || sideEnd) { - const uSeg = normalize(sub(p2, p1)); - const nSeg = leftNormal(uSeg); - const sidePoint = (base: Vec2, layerOff: number, cut: Line): Vec2 => { - const pt = add(base, scale(nSeg, layerOff)); - return lineIntersect(pt, uSeg, cut.point, cut.dir) ?? pt; - }; - if (sideStart) { - out.push({ - kind: "line", - a: sidePoint(p1, off, sideStart), - b: sidePoint(p1, off + layer.thickness, sideStart), - cls: "layer-joint-l", - weightMm: layerLineMm, - color: stroke, - greyed, - }); - } - if (sideEnd) { - out.push({ - kind: "line", - a: sidePoint(p2, off, sideEnd), - b: sidePoint(p2, off + layer.thickness, sideEnd), - cls: "layer-joint-l", - weightMm: layerLineMm, - color: stroke, - greyed, - }); - } - } - off += layer.thickness; - // Innere Schichtfuge (zwischen dieser und der nächst-inneren Schicht) als - // eigene Linie am kumulierten Offset `off`, mit dem Cut der Bänder geclippt. - // Stil aus layer.jointLineStyleId (Gewicht/Farbe/Strich); Rückfall = Haar- - // linie (LAYER_LINE_MM) in Wandfarbe. Das Gewicht folgt demselben Detail- - // Faktor wie die frühere Schichtfuge (`layerLineMm`), damit die Detailgrade - // sich unverändert verhalten. Die innerste Schicht hat keine innere Fuge. - // Nutzt bewusst weiterhin den einheitlichen startCut/endCut (nicht die - // Pro-Schicht-Cuts): die Fuge markiert den Materialwechsel INNERHALB - // dieser Wand und bleibt daher an der bisherigen Nahfläche. - if (li < wt.layers.length - 1) { - const jls = layer.jointLineStyleId - ? project.lineStyles.find((l) => l.id === layer.jointLineStyleId) - : undefined; - // Durchgangswand-Aussparung: liegt die Fuge im (geschlossenen) Nah-Putz- - // Bereich einer Aussparung — inkl. der Rückgrat-Nahfläche (Merge-Kontakt) - // —, wird sie über das Durchstoss-Intervall unterbrochen. So bleibt an der - // Verschmelzungsfläche keine Trennlinie stehen. - const fugeHoles: Array<[number, number]> = []; - for (const c of segCutouts) { - const cLo = Math.min(c.offA, c.offB); - const cHi = Math.max(c.offA, c.offB); - if (off >= cLo - CUTOUT_EPS && off <= cHi + CUTOUT_EPS) - fugeHoles.push([c.from, c.to]); - } - for (const [a, b] of subtractIntervals(s, e, fugeHoles)) { - const sc = a <= s + CUTOUT_EPS ? startCut : null; - const ec = b >= e - CUTOUT_EPS ? endCut : null; - // clippedBand(pa, pb, off, off, …) liefert [edgeStart, edgeEnd, edgeEnd, - // edgeStart] → die zwei distinkten Endpunkte sind Index 0 (Start) und 1 - // (Ende), beide am Cut abgeschnitten wie die Bandlängskante. - const jq = clippedBand(axisPt(a), axisPt(b), off, off, sc, ec); - out.push({ - kind: "line", - a: jq[0], - b: jq[1], - cls: "layer-joint", - weightMm: jls ? jls.weight * LAYER_DETAIL_FACTOR[detail] : layerLineMm, - color: jls ? jls.color : stroke, - dash: jls ? jls.dash : null, - // Zickzack-Fuge (LineStyle kind==="zigzag") ebenfalls durchreichen. - zigzag: jls?.kind === "zigzag" ? jls.zigzag : undefined, - // Custom-Motiv-Fuge (LineStyle kind==="custom") ebenfalls durchreichen. - motif: jls?.kind === "custom" ? jls.motif : undefined, - greyed, - }); - } - } - } - // Kräftige Wand-Umrisslinie über die volle Dicke (nur Kontur, keine Füllung), - // damit die Wand sich klar von den dünnen Schichtfugen abhebt. Die Gehrungs- - // Stirnkanten am Knoten entfallen → sauberer Eck-Apex ohne überschießende Barbe. - // Bei einer Durchgangswand-Aussparung wird zusätzlich die NAHFLÄCHEN-Kante - // (die Längskante auf der Durchstoss-Seite) über [from,to] strokelos gemacht - // und als separate Segmente vor/nach dem Durchstoss gezeichnet — sonst liefe - // die Umrisslinie über die Durchstoss-Breite. - const offLo = refOff - total / 2; - const offHi = refOff + total / 2; - const holesHi: Array<[number, number]> = []; - const holesLo: Array<[number, number]> = []; - for (const c of segCutouts) { - // `offA` ist stets die Nahfläche (Wandoberfläche); ordne die Aussparung der - // passenden Längskante (offHi bzw. offLo) zu. - if (Math.abs(c.offA - offHi) < 1e-6) holesHi.push([c.from, c.to]); - else if (Math.abs(c.offA - offLo) < 1e-6) holesLo.push([c.from, c.to]); - } - const outlineNoStroke = [...bandJoinEdges]; - // clippedBand-Kantenreihenfolge [A.start(offLo), A.end(offLo), B.end(offHi), - // B.start(offHi)]: Kante 0 ist die offLo-Längskante, Kante 2 die offHi-Längskante. - if (holesHi.length) outlineNoStroke.push(2); - if (holesLo.length) outlineNoStroke.push(0); - out.push({ - kind: "polygon", - pts: clippedBand(p1, p2, offLo, offHi, startCut, endCut), - fill: "none", - stroke, - strokeWidthMm: outlineMm, - hatch: NO_HATCH, - greyed, - noStrokeEdges: outlineNoStroke, - wallId, - }); - const drawNearEdge = (edgeOff: number, holes: Array<[number, number]>): void => { - for (const [a, b] of subtractIntervals(s, e, holes)) { - const sc = a <= s + CUTOUT_EPS ? startCut : null; - const ec = b >= e - CUTOUT_EPS ? endCut : null; - const jq = clippedBand(axisPt(a), axisPt(b), edgeOff, edgeOff, sc, ec); + } else { + const art = f[i + 1]; + const li = f[i + 2]; + const a = { x: f[i + 3], y: f[i + 4] }; + const b = { x: f[i + 5], y: f[i + 6] }; + i += 7; + if (art === 0) { + out.push({ kind: "line", a, b, cls: "layer-joint-l", weightMm: layerLineMm, color: stroke, greyed }); + } else if (art === 1) { + // Innere Schichtfuge: Stil aus layer.jointLineStyleId (Gewicht/Farbe/Strich), Rückfall = + // Haarlinie in Wandfarbe. + const id = wt.layers[li].jointLineStyleId; + const jls = id ? project.lineStyles.find((l) => l.id === id) : undefined; out.push({ kind: "line", - a: jq[0], - b: jq[1], - cls: "wall-outline", - weightMm: outlineMm, - color: stroke, + a, + b, + cls: "layer-joint", + weightMm: jls ? jls.weight * LAYER_DETAIL_FACTOR[detail] : layerLineMm, + color: jls ? jls.color : stroke, + dash: jls ? jls.dash : null, + zigzag: jls?.kind === "zigzag" ? jls.zigzag : undefined, + motif: jls?.kind === "custom" ? jls.motif : undefined, greyed, }); + } else { + out.push({ kind: "line", a, b, cls: "wall-outline", weightMm: outlineMm, color: stroke, greyed }); } - }; - if (holesHi.length) drawNearEdge(offHi, holesHi); - if (holesLo.length) drawNearEdge(offLo, holesLo); + } } } From c134d32fcce6a52b389b4c490a2497dd40ec6f21 Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 00:58:28 +0100 Subject: [PATCH 03/31] [K3a] Oeffnungssymbole im Grundriss in Rust (opening_geom.rs, plan_openings.rs); windowSymbol Fassade; tote Ports in kernel2d entfernt --- TODO.md | 7 +- src-tauri/core/src/lib.rs | 2 + src-tauri/core/src/opening_geom.rs | 329 +++++++++++++ src-tauri/core/src/plan_openings.rs | 446 +++++++++++++++++ src-tauri/core/src/web/mod.rs | 1 + src-tauri/core/src/web/plan_openings.rs | 15 + src-tauri/kernel2d/src/lib.rs | 200 -------- src/geometry/opening.ts | 375 ++------------ src/plan/generatePlan/openings.ts | 623 +++++------------------- 9 files changed, 964 insertions(+), 1034 deletions(-) create mode 100644 src-tauri/core/src/opening_geom.rs create mode 100644 src-tauri/core/src/plan_openings.rs create mode 100644 src-tauri/core/src/web/plan_openings.rs diff --git a/TODO.md b/TODO.md index 2dc700cd..be6bd08b 100644 --- a/TODO.md +++ b/TODO.md @@ -91,7 +91,12 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern Fugen-Linienstil) bleibt in TS, bis das Modell in Rust liegt [K4]; Zuordnung über den Schichtindex. Bitgleich zur alten Fassung (60 Zufallspläne × 3 Detailgrade, Öffnungen, Beispielprojekt, Decken mit/ohne Loch); `subtractIntervals`/ `segmentInsideWallBand` aus TS gelöscht. Nicht in der Tauri-App angesehen. - Offen: Öffnungssymbole, Räume, Dächer, Stützen, 2D-Zeichnung, Kontext, Schnittlinien. + ✅ Öffnungssymbole (Tür/Fenster): `opening_geom.rs` (Pfosten, Lücke, Türblätter, Fenster-Symbol mit Flügel-/Stulpmarken) + und `plan_openings.rs` (Symbol, Rahmenband, Sturzlinien, Sims, Rollladenkasten); Linien-Overrides lösen in TS auf, + Farben kommen als Slot zurück. `geometry/opening.ts`: `doorSymbol`/`doorLeaves` gelöscht, `windowSymbol` ist Fassade + (Schnitt nutzt sie weiter). Bitgleich zur alten Fassung (80 Zufallsfälle × 3 Detailgrade, alle 13 Linienklassen; + 600 Zufalls-Fenstersymbole). Tote halbe Ports in `kernel2d` (door/window_symbol, jambs …) entfernt. + Offen: Räume, Dächer, Stützen, 2D-Zeichnung, Kontext, Schnittlinien. - ○ **[K3c] Schnitt und Ansicht** (`toSection`, `toElevation`, `meshSection`) im selben Puffer-Format. - ○ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. Nachteile (bewusst): Übergang mit doppelter Datenhaltung, Format muss TS/Rust gleich bleiben diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index fd767c28..020fde02 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -35,6 +35,8 @@ pub mod plan_buf; pub mod gpu_compile; pub mod plan_stairs; pub mod plan_walls; +pub mod opening_geom; +pub mod plan_openings; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/opening_geom.rs b/src-tauri/core/src/opening_geom.rs new file mode 100644 index 00000000..c389e389 --- /dev/null +++ b/src-tauri/core/src/opening_geom.rs @@ -0,0 +1,329 @@ +//! Öffnungs-Geometrie im Grundriss ([K3a]): Pfosten, Lücke, Türblätter und das Fenster-Symbol +//! (Rahmen, Glaslinien, Flügel- und Stulpmarken). Port von `src/geometry/opening.ts`; Rechen- +//! reihenfolge und Zahlsemantik wie in TS (`Math.hypot` über `jsmath`, `Math.min/max/round` +//! über `jsnum`, `cos/sin` über `jsnum`), damit die Ausgabe bitgleich bleibt. + +use crate::jsmath::hypot2; +use crate::jsnum::{cos, max, min, round, sin}; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct V { + pub x: f64, + pub y: f64, +} + +pub fn v(x: f64, y: f64) -> V { + V { x, y } +} +pub fn sub(a: V, b: V) -> V { + v(a.x - b.x, a.y - b.y) +} +pub fn add(a: V, b: V) -> V { + v(a.x + b.x, a.y + b.y) +} +pub fn scale(a: V, s: f64) -> V { + v(a.x * s, a.y * s) +} +pub fn dot(p: V, q: V) -> f64 { + p.x * q.x + p.y * q.y +} +pub fn normalize(a: V) -> V { + let l = hypot2(a.x, a.y); + let l = if l == 0.0 || l.is_nan() { 1.0 } else { l }; + v(a.x / l, a.y / l) +} +pub fn left_normal(a: V) -> V { + v(-a.y, a.x) +} +pub fn along(p1: V, p2: V, d: f64) -> V { + add(p1, scale(normalize(sub(p2, p1)), d)) +} + +const DEG: f64 = std::f64::consts::PI / 180.0; +const DEFAULT_POST_WIDTH: f64 = 0.06; +const DEFAULT_FRAME_DEPTH: f64 = 0.07; + +/// Wand für die Öffnungs-Geometrie: Achse, aufgelöste Dicke und Referenzversatz. +#[derive(Clone, Copy, Debug)] +pub struct WallRef { + pub start: V, + pub end: V, + pub total: f64, + pub ref_off: f64, +} + +impl WallRef { + pub fn frame(&self) -> (V, V) { + let u = normalize(sub(self.end, self.start)); + (u, left_normal(u)) + } +} + +/// Öffnungs-Intervall entlang der Achse (auf die Achslänge geklemmt) oder `None` (entartet). +pub fn opening_interval(w: &WallRef, position: f64, width: f64) -> Option<(f64, f64)> { + let axis = hypot2(w.end.x - w.start.x, w.end.y - w.start.y); + let from = max(0.0, min(position, axis)); + let to = max(from, min(position + width, axis)); + if to - from < 1e-4 { + None + } else { + Some((from, to)) + } +} + +pub fn opening_jambs(w: &WallRef, position: f64, width: f64) -> Option<(V, V)> { + let (from, to) = opening_interval(w, position, width)?; + Some((along(w.start, w.end, from), along(w.start, w.end, to))) +} + +/// Lücken-Rechteck über die volle Wanddicke (jambStart+n/2 → jambEnd+n/2 → jambEnd−n/2 → jambStart−n/2). +pub fn opening_gap_quad(w: &WallRef, position: f64, width: f64) -> Option> { + let (js, je) = opening_jambs(w, position, width)?; + let n = w.frame().1; + let outer = w.ref_off + w.total / 2.0; + let inner = w.ref_off - w.total / 2.0; + Some(vec![add(js, scale(n, outer)), add(je, scale(n, outer)), add(je, scale(n, inner)), add(js, scale(n, inner))]) +} + +#[derive(Clone, Copy, Debug)] +pub struct DoorLeaf { + pub hinge: V, + pub open_end: V, + pub closed_end: V, + pub radius: f64, +} + +fn compute_leaf(hinge: V, closed_dir: V, swing_dir: V, angle: f64, width: f64) -> DoorLeaf { + let open_dir = v(closed_dir.x * cos(angle) + swing_dir.x * sin(angle), closed_dir.y * cos(angle) + swing_dir.y * sin(angle)); + DoorLeaf { hinge, open_end: add(hinge, scale(open_dir, width)), closed_end: add(hinge, scale(closed_dir, width)), radius: width } +} + +/// Tür-Parameter: `swing_right`, `open_out`, `hinge_end` (false = Start), `swing_angle` in Grad. +#[derive(Clone, Copy, Debug)] +pub struct DoorParams { + pub swing_right: bool, + pub open_out: bool, + pub hinge_end: bool, + pub swing_angle: f64, +} + +/// Türblätter (1 oder 2 Flügel); leer bei entarteter Öffnung. +pub fn door_leaves(w: &WallRef, position: f64, width: f64, p: &DoorParams, leaf_count: f64) -> Vec { + let Some((js, je)) = opening_jambs(w, position, width) else { return Vec::new() }; + let (u, n) = w.frame(); + let wd = hypot2(je.x - js.x, je.y - js.y); + let swing_sign = if p.swing_right { -1.0 } else { 1.0 }; + let dir_sign = if p.open_out { -1.0 } else { 1.0 }; + let swing_dir = scale(n, swing_sign * dir_sign); + let angle = p.swing_angle * DEG; + if leaf_count >= 2.0 { + let hw = wd / 2.0; + return vec![compute_leaf(js, u, swing_dir, angle, hw), compute_leaf(je, scale(u, -1.0), swing_dir, angle, hw)]; + } + let (hinge, closed_dir) = if p.hinge_end { (je, scale(u, -1.0)) } else { (js, u) }; + vec![compute_leaf(hinge, closed_dir, swing_dir, angle, wd)] +} + +/// Eintrag der Flügeleinteilung. +#[derive(Clone, Copy, Debug)] +pub struct Sash { + pub post: bool, + /// `false` ⇔ `autoWidth === false`. + pub auto_width: bool, + /// feste Breite (nur wenn `!auto_width`), NaN = nicht gesetzt + pub width: f64, + pub post_width: f64, + pub operable: bool, +} + +#[derive(Clone, Debug)] +pub struct WindowSpec { + pub sashes: Vec, + pub frame_width: f64, + /// NaN = nicht gesetzt + pub frame_depth: f64, + /// NaN = nicht gesetzt + pub inset_from_face: f64, + pub inset_inner: bool, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Detail { + Grob, + Mittel, + Fein, +} + +#[derive(Default, Clone, Debug)] +pub struct WindowSymbol { + pub frame: Vec, + pub glass_lines: Vec<(V, V)>, + pub mullion_lines: Vec<(V, V)>, + pub sash_frames: Vec>, + pub meeting_marks: Vec>, + pub jamb_marks: Vec>, +} + +fn or_zero(x: f64) -> f64 { + if x.is_nan() { + 0.0 + } else { + x + } +} + +fn sash_segments(sashes: &[Sash], total_width: f64) -> Vec<(usize, f64, f64)> { + if sashes.is_empty() { + return Vec::new(); + } + let post_w = |s: &Sash| max(0.0, if s.post_width.is_nan() { DEFAULT_POST_WIDTH } else { s.post_width }); + let fixed_w = |s: &Sash| max(0.0, or_zero(s.width)); + let mut fixed_sum = 0.0; + let mut auto_count = 0.0; + for s in sashes { + if s.post { + fixed_sum += post_w(s); + } else if !s.auto_width { + fixed_sum += fixed_w(s); + } else { + auto_count += 1.0; + } + } + let remaining = max(0.0, total_width - fixed_sum); + let auto_width = if auto_count > 0.0 { remaining / auto_count } else { 0.0 }; + let mut segs = Vec::with_capacity(sashes.len()); + let mut cursor = 0.0; + for (i, s) in sashes.iter().enumerate() { + let w = if s.post { + post_w(s) + } else if !s.auto_width { + fixed_w(s) + } else { + auto_width + }; + segs.push((i, cursor, cursor + w)); + cursor += w; + } + segs +} + +/// Fenster-Symbol; `spec` nur mit auflösbarem Typ (sonst Alt-Pfad mit `wing_count`, NaN = 1). +pub fn window_symbol( + w: &WallRef, + position: f64, + width: f64, + glass_count: f64, + spec: Option<&WindowSpec>, + wing_count: f64, + detail: Detail, +) -> Option { + let (js, je) = opening_jambs(w, position, width)?; + let n = w.frame().1; + let total = w.total; + let ref_off = w.ref_off; + let outer = ref_off + total / 2.0; + let inner = ref_off - total / 2.0; + + if let Some(spec) = spec.filter(|s| !s.sashes.is_empty()) { + let fw = max(0.01, spec.frame_width); + let depth = min(total, if !spec.frame_depth.is_nan() && spec.frame_depth > 1e-9 { spec.frame_depth } else { DEFAULT_FRAME_DEPTH }); + let inset = max(0.0, or_zero(spec.inset_from_face)); + let half_t = total / 2.0; + let sign = if spec.inset_inner { 1.0 } else { -1.0 }; + let mut front_rel = sign * (half_t - inset); + let mut back_rel = front_rel - sign * depth; + front_rel = max(-half_t, min(half_t, front_rel)); + back_rel = max(-half_t, min(half_t, back_rel)); + let frame_outer_n = ref_off + max(front_rel, back_rel); + let frame_inner_n = ref_off + min(front_rel, back_rel); + let band_depth = frame_outer_n - frame_inner_n; + let g_mid_base = (frame_outer_n + frame_inner_n) / 2.0; + + let frame = vec![ + add(js, scale(n, frame_outer_n)), + add(je, scale(n, frame_outer_n)), + add(je, scale(n, frame_inner_n)), + add(js, scale(n, frame_inner_n)), + ]; + let mut sym = WindowSymbol { frame, ..Default::default() }; + + if detail == Detail::Grob { + sym.glass_lines.push((add(js, scale(n, g_mid_base)), add(je, scale(n, g_mid_base)))); + return Some(sym); + } + let fein = detail == Detail::Fein; + let axis_width = hypot2(je.x - js.x, je.y - js.y); + let segs = sash_segments(&spec.sashes, axis_width); + let reveal = if fein { min(band_depth * 0.3, fw * 0.7) } else { 0.0 }; + let frame_block = |u_center: f64, half_u: f64| -> Vec { + let a = along(js, je, u_center - half_u); + let b = along(js, je, u_center + half_u); + vec![add(a, scale(n, frame_outer_n)), add(b, scale(n, frame_outer_n)), add(b, scale(n, frame_inner_n)), add(a, scale(n, frame_inner_n))] + }; + sym.jamb_marks.push(frame_block(fw / 2.0, fw / 2.0)); + sym.jamb_marks.push(frame_block(axis_width - fw / 2.0, fw / 2.0)); + for i in 0..segs.len().saturating_sub(1) { + let u_pos = segs[i].2; + if fein { + sym.meeting_marks.push(frame_block(u_pos - fw / 2.0, fw / 2.0)); + sym.meeting_marks.push(frame_block(u_pos + fw / 2.0, fw / 2.0)); + } else { + sym.meeting_marks.push(frame_block(u_pos, fw / 2.0)); + } + } + for &(si, from, to) in &segs { + let s = &spec.sashes[si]; + if s.post { + continue; + } + let clear_from = from + fw; + let clear_to = to - fw; + if clear_to - clear_from <= 1e-6 { + continue; + } + if !fein { + continue; + } + let g_outer_n = frame_outer_n - if s.operable { reveal } else { 0.0 }; + let g_inner_n = frame_inner_n + if s.operable { reveal } else { 0.0 }; + if s.operable { + let s_from = along(js, je, clear_from); + let s_to = along(js, je, clear_to); + sym.sash_frames.push(vec![ + add(s_from, scale(n, g_outer_n)), + add(s_to, scale(n, g_outer_n)), + add(s_to, scale(n, g_inner_n)), + add(s_from, scale(n, g_inner_n)), + ]); + } + } + return Some(sym); + } + + // Alt-Pfad + let frame = vec![add(js, scale(n, outer)), add(je, scale(n, outer)), add(je, scale(n, inner)), add(js, scale(n, inner))]; + let mut sym = WindowSymbol { frame, ..Default::default() }; + let count = max(1.0, glass_count); + let mut i = 0.0; + while i < count { + let spread = total / 8.0; + let off = ref_off + if count == 1.0 { 0.0 } else { (i - (count - 1.0) / 2.0) * spread * 2.0 }; + sym.glass_lines.push((add(js, scale(n, off)), add(je, scale(n, off)))); + i += 1.0; + } + let wc = if wing_count.is_nan() { 1.0 } else { wing_count }; + let wings = max(1.0, min(4.0, round(wc))); + if wings > 1.0 { + let post_depth = total * 0.6; + let p_outer = ref_off + post_depth / 2.0; + let p_inner = ref_off - post_depth / 2.0; + let mut k = 1.0; + while k < wings { + let t = k / wings; + let on_axis = add(js, scale(sub(je, js), t)); + sym.mullion_lines.push((add(on_axis, scale(n, p_outer)), add(on_axis, scale(n, p_inner)))); + k += 1.0; + } + } + Some(sym) +} diff --git a/src-tauri/core/src/plan_openings.rs b/src-tauri/core/src/plan_openings.rs new file mode 100644 index 00000000..c8a83b80 --- /dev/null +++ b/src-tauri/core/src/plan_openings.rs @@ -0,0 +1,446 @@ +//! Öffnungs-Symbol (Tür/Fenster) im Grundriss ([K3a]): Port von `generatePlan/openings.ts` +//! (`addOpeningSymbol`, `addOpeningFrameBand`). Geometrie aus `opening_geom.rs`. Stil löst TS aus dem +//! Modell: Strichstärken kommen als Zahlen herein, Farben als Platz (Slot) heraus (0 = keine, +//! 1 Strichfarbe, 2 Rahmen, 3 Rahmen-Aufsicht, 4 Flügel/Sprossen, 5 Fensterbank-/Sims-Linie). +//! +//! Eingabe (`f64`): `[sx, sy, ex, ey, dicke, refOff, position, breite, art (0 Fenster | 1 Tür), +//! detail (0 grob | 1 mittel | 2 fein), +//! Tür: schwenkRechts, ausen, anschlagEnde, schwenkwinkel (NaN = 90), wandoeffnung, fluegel, +//! sturz (0 keine | 1 aussen | 2 innen | 3 beide), +//! Rahmen: hat, breite, art (0 Zarge | 1 Blockrahmen), einzug, einzugInnen, +//! Fenster: hatTyp, profilbreite, rahmentiefe (NaN), einzug (NaN), einzugInnen, altFluegel (NaN = 1), +//! glasAlt, sims (0 keine | 1 aussen | 2 innen | 3 beide), simsUnter (0|1), kasten (0|1), +//! kastenBreite, kastenHoehe, +//! Stärken: haar, rahmenHaar, rahmenAufsicht, fluegel, sims, +//! nFluegel, (pfosten, auto, breite, pfostenbreite, oeffenbar) × n]`. +//! +//! Ausgabe `[n, Eintrag × n]` in Zeichenreihenfolge: +//! ```text +//! 1 polygon [1, art (0 Pick-Fläche | 1 Rahmen-Aufsicht), weightMm, farbSlot, nPts, x, y …] +//! 2 line [2, cls, weightMm, farbSlot, strich, ax, ay, bx, by] +//! 3 arc [3, weightMm, cx, cy, fromX, fromY, toX, toY, r] (cls door-swing) +//! cls 0 door-leaf · 1 door-frame · 2 door-lintel · 3 opening-frame · 4 window-glass · +//! 5 window-mullion · 6 window-sash · 7 window-stulp · 8 window-sill · 9 window-frame · +//! 10 window-shading +//! strich 0 keiner (Schlüssel fehlt) · 1 Sturz [0.18, 0.09] · 2 Überkopf · 3 gepunktet [0.04, 0.08] +//! ``` + +use crate::jsmath::hypot2; +use crate::jsnum::{max, min, round}; +use crate::opening_geom::*; +use crate::flat_read::Reader; + +struct Out { + buf: Vec, + n: usize, +} + +const C_LEAF: f64 = 0.0; +const C_DOOR_FRAME: f64 = 1.0; +const C_LINTEL: f64 = 2.0; +const C_OPENING_FRAME: f64 = 3.0; +const C_GLASS: f64 = 4.0; +const C_MULLION: f64 = 5.0; +const C_SASH: f64 = 6.0; +const C_STULP: f64 = 7.0; +const C_SILL: f64 = 8.0; +const C_WINDOW_FRAME: f64 = 9.0; +const C_SHADING: f64 = 10.0; + +impl Out { + fn polygon(&mut self, art: f64, weight: f64, color: f64, pts: &[V]) { + self.n += 1; + self.buf.extend([1.0, art, weight, color, pts.len() as f64]); + for p in pts { + self.buf.extend([p.x, p.y]); + } + } + fn line(&mut self, cls: f64, weight: f64, color: f64, dash: f64, a: V, b: V) { + self.n += 1; + self.buf.extend([2.0, cls, weight, color, dash, a.x, a.y, b.x, b.y]); + } + fn arc(&mut self, weight: f64, c: V, from: V, to: V, r: f64) { + self.n += 1; + self.buf.extend([3.0, weight, c.x, c.y, from.x, from.y, to.x, to.y, r]); + } + /// Geschlossener Linienzug aus Eckpunkten (Kante i → i+1, zuletzt → 0). + fn ring(&mut self, cls: f64, weight: f64, color: f64, pts: &[V]) { + for i in 0..pts.len() { + self.line(cls, weight, color, 0.0, pts[i], pts[(i + 1) % pts.len()]); + } + } +} + +pub fn plan_opening(buf: &[f64]) -> Vec { + plan_opening_inner(buf).unwrap_or_default() +} + +fn plan_opening_inner(buf: &[f64]) -> Option> { + let mut r = Reader::new(buf); + let (sx, sy, ex, ey, total, ref_off) = (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?); + let (position, width) = (r.num()?, r.num()?); + let is_door = r.num()? != 0.0; + let detail = match r.num()? as i64 { + 0 => Detail::Grob, + 1 => Detail::Mittel, + _ => Detail::Fein, + }; + let door = DoorParams { swing_right: r.num()? != 0.0, open_out: r.num()? != 0.0, hinge_end: r.num()? != 0.0, swing_angle: 0.0 }; + let swing_angle = r.num()?; + let door = DoorParams { swing_angle: if swing_angle.is_nan() { 90.0 } else { swing_angle }, ..door }; + let wandoeffnung = r.num()? != 0.0; + let leaf_count = r.num()?; + let lintel = r.num()? as i64; + let has_frame = r.num()? != 0.0; + let frame_width = r.num()?; + let frame_block = r.num()? != 0.0; + let frame_inset = r.num()?; + let frame_inset_inner = r.num()? != 0.0; + let has_type = r.num()? != 0.0; + let win_frame_width = r.num()?; + let win_frame_depth = r.num()?; + let win_inset = r.num()?; + let win_inset_inner = r.num()? != 0.0; + let wing_count = r.num()?; + let glass_alt = r.num()?; + let sill_faces = r.num()? as i64; + let sill_under = r.num()? != 0.0; + let shading = r.num()? != 0.0; + let shading_width = r.num()?; + let shading_height = r.num()?; + let (hair, frame_hair, frame_view_w, sash_w, sill_w) = (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?); + let n_sash = r.count()?; + let mut sashes = Vec::with_capacity(n_sash); + for _ in 0..n_sash { + sashes.push(Sash { + post: r.num()? != 0.0, + auto_width: r.num()? != 0.0, + width: r.num()?, + post_width: r.num()?, + operable: r.num()? != 0.0, + }); + } + if ![sx, sy, ex, ey, total, ref_off, position, width].iter().all(|x| x.is_finite()) { + return None; + } + let w = WallRef { start: v(sx, sy), end: v(ex, ey), total, ref_off }; + let (_, wn) = w.frame(); + let mut o = Out { buf: Vec::new(), n: 0 }; + + if is_door { + let (jamb_start, jamb_end) = opening_jambs(&w, position, width)?; + if let Some(gap) = opening_gap_quad(&w, position, width) { + o.polygon(0.0, 0.0, 0.0, &gap); + } + if !wandoeffnung { + let count = max(1.0, round(if leaf_count.is_nan() { 1.0 } else { leaf_count })); + for leaf in door_leaves(&w, position, width, &door, count) { + o.line(C_LEAF, hair, 0.0, 0.0, leaf.hinge, leaf.open_end); + if detail != Detail::Grob { + o.arc(hair, leaf.hinge, leaf.closed_end, leaf.open_end, leaf.radius); + } + } + } + if detail == Detail::Fein { + let reveal = 0.06; + for jamb in [jamb_start, jamb_end] { + o.line(C_DOOR_FRAME, hair, 0.0, 0.0, add(jamb, scale(wn, reveal)), add(jamb, scale(wn, -reveal))); + } + } + if has_frame { + frame_band(&mut o, &w, position, width, frame_width, frame_block, frame_inset, frame_inset_inner, hair); + } + if lintel != 0 { + let half_d = total / 2.0; + let outer_off = ref_off - half_d; + let inner_off = ref_off + half_d; + let line = |off: f64| (add(jamb_start, scale(wn, off)), add(jamb_end, scale(wn, off))); + if lintel == 1 || lintel == 3 { + let (a, b) = line(outer_off); + o.line(C_LINTEL, hair, 1.0, 1.0, a, b); + } + if lintel == 2 || lintel == 3 { + let (a, b) = line(inner_off); + o.line(C_LINTEL, hair, 1.0, 1.0, a, b); + } + } + return Some(finish(o)); + } + + // Fenster + let spec = if has_type { + Some(WindowSpec { + sashes, + frame_width: win_frame_width, + frame_depth: win_frame_depth, + inset_from_face: win_inset, + inset_inner: win_inset_inner, + }) + } else { + None + }; + let sym = window_symbol(&w, position, width, glass_alt, spec.as_ref(), wing_count, detail)?; + if let Some(gap) = opening_gap_quad(&w, position, width) { + o.polygon(0.0, 0.0, 0.0, &gap); + } + if detail == Detail::Grob { + let idx = sym.glass_lines.len() / 2; + if let Some(g) = sym.glass_lines.get(idx).or_else(|| sym.glass_lines.first()) { + o.line(C_GLASS, sash_w, 4.0, 0.0, g.0, g.1); + } + } else { + o.polygon(1.0, frame_view_w, 3.0, &sym.frame); + for (a, b) in &sym.mullion_lines { + o.line(C_MULLION, sash_w, 4.0, 0.0, *a, *b); + } + if detail == Detail::Fein { + for pts in &sym.sash_frames { + o.ring(C_SASH, sash_w, 4.0, pts); + } + } + for mark in &sym.jamb_marks { + o.ring(C_STULP, frame_hair, 2.0, mark); + } + for mark in &sym.meeting_marks { + o.ring(C_STULP, sash_w, 4.0, mark); + } + for (a, b) in &sym.glass_lines { + o.line(C_GLASS, hair, 0.0, 0.0, *a, *b); + } + if detail == Detail::Fein { + if let Some((js, je)) = opening_jambs(&w, position, width) { + let outer_n = min(dot(sub(sym.frame[0], js), wn), dot(sub(sym.frame[2], js), wn)); + let (ov, proj) = (0.03, 0.04); + let s0 = along(js, je, -ov); + let s1 = along(je, js, -ov); + let b0 = add(s0, scale(wn, outer_n)); + let b1 = add(s1, scale(wn, outer_n)); + let b2 = add(s1, scale(wn, outer_n - proj)); + let b3 = add(s0, scale(wn, outer_n - proj)); + for (a, b) in [(b0, b1), (b1, b2), (b2, b3), (b3, b0)] { + o.line(C_SILL, hair, 1.0, 0.0, a, b); + } + let reveal = 0.06; + for jamb in [js, je] { + o.line(C_WINDOW_FRAME, hair, 1.0, 0.0, add(jamb, scale(wn, reveal)), add(jamb, scale(wn, -reveal))); + } + } + } + } + if detail != Detail::Grob && sill_faces != 0 { + let dash = if sill_under { 2.0 } else { 3.0 }; + let pair01_is_outer = dot(sym.frame[0], wn) <= dot(sym.frame[3], wn); + let (outer_pair, inner_pair) = if pair01_is_outer { + ((sym.frame[0], sym.frame[1]), (sym.frame[3], sym.frame[2])) + } else { + ((sym.frame[3], sym.frame[2]), (sym.frame[0], sym.frame[1])) + }; + if sill_faces == 1 || sill_faces == 3 { + o.line(C_SILL, sill_w, 5.0, dash, outer_pair.0, outer_pair.1); + } + if sill_faces == 2 || sill_faces == 3 { + o.line(C_SILL, sill_w, 5.0, dash, inner_pair.0, inner_pair.1); + } + } + if shading { + if let Some((js, je)) = opening_jambs(&w, position, width) { + let (u, nrm) = w.frame(); + let outer_face = ref_off - total / 2.0; + let axis_width = hypot2(je.x - js.x, je.y - js.y); + let box_width = if shading_width > 0.0 { shading_width } else { axis_width }; + let box_height = max(0.0, shading_height); + let center = add(js, scale(u, axis_width / 2.0)); + let half = box_width / 2.0; + let c1 = add(center, scale(u, -half)); + let c2 = add(center, scale(u, half)); + let p1 = add(c1, scale(nrm, outer_face)); + let p2 = add(c2, scale(nrm, outer_face)); + let p3 = add(c2, scale(nrm, outer_face + box_height)); + let p4 = add(c1, scale(nrm, outer_face + box_height)); + for (a, b) in [(p1, p2), (p2, p3), (p3, p4), (p4, p1)] { + o.line(C_SHADING, hair, 1.0, 2.0, a, b); + } + } + } + Some(finish(o)) +} + +fn finish(o: Out) -> Vec { + let mut out = Vec::with_capacity(o.buf.len() + 1); + out.push(o.n as f64); + out.extend(o.buf); + out +} + +/// Rahmenband einer Tür (Zarge/Blockrahmen) aus dem Typ der Tür. +#[allow(clippy::too_many_arguments)] +fn frame_band(o: &mut Out, w: &WallRef, position: f64, width: f64, frame_width: f64, block: bool, inset_from_face: f64, inset_inner: bool, hair: f64) { + let Some((js, je)) = opening_jambs(w, position, width) else { return }; + let n = w.frame().1; + let total = w.total; + let outer_face = w.ref_off - total / 2.0; + let inner_face = w.ref_off + total / 2.0; + let clamped_inset = max(0.0, min(inset_from_face, total)); + let near_is_aussen = !inset_inner; + let face_near = if near_is_aussen { outer_face + clamped_inset } else { inner_face - clamped_inset }; + let face_far = if near_is_aussen { inner_face } else { outer_face }; + let lo = min(face_near, face_far); + let hi = max(face_near, face_far); + let fw = max(0.0, frame_width); + let (band_lo, band_hi, j_start, j_end, weight); + if block { + let depth = min(fw, hi - lo); + band_lo = if near_is_aussen { lo } else { hi - depth }; + band_hi = if near_is_aussen { lo + depth } else { hi }; + j_start = js; + j_end = je; + weight = hair * 2.2; + } else { + let jamb_span = hypot2(je.x - js.x, je.y - js.y); + let jamb_inset = min(fw, jamb_span / 2.0); + j_start = along(js, je, jamb_inset); + j_end = along(je, js, jamb_inset); + let depth_inset = min(fw, (hi - lo) / 2.0); + band_lo = lo + depth_inset; + band_hi = hi - depth_inset; + weight = hair; + } + let p1 = add(j_start, scale(n, band_lo)); + let p2 = add(j_end, scale(n, band_lo)); + let p3 = add(j_end, scale(n, band_hi)); + let p4 = add(j_start, scale(n, band_hi)); + for (a, b) in [(p1, p2), (p2, p3), (p3, p4), (p4, p1)] { + o.line(C_OPENING_FRAME, weight, 1.0, 0.0, a, b); + } +} + +// ── Fenster-Symbol als Einzelaufruf (für die Fassade `windowSymbol`, z. B. im Schnitt) ────────── + +/// Eingabe `[sx, sy, ex, ey, dicke, refOff, position, breite, glasAnzahl, altFluegel (NaN = 1), +/// detail, hatTyp, profilbreite, rahmentiefe (NaN), einzug (NaN), einzugInnen, nFluegel, +/// (pfosten, auto, breite, pfostenbreite, oeffenbar) × n]`; Ausgabe +/// `[1, Rahmen(4 Punkte), nGlas, 4 Zahlen × n, nPfosten, 4 × n, nFluegelRahmen, (nPts, pts…) × n, +/// nStoss, (nPts, pts…) × n, nLaibung, (nPts, pts…) × n]` oder leer. +pub fn window_symbol_flat(buf: &[f64]) -> Vec { + (|| { + let mut r = Reader::new(buf); + let (sx, sy, ex, ey, total, ref_off, position, width) = + (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?); + let glass = r.num()?; + let wings = r.num()?; + let detail = match r.num()? as i64 { + 0 => Detail::Grob, + 1 => Detail::Mittel, + _ => Detail::Fein, + }; + let has_type = r.num()? != 0.0; + let (fw, fd, inset) = (r.num()?, r.num()?, r.num()?); + let inner = r.num()? != 0.0; + let n = r.count()?; + let mut sashes = Vec::with_capacity(n); + for _ in 0..n { + sashes.push(Sash { post: r.num()? != 0.0, auto_width: r.num()? != 0.0, width: r.num()?, post_width: r.num()?, operable: r.num()? != 0.0 }); + } + if ![sx, sy, ex, ey, total, ref_off, position, width].iter().all(|x| x.is_finite()) { + return None; + } + let w = WallRef { start: v(sx, sy), end: v(ex, ey), total, ref_off }; + let spec = if has_type { Some(WindowSpec { sashes, frame_width: fw, frame_depth: fd, inset_from_face: inset, inset_inner: inner }) } else { None }; + let s = window_symbol(&w, position, width, glass, spec.as_ref(), wings, detail)?; + let mut out = vec![1.0]; + for p in &s.frame { + out.extend([p.x, p.y]); + } + for list in [&s.glass_lines, &s.mullion_lines] { + out.push(list.len() as f64); + for (a, b) in list.iter() { + out.extend([a.x, a.y, b.x, b.y]); + } + } + for rings in [&s.sash_frames, &s.meeting_marks, &s.jamb_marks] { + out.push(rings.len() as f64); + for pts in rings.iter() { + out.push(pts.len() as f64); + for p in pts { + out.extend([p.x, p.y]); + } + } + } + Some(out) + })() + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + + const NAN: f64 = f64::NAN; + + /// Wand 0..6 m entlang x, Dicke 0.3, Öffnung ab 1.0 m, 0.9 m breit. + fn input(door: bool, detail: f64, has_type: bool, sashes: &[[f64; 5]]) -> Vec { + let mut b = vec![0.0, 0.0, 6.0, 0.0, 0.3, 0.0, 1.0, 0.9, door as u8 as f64, detail]; + b.extend([0.0, 0.0, 0.0, NAN, 0.0, 1.0, 3.0]); // Tür: links, innen, Start, 90°, normal, 1 Blatt, Sturz beide + b.extend([0.0, 0.06, 0.0, 0.0, 0.0]); // kein Rahmenband + b.extend([has_type as u8 as f64, 0.06, NAN, NAN, 0.0, NAN, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]); // Fenster + b.extend([0.02, 0.02, 0.02, 0.02, 0.02]); // Strichstärken + b.push(sashes.len() as f64); + for s in sashes { + b.extend(s); + } + b + } + + fn tags(buf: &[f64]) -> Vec { + let (mut i, mut t) = (1, Vec::new()); + for _ in 0..buf[0] as usize { + t.push(buf[i]); + i += match buf[i] as i64 { + 1 => 5 + 2 * buf[i + 4] as usize, + 2 => 9, + _ => 9, + }; + } + assert_eq!(i, buf.len()); + t + } + + #[test] + fn tuer_grob_hat_pick_blatt_und_zwei_sturzlinien() { + let t = tags(&plan_opening(&input(true, 0.0, false, &[]))); + assert_eq!(t, vec![1.0, 2.0, 2.0, 2.0]); + } + + #[test] + fn tuer_fein_hat_bogen_und_anschlagstriche() { + let t = tags(&plan_opening(&input(true, 2.0, false, &[]))); + assert_eq!(t.iter().filter(|x| **x == 3.0).count(), 1); + assert_eq!(t.len(), 1 + 1 + 1 + 2 + 2); + } + + #[test] + fn fenster_grob_hat_eine_glaslinie() { + let t = tags(&plan_opening(&input(false, 0.0, false, &[]))); + assert_eq!(t, vec![1.0, 2.0]); + } + + #[test] + fn entartete_oeffnung_und_unsinn_ergeben_leeres_ergebnis() { + let mut b = input(false, 1.0, false, &[]); + b[7] = 0.0; + assert!(plan_opening(&b).is_empty()); + assert!(plan_opening(&[1.0]).is_empty()); + let mut c = input(true, 1.0, false, &[]); + c[0] = f64::NAN; + assert!(plan_opening(&c).is_empty()); + assert!(window_symbol_flat(&[]).is_empty()); + } + + #[test] + fn typisiertes_fenster_fein_hat_fluegelrahmen() { + let sashes = [[0.0, 1.0, NAN, NAN, 1.0], [0.0, 1.0, NAN, NAN, 1.0]]; + let a = plan_opening(&input(false, 2.0, true, &sashes)); + let g = plan_opening(&input(false, 1.0, true, &sashes)); + assert!(a[0] > g[0]); + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 2cea7b21..fe186a76 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -27,6 +27,7 @@ mod plan_buf; mod gpu_compile; mod plan_stairs; mod plan_walls; +mod plan_openings; mod hatch; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/plan_openings.rs b/src-tauri/core/src/web/plan_openings.rs new file mode 100644 index 00000000..6eff0a87 --- /dev/null +++ b/src-tauri/core/src/web/plan_openings.rs @@ -0,0 +1,15 @@ +//! Bindungen von Öffnungs-Symbol und Fenster-Symbol (`crate::plan_openings`). Layout s. dort. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Tür-/Fenster-Symbol einer Öffnung im Grundriss; Unsinn → leer. +#[wasm_bindgen] +pub fn plan_opening_flat(buf: &[f64]) -> Vec { + crate::plan_openings::plan_opening(buf) +} + +/// Fenster-Symbol (Rahmen, Glas, Flügel, Stulp) einer Öffnung; Unsinn/entartet → leer. +#[wasm_bindgen] +pub fn window_symbol_flat(buf: &[f64]) -> Vec { + crate::plan_openings::window_symbol_flat(buf) +} diff --git a/src-tauri/kernel2d/src/lib.rs b/src-tauri/kernel2d/src/lib.rs index dbdc3f60..f5e1d4ce 100644 --- a/src-tauri/kernel2d/src/lib.rs +++ b/src-tauri/kernel2d/src/lib.rs @@ -2266,206 +2266,6 @@ pub fn along(p1: Vec2, p2: Vec2, d: f64) -> Vec2 { add(p1, scale(normalize(sub(p2, p1)), d)) } -/// Achslaenge einer Wand (Port von `wallAxisLength`; Wand → start/end). -pub fn wall_axis_length(start: Vec2, end: Vec2) -> f64 { - (end.x - start.x).hypot(end.y - start.y) -} - -/// Oeffnungs-Intervall entlang der Achse (Port von `openingInterval`). -#[derive(Serialize, Deserialize, Clone, Copy, Debug)] -#[serde(rename_all = "camelCase")] -pub struct Interval { - pub from: f64, - pub to: f64, -} - -pub fn opening_interval(start: Vec2, end: Vec2, position: f64, width: f64) -> Option { - let axis = wall_axis_length(start, end); - let from = position.min(axis).max(0.0); - let to = (position + width).min(axis).max(from); - if to - from < 1e-4 { - return None; // entartet: Breite <= 0 oder vollstaendig ausserhalb der Achse - } - Some(Interval { from, to }) -} - -/// Einheits-Laufrichtung (u) und linke Normale (n) der Wandachse (Port von -/// `wallAxisFrame`). -#[derive(Serialize, Deserialize, Clone, Copy, Debug)] -pub struct AxisFrame { - pub u: Vec2, - pub n: Vec2, -} - -pub fn wall_axis_frame(start: Vec2, end: Vec2) -> AxisFrame { - let u = normalize(sub(end, start)); - AxisFrame { u, n: left_normal(u) } -} - -/// Die beiden Pfosten-Punkte einer Oeffnung im Grundriss (Port von `openingJambs`). -#[derive(Serialize, Deserialize, Clone, Copy, Debug)] -#[serde(rename_all = "camelCase")] -pub struct Jambs { - pub jamb_start: Vec2, - pub jamb_end: Vec2, -} - -pub fn opening_jambs(start: Vec2, end: Vec2, position: f64, width: f64) -> Option { - let iv = opening_interval(start, end, position, width)?; - Some(Jambs { - jamb_start: along(start, end, iv.from), - jamb_end: along(start, end, iv.to), - }) -} - -/// Luecken-Rechteck-Ecken ueber die volle Wanddicke (Port von `openingGapQuad`). -/// Reihenfolge: jambStart(+n/2) → jambEnd(+n/2) → jambEnd(−n/2) → jambStart(−n/2). -pub fn opening_gap_quad( - start: Vec2, - end: Vec2, - position: f64, - width: f64, - thickness: f64, - ref_offset: f64, -) -> Option> { - let jambs = opening_jambs(start, end, position, width)?; - let n = wall_axis_frame(start, end).n; - let outer = ref_offset + thickness / 2.0; - let inner = ref_offset - thickness / 2.0; - Some(vec![ - add(jambs.jamb_start, scale(n, outer)), - add(jambs.jamb_end, scale(n, outer)), - add(jambs.jamb_end, scale(n, inner)), - add(jambs.jamb_start, scale(n, inner)), - ]) -} - -/// Mittelpunkt einer Oeffnung im Grundriss (Port von `openingCenter`). -pub fn opening_center(start: Vec2, end: Vec2, position: f64, width: f64) -> Option { - let iv = opening_interval(start, end, position, width)?; - Some(along(start, end, (iv.from + iv.to) / 2.0)) -} - -/// Aufgeloeste Tuer-Symbol-Geometrie im Grundriss (Port von `DoorSymbol`). -#[derive(Serialize, Deserialize, Clone, Debug)] -#[serde(rename_all = "camelCase")] -pub struct DoorSymbol { - pub hinge: Vec2, - pub open_end: Vec2, - pub closed_end: Vec2, - pub radius: f64, - pub jamb_start: Vec2, - pub jamb_end: Vec2, - pub normal: Vec2, -} - -/// Port von `doorSymbol`. `swing`/`opening_dir`/`hinge_side` folgen der TS- -/// `??`-Fallback-Semantik (`None` → TS-Default); `swing_angle` `None` → 90°. -pub fn door_symbol( - start: Vec2, - end: Vec2, - position: f64, - width: f64, - swing: Option<&str>, - opening_dir: Option<&str>, - hinge_side: Option<&str>, - swing_angle: Option, -) -> Option { - let jambs = opening_jambs(start, end, position, width)?; - let frame = wall_axis_frame(start, end); - let (jamb_start, jamb_end) = (jambs.jamb_start, jambs.jamb_end); - // TS berechnet die Breite NEU aus den geklemmten Pfosten (nicht das rohe - // `o.width`) — bewusst repliziert. - let w = (jamb_end.x - jamb_start.x).hypot(jamb_end.y - jamb_start.y); - - let swing_sign = if swing.unwrap_or("left") == "left" { 1.0 } else { -1.0 }; - let dir_sign = if opening_dir.unwrap_or("in") == "in" { 1.0 } else { -1.0 }; - let swing_dir = scale(frame.n, swing_sign * dir_sign); - - let hinge_at_start = hinge_side.unwrap_or("start") == "start"; - let hinge = if hinge_at_start { jamb_start } else { jamb_end }; - let closed_dir = if hinge_at_start { frame.u } else { scale(frame.u, -1.0) }; - - let angle = swing_angle.unwrap_or(90.0) * DEG; - let open_dir = Vec2 { - x: closed_dir.x * angle.cos() + swing_dir.x * angle.sin(), - y: closed_dir.y * angle.cos() + swing_dir.y * angle.sin(), - }; - Some(DoorSymbol { - hinge, - open_end: add(hinge, scale(open_dir, w)), - closed_end: add(hinge, scale(closed_dir, w)), - radius: w, - jamb_start, - jamb_end, - normal: frame.n, - }) -} - -/// Aufgeloeste Fenster-Linien im Grundriss (Port von `WindowSymbol`). -#[derive(Serialize, Deserialize, Clone, Debug)] -#[serde(rename_all = "camelCase")] -pub struct WindowSymbol { - pub frame: Vec, - pub glass_lines: Vec<(Vec2, Vec2)>, - pub mullion_lines: Vec<(Vec2, Vec2)>, -} - -/// Port von `windowSymbol`. `thickness`/`ref_offset` sind bereits aufgeloeste -/// Werte (siehe Modul-Kommentar); `wing_count` `None` → TS-Default `1`. -pub fn window_symbol( - start: Vec2, - end: Vec2, - position: f64, - width: f64, - thickness: f64, - ref_offset: f64, - glass_count: f64, - wing_count: Option, -) -> Option { - let jambs = opening_jambs(start, end, position, width)?; - let (jamb_start, jamb_end) = (jambs.jamb_start, jambs.jamb_end); - let n = wall_axis_frame(start, end).n; - let outer = ref_offset + thickness / 2.0; - let inner = ref_offset - thickness / 2.0; - let frame_quad = vec![ - add(jamb_start, scale(n, outer)), - add(jamb_end, scale(n, outer)), - add(jamb_end, scale(n, inner)), - add(jamb_start, scale(n, inner)), - ]; - - let mut glass_lines: Vec<(Vec2, Vec2)> = Vec::new(); - let count = glass_count.max(1.0); - let mut i: i64 = 0; - while (i as f64) < count { - let spread = thickness / 8.0; - let off = if count == 1.0 { - ref_offset - } else { - ref_offset + ((i as f64) - (count - 1.0) / 2.0) * spread * 2.0 - }; - glass_lines.push((add(jamb_start, scale(n, off)), add(jamb_end, scale(n, off)))); - i += 1; - } - - let mut mullion_lines: Vec<(Vec2, Vec2)> = Vec::new(); - let wings = wing_count.unwrap_or(1.0).round().min(4.0).max(1.0); - if wings > 1.0 { - let post_depth = thickness * 0.6; - let p_outer = ref_offset + post_depth / 2.0; - let p_inner = ref_offset - post_depth / 2.0; - let wings_n = wings as i64; - for k in 1..wings_n { - let t = k as f64 / wings; - let on_axis = add(jamb_start, scale(sub(jamb_end, jamb_start), t)); - mullion_lines.push((add(on_axis, scale(n, p_outer)), add(on_axis, scale(n, p_inner)))); - } - } - - Some(WindowSymbol { frame: frame_quad, glass_lines, mullion_lines }) -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/geometry/opening.ts b/src/geometry/opening.ts index f4cf9311..91c035e5 100644 --- a/src/geometry/opening.ts +++ b/src/geometry/opening.ts @@ -1,8 +1,7 @@ // Geometrie-Helfer für Öffnungen (Fenster/Türen) — reine Funktionen, die eine // `Opening` relativ zu ihrer Wirts-Wand in konkrete Welt-Geometrie auflösen: // • die Öffnungs-Lücke entlang der Wandachse (from/to in Metern), -// • das Türblatt (Scharnier → offenes/geschlossenes Ende) + Schwenkbogen, -// • die Fenster-Rahmen-/Glaslinien quer über die Lücke, +// • die Fenster-Rahmen-/Glaslinien quer über die Lücke (`windowSymbol`, Fassade über den Rust-Kern), // • die vertikale Lage (UK/OK der Öffnung, absolut in Metern). // // Da JEDE Größe aus der aktuellen Wandachse (`wall.start`/`wall.end`) abgeleitet @@ -12,12 +11,11 @@ // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import type { Opening, Project, SashDef, Vec2, Wall } from "../model/types"; +import { core } from "../engine/coreWasm"; import { getWallType, wallTypeThickness } from "../model/types"; import { add, along, leftNormal, normalize, scale, sub } from "../model/geometry"; import { wallReferenceOffset, wallVerticalExtent } from "../model/wall"; -const DEG = Math.PI / 180; - /** Achslänge einer Wand (Meter). */ export function wallAxisLength(wall: Wall): number { return Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y); @@ -104,121 +102,6 @@ export function openingCenter(wall: Wall, o: Opening): Vec2 | null { return along(wall.start, wall.end, (iv.from + iv.to) / 2); } -// ── Tür-Symbol (Plan) ──────────────────────────────────────────────────────── - -/** Aufgelöste Tür-Symbol-Geometrie im Grundriss (Weltkoordinaten). */ -export interface DoorSymbol { - /** Scharnierpunkt (auf der Achse). */ - hinge: Vec2; - /** Ende des Blatts in GEÖFFNETER Stellung. */ - openEnd: Vec2; - /** Ende des Blatts in GESCHLOSSENER Stellung (Bogen-Startpunkt). */ - closedEnd: Vec2; - /** Radius (= Türbreite) des Schwenkbogens. */ - radius: number; - /** Beide Pfosten-Punkte (für Rahmen-/Anschlagstriche). */ - jambStart: Vec2; - jambEnd: Vec2; - /** Achs-Normale (für kurze Anschlagstriche quer zur Wand). */ - normal: Vec2; -} - -/** - * Löst die Tür-Symbolik auf. `swing` wählt die Aufschlagseite (linke/rechte - * Achs-Normale), `openingDir` ("out") spiegelt sie auf die andere Seite, - * `hinge` wählt den Scharnier-Pfosten, `swingAngle` (Grad, Default 90) bestimmt, - * wie weit das Blatt in der offenen Stellung aufsteht. - */ -export function doorSymbol(wall: Wall, o: Opening): DoorSymbol | null { - const jambs = openingJambs(wall, o); - if (!jambs) return null; - const { u, n } = wallAxisFrame(wall); - const { jambStart, jambEnd } = jambs; - const width = Math.hypot(jambEnd.x - jambStart.x, jambEnd.y - jambStart.y); - - const swingSign = (o.swing ?? "left") === "left" ? 1 : -1; - const dirSign = (o.openingDir ?? "in") === "in" ? 1 : -1; - const swingDir = scale(n, swingSign * dirSign); - - const hinge = (o.hinge ?? "start") === "start" ? jambStart : jambEnd; - // Geschlossene Richtung zeigt vom Scharnier zum GEGENüberliegenden Pfosten. - const closedDir = (o.hinge ?? "start") === "start" ? u : scale(u, -1); - - const angle = (o.swingAngle ?? 90) * DEG; - // Offenes Blatt-Ende: um `angle` von der geschlossenen Richtung zur - // Schwenkrichtung gedreht (Interpolation über die Basis closedDir/swingDir). - const openDir = { - x: closedDir.x * Math.cos(angle) + swingDir.x * Math.sin(angle), - y: closedDir.y * Math.cos(angle) + swingDir.y * Math.sin(angle), - }; - return { - hinge, - openEnd: add(hinge, scale(openDir, width)), - closedEnd: add(hinge, scale(closedDir, width)), - radius: width, - jambStart, - jambEnd, - normal: n, - }; -} - -/** Ein einzelnes Türblatt (Grundriss): Scharnier + geschlossenes/offenes Ende + Radius. */ -export interface DoorLeaf { - hinge: Vec2; - openEnd: Vec2; - closedEnd: Vec2; - radius: number; -} - -/** Blatt-Geometrie aus Scharnier, geschlossener Richtung, Schwenkrichtung, Winkel, Breite. */ -function computeLeaf( - hinge: Vec2, - closedDir: Vec2, - swingDir: Vec2, - angle: number, - width: number, -): DoorLeaf { - const openDir = { - x: closedDir.x * Math.cos(angle) + swingDir.x * Math.sin(angle), - y: closedDir.y * Math.cos(angle) + swingDir.y * Math.sin(angle), - }; - return { - hinge, - openEnd: add(hinge, scale(openDir, width)), - closedEnd: add(hinge, scale(closedDir, width)), - radius: width, - }; -} - -/** - * Türblätter im Grundriss (1 oder 2 Flügel). Einflüglig: ein Blatt über die - * volle Breite (Scharnier je `o.hinge`). Zweiflüglig (`leafCount === 2`): zwei - * halbbreite Blätter, an den GEGENüberliegenden Pfosten angeschlagen, beide zur - * selben Seite schwenkend (symmetrische Doppeltür / Stulptür). `doorSymbol` - * bleibt unverändert (einflügelig) für Bestandspfade/Parität; dies ist additiv. - */ -export function doorLeaves(wall: Wall, o: Opening, leafCount: number): DoorLeaf[] { - const jambs = openingJambs(wall, o); - if (!jambs) return []; - const { u, n } = wallAxisFrame(wall); - const { jambStart, jambEnd } = jambs; - const width = Math.hypot(jambEnd.x - jambStart.x, jambEnd.y - jambStart.y); - const swingSign = (o.swing ?? "left") === "left" ? 1 : -1; - const dirSign = (o.openingDir ?? "in") === "in" ? 1 : -1; - const swingDir = scale(n, swingSign * dirSign); - const angle = (o.swingAngle ?? 90) * DEG; - if (leafCount >= 2) { - const hw = width / 2; - return [ - computeLeaf(jambStart, u, swingDir, angle, hw), - computeLeaf(jambEnd, scale(u, -1), swingDir, angle, hw), - ]; - } - const hinge = (o.hinge ?? "start") === "start" ? jambStart : jambEnd; - const closedDir = (o.hinge ?? "start") === "start" ? u : scale(u, -1); - return [computeLeaf(hinge, closedDir, swingDir, angle, width)]; -} - // ── Fenster-Symbol (Plan) ──────────────────────────────────────────────────── /** Aufgelöste Fenster-Linien im Grundriss (Weltkoordinaten). */ @@ -288,62 +171,6 @@ export interface WindowRenderSpec { insetFace?: "aussen" | "innen"; } -/** Ein Segment (Flügel/Pfosten) der Flügeleinteilung, mit aufgelöster Breite. */ -interface SashSegment { - sash: SashDef; - /** Abstand vom Laibungsstart in Metern (0 = jambStart). */ - from: number; - /** Abstand vom Laibungsstart in Metern. */ - to: number; -} - -/** Default-Pfostenbreite (Meter), wenn ein `kind:"pfosten"`-Eintrag keine `postWidth` angibt. */ -const DEFAULT_POST_WIDTH = 0.06; -/** - * Default-Rahmentiefe (Meter), wenn ein Fenster-/Türtyp keine explizite - * `frameDepth` trägt: reale Fensterrahmen sind ~70–90 mm tief (Holz/PVC/Alu), - * unabhängig von der Wanddicke — NICHT die volle Wanddicke (das liess Fenster - * wie einen massiven Block in der Öffnung wirken statt eines schlanken Rahmens - * mit sichtbarer Laibung/Leibung ringsum, s. Recherche zu VW/ArchiCAD-Fenster- - * konstruktion). Deckt sich mit `toWalls3d.ts::DEFAULT_FRAME_DEPTH` (2D=3D). - */ -const DEFAULT_FRAME_DEPTH = 0.07; - -/** - * Löst eine Flügeleinteilung ({@link SashDef}-Liste) zu konkreten Segment- - * Intervallen (Meter, gemessen ab Laibungsstart) über die gegebene - * Gesamtbreite auf: `kind:"pfosten"` und Flügel mit `autoWidth === false` - * erhalten ihre feste Breite (`postWidth` bzw. `width`), die restlichen - * (`autoWidth`, Default) teilen sich die verbleibende Breite gleichmäßig. - * Degeneriert bei GLEICHMÄSSIGEN Flügeln (alle `autoWidth`, keine Pfosten) zur - * bisherigen `wingCount`-Gleichverteilung (Regressionssicherheit). - */ -function sashSegments(sashes: SashDef[], totalWidth: number): SashSegment[] { - if (sashes.length === 0) return []; - let fixedSum = 0; - let autoCount = 0; - for (const s of sashes) { - if (s.kind === "pfosten") fixedSum += Math.max(0, s.postWidth ?? DEFAULT_POST_WIDTH); - else if (s.autoWidth === false) fixedSum += Math.max(0, s.width ?? 0); - else autoCount++; - } - const remaining = Math.max(0, totalWidth - fixedSum); - const autoWidth = autoCount > 0 ? remaining / autoCount : 0; - const segs: SashSegment[] = []; - let cursor = 0; - for (const s of sashes) { - const w = - s.kind === "pfosten" - ? Math.max(0, s.postWidth ?? DEFAULT_POST_WIDTH) - : s.autoWidth === false - ? Math.max(0, s.width ?? 0) - : autoWidth; - segs.push({ sash: s, from: cursor, to: cursor + w }); - cursor += w; - } - return segs; -} - /** * Löst die Fenster-Symbolik auf: ein Rahmen-Rechteck über die Lücke (volle * Wanddicke) plus 1–3 Glaslinien (dünne parallele Linien in der Wandmitte, @@ -355,6 +182,9 @@ function sashSegments(sashes: SashDef[], totalWidth: number): SashSegment[] { * referenziert/auflösbar), bleibt die Mittelpfosten-Berechnung beim * BISHERIGEN Verhalten — `o.wingCount` gleichmäßig verteilt, KEINE * Öffnungsandeutungen — exakt wie vor dieser Erweiterung (Rückwärtskompatibilität). + * + * Die Berechnung läuft im Rust-Kern (`src-tauri/core/src/opening_geom.rs`, [K3a]); diese Funktion + * ist die Fassade mit unveränderter Signatur. */ export function windowSymbol( project: Project, @@ -364,167 +194,44 @@ export function windowSymbol( spec?: WindowRenderSpec, detail: "grob" | "mittel" | "fein" = "fein", ): WindowSymbol | null { - const jambs = openingJambs(wall, o); - if (!jambs) return null; - const { n } = wallAxisFrame(wall); const total = wallTypeThickness(getWallType(project, wall)); - const refOff = wallReferenceOffset(wall, total); - const outer = refOff + total / 2; - const inner = refOff - total / 2; - const { jambStart, jambEnd } = jambs; - - // ── Reicher Pfad (typisiertes Fenster mit Flügeltabelle), SIA-Darstellung ─ - // Detailstufe = SIA-Massstab (fig. 36/37/38): - // • grob (1:100): NUR Blendrahmen-Band + eine Glaslinie über die ganze - // Öffnung — schematisch (SIA fig. 36). - // • mittel(1:50): Blendrahmen + Flügel-Trennlinien + je Flügel eine Glas- - // linie + kleines Stulp-Quadrat je Stoss (SIA fig. 37). KEINE Flügelrahmen. - // • fein (1:20): zusätzlich verschachtelte Flügelrahmen, Glas als Doppel- - // linie (Isolierverglasung) und je Stoss ZWEI Stulp-Quadrate (SIA fig. 38). - if (spec && spec.sashes.length > 0) { - const fw = Math.max(0.01, spec.frameWidth); - const depth = Math.min(total, spec.frameDepth && spec.frameDepth > 1e-9 ? spec.frameDepth : DEFAULT_FRAME_DEPTH); - const inset = Math.max(0, spec.insetFromFace ?? 0); - const halfT = total / 2; - // "aussen" = die Wandfläche, an der die ERSTE Wandtyp-Schicht (Aussenputz - // etc., "Schichten außen → innen") liegt — das ist die Seite mit dem - // NEGATIVEN Achs-Offset (s. addWallPoche: `off` startet bei `refOff-total/2` - // für die erste Schicht). Bug bis 2026-07-12: hier stand `+1` für "aussen" - // (positiver, NICHT negativer Offset) — der Rahmen landete dadurch bündig - // an der INNEREN statt der äusseren Wandfläche (Nutzer-Report: "im 2D innen - // bündig und im 3D aussen bündig" — das 3D-Pendant nutzt kompensierend eine - // gespiegelte Normale, s. resolveFrameNormalRange/openingAxisBox). - const sign = (spec.insetFace ?? "aussen") === "aussen" ? -1 : 1; - // Rahmen-Vorderkante bündig mit der Bezugsfläche, um `inset` zurück; der - // Körper reicht `depth` zur Wandmitte. Auf die Wanddicke geklemmt (mirror - // von resolveFrameNormalRange im 3D). Alles relativ zur Referenzlinie. - let frontRel = sign * (halfT - inset); - let backRel = frontRel - sign * depth; - frontRel = Math.max(-halfT, Math.min(halfT, frontRel)); - backRel = Math.max(-halfT, Math.min(halfT, backRel)); - const frameOuterN = refOff + Math.max(frontRel, backRel); - const frameInnerN = refOff + Math.min(frontRel, backRel); - const bandDepth = frameOuterN - frameInnerN; - const gMidBase = (frameOuterN + frameInnerN) / 2; - - const frame = [ - add(jambStart, scale(n, frameOuterN)), - add(jambEnd, scale(n, frameOuterN)), - add(jambEnd, scale(n, frameInnerN)), - add(jambStart, scale(n, frameInnerN)), - ]; - - const glassLines: [Vec2, Vec2][] = []; - const mullionLines: [Vec2, Vec2][] = []; - const sashFrames: Vec2[][] = []; - const meetingMarks: Vec2[][] = []; - const jambMarks: Vec2[][] = []; - - // grob (1:100): nur der Rahmenkasten + EINE Glaslinie über die ganze Öffnung. - if (detail === "grob") { - glassLines.push([add(jambStart, scale(n, gMidBase)), add(jambEnd, scale(n, gMidBase))]); - return { frame, glassLines, mullionLines, sashFrames, sashOpeningLines: [], meetingMarks, jambMarks }; - } - - const fein = detail === "fein"; - const axisWidth = Math.hypot(jambEnd.x - jambStart.x, jambEnd.y - jambStart.y); - const segs = sashSegments(spec.sashes, axisWidth); - // Öffenbarer Flügel sitzt `reveal` tiefer im Blendrahmen (nur „fein"). - const reveal = fein ? Math.min(bandDepth * 0.3, fw * 0.7) : 0; - // Profil-Block über die VOLLE Rahmentiefe (aussen bis innen), Breite `2·halfU` - // entlang der Achse, zentriert bei `uCenter` (Achsabstand ab jambStart) — der - // Rahmenquerschnitt, wie er im Grundriss-Schnitt sichtbar ist (Nutzer: - // „Rahmen aussen als zwei Flächen gleichbreit wie das Fenster [tief]"). - const frameBlock = (uCenter: number, halfU: number): Vec2[] => { - const a = along(jambStart, jambEnd, uCenter - halfU); - const b = along(jambStart, jambEnd, uCenter + halfU); - return [ - add(a, scale(n, frameOuterN)), - add(b, scale(n, frameOuterN)), - add(b, scale(n, frameInnerN)), - add(a, scale(n, frameInnerN)), - ]; - }; - // Laibungs-Pfosten an beiden Enden (Blendrahmen-Querschnitt an der Wand- - // öffnung) — EIN Block je Seite, unabhängig vom Detailgrad. Teil des - // Blendrahmens (jambMarks), NICHT der Flügelstoss-Marken (meetingMarks) — - // separat steuerbar (Nutzer-Feedback). - jambMarks.push(frameBlock(fw / 2, fw / 2), frameBlock(axisWidth - fw / 2, fw / 2)); - - // Flügel-Trennlinien (Mittelpfosten) an den inneren Segmentgrenzen + - // Stulp-Block: mittel 1, fein 2 (die beiden zusammenstossenden Profile) — - // je über die volle Rahmentiefe. KEINE zusätzliche dünne Trennlinie mehr - // daneben (Nutzer-Feedback: „keine vertikale Trennlinie, sondern ein - // Rechteck") — der Block selbst markiert den Stoss. - for (let i = 0; i < segs.length - 1; i++) { - const uPos = segs[i].to; - if (fein) { - meetingMarks.push(frameBlock(uPos - fw / 2, fw / 2), frameBlock(uPos + fw / 2, fw / 2)); - } else { - meetingMarks.push(frameBlock(uPos, fw / 2)); - } - } - - for (const seg of segs) { - if (seg.sash.kind === "pfosten") continue; - const clearFrom = seg.from + fw; - const clearTo = seg.to - fw; - if (clearTo - clearFrom <= 1e-6) continue; - const operable = !!seg.sash.opening && seg.sash.opening !== "fest"; - // „mittel" (SIA fig. 37) zeigt NUR Blendrahmen + Pfosten/Stulp — noch KEINE - // Glaslinie/Flügelrahmen (Nutzer-Vorgabe: „im 1:50 muss man die Fenster- - // linie noch nicht sehen, nur die Vierecke aussen/innen"). Das kommt erst - // bei „fein" (SIA fig. 38) dazu. - if (!fein) continue; - const gOuterN = frameOuterN - (operable ? reveal : 0); - const gInnerN = frameInnerN + (operable ? reveal : 0); - // Verschachtelter Flügelrahmen NUR bei „fein" (SIA fig. 38); „mittel" bleibt - // beim reinen Blendrahmen-Band (SIA fig. 37). - // Keine Glaslinie mehr im Feld (auch nicht bei „fein") — Nutzer-Feedback: - // eine feine Haarlinie mittig im Glasfeld wird nicht gebraucht, unabhängig - // von der Fensterposition. Der Flügelrahmen (nur bei öffenbaren Flügeln) - // bleibt als einzige zusätzliche Kontur bei „fein" bestehen. - if (operable) { - const sFrom = along(jambStart, jambEnd, clearFrom); - const sTo = along(jambStart, jambEnd, clearTo); - sashFrames.push([ - add(sFrom, scale(n, gOuterN)), - add(sTo, scale(n, gOuterN)), - add(sTo, scale(n, gInnerN)), - add(sFrom, scale(n, gInnerN)), - ]); - } - } - return { frame, glassLines, mullionLines, sashFrames, sashOpeningLines: [], meetingMarks, jambMarks }; - } - - // ── Alt-Pfad (kein Typ auflösbar) ──────────────────────────────────────── - // UNVERÄNDERT (Rust-Parität kernel2d): Rahmen an voller Wanddicke, Glaslinien - // mittig, (wingCount−1) gleichmäßige Mittelpfosten. Keine Flügelrahmen. - const frame = [ - add(jambStart, scale(n, outer)), - add(jambEnd, scale(n, outer)), - add(jambEnd, scale(n, inner)), - add(jambStart, scale(n, inner)), + const b: number[] = [ + wall.start.x, wall.start.y, wall.end.x, wall.end.y, total, wallReferenceOffset(wall, total), + o.position, o.width, glassCount, o.wingCount ?? Number.NaN, + detail === "grob" ? 0 : detail === "mittel" ? 1 : 2, + spec ? 1 : 0, + spec?.frameWidth ?? 0, spec?.frameDepth ?? Number.NaN, spec?.insetFromFace ?? Number.NaN, + spec?.insetFace === "innen" ? 1 : 0, + spec?.sashes.length ?? 0, ]; - const glassLines: [Vec2, Vec2][] = []; - const count = Math.max(1, glassCount); - for (let i = 0; i < count; i++) { - const spread = total / 8; - const off = refOff + (count === 1 ? 0 : (i - (count - 1) / 2) * spread * 2); - glassLines.push([add(jambStart, scale(n, off)), add(jambEnd, scale(n, off))]); + for (const s of spec?.sashes ?? []) { + b.push(s.kind === "pfosten" ? 1 : 0, s.autoWidth === false ? 0 : 1, s.width ?? Number.NaN, s.postWidth ?? Number.NaN, + s.opening && s.opening !== "fest" ? 1 : 0); } - const mullionLines: [Vec2, Vec2][] = []; - const wings = Math.max(1, Math.min(4, Math.round(o.wingCount ?? 1))); - if (wings > 1) { - const postDepth = total * 0.6; - const pOuter = refOff + postDepth / 2; - const pInner = refOff - postDepth / 2; - for (let i = 1; i < wings; i++) { - const t = i / wings; - const onAxis = add(jambStart, scale(sub(jambEnd, jambStart), t)); - mullionLines.push([add(onAxis, scale(n, pOuter)), add(onAxis, scale(n, pInner))]); + const f = core().window_symbol_flat(Float64Array.from(b)); + if (f.length === 0) return null; + let i = 1; + const pt = (): Vec2 => ({ x: f[i++], y: f[i++] }); + const frame = [pt(), pt(), pt(), pt()]; + const segs = (): [Vec2, Vec2][] => { + const n = f[i++]; + const out: [Vec2, Vec2][] = []; + for (let k = 0; k < n; k++) out.push([pt(), pt()]); + return out; + }; + const rings = (): Vec2[][] => { + const n = f[i++]; + const out: Vec2[][] = []; + for (let k = 0; k < n; k++) { + const m = f[i++]; + out.push(Array.from({ length: m }, pt)); } - } - return { frame, glassLines, mullionLines, sashFrames: [], sashOpeningLines: [], meetingMarks: [], jambMarks: [] }; + return out; + }; + const glassLines = segs(); + const mullionLines = segs(); + const sashFrames = rings(); + const meetingMarks = rings(); + const jambMarks = rings(); + return { frame, glassLines, mullionLines, sashFrames, sashOpeningLines: [], meetingMarks, jambMarks }; } diff --git a/src/plan/generatePlan/openings.ts b/src/plan/generatePlan/openings.ts index 1ba08b7e..d8f18edc 100644 --- a/src/plan/generatePlan/openings.ts +++ b/src/plan/generatePlan/openings.ts @@ -1,9 +1,12 @@ // Öffnungs-Domäne des Grundriss-Generators: Tür-/Fenstersymbole je Detailgrad // (Blatt/Schwenkbogen/Anschlag bzw. Rahmen/Sprossen/Glas), das optionale -// Rahmenband (Zarge/Blockrahmen) samt Schichteinzug aus der Typ-Bibliothek, -// sowie das Legacy-Türsymbol (`Door`, vor der Öffnungs-Typ-Bibliothek). +// Rahmenband (Zarge/Blockrahmen) samt Schichteinzug aus der Typ-Bibliothek. +// +// Die Geometrie entsteht im Rust-Kern (`src-tauri/core/src/plan_openings.rs`, [K3a]); hier bleibt +// die Auflösung aus dem Modell (Typ-Bibliothek, Linien-Overrides) und die Übersetzung in +// `Primitive`-Objekte mit Farbe, Strichstärke und `openingId`. Fällt mit [K3d] weg. -import type { Opening, Project, Vec2, Wall } from "../../model/types"; +import type { Opening, Project, Wall } from "../../model/types"; import { getDoorType, getWindowType, @@ -11,16 +14,8 @@ import { sashesOfWindowType, wallTypeThickness, } from "../../model/types"; -import { - doorLeaves, - doorSymbol, - openingGapQuad, - openingJambs, - wallAxisFrame, - windowSymbol, -} from "../../geometry/opening"; import { wallReferenceOffset } from "../../model/wall"; -import { add, along, dot, scale, sub } from "../../model/geometry"; +import { core } from "../../engine/coreWasm"; import { NO_HATCH, OVERHEAD_DASH, @@ -30,6 +25,17 @@ import { type Primitive, } from "./shared"; +/** Linienklassen in der Reihenfolge der Kern-Kodierung (`plan_openings.rs`). */ +const LINE_CLS = [ + "door-leaf", "door-frame", "door-lintel", "opening-frame", "window-glass", "window-mullion", + "window-sash", "window-stulp", "window-sill", "window-frame", "window-shading", +] as const; +/** Strichmuster (Kern-Kodierung): 1 Sturz, 2 Überkopf, 3 gepunktet. */ +const DASHES: (number[] | undefined)[] = [undefined, [0.18, 0.09], OVERHEAD_DASH, [0.04, 0.08]]; +const DETAIL_CODE: Record = { grob: 0, mittel: 1, fein: 2 }; +const LINTEL_CODE = { keine: 0, aussen: 1, innen: 2, beide: 3 } as const; +const SILL_CODE = { aussen: 1, innen: 2, beide: 3 } as const; + /** * Aufgelöste Rahmen-Parameter (Typ-Bibliothek) einer Tür-/Fenster-Öffnung — * nur vorhanden, wenn die Öffnung einen Bauteil-Typ referenziert (`typeId`). @@ -74,133 +80,8 @@ function resolveOpeningFrameSpec(project: Project, o: Opening): OpeningFrameSpec } /** - * Rahmenband + Oberlicht-Andeutung einer Tür-/Fenstertyp-Öffnung im - * Grundriss-Schnitt. Nur aufgerufen, wenn `resolveOpeningFrameSpec` einen Typ - * liefert — sonst bleibt die Darstellung exakt wie zuvor (kein neues Primitiv). - * - * • Zarge — schmales Umlauf-Rahmenband, ringsum um `frameWidth` - * von der vollen Öffnung (Pfosten × Wanddicke) nach innen eingezogen. - * • Blockrahmen (Tür) — kräftiges Rechteckprofil, sitzt PROUD an der - * gewählten Fläche (kein Einzug an den Pfosten, nur eine Tiefenscheibe von - * `frameWidth` ab der Nah-Fläche), kräftigere Linie. - * • Schichteinzug — verschiebt die Nah-Fläche des Rahmens um - * `insetFromFace` von der gewählten Wandfläche nach innen; die Gegenfläche - * bleibt unverändert (der Rahmen reicht weiterhin bis dorthin). - * • Oberlicht — Überkopf-Andeutung (gestrichelte Linie quer über die - * Öffnung), nur wenn `transomHeight > 0`. - */ -function addOpeningFrameBand( - out: Primitive[], - project: Project, - wall: Wall, - o: Opening, - spec: OpeningFrameSpec, - greyed: boolean, -): void { - const jambs = openingJambs(wall, o); - if (!jambs) return; - const { n } = wallAxisFrame(wall); - const total = wallTypeThickness(getWallType(project, wall)); - const refOff = wallReferenceOffset(wall, total); - // "aussen" = die Fläche der ERSTEN Wandtyp-Schicht (kleinster Achs-Offset, - // s. addWallPoche/`off` startet bei `refOff-total/2`) — mit `n = leftNormal(u)` - // ist das die NEGATIVE Seite. Bug bis 2026-07-12: hier stand `+total/2` für - // "aussen" (positive Seite, tatsächlich "innen") — Türrahmenbänder mit - // insetFace:"aussen" landeten dadurch an der falschen Wandfläche. - const outerFace = refOff - total / 2; // "aussen"-Fläche (−n, erste Schicht) - const innerFace = refOff + total / 2; // "innen"-Fläche (+n, letzte Schicht) - - // Schichteinzug: die GEWÄHLTE Fläche rückt um `insetFromFace` nach innen; die - // gegenüberliegende Fläche bleibt unverändert (der Rahmen reicht weiterhin - // bis dorthin) — vgl. DoorType.insetFromFace/WindowType.insetFromFace. - const clampedInset = Math.max(0, Math.min(spec.insetFromFace, total)); - const nearIsAussen = spec.insetFace !== "innen"; - // "Nach innen" heisst: von der gewählten Fläche RICHTUNG WANDMITTE (refOff) — - // von aussen (negative Seite) aus AUFWÄRTS (+clampedInset), von innen - // (positive Seite) aus ABWÄRTS (−clampedInset). - const faceNear = nearIsAussen ? outerFace + clampedInset : innerFace - clampedInset; - const faceFar = nearIsAussen ? innerFace : outerFace; - const lo = Math.min(faceNear, faceFar); - const hi = Math.max(faceNear, faceFar); - - const { jambStart, jambEnd } = jambs; - const color = o.color ?? POCHE_STROKE; - - // Rahmen-Rechteck NUR bei Türen zeichnen. Beim Fenster stellt bereits - // `windowSymbol` den Rahmen dar (voller Öffnungsumriss + Glaslinien); ein - // zusätzliches Band ergäbe ein doppeltes, verschachteltes Rechteck — genau - // das wirkte im 2D „nicht korrekt". Die Tür hat dort nur Blatt+Bogen, daher - // ist ihr Rahmenband die einzige Rahmenkontur und bleibt. - if (o.kind === "door") { - const frameWidth = Math.max(0, spec.frameWidth); - const isBlock = spec.frameKind === "blockrahmen"; - let bandLo: number; - let bandHi: number; - let jStart: Vec2; - let jEnd: Vec2; - let weightMm: number; - if (isBlock) { - // Blockrahmen: volle Öffnungsbreite (kein Pfosten-Einzug), nur eine - // Tiefenscheibe von frameWidth ab der Nah-Fläche — sitzt proud VOR/auf der - // Laibung, statt schmal darin zu verschwinden (Zargen-Optik). "aussen" - // liegt bei `lo` (s. Kommentar zu outerFace/innerFace oben), die Scheibe - // beginnt dort und wächst RICHTUNG WANDMITTE (Richtung `hi`). - const depth = Math.min(frameWidth, hi - lo); - bandLo = nearIsAussen ? lo : hi - depth; - bandHi = nearIsAussen ? lo + depth : hi; - jStart = jambStart; - jEnd = jambEnd; - weightMm = SYMBOL_HAIRLINE_MM * 2.2; - } else { - // Zarge: ringsum um frameWidth von der vollen Öffnung eingezogenes, - // schmales Rahmenband (Laibungs-Anschlaglinie). - const jambSpan = Math.hypot(jambEnd.x - jambStart.x, jambEnd.y - jambStart.y); - const jambInset = Math.min(frameWidth, jambSpan / 2); - jStart = along(jambStart, jambEnd, jambInset); - jEnd = along(jambEnd, jambStart, jambInset); - const depthInset = Math.min(frameWidth, (hi - lo) / 2); - bandLo = lo + depthInset; - bandHi = hi - depthInset; - weightMm = SYMBOL_HAIRLINE_MM; - } - - // Geschlossenes Rechteck aus 4 Kanten (Primitive "line", nicht "polygon" — - // so bleibt das Band per `cls` selektierbar/testbar wie die übrigen Symbole). - const p1 = add(jStart, scale(n, bandLo)); - const p2 = add(jEnd, scale(n, bandLo)); - const p3 = add(jEnd, scale(n, bandHi)); - const p4 = add(jStart, scale(n, bandHi)); - const edges: [Vec2, Vec2][] = [ - [p1, p2], - [p2, p3], - [p3, p4], - [p4, p1], - ]; - for (const [a, b] of edges) { - out.push({ - kind: "line", - a, - b, - cls: "opening-frame", - weightMm, - color, - greyed, - openingId: o.id, - }); - } - } - - // Die frühere Oberlicht-Andeutung (gestrichelte Linie quer über die ganze - // Öffnung bei transomHeight>0) ist entfernt (Nutzer-Report: erscheint immer - // auf der Wandachse, unabhängig davon, ob die Schnittebene den Kämpfer - // überhaupt trifft — im horizontalen Grundriss-Schnitt architektonisch nicht - // aussagekräftig, ein Kämpfer ist ein Höhen-, kein Grundriss-Merkmal). -} - -/** - * Öffnungs-Symbol (Fenster/Tür) je Detailgrad. Anders als das Legacy-`addDoorSymbol` - * arbeitet diese Funktion über die reinen Geometrie-Helfer (opening.ts) und taggt - * ihre Primitive mit `openingId`, sodass die Öffnung im Plan selektierbar ist. + * Öffnungs-Symbol (Fenster/Tür) je Detailgrad. Arbeitet über den Kern (`plan_openings.rs`) und + * taggt ihre Primitive mit `openingId`, sodass die Öffnung im Plan selektierbar ist. * * Tür: * • grob — gerade Türblatt-Linie (die Lücke kommt aus der ausgesparten Poché). @@ -208,8 +89,8 @@ function addOpeningFrameBand( * • fein — + Anschlag-Striche an beiden Pfosten. * Fenster: * • grob — eine einzelne Glaslinie über die Lücke. - * • mittel — Rahmen-Rechteck (Umriss) + eine Glaslinie. - * • fein — Rahmen + zwei Glaslinien (Doppelverglasung angedeutet). + * • mittel — Rahmen-Rechteck (Umriss) + Pfosten/Stulp. + * • fein — + Flügelrahmen, Fensterbank, Anschlagkerben. */ export function addOpeningSymbol( out: Primitive[], @@ -220,374 +101,118 @@ export function addOpeningSymbol( detail: DetailLevel, lwMm: number, ): void { - if (o.kind === "door") { - const sym = doorSymbol(wall, o); - if (!sym) return; - // Unsichtbares Pick-Polygon über der Öffnungslücke (Laibung × Wanddicke) — - // damit die Tür wie ein Fenster per Punkt-in-Polygon über die ganze - // Öffnungsfläche selektierbar ist (Türsymbol besteht sonst nur aus dünnem - // Blatt + Bogen, die man exakt treffen müsste). fill/stroke "none" ⇒ zeichnet - // nichts; `pickOpening` (PlanView) testet nur die `pts`. - const gap = openingGapQuad(project, wall, o); - if (gap) { + const total = wallTypeThickness(getWallType(project, wall)); + const refOff = wallReferenceOffset(wall, total); + const door = o.kind === "door"; + const wt = door ? undefined : getWindowType(project, o); + const frameSpec = door ? resolveOpeningFrameSpec(project, o) : undefined; + const sashes = wt ? sashesOfWindowType(wt) : []; + const strokeColor = o.color ?? POCHE_STROKE; + // Linien-Kategorien einzeln übersteuerbar: Rahmen-Schnitt, Rahmen-Aufsicht, Fenster + // (Flügelrahmen/Sprossen), Sims. `undefined` ⇒ Strichfarbe/Haarlinie. + const frameColor = o.frameLine?.color ?? strokeColor; + const frameWeight = o.frameLine?.weight ?? lwMm; + const frameViewWeight = o.frameViewLine?.weight ?? frameWeight; + const colors = [ + "", + strokeColor, + frameColor, + o.frameViewLine?.color ?? frameColor, + o.sashLine?.color ?? strokeColor, + o.sillLineStyle?.color ?? strokeColor, + ]; + const b: number[] = [ + wall.start.x, wall.start.y, wall.end.x, wall.end.y, total, refOff, + o.position, o.width, door ? 1 : 0, DETAIL_CODE[detail], + // Tür + (o.swing ?? "left") !== "left" ? 1 : 0, + (o.openingDir ?? "in") !== "in" ? 1 : 0, + (o.hinge ?? "start") !== "start" ? 1 : 0, + o.swingAngle ?? Number.NaN, + (o.doorType ?? "normal") === "wandoeffnung" ? 1 : 0, + door ? Math.max(1, Math.round(getDoorType(project, o)?.leafCount ?? 1)) : 1, + LINTEL_CODE[o.lintelLines ?? "beide"], + // Rahmenband + frameSpec ? 1 : 0, + frameSpec?.frameWidth ?? 0, + frameSpec?.frameKind === "blockrahmen" ? 1 : 0, + frameSpec?.insetFromFace ?? 0, + frameSpec?.insetFace === "innen" ? 1 : 0, + // Fenster + wt ? 1 : 0, + wt ? wt.frameWidth ?? 0.06 : 0, + wt?.frameDepth ?? Number.NaN, + wt?.insetFromFace ?? Number.NaN, + wt?.insetFace === "innen" ? 1 : 0, + o.wingCount ?? Number.NaN, + detail === "fein" ? 2 : 1, + wt?.sillLine ? SILL_CODE[wt.sillLine.faces] : 0, + wt?.sillLine?.view === "unter" ? 1 : 0, + wt?.shading?.create ? 1 : 0, + wt?.shading?.box.width ?? 0, + wt?.shading?.box.height ?? 0, + // Strichstärken + SYMBOL_HAIRLINE_MM, + o.frameLine?.weight ?? SYMBOL_HAIRLINE_MM, + frameViewWeight, + o.sashLine?.weight ?? SYMBOL_HAIRLINE_MM, + o.sillLineStyle?.weight ?? SYMBOL_HAIRLINE_MM, + sashes.length, + ]; + for (const s of sashes) { + b.push(s.kind === "pfosten" ? 1 : 0, s.autoWidth === false ? 0 : 1, s.width ?? Number.NaN, s.postWidth ?? Number.NaN, + s.opening && s.opening !== "fest" ? 1 : 0); + } + const f = core().plan_opening_flat(Float64Array.from(b)); + if (f.length === 0) return; + const openingId = o.id; + const n = f[0]; + let i = 1; + for (let k = 0; k < n; k++) { + if (f[i] === 1) { + const count = f[i + 4]; + const pts = new Array<{ x: number; y: number }>(count); + for (let j = 0; j < count; j++) pts[j] = { x: f[i + 5 + 2 * j], y: f[i + 6 + 2 * j] }; + const frame = f[i + 1] === 1; out.push({ kind: "polygon", - pts: gap, + pts, fill: "none", - stroke: "none", - strokeWidthMm: 0, + stroke: frame ? colors[f[i + 3]] : "none", + strokeWidthMm: f[i + 2], hatch: NO_HATCH, greyed, - openingId: o.id, + openingId, }); - } - // Tür-Typ „wandoeffnung": reiner Wanddurchbruch — KEIN Türblatt, KEIN - // Schwenkbogen. Nur die Öffnung/Laibung bleibt (die Wandlücke kommt aus der - // ausgesparten Poché; Sturz-/Anschlaglinien werden weiter unten gezeichnet). - // Entspricht `oeff_tuer_typ == "wandoeffnung"` im Rhino-Plugin. - const isWandoeffnung = (o.doorType ?? "normal") === "wandoeffnung"; - if (!isWandoeffnung) { - // Türblätter (1 oder 2 Flügel, je DoorType.leafCount). Zweiflüglig ⇒ zwei - // halbbreite Blätter an gegenüberliegenden Pfosten (symmetrische Doppeltür). - const leafCount = Math.max(1, Math.round(getDoorType(project, o)?.leafCount ?? 1)); - for (const leaf of doorLeaves(wall, o, leafCount)) { - out.push({ - kind: "line", - a: leaf.hinge, - b: leaf.openEnd, - cls: "door-leaf", - weightMm: SYMBOL_HAIRLINE_MM, - greyed, - openingId: o.id, - }); - // mittel + fein: Schwenkbogen von geschlossen → offen je Blatt. - if (detail !== "grob") { - out.push({ - kind: "arc", - center: leaf.hinge, - from: leaf.closedEnd, - to: leaf.openEnd, - r: leaf.radius, - cls: "door-swing", - weightMm: SYMBOL_HAIRLINE_MM, - greyed, - openingId: o.id, - }); - } - } - } - // fein: Anschlag-Striche an beiden Pfosten (quer zur Wand). - if (detail === "fein") { - const reveal = 0.06; - for (const jamb of [sym.jambStart, sym.jambEnd]) { - out.push({ - kind: "line", - a: add(jamb, scale(sym.normal, reveal)), - b: add(jamb, scale(sym.normal, -reveal)), - cls: "door-frame", - weightMm: SYMBOL_HAIRLINE_MM, - greyed, - openingId: o.id, - }); - } - } - // Rahmenband (Zarge/Blockrahmen) + Oberlicht-Andeutung — nur wenn die - // Öffnung einen Türtyp referenziert (siehe `resolveOpeningFrameSpec`). - const doorFrameSpec = resolveOpeningFrameSpec(project, o); - if (doorFrameSpec) addOpeningFrameBand(out, project, wall, o, doorFrameSpec, greyed); - // Sturzlinien (SIA, gestrichelt) — Überkopf-Projektion des Sturzes quer über - // die Öffnung an der Wand-Innen-/Aussenkante. Entspricht `_make_tuer_sturz_curves` - // im Rhino-Plugin. Default „beide" wenn nicht explizit gesetzt. - const lintelMode = o.lintelLines ?? "beide"; - if (lintelMode !== "keine") { - const jambs = openingJambs(wall, o); - if (jambs) { - const { n } = wallAxisFrame(wall); - const total = wallTypeThickness(getWallType(project, wall)); - const refOff = wallReferenceOffset(wall, total); - const halfD = total / 2; - // "aussen" = negative Seite (erste Wandtyp-Schicht), s. Kommentar in - // addOpeningFrameBand — Bug bis 2026-07-12: stand hier vertauscht. - const outerOff = refOff - halfD; - const innerOff = refOff + halfD; - // Strichmuster: gestrichelt (Überkopf-Projektion, SIA-Konvention). - const dash: number[] = [0.18, 0.09]; - const strokeColor = o.color ?? POCHE_STROKE; - /** Linie quer über die Öffnung am gegebenen Perp-Offset. */ - const lintelLine = (perpOff: number) => ({ - a: add(jambs.jambStart, scale(n, perpOff)), - b: add(jambs.jambEnd, scale(n, perpOff)), - }); - if (lintelMode === "aussen" || lintelMode === "beide") { - const seg = lintelLine(outerOff); - out.push({ - kind: "line" as const, - a: seg.a, - b: seg.b, - cls: "door-lintel", - weightMm: SYMBOL_HAIRLINE_MM, - dash, - color: strokeColor, - greyed, - openingId: o.id, - }); - } - if (lintelMode === "innen" || lintelMode === "beide") { - const seg = lintelLine(innerOff); - out.push({ - kind: "line" as const, - a: seg.a, - b: seg.b, - cls: "door-lintel", - weightMm: SYMBOL_HAIRLINE_MM, - dash, - color: strokeColor, - greyed, - openingId: o.id, - }); - } - } - } - return; - } - - // Fenster: Rahmen (mittel/fein) + Glaslinie(n) je Detailgrad + Fenstertyp. - const wt = getWindowType(project, o); - // Flügeltabelle NUR übergeben, wenn ein Fenstertyp auflösbar ist — fehlt er - // (kein `typeId`/unbekannt), bleibt `windowSymbol` beim reinen - // `o.wingCount`-Alt-Verhalten (siehe dortiger Kommentar, Regressionssicherheit). - const spec = wt - ? { - sashes: sashesOfWindowType(wt), - frameWidth: wt.frameWidth ?? 0.06, - frameDepth: wt.frameDepth, - insetFromFace: wt.insetFromFace, - insetFace: wt.insetFace, - } - : undefined; - // Glaslinienzahl NUR für den Alt-Pfad (kein `spec`) relevant — der typisierte - // Pfad entscheidet die Anzahl selbst nach SIA-Detailgrad (s. windowSymbol). - const glassCount = detail === "fein" ? 2 : 1; - const sym = windowSymbol(project, wall, o, glassCount, spec, detail); - if (!sym) return; - // Unsichtbares Pick-Polygon über der Öffnungslücke — macht das Fenster über - // die ganze Fläche selektierbar, auch bei „grob" (nur eine Glaslinie, sonst - // schwer zu treffen). Siehe Tür-Zweig oben. - const wgap = openingGapQuad(project, wall, o); - if (wgap) { - out.push({ - kind: "polygon", - pts: wgap, - fill: "none", - stroke: "none", - strokeWidthMm: 0, - hatch: NO_HATCH, - greyed, - openingId: o.id, - }); - } - // ── SIA-Fensterdarstellung, nach Detailgrad gestaffelt ──────────────────── - // grob (1:100): weisse Öffnung + EINE dünne Glaslinie, sonst nichts. - // mittel (1:50): Blendrahmen-Rechteck + Pfosten-Trennlinien + Stulp-Mittel- - // quadrat je Flügel-Junction + Glaslinie(n). - // fein (1:20): zusätzlich Flügelrahmen, Stulp als ZWEI Rechtecke, Fensterbank - // (aussen) und Anschlag-/Laibungskerben — deutlich reicher als mittel. - const strokeColor = o.color ?? POCHE_STROKE; - const { n: wn } = wallAxisFrame(wall); - - if (detail === "grob") { - // SIA 1:100 — nur eine dünne Glaslinie mittig über die weisse Öffnung. - // Zählt zur "Fenster"-Kategorie (sashLine) — dieselbe Glaslinie, die bei - // mittel/fein früher sichtbar war (jetzt dort entfernt, s. Fenster-Session). - const g = sym.glassLines[Math.floor(sym.glassLines.length / 2)] ?? sym.glassLines[0]; - if (g) { + i += 5 + 2 * count; + } else if (f[i] === 2) { + const slot = f[i + 3]; + const dash = DASHES[f[i + 4]]; out.push({ kind: "line", - a: g[0], - b: g[1], - cls: "window-glass", - weightMm: o.sashLine?.weight ?? SYMBOL_HAIRLINE_MM, - color: o.sashLine?.color ?? strokeColor, + a: { x: f[i + 5], y: f[i + 6] }, + b: { x: f[i + 7], y: f[i + 8] }, + cls: LINE_CLS[f[i + 1]], + weightMm: f[i + 2], + ...(dash ? { dash } : {}), + ...(slot ? { color: colors[slot] } : {}), greyed, - openingId: o.id, + openingId, }); - } - } else { - // Linien-Kategorien einzeln übersteuerbar (Nutzer-Wunsch): Rahmen-Schnitt - // (Laibungs-/Stulp-Blöcke, geschnittenes Profil), Rahmen-Aufsicht (die - // durchlaufende Kontur DAZWISCHEN, projiziert statt geschnitten), Fenster - // (Flügelrahmen/Sprossen), Sims (Auf-/Untersicht-Andeutung, s. u.). - // `undefined` ⇒ bisheriges Verhalten (strokeColor/SYMBOL_HAIRLINE_MM); - // `frameViewLine` fällt zusätzlich auf `frameLine` zurück (eine Farbe für - // Schnitt+Aufsicht, bis der Nutzer sie explizit trennt). - const frameColor = o.frameLine?.color ?? strokeColor; - const frameWeight = o.frameLine?.weight ?? lwMm; - const frameHairline = o.frameLine?.weight ?? SYMBOL_HAIRLINE_MM; - const frameViewColor = o.frameViewLine?.color ?? frameColor; - const frameViewWeight = o.frameViewLine?.weight ?? frameWeight; - const sashColor = o.sashLine?.color ?? strokeColor; - const sashWeight = o.sashLine?.weight ?? SYMBOL_HAIRLINE_MM; - - // Blendrahmen-Rechteck in Aufsicht (mittel + fein) — die durchlaufende - // Kontur zwischen den geschnittenen Laibungs-/Stulp-Blöcken. - out.push({ - kind: "polygon", - pts: sym.frame, - fill: "none", - stroke: frameViewColor, - strokeWidthMm: frameViewWeight, - hatch: NO_HATCH, - greyed, - openingId: o.id, - }); - // Pfosten-/Flügel-Trennlinien (Alt-Pfad ohne Typ — zählt als "Fenster"). - for (const [a, b] of sym.mullionLines) { - out.push({ kind: "line", a, b, cls: "window-mullion", weightMm: sashWeight, color: sashColor, greyed, openingId: o.id }); - } - // fein: Flügelrahmen (Flügelkontur) je öffenbarem Flügel — Schachtelung - // Blendrahmen → Flügelrahmen → Glas (Feindetail, hebt fein klar von mittel ab). - if (detail === "fein") { - for (const pts of sym.sashFrames) { - for (let i = 0; i < pts.length; i++) { - out.push({ kind: "line", a: pts[i], b: pts[(i + 1) % pts.length], cls: "window-sash", weightMm: sashWeight, color: sashColor, greyed, openingId: o.id }); - } - } - } - // Laibungs-Blöcke an den Öffnungsenden (Blendrahmen-Querschnitt) — Teil des - // Blendrahmens, zählt zu "Rahmen". - for (const mark of sym.jambMarks) { - for (let i = 0; i < mark.length; i++) { - out.push({ kind: "line", a: mark[i], b: mark[(i + 1) % mark.length], cls: "window-stulp", weightMm: frameHairline, color: frameColor, greyed, openingId: o.id }); - } - } - // Stulp-Mittelquadrat je Flügel-Junction (SIA-Signatur): mittel = EIN Quadrat, - // fein = ZWEI anliegende Rechtecke (die beiden Stulp-Stäbe der Flügel) — - // bereits tiefenkorrekt (inset-/insetFace-bewusst) in windowSymbol berechnet. - // Sitzt zwischen den Flügeln, zählt zu "Fenster" (separat vom Blendrahmen - // steuerbar — Nutzer-Feedback). - for (const mark of sym.meetingMarks) { - for (let i = 0; i < mark.length; i++) { - out.push({ kind: "line", a: mark[i], b: mark[(i + 1) % mark.length], cls: "window-stulp", weightMm: sashWeight, color: sashColor, greyed, openingId: o.id }); - } - } - // Glaslinien (Anzahl je Detailgrad/Verglasung, s. glassCount). - for (const [a, b] of sym.glassLines) { - out.push({ kind: "line", a, b, cls: "window-glass", weightMm: SYMBOL_HAIRLINE_MM, greyed, openingId: o.id }); - } - // Oberlicht-Andeutung (transom, gestrichelt) — mittel/fein. - const windowFrameSpec = resolveOpeningFrameSpec(project, o); - if (windowFrameSpec) addOpeningFrameBand(out, project, wall, o, windowFrameSpec, greyed); - // fein: Fensterbank (aussen) + Anschlag-/Laibungskerben. - if (detail === "fein") { - const jb = openingJambs(wall, o); - if (jb) { - const { jambStart, jambEnd } = jb; - // Tatsächliche Rahmen-Aussenkante (NICHT pauschal die volle Wandfläche — - // ein eingezogener Rahmen, s. {@link WindowType.insetFromFace}, hat seine - // Aussenkante weiter innen). "Aussen" ist der ALGEBRAISCH KLEINERE der - // beiden Tiefen-Werte in sym.frame (s. windowSymbol: frontRel für - // insetFace:"aussen" ist negativ) — welcher der beiden Eckpunkt-Paare das - // ist, hängt von insetFace ab, daher robust über Math.min bestimmt statt - // fest über sym.frame[0]. - const outerN = Math.min( - dot(sub(sym.frame[0], jambStart), wn), - dot(sub(sym.frame[2], jambStart), wn), - ); - // Fensterbank: schmales Rechteck vor der Aussenfläche, seitlich ~3 cm - // überstehend, ~4 cm auskragend (SIA-Sims-Andeutung im Grundriss). - // Auskragung geht IMMER weiter nach aussen (algebraisch kleiner, s. o.). - const ov = 0.03; - const proj = 0.04; - const s0 = along(jambStart, jambEnd, -ov); - const s1 = along(jambEnd, jambStart, -ov); - const b0 = add(s0, scale(wn, outerN)); - const b1 = add(s1, scale(wn, outerN)); - const b2 = add(s1, scale(wn, outerN - proj)); - const b3 = add(s0, scale(wn, outerN - proj)); - for (const [a, b] of [[b0, b1], [b1, b2], [b2, b3], [b3, b0]] as [Vec2, Vec2][]) { - out.push({ kind: "line", a, b, cls: "window-sill", weightMm: SYMBOL_HAIRLINE_MM, color: strokeColor, greyed, openingId: o.id }); - } - // Anschlag-Kerben an beiden Pfosten (kurz quer zur Wand). - const reveal = 0.06; - for (const jamb of [jambStart, jambEnd]) { - out.push({ kind: "line", a: add(jamb, scale(wn, reveal)), b: add(jamb, scale(wn, -reveal)), cls: "window-frame", weightMm: SYMBOL_HAIRLINE_MM, color: strokeColor, greyed, openingId: o.id }); - } - } - } - } - // Auf-/Untersicht-Andeutung ({@link WindowType.sillLine}): eine Referenzlinie - // an der Rahmen-Aussen-/Innenkante (NICHT der Wandachse — ersetzt die frühere, - // falsch positionierte Brüstungslinie), nur wenn der Typ es explizit wählt. - // "auf" (Aufsicht von oben, dünn gepunktet) vs. "unter" (Untersicht von unten, - // gestrichelt wie die übrigen Überkopf-Projektionen). - if (detail !== "grob" && wt?.sillLine) { - const { faces, view } = wt.sillLine; - const dash = view === "unter" ? OVERHEAD_DASH : [0.04, 0.08]; - const sillColor = o.sillLineStyle?.color ?? strokeColor; - const sillWeight = o.sillLineStyle?.weight ?? SYMBOL_HAIRLINE_MM; - // Welches der beiden sym.frame-Eckpunkt-Paare physisch "aussen" ist, hängt - // von insetFace ab (s. windowSymbol) — robust über den Tiefen-Vergleich - // entlang wn bestimmt statt fest über den Index. - const pair01IsOuter = dot(sym.frame[0], wn) <= dot(sym.frame[3], wn); - const outerPair: [Vec2, Vec2] = pair01IsOuter ? [sym.frame[0], sym.frame[1]] : [sym.frame[3], sym.frame[2]]; - const innerPair: [Vec2, Vec2] = pair01IsOuter ? [sym.frame[3], sym.frame[2]] : [sym.frame[0], sym.frame[1]]; - if (faces === "aussen" || faces === "beide") { - out.push({ kind: "line", a: outerPair[0], b: outerPair[1], cls: "window-sill", weightMm: sillWeight, dash, color: sillColor, greyed, openingId: o.id }); - } - if (faces === "innen" || faces === "beide") { - out.push({ kind: "line", a: innerPair[0], b: innerPair[1], cls: "window-sill", weightMm: sillWeight, dash, color: sillColor, greyed, openingId: o.id }); - } - } - // Rollladen-/Sonnenschutzkasten (P0-Minimalfassung, reine 2D-Kontur): ein - // gestricheltes Rechteck ÜBER der Öffnung, ausserhalb der Wand-Aussenfläche — - // Breite = `shading.box.width` (0/fehlt ⇒ Öffnungsbreite), die zweite - // Rechteckseite = `shading.box.height`. Die 3D-Tiefe (`box.depth`) bleibt für - // eine spätere 3D-Box reserviert (Fokus hier bewusst 2D, s. Aufgabenstellung). - // Gestrichelt wie die übrigen Überkopf-Projektionen (Sturz/Oberlicht) — der - // Kasten liegt oberhalb der Schnittebene und wird nur angedeutet. - if (wt?.shading?.create) { - const jambs = openingJambs(wall, o); - if (jambs) { - const { u, n: nrm } = wallAxisFrame(wall); - const total = wallTypeThickness(getWallType(project, wall)); - const refOff = wallReferenceOffset(wall, total); - // "aussen" = negative Seite (erste Wandtyp-Schicht), s. Kommentar in - // addOpeningFrameBand — Bug bis 2026-07-12: stand hier vertauscht (der - // Rollladenkasten landete an der Innenfläche statt aussen am Sturz). - const outerFace = refOff - total / 2; - const axisWidth = Math.hypot( - jambs.jambEnd.x - jambs.jambStart.x, - jambs.jambEnd.y - jambs.jambStart.y, - ); - const boxWidth = wt.shading.box.width > 0 ? wt.shading.box.width : axisWidth; - const boxHeight = Math.max(0, wt.shading.box.height); - const center = add(jambs.jambStart, scale(u, axisWidth / 2)); - const half = boxWidth / 2; - const c1 = add(center, scale(u, -half)); - const c2 = add(center, scale(u, half)); - const p1 = add(c1, scale(nrm, outerFace)); - const p2 = add(c2, scale(nrm, outerFace)); - const p3 = add(c2, scale(nrm, outerFace + boxHeight)); - const p4 = add(c1, scale(nrm, outerFace + boxHeight)); - const edges: [Vec2, Vec2][] = [ - [p1, p2], - [p2, p3], - [p3, p4], - [p4, p1], - ]; - for (const [a, b] of edges) { - out.push({ - kind: "line", - a, - b, - cls: "window-shading", - weightMm: SYMBOL_HAIRLINE_MM, - dash: OVERHEAD_DASH, - color: o.color ?? POCHE_STROKE, - greyed, - openingId: o.id, - }); - } + i += 9; + } else { + out.push({ + kind: "arc", + center: { x: f[i + 2], y: f[i + 3] }, + from: { x: f[i + 4], y: f[i + 5] }, + to: { x: f[i + 6], y: f[i + 7] }, + r: f[i + 8], + cls: "door-swing", + weightMm: f[i + 1], + greyed, + openingId, + }); + i += 9; } } } From 125422afec80f6928e7bd0288eda62f924f289cb Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:01:04 +0100 Subject: [PATCH 04/31] [K3a] Kontext-Mesh, Schnittfuehrung und Linienenden im Grundriss in Rust (plan_misc.rs) --- TODO.md | 5 +- src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/plan_misc.rs | 278 ++++++++++++++++++++++++++++ src-tauri/core/src/web/mod.rs | 1 + src-tauri/core/src/web/plan_misc.rs | 27 +++ src/plan/generatePlan/context.ts | 100 +++------- src/plan/generatePlan/endMarks.ts | 97 +++------- src/plan/generatePlan/sections.ts | 144 +++++--------- 8 files changed, 408 insertions(+), 245 deletions(-) create mode 100644 src-tauri/core/src/plan_misc.rs create mode 100644 src-tauri/core/src/web/plan_misc.rs diff --git a/TODO.md b/TODO.md index be6bd08b..c9aebce7 100644 --- a/TODO.md +++ b/TODO.md @@ -96,7 +96,10 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern Farben kommen als Slot zurück. `geometry/opening.ts`: `doorSymbol`/`doorLeaves` gelöscht, `windowSymbol` ist Fassade (Schnitt nutzt sie weiter). Bitgleich zur alten Fassung (80 Zufallsfälle × 3 Detailgrade, alle 13 Linienklassen; 600 Zufalls-Fenstersymbole). Tote halbe Ports in `kernel2d` (door/window_symbol, jambs …) entfernt. - Offen: Räume, Dächer, Stützen, 2D-Zeichnung, Kontext, Schnittlinien. + ✅ Kontext-Mesh (Fussabdruck, Rahmen), Schnittführungs-Symbol, Linienenden: `plan_misc.rs`; bitgleich (200 Zufalls-Meshes, + 200 Schnittebenen-Sätze, 400 Linienenden). Räume, Dächer, Stützen, Extrusions-Umriss, Baurecht, Schatten sind nur + noch Stil-Glue um schon in Rust berechnete Geometrie (kein Rechenanteil) — bleiben bis [K4] in TS. + Offen: 2D-Zeichnung (`drawing2d.ts`, 950 Zeilen: Kurven, Bemassung, Kote, Detailverweis, Block, Text …). - ○ **[K3c] Schnitt und Ansicht** (`toSection`, `toElevation`, `meshSection`) im selben Puffer-Format. - ○ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. Nachteile (bewusst): Übergang mit doppelter Datenhaltung, Format muss TS/Rust gleich bleiben diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 020fde02..b3366ce7 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -37,6 +37,7 @@ pub mod plan_stairs; pub mod plan_walls; pub mod opening_geom; pub mod plan_openings; +pub mod plan_misc; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/plan_misc.rs b/src-tauri/core/src/plan_misc.rs new file mode 100644 index 00000000..7ca6523e --- /dev/null +++ b/src-tauri/core/src/plan_misc.rs @@ -0,0 +1,278 @@ +//! Kleine Plan-Bausteine ([K3a]): Kontext-Mesh-Fussabdruck und -Rahmen (`generatePlan/context.ts`), +//! Schnittführungs-Symbol (`sections.ts`) und Linienenden (`endMarks.ts`). Stil, Farbe, Pick-IDs und +//! Beschriftungstext setzt TS; Rechenreihenfolge und Zahlsemantik wie dort (`Math.hypot`, `Math.round`). +//! +//! ## Kontext-Mesh +//! `context_footprint(positions, indices)` → `[n, ax, ay, bx, by …]` (Sockelkanten, entdoppelt). +//! `bbox(positions)` → `[minX, minY, maxX, maxY]` oder leer. +//! +//! ## Schnittführung +//! `section_line(p0x, p0y, p1x, p1y, vorzeichen)` → `[n, Eintrag × n]` in Zeichenreihenfolge (leer +//! bei zu kurzer Linie): +//! ```text +//! 2 line [2, art (0 Hauptlinie | 1 Marke), ax, ay, bx, by] +//! 5 label [5, x, y] (Kurz-Tag setzt TS) +//! 1 polygon [1, x0, y0 … x3, y3] (unsichtbares Pick-Band) +//! ``` +//! +//! ## Linienende +//! `end_mark(x, y, dx, dy, art, mm, massstab)` → `[verkuerzung, n, Eintrag × n]` (leer = nichts): +//! ```text +//! art 1 arrow · 2 arrowOpen · 3 dot · 4 tick · 5 square +//! 1 polygon [1, nPts, x, y …] gefüllt in Strichfarbe +//! 2 line [2, ax, ay, bx, by] +//! 4 circle [4, cx, cy, r] gefüllt in Strichfarbe +//! ``` + +use crate::jsmath::hypot2; +use crate::jsnum::round; +use std::collections::HashSet; + +const FOOTPRINT_Z_TOL: f64 = 0.6; +const SECTION_MARK_LEN: f64 = 0.6; +const SECTION_PICK_HALF: f64 = 0.3; +const SECTION_LABEL_H: f64 = 0.5; +const ARROW_ASPECT: f64 = 0.32; + +/// Ganzzahl-Schlüssel für die Quantisierung; NaN/∞ bekommen feste Platzhalter (wie ihre Textform in JS). +fn qkey(v: f64) -> i64 { + if v.is_nan() { + i64::MIN + } else if v == f64::INFINITY { + i64::MAX + } else if v == f64::NEG_INFINITY { + i64::MIN + 1 + } else { + v as i64 + } +} + +pub fn context_footprint(positions: &[f64], indices: &[f64]) -> Vec { + let vcount = positions.len() / 3; + if vcount < 3 || indices.len() < 3 { + return Vec::new(); + } + let mut min_z = f64::INFINITY; + let mut i = 2; + while i < positions.len() { + if positions[i] < min_z { + min_z = positions[i]; + } + i += 3; + } + if !min_z.is_finite() { + return Vec::new(); + } + let z_limit = min_z + FOOTPRINT_Z_TOL; + let q = |v: f64| round(v * 100.0); + let mut seen: HashSet<((i64, i64), (i64, i64))> = HashSet::new(); + let mut lines: Vec = Vec::new(); + let mut count = 0usize; + let mut edge = |ia: f64, ib: f64, lines: &mut Vec, count: &mut usize| { + // Indizes wie in TS: Zahlen ohne Prüfung auf Ganzzahligkeit; ausserhalb → Kante verwerfen + if !(ia >= 0.0 && ib >= 0.0) || ia.fract() != 0.0 || ib.fract() != 0.0 { + return; + } + let (ia, ib) = (ia as usize, ib as usize); + if ia >= vcount || ib >= vcount { + return; + } + let za = positions[ia * 3 + 2]; + let zb = positions[ib * 3 + 2]; + if za > z_limit || zb > z_limit { + return; + } + let (ax, ay) = (positions[ia * 3], positions[ia * 3 + 1]); + let (bx, by) = (positions[ib * 3], positions[ib * 3 + 1]); + let ka = (qkey(q(ax)), qkey(q(ay))); + let kb = (qkey(q(bx)), qkey(q(by))); + if ka == kb { + return; + } + let key = if ka < kb { (ka, kb) } else { (kb, ka) }; + if !seen.insert(key) { + return; + } + lines.extend([ax, ay, bx, by]); + *count += 1; + }; + let mut k = 0; + while k + 2 < indices.len() { + let (a, b, c) = (indices[k], indices[k + 1], indices[k + 2]); + edge(a, b, &mut lines, &mut count); + edge(b, c, &mut lines, &mut count); + edge(c, a, &mut lines, &mut count); + k += 3; + } + let mut out = vec![count as f64]; + out.extend(lines); + out +} + +pub fn bbox(positions: &[f64]) -> Vec { + let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + let mut i = 0; + while i + 2 < positions.len() { + let (x, y) = (positions[i], positions[i + 1]); + if x < min_x { + min_x = x; + } + if x > max_x { + max_x = x; + } + if y < min_y { + min_y = y; + } + if y > max_y { + max_y = y; + } + i += 3; + } + if !min_x.is_finite() { + return Vec::new(); + } + vec![min_x, min_y, max_x, max_y] +} + +pub fn section_line(p0x: f64, p0y: f64, p1x: f64, p1y: f64, sign: f64) -> Vec { + if ![p0x, p0y, p1x, p1y, sign].iter().all(|x| x.is_finite()) { + return Vec::new(); + } + let (ax, ay) = (p1x - p0x, p1y - p0y); + let len = hypot2(ax, ay); + if len < 1e-6 { + return Vec::new(); + } + let (ux, uy) = (ax / len, ay / len); + let (nx, ny) = (-uy, ux); + let (bnx, bny) = (nx * sign, ny * sign); + let mut o: Vec = Vec::new(); + let mut n = 0usize; + let line = |o: &mut Vec, n: &mut usize, art: f64, a: (f64, f64), b: (f64, f64)| { + o.extend([2.0, art, a.0, a.1, b.0, b.1]); + *n += 1; + }; + line(&mut o, &mut n, 0.0, (p0x, p0y), (p1x, p1y)); + let half = SECTION_MARK_LEN / 2.0; + for end in [(p0x, p0y), (p1x, p1y)] { + line(&mut o, &mut n, 1.0, (end.0 - nx * half, end.1 - ny * half), (end.0 + nx * half, end.1 + ny * half)); + let base = (end.0 + bnx * half, end.1 + bny * half); + let tip = (base.0 + bnx * SECTION_MARK_LEN, base.1 + bny * SECTION_MARK_LEN); + let wing_back = (tip.0 - bnx * SECTION_MARK_LEN * 0.4, tip.1 - bny * SECTION_MARK_LEN * 0.4); + let w = SECTION_MARK_LEN * 0.25; + line(&mut o, &mut n, 1.0, base, tip); + line(&mut o, &mut n, 1.0, tip, (wing_back.0 + ux * w, wing_back.1 + uy * w)); + line(&mut o, &mut n, 1.0, tip, (wing_back.0 - ux * w, wing_back.1 - uy * w)); + let lx = tip.0 + bnx * SECTION_MARK_LEN * 0.4 - SECTION_LABEL_H * 0.3; + let ly = tip.1 + bny * SECTION_MARK_LEN * 0.4 + SECTION_LABEL_H * 0.5; + o.extend([5.0, lx, ly]); + n += 1; + } + let (ox, oy) = (nx * SECTION_PICK_HALF, ny * SECTION_PICK_HALF); + o.push(1.0); + o.extend([p0x + ox, p0y + oy, p1x + ox, p1y + oy, p1x - ox, p1y - oy, p0x - ox, p0y - oy]); + n += 1; + let mut out = vec![n as f64]; + out.extend(o); + out +} + +pub fn end_mark(x: f64, y: f64, dx: f64, dy: f64, art: f64, mm: f64, scale_denominator: f64) -> Vec { + if ![x, y, dx, dy, mm, scale_denominator].iter().all(|v| v.is_finite()) { + return Vec::new(); + } + let len = hypot2(dx, dy); + if len < 1e-9 { + return Vec::new(); + } + let size = (mm / 1000.0) * scale_denominator; + let (ux, uy) = (dx / len, dy / len); + let (nx, ny) = (-uy, ux); + let base = (x - ux * size, y - uy * size); + let half = size * ARROW_ASPECT; + let wing_a = (base.0 + nx * half, base.1 + ny * half); + let wing_b = (base.0 - nx * half, base.1 - ny * half); + let at = (x, y); + let mut o: Vec = Vec::new(); + let mut n = 0usize; + let mut shorten = 0.0; + let line = |o: &mut Vec, n: &mut usize, a: (f64, f64), b: (f64, f64)| { + o.extend([2.0, a.0, a.1, b.0, b.1]); + *n += 1; + }; + match art as i64 { + 1 => { + o.extend([1.0, 3.0, at.0, at.1, wing_a.0, wing_a.1, wing_b.0, wing_b.1]); + n += 1; + shorten = size; + } + 2 => { + line(&mut o, &mut n, wing_a, at); + line(&mut o, &mut n, wing_b, at); + } + 3 => { + o.extend([4.0, x, y, size * 0.25]); + n += 1; + } + 4 => { + let tx = (ux + nx) / std::f64::consts::SQRT_2; + let ty = (uy + ny) / std::f64::consts::SQRT_2; + let h = size / 2.0; + line(&mut o, &mut n, (x - tx * h, y - ty * h), (x + tx * h, y + ty * h)); + } + 5 => { + let h = size * 0.3; + o.extend([ + 1.0, 4.0, + x + (ux + nx) * h, y + (uy + ny) * h, + x + (ux - nx) * h, y + (uy - ny) * h, + x + (-ux - nx) * h, y + (-uy - ny) * h, + x + (-ux + nx) * h, y + (-uy + ny) * h, + ]); + n += 1; + } + _ => return Vec::new(), + } + let mut out = vec![shorten, n as f64]; + out.extend(o); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sockelkanten_werden_entdoppelt() { + // zwei Dreiecke mit gemeinsamer Kante, alle auf z=0; ein Punkt hoch → Kanten dorthin entfallen + let pos = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 9.0]; + let idx = [0.0, 1.0, 2.0, 0.0, 2.0, 3.0, 0.0, 1.0, 4.0]; + let f = context_footprint(&pos, &idx); + assert_eq!(f[0], 5.0); // 4 Aussenkanten + Diagonale + assert_eq!(f.len(), 1 + 5 * 4); + } + + #[test] + fn unsinn_ohne_panic() { + assert!(context_footprint(&[0.0, 1.0], &[0.0]).is_empty()); + assert!(bbox(&[]).is_empty()); + assert!(section_line(0.0, 0.0, 0.0, 0.0, 1.0).is_empty()); + assert!(section_line(f64::NAN, 0.0, 1.0, 0.0, 1.0).is_empty()); + assert!(end_mark(0.0, 0.0, 0.0, 0.0, 1.0, 3.0, 100.0).is_empty()); + assert!(end_mark(0.0, 0.0, 1.0, 0.0, 99.0, 3.0, 100.0).is_empty()); + } + + #[test] + fn schnittlinie_hat_hauptlinie_marken_label_und_pickband() { + let f = section_line(0.0, 0.0, 4.0, 0.0, 1.0); + // 1 Hauptlinie + 2 × (Querstrich + 3 Pfeillinien + Label) + Pick = 12 + assert_eq!(f[0], 12.0); + } + + #[test] + fn gefuellter_pfeil_verkuerzt_die_linie() { + let a = end_mark(0.0, 0.0, 1.0, 0.0, 1.0, 3.0, 100.0); + assert!((a[0] - 0.3).abs() < 1e-12); + assert_eq!(end_mark(0.0, 0.0, 1.0, 0.0, 2.0, 3.0, 100.0)[0], 0.0); + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index fe186a76..74545534 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -28,6 +28,7 @@ mod gpu_compile; mod plan_stairs; mod plan_walls; mod plan_openings; +mod plan_misc; mod hatch; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/plan_misc.rs b/src-tauri/core/src/web/plan_misc.rs new file mode 100644 index 00000000..e00fb9ae --- /dev/null +++ b/src-tauri/core/src/web/plan_misc.rs @@ -0,0 +1,27 @@ +//! Bindungen kleiner Plan-Bausteine (`crate::plan_misc`). Layouts s. dort. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Grundriss-Fussabdruck eines Meshes (Sockelkanten); Unsinn → leer. +#[wasm_bindgen] +pub fn context_footprint_flat(positions: &[f64], indices: &[f64]) -> Vec { + crate::plan_misc::context_footprint(positions, indices) +} + +/// `[minX, minY, maxX, maxY]` der x/y-Werte eines [x,y,z…]-Arrays; leer ohne Punkte. +#[wasm_bindgen] +pub fn context_bbox_flat(positions: &[f64]) -> Vec { + crate::plan_misc::bbox(positions) +} + +/// Schnittführungs-Symbol einer Linie; leer bei zu kurzer Linie. +#[wasm_bindgen] +pub fn section_line_flat(p0x: f64, p0y: f64, p1x: f64, p1y: f64, sign: f64) -> Vec { + crate::plan_misc::section_line(p0x, p0y, p1x, p1y, sign) +} + +/// Linienende (Pfeil, Punkt, Schrägstrich, Quadrat); leer ohne Wirkung. +#[wasm_bindgen] +pub fn end_mark_flat(x: f64, y: f64, dx: f64, dy: f64, art: f64, mm: f64, scale_denominator: f64) -> Vec { + crate::plan_misc::end_mark(x, y, dx, dy, art, mm, scale_denominator) +} diff --git a/src/plan/generatePlan/context.ts b/src/plan/generatePlan/context.ts index 9dc1c2de..b2c89304 100644 --- a/src/plan/generatePlan/context.ts +++ b/src/plan/generatePlan/context.ts @@ -1,9 +1,11 @@ // Kontext-Domäne des Grundriss-Generators: zeichnet `project.context` // (Höhenlinien, importierte Gebäude/Terrain-Meshes) als dezente Referenz- // Konturen — für Meshes der Grundriss-Fussabdruck nahe der Objekt-Unterkante, -// nicht das volle Drahtgitter. +// nicht das volle Drahtgitter. Fussabdruck (Sockelkanten, entdoppelt) und Rahmen berechnet der +// Rust-Kern (`src-tauri/core/src/plan_misc.rs`, [K3a]). import type { Project } from "../../model/types"; +import { core } from "../../engine/coreWasm"; import { NO_HATCH, SHOW_ALL, type CategoryDisplayResolver, type Primitive } from "./shared"; /** Dezente Plan-Farbe der Kontext-Konturen (gedämpftes Grau). */ @@ -11,11 +13,6 @@ const CONTEXT_LINE_COLOR = "#9aa3ad"; /** Strichstärke der Kontext-Konturen (mm Papier, dünn). */ const CONTEXT_LINE_MM = 0.1; -/** Höhen-Toleranz (Meter): Dreieckskanten, deren beide Endpunkte höchstens so - * weit über der Objekt-Unterkante (minZ) liegen, gelten als „Sockelkante" und - * bilden den Grundriss-Fussabdruck eines importierten Gebäudes. */ -const FOOTPRINT_Z_TOL = 0.6; - /** * Zeichnet die Kontext-Schicht `project.context` in den Grundriss: * • ContourSet (Höhenlinien) → dünne Referenz-Linien (Z ignoriert). @@ -77,68 +74,41 @@ export function addContextContours( /** * Zeichnet den Grundriss-Fussabdruck eines Meshes: Dreieckskanten nahe der - * Unterkante (minZ + {@link FOOTPRINT_Z_TOL}), auf XY projiziert, über - * quantisierte Endpunkt-Schlüssel entdoppelt. `positions` = flaches [x,y,z…]- - * Array (Modell-Meter, z = Höhe), `indices` = Dreiecks-Indizes. + * Unterkante (minZ + 0.6 m), auf XY projiziert, über 1-cm-quantisierte Endpunkte + * entdoppelt. `positions` = flaches [x,y,z…]-Array (Modell-Meter, z = Höhe), + * `indices` = Dreiecks-Indizes. */ function addMeshFootprint(out: Primitive[], positions: number[], indices: number[]): void { - const vcount = Math.floor(positions.length / 3); - if (vcount < 3 || indices.length < 3) return; - let minZ = Infinity; - for (let i = 2; i < positions.length; i += 3) if (positions[i] < minZ) minZ = positions[i]; - if (!Number.isFinite(minZ)) return; - const zLimit = minZ + FOOTPRINT_Z_TOL; - const q = (v: number) => Math.round(v * 100); // 1-cm-Quantisierung (Entdopplung) - const seen = new Set(); - const edge = (ia: number, ib: number) => { - if (ia >= vcount || ib >= vcount) return; - const za = positions[ia * 3 + 2]; - const zb = positions[ib * 3 + 2]; - if (za > zLimit || zb > zLimit) return; // nur Sockelkanten - const ax = positions[ia * 3], ay = positions[ia * 3 + 1]; - const bx = positions[ib * 3], by = positions[ib * 3 + 1]; - // Kanten-Schlüssel richtungsunabhängig (kleinerer Endpunkt zuerst). - const ka = `${q(ax)},${q(ay)}`; - const kb = `${q(bx)},${q(by)}`; - if (ka === kb) return; - const key = ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`; - if (seen.has(key)) return; - seen.add(key); + const f = core().context_footprint_flat(Float64Array.from(positions), Float64Array.from(indices)); + for (let i = 0; i < f[0]; i++) { out.push({ kind: "line", - a: { x: ax, y: ay }, - b: { x: bx, y: by }, + a: { x: f[1 + 4 * i], y: f[2 + 4 * i] }, + b: { x: f[3 + 4 * i], y: f[4 + 4 * i] }, cls: "context-line", weightMm: CONTEXT_LINE_MM, color: CONTEXT_LINE_COLOR, }); - }; - for (let i = 0; i + 2 < indices.length; i += 3) { - const a = indices[i], b = indices[i + 1], c = indices[i + 2]; - edge(a, b); - edge(b, c); - edge(c, a); } } +/** Grundriss-Rahmen eines Meshes (nur x/y) als vier Eckpunkte, oder `null` ohne Punkte. */ +function meshBboxCorners(positions: number[]): { x: number; y: number }[] | null { + const b = core().context_bbox_flat(Float64Array.from(positions)); + if (b.length === 0) return null; + return [ + { x: b[0], y: b[1] }, + { x: b[2], y: b[1] }, + { x: b[2], y: b[3] }, + { x: b[0], y: b[3] }, + ]; +} + /** Zeichnet nur den achsenparallelen 2D-Umriss (Bounding-Box) eines Meshes — * für Terrain, dessen volles TIN-Gitter im Plan zu dicht wäre. */ function addMeshBboxOutline(out: Primitive[], positions: number[]): void { - let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; - for (let i = 0; i + 2 < positions.length; i += 3) { - const x = positions[i], y = positions[i + 1]; - if (x < minX) minX = x; - if (x > maxX) maxX = x; - if (y < minY) minY = y; - if (y > maxY) maxY = y; - } - if (!Number.isFinite(minX)) return; - const corners = [ - { x: minX, y: minY }, - { x: maxX, y: minY }, - { x: maxX, y: maxY }, - { x: minX, y: maxY }, - ]; + const corners = meshBboxCorners(positions); + if (!corners) return; for (let i = 0; i < 4; i++) { out.push({ kind: "line", @@ -157,28 +127,14 @@ function addMeshBboxOutline(out: Primitive[], positions: number[]): void { * trägt die `ContextObject.id` (analog `sectionLineId`, s. dort). Macht das * Objekt IRGENDWO innerhalb seiner Grundfläche anklickbar (nicht nur exakt auf * der dünnen Umriss-/Fussabdrucklinie) — wie bei Wänden, deren Poché-Fläche - * ebenfalls als Ganzes klickbar ist (Nutzer-Wunsch: „eigene Elemente wie Wände"). - * `positions` = flaches [x,y,z…]-Array (Modell-Meter); die Bbox nutzt NUR x/y, - * unabhängig von der Höhe. + * ebenfalls als Ganzes klickbar ist. */ function addContextPickRegion(out: Primitive[], positions: number[], id: string): void { - let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; - for (let i = 0; i + 2 < positions.length; i += 3) { - const x = positions[i], y = positions[i + 1]; - if (x < minX) minX = x; - if (x > maxX) maxX = x; - if (y < minY) minY = y; - if (y > maxY) maxY = y; - } - if (!Number.isFinite(minX)) return; + const pts = meshBboxCorners(positions); + if (!pts) return; out.push({ kind: "polygon", - pts: [ - { x: minX, y: minY }, - { x: maxX, y: minY }, - { x: maxX, y: maxY }, - { x: minX, y: maxY }, - ], + pts, fill: "none", stroke: "none", strokeWidthMm: 0, diff --git a/src/plan/generatePlan/endMarks.ts b/src/plan/generatePlan/endMarks.ts index da03dbe8..263f265b 100644 --- a/src/plan/generatePlan/endMarks.ts +++ b/src/plan/generatePlan/endMarks.ts @@ -9,18 +9,18 @@ // Die Grösse kommt in PAPIER-MILLIMETERN herein und wird mit dem Massstab des // Plans in Modellmass umgerechnet (gleiche Linie wie die Bemassung, s. // `model/dimension.ts`): eine 3-mm-Pfeilspitze soll auf dem Papier 3 mm sein, -// egal ob der Plan 1:50 oder 1:200 steht. +// egal ob der Plan 1:50 oder 1:200 steht. Die Geometrie berechnet der Rust-Kern (`plan_misc.rs`, [K3a]). import type { EndMark, Vec2 } from "../../model/types"; -import { mmToModel } from "../../model/dimension"; +import { core } from "../../engine/coreWasm"; import type { Primitive } from "./shared"; import { NO_HATCH } from "./shared"; /** Default-Grösse der Linienenden in Papier-Millimetern. */ export const END_MARK_DEFAULT_SIZE_MM = 3; -/** Öffnungsverhältnis der Pfeilspitze (halbe Breite ÷ Länge) — schlanke Spitze. */ -const ARROW_ASPECT = 0.32; +/** Kodierung der Linienenden im Kern (`plan_misc.rs`). */ +const MARK_CODE: Record, number> = { arrow: 1, arrowOpen: 2, dot: 3, tick: 4, square: 5 }; export interface EndMarkStyle { weightMm: number; @@ -49,82 +49,35 @@ export function addEndMark( style: EndMarkStyle, ): number { if (!mark || mark === "none") return 0; - const len = Math.hypot(dir.x, dir.y); - if (len < 1e-9) return 0; - const size = mmToModel(sizeMm, scaleDenominator); - const ux = dir.x / len; - const uy = dir.y / len; - const nx = -uy; - const ny = ux; + const f = core().end_mark_flat(at.x, at.y, dir.x, dir.y, MARK_CODE[mark], sizeMm, scaleDenominator); + if (f.length === 0) return 0; const { weightMm, color, greyed, drawingId } = style; - - /** Fusspunkt der Spitze (size zurück entlang der Linie). */ - const base: Vec2 = { x: at.x - ux * size, y: at.y - uy * size }; - const half = size * ARROW_ASPECT; - const wingA: Vec2 = { x: base.x + nx * half, y: base.y + ny * half }; - const wingB: Vec2 = { x: base.x - nx * half, y: base.y - ny * half }; - const line = (a: Vec2, b: Vec2) => - out.push({ kind: "line", a, b, cls: "draw2d", weightMm, dash: null, color, greyed, drawingId }); - - switch (mark) { - case "arrow": + let i = 2; + for (let k = 0; k < f[1]; k++) { + if (f[i] === 1) { + const count = f[i + 1]; + const pts = Array.from({ length: count }, (_, j) => ({ x: f[i + 2 + 2 * j], y: f[i + 3 + 2 * j] })); + out.push({ kind: "polygon", pts, fill: color, stroke: color, strokeWidthMm: weightMm, hatch: NO_HATCH, greyed, drawingId }); + i += 2 + 2 * count; + } else if (f[i] === 2) { out.push({ - kind: "polygon", - pts: [at, wingA, wingB], - fill: color, - stroke: color, - strokeWidthMm: weightMm, - hatch: NO_HATCH, - greyed, - drawingId, - }); - // Die gefüllte Spitze überdeckt die Linie — dort darf sie enden. - return size; - case "arrowOpen": - line(wingA, at); - line(wingB, at); - // Offene Spitze: die Linie läuft bis zum Punkt durch (sie ist Teil des Bildes). - return 0; - case "dot": - out.push({ - kind: "drawingCircle", - center: at, - r: size * 0.25, - fill: color, - stroke: color, + kind: "line", + a: { x: f[i + 1], y: f[i + 2] }, + b: { x: f[i + 3], y: f[i + 4] }, + cls: "draw2d", weightMm, + dash: null, + color, greyed, drawingId, }); - return 0; - case "tick": { - // 45°-Schrägstrich, mittig auf dem Endpunkt (SIA-Massstrich-Anmutung). - const tx = (ux + nx) / Math.SQRT2; - const ty = (uy + ny) / Math.SQRT2; - const h = size / 2; - line({ x: at.x - tx * h, y: at.y - ty * h }, { x: at.x + tx * h, y: at.y + ty * h }); - return 0; - } - case "square": { - const h = size * 0.3; - out.push({ - kind: "polygon", - pts: [ - { x: at.x + (ux + nx) * h, y: at.y + (uy + ny) * h }, - { x: at.x + (ux - nx) * h, y: at.y + (uy - ny) * h }, - { x: at.x + (-ux - nx) * h, y: at.y + (-uy - ny) * h }, - { x: at.x + (-ux + nx) * h, y: at.y + (-uy + ny) * h }, - ], - fill: color, - stroke: color, - strokeWidthMm: weightMm, - hatch: NO_HATCH, - greyed, - drawingId, - }); - return 0; + i += 5; + } else { + out.push({ kind: "drawingCircle", center: { x: f[i + 1], y: f[i + 2] }, r: f[i + 3], fill: color, stroke: color, weightMm, greyed, drawingId }); + i += 4; } } + return f[0]; } /** Punkt `p` um `d` in Richtung `dir` (normiert) zurückgezogen — für die Linienverkürzung. */ diff --git a/src/plan/generatePlan/sections.ts b/src/plan/generatePlan/sections.ts index 633e5b87..d3bd20dd 100644 --- a/src/plan/generatePlan/sections.ts +++ b/src/plan/generatePlan/sections.ts @@ -2,9 +2,9 @@ // Strichpunkt-Schnittlinie mit Endmarken + Label) — NICHT zu verwechseln mit // `generateSectionPlan()` (der Schnitt-ALS-Plan-Übersetzung, bleibt Orchestrator // in `../generatePlan.ts`): diese Domäne zeichnet nur das Führungssymbol EINER -// Schnitt-/Ansichtsebene IM Grundriss. +// Schnitt-/Ansichtsebene IM Grundriss. Die Geometrie berechnet der Rust-Kern (`plan_misc.rs`, [K3a]). -import { leftNormal, normalize, sub } from "../../model/geometry"; +import { core } from "../../engine/coreWasm"; import type { Project } from "../../model/types"; import { NO_HATCH, SHOW_ALL, type CategoryDisplayResolver, type Primitive } from "./shared"; @@ -26,10 +26,6 @@ const SECTION_LINE_MM = 0.18; const SECTION_LINE_MARK_MM = 0.5; /** Strichpunkt-Muster der Schnittlinie (lange Striche + Punkt, mm Papier). */ const SECTION_LINE_DASH: number[] = [6, 1.5, 0.4, 1.5]; -/** Länge der Endmarken (Querstrich/Pfeil) in Modell-Metern. */ -const SECTION_MARK_LEN = 0.6; -/** Halbe Breite des unsichtbaren Pick-Bands über der Linie (Modell-Meter). */ -const SECTION_PICK_HALF = 0.3; /** Schrifthöhe des Schnitt-Labels (Modell-Meter). */ const SECTION_LABEL_H = 0.5; @@ -72,100 +68,48 @@ export function addSectionLines( const line = level.linePoints; if (!line) continue; const [p0, p1] = line; - const axis = sub(p1, p0); - const len = Math.hypot(axis.x, axis.y); - if (len < 1e-6) continue; - const u = normalize(axis); - const n = leftNormal(u); // (-uy, ux) - const sign = level.directionSign ?? 1; - const bn = { x: n.x * sign, y: n.y * sign }; // Blicknormale - - // Hauptlinie (Strichpunkt-Haarlinie). - out.push({ - kind: "line", - a: p0, - b: p1, - cls: "section-line", - weightMm: SECTION_LINE_MM, - dash: SECTION_LINE_DASH, - color: SECTION_LINE_INK, - greyed, - }); - - // Endmarken (Querstrich + Richtungspfeil + Label) an beiden Enden. - const half = SECTION_MARK_LEN / 2; - for (const end of [p0, p1]) { - // Querstrich senkrecht zur Linie, mittig am Endpunkt. - const t0 = { x: end.x - n.x * half, y: end.y - n.y * half }; - const t1 = { x: end.x + n.x * half, y: end.y + n.y * half }; - out.push({ - kind: "line", - a: t0, - b: t1, - cls: "section-line", - weightMm: SECTION_LINE_MARK_MM, - color: SECTION_LINE_INK, - greyed, - }); - // Richtungspfeil: vom Querstrich-Ende auf der Blickseite entlang bn. - const base = { x: end.x + bn.x * half, y: end.y + bn.y * half }; - const tip = { x: base.x + bn.x * SECTION_MARK_LEN, y: base.y + bn.y * SECTION_MARK_LEN }; - const wingBack = { - x: tip.x - bn.x * SECTION_MARK_LEN * 0.4, - y: tip.y - bn.y * SECTION_MARK_LEN * 0.4, - }; - const w = SECTION_MARK_LEN * 0.25; - out.push({ kind: "line", a: base, b: tip, cls: "section-line", weightMm: SECTION_LINE_MARK_MM, color: SECTION_LINE_INK, greyed }); - out.push({ - kind: "line", - a: tip, - b: { x: wingBack.x + u.x * w, y: wingBack.y + u.y * w }, - cls: "section-line", - weightMm: SECTION_LINE_MARK_MM, - color: SECTION_LINE_INK, - greyed, - }); - out.push({ - kind: "line", - a: tip, - b: { x: wingBack.x - u.x * w, y: wingBack.y - u.y * w }, - cls: "section-line", - weightMm: SECTION_LINE_MARK_MM, - color: SECTION_LINE_INK, - greyed, - }); - // Label (Kurz-Tag) etwas hinter dem Pfeil, horizontal. - const labelAt = { - x: tip.x + bn.x * SECTION_MARK_LEN * 0.4 - SECTION_LABEL_H * 0.3, - y: tip.y + bn.y * SECTION_MARK_LEN * 0.4 + SECTION_LABEL_H * 0.5, - }; - out.push({ - kind: "drawingText", - at: labelAt, - text: sectionLabelTag(level.name), - heightM: SECTION_LABEL_H, - angle: 0, - color: SECTION_LINE_INK, - greyed, - }); + const f = core().section_line_flat(p0.x, p0.y, p1.x, p1.y, level.directionSign ?? 1); + if (f.length === 0) continue; + let i = 1; + for (let k = 0; k < f[0]; k++) { + if (f[i] === 2) { + const main = f[i + 1] === 0; + out.push({ + kind: "line", + a: { x: f[i + 2], y: f[i + 3] }, + b: { x: f[i + 4], y: f[i + 5] }, + cls: "section-line", + weightMm: main ? SECTION_LINE_MM : SECTION_LINE_MARK_MM, + ...(main ? { dash: SECTION_LINE_DASH } : {}), + color: SECTION_LINE_INK, + greyed, + }); + i += 6; + } else if (f[i] === 5) { + out.push({ + kind: "drawingText", + at: { x: f[i + 1], y: f[i + 2] }, + text: sectionLabelTag(level.name), + heightM: SECTION_LABEL_H, + angle: 0, + color: SECTION_LINE_INK, + greyed, + }); + i += 3; + } else { + // Unsichtbares Pick-Band (Rechteck entlang der Linie) — klickbar per Punkt-in-Polygon in + // PlanView, trägt die DrawingLevel-Id. + out.push({ + kind: "polygon", + pts: [0, 1, 2, 3].map((j) => ({ x: f[i + 1 + 2 * j], y: f[i + 2 + 2 * j] })), + fill: "none", + stroke: "none", + strokeWidthMm: 0, + hatch: NO_HATCH, + sectionLineId: level.id, + }); + i += 9; + } } - - // Unsichtbares Pick-Band (Rechteck entlang der Linie) — klickbar per - // Punkt-in-Polygon in PlanView, trägt die DrawingLevel-Id. - const off = { x: n.x * SECTION_PICK_HALF, y: n.y * SECTION_PICK_HALF }; - out.push({ - kind: "polygon", - pts: [ - { x: p0.x + off.x, y: p0.y + off.y }, - { x: p1.x + off.x, y: p1.y + off.y }, - { x: p1.x - off.x, y: p1.y - off.y }, - { x: p0.x - off.x, y: p0.y - off.y }, - ], - fill: "none", - stroke: "none", - strokeWidthMm: 0, - hatch: NO_HATCH, - sectionLineId: level.id, - }); } } From 0ad4c104c83024d6e6007debe3bf27eb6ea68d15 Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:02:56 +0100 Subject: [PATCH 05/31] [K1] Kurven-Tessellierung (Ellipse, Bezier, Catmull-Rom, B-Spline) in Rust (curves.rs); curves.ts Fassade --- TODO.md | 6 +- src-tauri/core/src/curves.rs | 187 +++++++++++++++++++++++++++++++ src-tauri/core/src/jsnum.rs | 14 ++- src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/web/curves.rs | 27 +++++ src-tauri/core/src/web/mod.rs | 1 + src/geometry/curves.ts | 132 ++++------------------ 7 files changed, 257 insertions(+), 111 deletions(-) create mode 100644 src-tauri/core/src/curves.rs create mode 100644 src-tauri/core/src/web/curves.rs diff --git a/TODO.md b/TODO.md index c9aebce7..2dd96f74 100644 --- a/TODO.md +++ b/TODO.md @@ -99,7 +99,11 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern ✅ Kontext-Mesh (Fussabdruck, Rahmen), Schnittführungs-Symbol, Linienenden: `plan_misc.rs`; bitgleich (200 Zufalls-Meshes, 200 Schnittebenen-Sätze, 400 Linienenden). Räume, Dächer, Stützen, Extrusions-Umriss, Baurecht, Schatten sind nur noch Stil-Glue um schon in Rust berechnete Geometrie (kein Rechenanteil) — bleiben bis [K4] in TS. - Offen: 2D-Zeichnung (`drawing2d.ts`, 950 Zeilen: Kurven, Bemassung, Kote, Detailverweis, Block, Text …). + ✅ Kurven (Ellipse, Bezier, Catmull-Rom, B-Spline): `curves.rs`, `geometry/curves.ts` ist Fassade; bitgleich (500 Zufallsfälle). + `jsnum::pow` (= `Math.pow` im Web-Build) für `x ** 3`. + Offen: `drawing2d.ts` (950 Zeilen) ist nach diesen Schritten Stil-Auflösung und Verteiler über Formen (Bemassung, Kote, + Detailverweis, Massstabsbalken, Block über `scaleGeom`); der Rechenanteil liegt in Rust. Der Verteiler zieht mit dem Modell + nach Rust [K4] — vorher würde ein Rust-`Drawing2D` doppelt gepflegt. Danach: [K3c] Schnitt/Ansicht, [K3d] Aufräumen. - ○ **[K3c] Schnitt und Ansicht** (`toSection`, `toElevation`, `meshSection`) im selben Puffer-Format. - ○ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. Nachteile (bewusst): Übergang mit doppelter Datenhaltung, Format muss TS/Rust gleich bleiben diff --git a/src-tauri/core/src/curves.rs b/src-tauri/core/src/curves.rs new file mode 100644 index 00000000..63b2e991 --- /dev/null +++ b/src-tauri/core/src/curves.rs @@ -0,0 +1,187 @@ +//! Ellipse, Bezier und Splines tessellieren ([K1]): Port von `src/geometry/curves.ts`. Punkte als flache +//! `[x0, y0, x1, y1, …]`. Rechenreihenfolge wie in TS; `cos/sin/pow` über `jsnum` (bitgleich zur +//! JS-Engine). Unsinn (zu viele Schritte) → leer, nie Panic. + +use crate::jsnum::{cos, pow, sin}; + +const MAX_STEPS: usize = 100_000; + +fn pts_of(f: &[f64]) -> Vec<(f64, f64)> { + f.chunks_exact(2).map(|c| (c[0], c[1])).collect() +} + +fn flat(p: &[(f64, f64)]) -> Vec { + p.iter().flat_map(|q| [q.0, q.1]).collect() +} + +pub fn ellipse(cx: f64, cy: f64, rx: f64, ry: f64, rotation: f64, n: f64) -> Vec { + if !(n >= 0.0) || n > MAX_STEPS as f64 { + return Vec::new(); + } + let n = n as usize; + let (cos_r, sin_r) = (cos(rotation), sin(rotation)); + let mut out = Vec::with_capacity(2 * n); + for i in 0..n { + let t = (i as f64 / n as f64) * std::f64::consts::PI * 2.0; + let lx = rx * cos(t); + let ly = ry * sin(t); + out.push(cx + lx * cos_r - ly * sin_r); + out.push(cy + lx * sin_r + ly * cos_r); + } + out +} + +fn cubic_point(p0: (f64, f64), p1: (f64, f64), p2: (f64, f64), p3: (f64, f64), t: f64) -> (f64, f64) { + let u = 1.0 - t; + let a = u * u * u; + let b = 3.0 * u * u * t; + let c = 3.0 * u * t * t; + let d = t * t * t; + (a * p0.0 + b * p1.0 + c * p2.0 + d * p3.0, a * p0.1 + b * p1.1 + c * p2.1 + d * p3.1) +} + +pub fn bezier_chain(f: &[f64], segs_per_curve: f64) -> Vec { + let pts = pts_of(f); + if pts.len() < 4 { + return flat(&pts); + } + if !(segs_per_curve >= 0.0) || segs_per_curve > 4096.0 { + return Vec::new(); + } + let segs = segs_per_curve as usize; + let mut out = vec![pts[0]]; + let mut i = 0; + while i + 3 < pts.len() { + for s in 1..=segs { + out.push(cubic_point(pts[i], pts[i + 1], pts[i + 2], pts[i + 3], s as f64 / segs as f64)); + } + i += 3; + } + flat(&out) +} + +fn cr_point(pts: &[(f64, f64)], i: i64, closed: bool) -> (f64, f64) { + let n = pts.len() as i64; + if closed { + return pts[(((i % n) + n) % n) as usize]; + } + if i < 0 { + return pts[0]; + } + if i >= n { + return pts[(n - 1) as usize]; + } + pts[i as usize] +} + +pub fn catmull_rom(f: &[f64], closed: bool, segs_per_span: f64) -> Vec { + let pts = pts_of(f); + if pts.len() < 3 { + return flat(&pts); + } + if !(segs_per_span >= 0.0) || segs_per_span > 4096.0 { + return Vec::new(); + } + let segs = segs_per_span as usize; + let mut out: Vec<(f64, f64)> = Vec::new(); + let spans = if closed { pts.len() } else { pts.len() - 1 }; + for i in 0..spans as i64 { + let p0 = cr_point(&pts, i - 1, closed); + let p1 = cr_point(&pts, i, closed); + let p2 = cr_point(&pts, i + 1, closed); + let p3 = cr_point(&pts, i + 2, closed); + for s in 0..segs { + let t = s as f64 / segs as f64; + let t2 = t * t; + let t3 = t2 * t; + let x = 0.5 + * (2.0 * p1.0 + (-p0.0 + p2.0) * t + (2.0 * p0.0 - 5.0 * p1.0 + 4.0 * p2.0 - p3.0) * t2 + (-p0.0 + 3.0 * p1.0 - 3.0 * p2.0 + p3.0) * t3); + let y = 0.5 + * (2.0 * p1.1 + (-p0.1 + p2.1) * t + (2.0 * p0.1 - 5.0 * p1.1 + 4.0 * p2.1 - p3.1) * t2 + (-p0.1 + 3.0 * p1.1 - 3.0 * p2.1 + p3.1) * t3); + out.push((x, y)); + } + } + if !closed { + out.push(pts[pts.len() - 1]); + } + flat(&out) +} + +fn bspline_seg_point(p0: (f64, f64), p1: (f64, f64), p2: (f64, f64), p3: (f64, f64), t: f64) -> (f64, f64) { + let t2 = t * t; + let t3 = t2 * t; + let b0 = pow(1.0 - t, 3.0) / 6.0; + let b1 = (3.0 * t3 - 6.0 * t2 + 4.0) / 6.0; + let b2 = (-3.0 * t3 + 3.0 * t2 + 3.0 * t + 1.0) / 6.0; + let b3 = t3 / 6.0; + (p0.0 * b0 + p1.0 * b1 + p2.0 * b2 + p3.0 * b3, p0.1 * b0 + p1.1 * b1 + p2.1 * b2 + p3.1 * b3) +} + +pub fn uniform_bspline(f: &[f64], closed: bool, segs_per_span: f64) -> Vec { + let pts = pts_of(f); + if pts.len() < 3 { + return flat(&pts); + } + if !(segs_per_span >= 0.0) || segs_per_span > 4096.0 { + return Vec::new(); + } + let segs = segs_per_span as usize; + let mut out: Vec<(f64, f64)> = Vec::new(); + if closed { + let n = pts.len() as i64; + let at = |i: i64| pts[(((i % n) + n) % n) as usize]; + for i in 0..n { + for s in 0..segs { + out.push(bspline_seg_point(at(i - 1), at(i), at(i + 1), at(i + 2), s as f64 / segs as f64)); + } + } + return flat(&out); + } + let last = pts[pts.len() - 1]; + let mut padded = vec![pts[0], pts[0]]; + padded.extend_from_slice(&pts); + padded.push(last); + padded.push(last); + let spans = padded.len() - 3; + for i in 0..spans { + for s in 0..segs { + out.push(bspline_seg_point(padded[i], padded[i + 1], padded[i + 2], padded[i + 3], s as f64 / segs as f64)); + } + } + out.push(last); + flat(&out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ellipse_hat_n_punkte_und_beginnt_rechts() { + let e = ellipse(1.0, 2.0, 3.0, 1.0, 0.0, 64.0); + assert_eq!(e.len(), 128); + assert!((e[0] - 4.0).abs() < 1e-12 && (e[1] - 2.0).abs() < 1e-12); + assert!(ellipse(0.0, 0.0, 1.0, 1.0, 0.0, 1e9).is_empty()); + } + + #[test] + fn bezier_endet_im_letzten_anker() { + let f = [0.0, 0.0, 1.0, 2.0, 2.0, 2.0, 3.0, 0.0]; + let b = bezier_chain(&f, 24.0); + assert_eq!(b.len(), 2 * 25); + assert_eq!(&b[b.len() - 2..], &[3.0, 0.0]); + assert_eq!(bezier_chain(&[0.0, 0.0, 1.0, 1.0], 24.0), vec![0.0, 0.0, 1.0, 1.0]); + } + + #[test] + fn spline_beruehrt_die_enden_offen() { + let f = [0.0, 0.0, 1.0, 1.0, 2.0, 0.0, 3.0, 1.0]; + let c = catmull_rom(&f, false, 16.0); + assert_eq!((c[0], c[1]), (0.0, 0.0)); + assert_eq!(&c[c.len() - 2..], &[3.0, 1.0]); + let b = uniform_bspline(&f, false, 16.0); + assert!((b[0]).abs() < 1e-9); + assert_eq!(&b[b.len() - 2..], &[3.0, 1.0]); + assert_eq!(uniform_bspline(&f, true, 16.0).len(), 2 * 4 * 16); + } +} diff --git a/src-tauri/core/src/jsnum.rs b/src-tauri/core/src/jsnum.rs index 21eb917c..6c317d43 100644 --- a/src-tauri/core/src/jsnum.rs +++ b/src-tauri/core/src/jsnum.rs @@ -3,7 +3,7 @@ //! - `Math.min/max` liefern bei NaN NaN (Rust `f64::min/max` ignorieren NaN). //! - `Math.round` rundet halbe Werte Richtung +∞ (Rust `round` weg von 0). //! - `x | 0` ist ToInt32 (Rest modulo 2³², Rust `as i32` sättigt). -//! - Trigonometrie: im Web-Build (wasm32 + Feature "web") ruft der Kern `Math.cos/sin/atan2/acos` +//! - `Math.pow` (`x ** 3`) und Trigonometrie: im Web-Build (wasm32 + Feature "web") ruft der Kern `Math.cos/sin/atan2/acos` //! der laufenden JS-Engine. Nur so sind die Werte bitgleich zur bisherigen TS-Fassung — V8 //! (glibc-abgeleitete sin/cos), JavaScriptCore (System-libm von macOS) und Rusts libm (musl) //! unterscheiden sich in einzelnen Fällen in der letzten Stelle. Nativ (`cargo test`, Tauri) @@ -23,6 +23,12 @@ mod trig { fn js_atan2(y: f64, x: f64) -> f64; #[wasm_bindgen(js_namespace = Math, js_name = acos)] fn js_acos(x: f64) -> f64; + #[wasm_bindgen(js_namespace = Math, js_name = pow)] + fn js_pow(x: f64, y: f64) -> f64; + } + #[inline] + pub fn pow(x: f64, y: f64) -> f64 { + js_pow(x, y) } #[inline] @@ -61,9 +67,13 @@ mod trig { pub fn acos(x: f64) -> f64 { x.acos() } + #[inline] + pub fn pow(x: f64, y: f64) -> f64 { + x.powf(y) + } } -pub use trig::{acos, atan2, cos, sin}; +pub use trig::{acos, atan2, cos, pow, sin}; /// `Math.min(a, b)` (NaN gewinnt; −0 < +0). #[inline] diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index b3366ce7..7e29298f 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -38,6 +38,7 @@ pub mod plan_walls; pub mod opening_geom; pub mod plan_openings; pub mod plan_misc; +pub mod curves; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/web/curves.rs b/src-tauri/core/src/web/curves.rs new file mode 100644 index 00000000..150802fb --- /dev/null +++ b/src-tauri/core/src/web/curves.rs @@ -0,0 +1,27 @@ +//! Bindungen der Kurven-Tessellierung (`crate::curves`). Punkte flach `[x0, y0, …]`. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Punkte einer (gedrehten) Ellipse, `n` gleichverteilte Parameterschritte. +#[wasm_bindgen] +pub fn curves_ellipse_flat(cx: f64, cy: f64, rx: f64, ry: f64, rotation: f64, n: f64) -> Vec { + crate::curves::ellipse(cx, cy, rx, ry, rotation, n) +} + +/// Kubische Bezier-Kette (Anker·Griff·Griff·Anker …); unter 4 Punkten unverändert. +#[wasm_bindgen] +pub fn curves_bezier_chain_flat(pts: &[f64], segs_per_curve: f64) -> Vec { + crate::curves::bezier_chain(pts, segs_per_curve) +} + +/// Catmull-Rom-Spline durch die Punkte; unter 3 Punkten unverändert. +#[wasm_bindgen] +pub fn curves_catmull_rom_flat(pts: &[f64], closed: bool, segs_per_span: f64) -> Vec { + crate::curves::catmull_rom(pts, closed, segs_per_span) +} + +/// Uniformer kubischer B-Spline über Kontrollpunkten; unter 3 Punkten unverändert. +#[wasm_bindgen] +pub fn curves_uniform_bspline_flat(pts: &[f64], closed: bool, segs_per_span: f64) -> Vec { + crate::curves::uniform_bspline(pts, closed, segs_per_span) +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 74545534..a38c29db 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -29,6 +29,7 @@ mod plan_stairs; mod plan_walls; mod plan_openings; mod plan_misc; +mod curves; mod hatch; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src/geometry/curves.ts b/src/geometry/curves.ts index d7ba9077..7f4d4577 100644 --- a/src/geometry/curves.ts +++ b/src/geometry/curves.ts @@ -1,9 +1,26 @@ // Geometrie-Helfer für Ellipse/Bezier/Spline — reine Sample-/Tessellierungs- // Funktionen, gemeinsam genutzt von den Zeichen-Werkzeugen (Vorschau), dem // Grundriss-Generator (finales Rendering als Linien-/Polygon-Primitive) und -// dem Snapping (Kandidaten-Strecken). +// dem Snapping (Kandidaten-Strecken). Fassade über den Rust-Kern +// (`src-tauri/core/src/curves.rs`, Bindungen `web/curves.rs`): die Formeln stehen nur dort. import type { Vec2 } from "../model/types"; +import { core } from "../engine/coreWasm"; + +function toPoints(f: Float64Array): Vec2[] { + const out: Vec2[] = new Array(f.length >> 1); + for (let i = 0; i < out.length; i++) out[i] = { x: f[2 * i], y: f[2 * i + 1] }; + return out; +} + +function toFlat(pts: Vec2[]): Float64Array { + const f = new Float64Array(pts.length * 2); + for (let i = 0; i < pts.length; i++) { + f[2 * i] = pts[i].x; + f[2 * i + 1] = pts[i].y; + } + return f; +} /** Punkte einer (ggf. gedrehten) Ellipse, N gleichverteilte Parameterschritte. */ export function ellipsePts( @@ -13,29 +30,7 @@ export function ellipsePts( rotation: number, n = 64, ): Vec2[] { - const pts: Vec2[] = []; - const cosR = Math.cos(rotation); - const sinR = Math.sin(rotation); - for (let i = 0; i < n; i++) { - const t = (i / n) * Math.PI * 2; - const lx = rx * Math.cos(t); - const ly = ry * Math.sin(t); - pts.push({ x: center.x + lx * cosR - ly * sinR, y: center.y + lx * sinR + ly * cosR }); - } - return pts; -} - -/** Punkt auf einer kubischen Bezier-Kurve (De-Casteljau-Formel) bei Parameter `t` ∈ [0,1]. */ -function cubicPoint(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, t: number): Vec2 { - const u = 1 - t; - const a = u * u * u; - const b = 3 * u * u * t; - const c = 3 * u * t * t; - const d = t * t * t; - return { - x: a * p0.x + b * p1.x + c * p2.x + d * p3.x, - y: a * p0.y + b * p1.y + c * p2.y + d * p3.y, - }; + return toPoints(core().curves_ellipse_flat(center.x, center.y, rx, ry, rotation, n)); } /** @@ -46,21 +41,7 @@ function cubicPoint(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, t: number): Vec2 { */ export function sampleBezierChain(pts: Vec2[], segsPerCurve = 24): Vec2[] { if (pts.length < 4) return [...pts]; - const out: Vec2[] = [pts[0]]; - for (let i = 0; i + 3 < pts.length; i += 3) { - const p0 = pts[i], p1 = pts[i + 1], p2 = pts[i + 2], p3 = pts[i + 3]; - for (let s = 1; s <= segsPerCurve; s++) out.push(cubicPoint(p0, p1, p2, p3, s / segsPerCurve)); - } - return out; -} - -/** Kontrollpunkt-Zugriff für Catmull-Rom mit Rand-Klemmung bzw. Ring-Umlauf. */ -function crPoint(pts: Vec2[], i: number, closed: boolean): Vec2 { - const n = pts.length; - if (closed) return pts[((i % n) + n) % n]; - if (i < 0) return pts[0]; - if (i >= n) return pts[n - 1]; - return pts[i]; + return toPoints(core().curves_bezier_chain_flat(toFlat(pts), segsPerCurve)); } /** @@ -73,48 +54,7 @@ function crPoint(pts: Vec2[], i: number, closed: boolean): Vec2 { */ export function sampleCatmullRom(pts: Vec2[], closed: boolean, segsPerSpan = 16): Vec2[] { if (pts.length < 3) return [...pts]; - const out: Vec2[] = []; - const spans = closed ? pts.length : pts.length - 1; - for (let i = 0; i < spans; i++) { - const p0 = crPoint(pts, i - 1, closed); - const p1 = crPoint(pts, i, closed); - const p2 = crPoint(pts, i + 1, closed); - const p3 = crPoint(pts, i + 2, closed); - for (let s = 0; s < segsPerSpan; s++) { - const t = s / segsPerSpan; - const t2 = t * t; - const t3 = t2 * t; - const x = - 0.5 * - (2 * p1.x + - (-p0.x + p2.x) * t + - (2 * p0.x - 5 * p1.x + 4 * p2.x - p3.x) * t2 + - (-p0.x + 3 * p1.x - 3 * p2.x + p3.x) * t3); - const y = - 0.5 * - (2 * p1.y + - (-p0.y + p2.y) * t + - (2 * p0.y - 5 * p1.y + 4 * p2.y - p3.y) * t2 + - (-p0.y + 3 * p1.y - 3 * p2.y + p3.y) * t3); - out.push({ x, y }); - } - } - if (!closed) out.push(pts[pts.length - 1]); - return out; -} - -/** Punkt auf einem uniformen kubischen B-Spline-Segment (Standard-Basis, 4 Kontrollpunkte). */ -function bsplineSegPoint(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, t: number): Vec2 { - const t2 = t * t; - const t3 = t2 * t; - const b0 = (1 - t) ** 3 / 6; - const b1 = (3 * t3 - 6 * t2 + 4) / 6; - const b2 = (-3 * t3 + 3 * t2 + 3 * t + 1) / 6; - const b3 = t3 / 6; - return { - x: p0.x * b0 + p1.x * b1 + p2.x * b2 + p3.x * b3, - y: p0.y * b0 + p1.y * b1 + p2.y * b2 + p3.y * b3, - }; + return toPoints(core().curves_catmull_rom_flat(toFlat(pts), closed, segsPerSpan)); } /** @@ -122,35 +62,11 @@ function bsplineSegPoint(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, t: number): Vec * `pts` — Gegenstück zu `sampleCatmullRom`: die Kurve verläuft NICHT durch * die inneren Punkte, sie wird nur von ihnen „gezogen" (Kontrollnetz statt * Durchgangspunkte, wie CV-Modus in AutoCAD/Rhino). Offen: GEKLEMMT — die - * Kurve berührt exakt `pts[0]`/`pts[n-1]` (Rand-Kontrollpunkte werden intern - * je 2× zusätzlich dupliziert, Multiplizität 3 an beiden Enden — der - * Standard-Trick für kubische B-Splines, ohne eine generische - * Knotenvektor-Auswertung/Cox-de-Boor-Rekursion zu brauchen). Geschlossen: - * periodisch (Kontrollpunkte laufen zyklisch um), die Kurve berührt dann - * KEINEN der Punkte. Mit weniger als 3 Punkten identisches + * Kurve berührt exakt `pts[0]`/`pts[n-1]`. Geschlossen: periodisch, die Kurve + * berührt dann KEINEN der Punkte. Mit weniger als 3 Punkten identisches * Fallback-Verhalten wie `sampleCatmullRom` (Rohpunkte, Gummiband-Vorschau). */ export function sampleUniformBSpline(pts: Vec2[], closed: boolean, segsPerSpan = 16): Vec2[] { if (pts.length < 3) return [...pts]; - const out: Vec2[] = []; - if (closed) { - const n = pts.length; - const at = (i: number) => pts[((i % n) + n) % n]; - for (let i = 0; i < n; i++) { - for (let s = 0; s < segsPerSpan; s++) { - out.push(bsplineSegPoint(at(i - 1), at(i), at(i + 1), at(i + 2), s / segsPerSpan)); - } - } - return out; - } - const last = pts[pts.length - 1]; - const padded = [pts[0], pts[0], ...pts, last, last]; - const spans = padded.length - 3; - for (let i = 0; i < spans; i++) { - for (let s = 0; s < segsPerSpan; s++) { - out.push(bsplineSegPoint(padded[i], padded[i + 1], padded[i + 2], padded[i + 3], s / segsPerSpan)); - } - } - out.push(last); - return out; + return toPoints(core().curves_uniform_bspline_flat(toFlat(pts), closed, segsPerSpan)); } From ba29192a237a4c45343e49822de060ad428de939 Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:07:35 +0100 Subject: [PATCH 06/31] [K3c] Schnitt-Baender (Dominanz, Verschmelzung, Rechteck-Vereinigung) in Rust (plan_section.rs); toSection nur noch Ein-/Ausgabe --- TODO.md | 3 +- src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/plan_section.rs | 365 +++++++++++++++++++++++++ src-tauri/core/src/web/mod.rs | 1 + src-tauri/core/src/web/plan_section.rs | 15 + src/plan/toSection.boolean.test.ts | 58 +--- src/plan/toSection.ts | 266 +++--------------- 7 files changed, 431 insertions(+), 278 deletions(-) create mode 100644 src-tauri/core/src/plan_section.rs create mode 100644 src-tauri/core/src/web/plan_section.rs diff --git a/TODO.md b/TODO.md index 2dd96f74..4c956f28 100644 --- a/TODO.md +++ b/TODO.md @@ -104,7 +104,8 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern Offen: `drawing2d.ts` (950 Zeilen) ist nach diesen Schritten Stil-Auflösung und Verteiler über Formen (Bemassung, Kote, Detailverweis, Massstabsbalken, Block über `scaleGeom`); der Rechenanteil liegt in Rust. Der Verteiler zieht mit dem Modell nach Rust [K4] — vorher würde ein Rust-`Drawing2D` doppelt gepflegt. Danach: [K3c] Schnitt/Ansicht, [K3d] Aufräumen. - - ○ **[K3c] Schnitt und Ansicht** (`toSection`, `toElevation`, `meshSection`) im selben Puffer-Format. + - ◐ **[K3c] Schnitt und Ansicht** (`toSection`, `toElevation`, `meshSection`) im selben Puffer-Format. + ✅ Schnitt-Bänder: Dominanz-Subtraktion, Verschmelzung, Rechteck-Vereinigung (`plan_section.rs`, 28.10.). - ○ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. 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. diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 7e29298f..0bd4953f 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -38,6 +38,7 @@ pub mod plan_walls; pub mod opening_geom; pub mod plan_openings; pub mod plan_misc; +pub mod plan_section; pub mod curves; #[cfg(feature = "web")] diff --git a/src-tauri/core/src/plan_section.rs b/src-tauri/core/src/plan_section.rs new file mode 100644 index 00000000..76f8bf2d --- /dev/null +++ b/src-tauri/core/src/plan_section.rs @@ -0,0 +1,365 @@ +//! Schnitt-Bänder ([K3c]): Dominanz-Subtraktion und Verschmelzung achsparalleler Schnitt-Rechtecke +//! (`toSection.ts`: `subtractDominantBands`, `mergeSameComponentBands`) sowie die Vereinigung zu +//! Aussenringen (`unionRectOutlines`). Stil, Füllung, Schraffur und Herkunft hängen in TS an den +//! Bändern; Rust rechnet nur auf Rechtecken. Rechenreihenfolge wie in TS. +//! +//! ## Dominanz +//! `dominant_bands(in)` mit `in = [n, Band × n]`, Band = `[gueltig, uMin, uMax, vMin, vMax, prio, comp]` +//! (`gueltig` 0 = weniger als 3 Ecken; `prio` NaN = keine; `comp` < 0 = keine Komponente) → +//! `[m, Eintrag × m]`, Eintrag = `[quelle, istRechteck, uMin, uMax, vMin, vMax]`. `istRechteck` 0 = +//! Quellband unverändert übernehmen, sonst neues Rechteck mit Stil von `quelle`. +//! +//! ## Umrisse +//! `union_outlines(in)` mit `in = [n, (uMin, uMax, vMin, vMax) × n]` → `[r, (k, x, y × k) × r]`. + +use crate::jsnum::{max, min}; +use std::collections::HashMap; + +const RECT_EPS: f64 = 1e-6; + +#[derive(Clone, Copy)] +struct Rect { + u_min: f64, + u_max: f64, + v_min: f64, + v_max: f64, +} + +#[derive(Clone, Copy)] +struct Band { + rect: Option, + prio: Option, + comp: Option, +} + +struct Out { + src: usize, + rect: Option, +} + +fn subtract_rect(base: Rect, cutter: Rect) -> Vec { + let o_min_u = max(base.u_min, cutter.u_min); + let o_max_u = min(base.u_max, cutter.u_max); + let o_min_v = max(base.v_min, cutter.v_min); + let o_max_v = min(base.v_max, cutter.v_max); + if o_max_u - o_min_u <= RECT_EPS || o_max_v - o_min_v <= RECT_EPS { + return vec![base]; + } + let mut out = Vec::new(); + let mut push = |r: Rect| { + if r.u_max - r.u_min > RECT_EPS && r.v_max - r.v_min > RECT_EPS { + out.push(r); + } + }; + push(Rect { u_min: base.u_min, u_max: o_min_u, v_min: base.v_min, v_max: base.v_max }); + push(Rect { u_min: o_max_u, u_max: base.u_max, v_min: base.v_min, v_max: base.v_max }); + push(Rect { u_min: o_min_u, u_max: o_max_u, v_min: base.v_min, v_max: o_min_v }); + push(Rect { u_min: o_min_u, u_max: o_max_u, v_min: o_max_v, v_max: base.v_max }); + out +} + +fn rect_union_if_rect(a: Rect, b: Rect) -> Option { + let e = RECT_EPS; + let a_in_b = b.u_min - a.u_min <= e && a.u_max - b.u_max <= e && b.v_min - a.v_min <= e && a.v_max - b.v_max <= e; + if a_in_b { + return Some(b); + } + let b_in_a = a.u_min - b.u_min <= e && b.u_max - a.u_max <= e && a.v_min - b.v_min <= e && b.v_max - a.v_max <= e; + if b_in_a { + return Some(a); + } + let u_aligned = (a.u_min - b.u_min).abs() <= e && (a.u_max - b.u_max).abs() <= e; + let v_aligned = (a.v_min - b.v_min).abs() <= e && (a.v_max - b.v_max).abs() <= e; + let v_touch = a.v_max >= b.v_min - e && b.v_max >= a.v_min - e; + let u_touch = a.u_max >= b.u_min - e && b.u_max >= a.u_min - e; + if (u_aligned && v_touch) || (v_aligned && u_touch) { + return Some(Rect { + u_min: min(a.u_min, b.u_min), + u_max: max(a.u_max, b.u_max), + v_min: min(a.v_min, b.v_min), + v_max: max(a.v_max, b.v_max), + }); + } + None +} + +fn merge_same_component(bands: &[Band], list: Vec) -> Vec { + let mut out = list; + let mut merged = true; + while merged { + merged = false; + let mut i = 0; + while i < out.len() && !merged { + let bi = bands[out[i].src]; + // Verschmolzene Rechtecke erben Komponente/Priorität des Quellbands. + if bi.comp.is_none() || bi.prio.is_none() { + i += 1; + continue; + } + let ri = match out[i].rect.or(bi.rect) { + Some(r) => r, + None => { + i += 1; + continue; + } + }; + for j in i + 1..out.len() { + let bj = bands[out[j].src]; + if bj.comp != bi.comp || bj.prio != bi.prio { + continue; + } + let rj = match out[j].rect.or(bj.rect) { + Some(r) => r, + None => continue, + }; + if let Some(u) = rect_union_if_rect(ri, rj) { + out[i].rect = Some(u); + out.remove(j); + merged = true; + break; + } + } + i += 1; + } + } + out +} + +pub fn dominant_bands(inp: &[f64]) -> Vec { + if inp.is_empty() || !inp[0].is_finite() || inp[0] < 0.0 { + return Vec::new(); + } + let n = inp[0] as usize; + if inp.len() != 1 + 7 * n { + return Vec::new(); + } + let bands: Vec = (0..n) + .map(|k| { + let b = &inp[1 + 7 * k..8 + 7 * k]; + Band { + rect: (b[0] != 0.0).then_some(Rect { u_min: b[1], u_max: b[2], v_min: b[3], v_max: b[4] }), + prio: (!b[5].is_nan()).then_some(b[5]), + comp: (b[6] >= 0.0).then_some(b[6] as i64), + } + }) + .collect(); + let mut out: Vec = Vec::new(); + for i in 0..n { + let (base, prio) = match (bands[i].rect, bands[i].prio) { + (Some(r), Some(p)) => (r, p), + _ => { + out.push(Out { src: i, rect: None }); + continue; + } + }; + let mut pieces = vec![base]; + for j in 0..n { + if pieces.is_empty() { + break; + } + if j == i { + continue; + } + let (cutter, other) = match (bands[j].rect, bands[j].prio) { + (Some(c), Some(p)) => (c, p), + _ => continue, + }; + if other <= prio { + continue; + } + let mut next = Vec::new(); + for p in pieces { + next.extend(subtract_rect(p, cutter)); + } + pieces = next; + } + for p in pieces { + out.push(Out { src: i, rect: Some(p) }); + } + } + let out = merge_same_component(&bands, out); + let mut f = Vec::with_capacity(1 + 6 * out.len()); + f.push(out.len() as f64); + for o in &out { + match o.rect { + Some(r) => f.extend([o.src as f64, 1.0, r.u_min, r.u_max, r.v_min, r.v_max]), + None => f.extend([o.src as f64, 0.0, 0.0, 0.0, 0.0, 0.0]), + } + } + f +} + +fn signed_area(ring: &[(f64, f64)]) -> f64 { + let mut a = 0.0; + for i in 0..ring.len() { + let (x0, y0) = ring[i]; + let (x1, y1) = ring[(i + 1) % ring.len()]; + a += x0 * y1 - x1 * y0; + } + a / 2.0 +} + +fn sorted_unique(mut v: Vec) -> Vec { + v.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + v.dedup_by(|a, b| *a == *b); + v +} + +pub fn union_outlines(inp: &[f64]) -> Vec { + if inp.is_empty() || !inp[0].is_finite() || inp[0] < 0.0 { + return Vec::new(); + } + let n = inp[0] as usize; + if inp.len() != 1 + 4 * n || inp.iter().any(|v| !v.is_finite()) { + return Vec::new(); + } + let rects: Vec = (0..n) + .map(|k| Rect { u_min: inp[1 + 4 * k], u_max: inp[2 + 4 * k], v_min: inp[3 + 4 * k], v_max: inp[4 + 4 * k] }) + .collect(); + let xs = sorted_unique(rects.iter().flat_map(|r| [r.u_min, r.u_max]).collect()); + let ys = sorted_unique(rects.iter().flat_map(|r| [r.v_min, r.v_max]).collect()); + if xs.len() < 2 || ys.len() < 2 { + return vec![0.0]; + } + let nx = xs.len() - 1; + let ny = ys.len() - 1; + let mut cell = vec![vec![false; ny]; nx]; + for i in 0..nx { + for j in 0..ny { + let cx = (xs[i] + xs[i + 1]) / 2.0; + let cy = (ys[j] + ys[j + 1]) / 2.0; + cell[i][j] = rects.iter().any(|r| cx > r.u_min && cx < r.u_max && cy > r.v_min && cy < r.v_max); + } + } + let at = |i: isize, j: isize| i >= 0 && j >= 0 && (i as usize) < nx && (j as usize) < ny && cell[i as usize][j as usize]; + // Gerichtete Randkanten in Einfügereihenfolge (wie `Map`: erneutes `set` behält die Position). + let mut keys: Vec<(usize, usize)> = Vec::new(); + let mut next: HashMap<(usize, usize), (usize, usize)> = HashMap::new(); + let mut set = |k: (usize, usize), v: (usize, usize)| { + if next.insert(k, v).is_none() { + keys.push(k); + } + }; + for i in 0..nx { + for j in 0..ny { + if !cell[i][j] { + continue; + } + let (ii, jj) = (i as isize, j as isize); + if !at(ii, jj - 1) { + set((i, j), (i + 1, j)); + } + if !at(ii + 1, jj) { + set((i + 1, j), (i + 1, j + 1)); + } + if !at(ii, jj + 1) { + set((i + 1, j + 1), (i, j + 1)); + } + if !at(ii - 1, jj) { + set((i, j + 1), (i, j)); + } + } + } + let mut rings: Vec> = Vec::new(); + let mut used: std::collections::HashSet<(usize, usize)> = std::collections::HashSet::new(); + for &start in &keys { + if used.contains(&start) { + continue; + } + let mut ring: Vec<(f64, f64)> = Vec::new(); + let mut k = start; + while !used.contains(&k) { + used.insert(k); + ring.push((xs[k.0], ys[k.1])); + match next.get(&k) { + Some(&nk) => k = nk, + None => break, + } + } + let len = ring.len(); + let simple: Vec<(f64, f64)> = ring + .iter() + .enumerate() + .filter(|(idx, p)| { + let a = ring[(idx + len - 1) % len]; + let b = ring[(idx + 1) % len]; + !((a.0 == p.0 && p.0 == b.0) || (a.1 == p.1 && p.1 == b.1)) + }) + .map(|(_, p)| *p) + .collect(); + if simple.len() >= 4 && signed_area(&simple) > 0.0 { + rings.push(simple); + } + } + let mut f = vec![rings.len() as f64]; + for r in &rings { + f.push(r.len() as f64); + for p in r { + f.push(p.0); + f.push(p.1); + } + } + f +} + +#[cfg(test)] +mod tests { + use super::*; + + fn band(u0: f64, u1: f64, v0: f64, v1: f64, prio: f64, comp: f64) -> [f64; 7] { + [1.0, u0, u1, v0, v1, prio, comp] + } + + #[test] + fn hoehere_prioritaet_schneidet_weg() { + let mut inp = vec![2.0]; + inp.extend(band(0.0, 1.0, 0.0, 1.0, 10.0, 0.0)); + inp.extend(band(0.0, 1.0, 0.5, 1.0, 100.0, 1.0)); + let f = dominant_bands(&inp); + // Basis behält die untere Hälfte, Cutter bleibt ganz. + assert_eq!(f[0], 2.0); + assert_eq!(&f[1..7], &[0.0, 1.0, 0.0, 1.0, 0.0, 0.5]); + } + + fn r(u0: f64, u1: f64, v0: f64, v1: f64) -> Rect { + Rect { u_min: u0, u_max: u1, v_min: v0, v_max: v1 } + } + + #[test] + fn rechteck_subtraktion() { + // Kein Überlapp, nur Berührung, volle Überdeckung, Ecke, Randstreifen. + assert_eq!(subtract_rect(r(0.0, 1.0, 0.0, 1.0), r(2.0, 3.0, 2.0, 3.0)).len(), 1); + assert_eq!(subtract_rect(r(0.0, 1.0, 0.0, 1.0), r(1.0, 2.0, 0.0, 1.0)).len(), 1); + assert!(subtract_rect(r(1.0, 2.0, 1.0, 2.0), r(0.0, 3.0, 0.0, 3.0)).is_empty()); + let ecke = subtract_rect(r(0.0, 2.0, 0.0, 2.0), r(1.0, 3.0, 1.0, 3.0)); + let flaeche: f64 = ecke.iter().map(|x| (x.u_max - x.u_min) * (x.v_max - x.v_min)).sum(); + assert_eq!((ecke.len(), flaeche), (2, 3.0)); + let rand = subtract_rect(r(0.0, 2.0, 0.0, 2.0), r(-1.0, 3.0, 1.0, 3.0)); + assert_eq!(rand.len(), 1); + assert_eq!((rand[0].v_min, rand[0].v_max), (0.0, 1.0)); + } + + #[test] + fn gleiche_komponente_verschmilzt() { + let mut inp = vec![2.0]; + inp.extend(band(0.0, 1.0, 0.0, 1.0, 10.0, 3.0)); + inp.extend(band(1.0, 2.0, 0.0, 1.0, 10.0, 3.0)); + let f = dominant_bands(&inp); + assert_eq!(f[0], 1.0); + assert_eq!(&f[1..7], &[0.0, 1.0, 0.0, 2.0, 0.0, 1.0]); + } + + #[test] + fn l_form_ergibt_einen_ring() { + let f = union_outlines(&[2.0, 0.0, 2.0, 0.0, 1.0, 0.0, 1.0, 0.0, 2.0]); + assert_eq!(f[0], 1.0); + assert_eq!(f[1], 6.0); + } + + #[test] + fn unsinn_ist_leer() { + assert!(dominant_bands(&[f64::NAN]).is_empty()); + assert!(dominant_bands(&[2.0, 1.0]).is_empty()); + assert!(union_outlines(&[1.0, f64::NAN, 1.0, 0.0, 1.0]).is_empty()); + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index a38c29db..9ab6f102 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -29,6 +29,7 @@ mod plan_stairs; mod plan_walls; mod plan_openings; mod plan_misc; +mod plan_section; mod curves; mod hatch; diff --git a/src-tauri/core/src/web/plan_section.rs b/src-tauri/core/src/web/plan_section.rs new file mode 100644 index 00000000..9d696f8f --- /dev/null +++ b/src-tauri/core/src/web/plan_section.rs @@ -0,0 +1,15 @@ +//! Bindungen der Schnitt-Bänder (`crate::plan_section`). Layouts s. dort. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Dominanz-Subtraktion und Verschmelzung der Schnitt-Rechtecke; Unsinn → leer. +#[wasm_bindgen] +pub fn section_dominant_bands_flat(input: &[f64]) -> Vec { + crate::plan_section::dominant_bands(input) +} + +/// Aussenringe der Vereinigung achsparalleler Rechtecke; Unsinn → leer. +#[wasm_bindgen] +pub fn section_union_outlines_flat(input: &[f64]) -> Vec { + crate::plan_section::union_outlines(input) +} diff --git a/src/plan/toSection.boolean.test.ts b/src/plan/toSection.boolean.test.ts index d0da8a55..52005dcc 100644 --- a/src/plan/toSection.boolean.test.ts +++ b/src/plan/toSection.boolean.test.ts @@ -4,16 +4,14 @@ * die schwächere per achsparalleler Rechteck-Subtraktion weg. Gleiche Priorität * koexistiert (kein Schnitt). * - * Getestet ohne WASM: - * 1. `subtractRect` direkt (Ecken-/Kanten-/Enthalten-/Kein-Overlap-Fälle). - * 2. `subtractDominantBands` gegen den Nutzer-Testfall — ELEMENTÜBERGREIFEND: + * Getestet über den Rust-Kern (`plan_section.rs`): + * `subtractDominantBands` gegen den Nutzer-Testfall — ELEMENTÜBERGREIFEND: * ein Decken-Beton-Band (100) schneidet ein überlappendes Wand-Putz-Band * (10) weg; Beton bleibt voll; gleiche Priorität koexistiert. */ import { describe, it, expect } from "vitest"; import { - subtractRect, subtractDominantBands, type Rect, type SectionCutPolygon, @@ -24,14 +22,6 @@ function r(uMin: number, uMax: number, vMin: number, vMax: number): Rect { return { uMin, uMax, vMin, vMax }; } -/** Rechteck einer Rest-Menge normalisieren (auf 1e-9 gerundet, sortiert) für stabile Vergleiche. */ -function norm(rects: Rect[]): Rect[] { - const round = (x: number) => Math.round(x * 1e9) / 1e9; - return rects - .map((x) => ({ uMin: round(x.uMin), uMax: round(x.uMax), vMin: round(x.vMin), vMax: round(x.vMax) })) - .sort((a, b) => a.uMin - b.uMin || a.vMin - b.vMin); -} - /** Ein achsparalleles Cut-Band mit joinPriority. */ function band( uMin: number, @@ -83,50 +73,6 @@ function area(items: Array): number { }, 0); } -describe("subtractRect: achsparallele Rechteck-Subtraktion", () => { - it("kein Overlap → base unverändert", () => { - expect(norm(subtractRect(r(0, 1, 0, 1), r(2, 3, 2, 3)))).toEqual(norm([r(0, 1, 0, 1)])); - }); - - it("nur Kantenberührung (Fläche 0) → base unverändert", () => { - // cutter grenzt bei u=1 an, überlappt aber nicht. - expect(norm(subtractRect(r(0, 1, 0, 1), r(1, 2, 0, 1)))).toEqual(norm([r(0, 1, 0, 1)])); - }); - - it("cutter enthält base vollständig → leere Restmenge", () => { - expect(subtractRect(r(1, 2, 1, 2), r(0, 3, 0, 3))).toEqual([]); - }); - - it("cutter mittig in base → 4 Rest-Rechtecke, Flächenbilanz stimmt", () => { - const rest = subtractRect(r(0, 3, 0, 3), r(1, 2, 1, 2)); - expect(rest).toHaveLength(4); - // 9 (base) − 1 (overlap) = 8. - expect(area(rest)).toBeCloseTo(8, 9); - // Rechtecke sind disjunkt: Summe der Einzelflächen = Gesamtfläche. - const sum = rest.reduce((s, x) => s + (x.uMax - x.uMin) * (x.vMax - x.vMin), 0); - expect(sum).toBeCloseTo(8, 9); - }); - - it("Ecküberlappung → 2 Rest-Rechtecke (L-Form)", () => { - // cutter überdeckt die obere-rechte Ecke von base. - const rest = subtractRect(r(0, 2, 0, 2), r(1, 3, 1, 3)); - // overlap = [1,2]×[1,2] (Fläche 1). Rest = 4 − 1 = 3. - expect(area(rest)).toBeCloseTo(3, 9); - expect(norm(rest)).toEqual( - norm([ - r(0, 1, 0, 2), // links, volle Höhe - r(1, 2, 0, 1), // mittlerer Streifen unten - ]), - ); - }); - - it("Kantenüberlappung (cutter deckt einen Randstreifen) → 1 Rest-Rechteck", () => { - // cutter deckt den oberen Rand v∈[1,2] über die volle Breite. - const rest = subtractRect(r(0, 2, 0, 2), r(-1, 3, 1, 3)); - expect(norm(rest)).toEqual(norm([r(0, 2, 0, 1)])); - }); -}); - describe("subtractDominantBands: stärkere Schicht schneidet schwächere", () => { it("Nutzer-Testfall ELEMENTÜBERGREIFEND: Decken-Beton(100) schneidet Wand-Putz(10) weg", () => { // Wand-Putz-Band (Element B): schwach, joinPriority 10, u∈[0,2], v∈[0,3]. diff --git a/src/plan/toSection.ts b/src/plan/toSection.ts index cbd9daa7..dd551428 100644 --- a/src/plan/toSection.ts +++ b/src/plan/toSection.ts @@ -27,6 +27,7 @@ import { projectToModel3d } from "./toWalls3d"; import { subtractVoidsInSection } from "./voids"; import { appendBodySections, appendTerrainProfiles } from "./sectionExtras"; import { loadEngine3d } from "../engine/engine3d"; +import { core } from "../engine/coreWasm"; import { HATCH_INK, HATCH_PAPER, @@ -582,8 +583,6 @@ function ceilingRepresentativePriority(project: Project, ceiling: Ceiling): numb // ── Schnitt-Boolean-Dominanz (achsparallele Rechteck-Subtraktion) ─────────── // Kleine Toleranz für Überlappungs-/Rest-Rechtecke: Null-/Negativflächen und // Rest-Streifen dünner als EPS werden verworfen (Float-Rauschen der u-/v-Meter). -const RECT_EPS = 1e-6; - /** Achsparalleles Rechteck in (u, v)-Metern. */ export interface Rect { uMin: number; @@ -605,177 +604,52 @@ function rectOfBand(band: SectionCutPolygon): Rect | null { }; } -/** - * Rechteck-minus-Rechteck (beide achsparallel): `base` ohne die Überlappung mit - * `cutter`, zerlegt in 0–4 disjunkte Rest-Rechtecke (links/rechts über die volle - * Höhe, dann oben/unten im mittleren u-Streifen — überlappungsfrei). Kein echter - * Überlapp (Fläche ≤ EPS in u oder v) ⇒ `base` bleibt ganz. Vollständige - * Überdeckung ⇒ leere Liste. Rest-Streifen dünner als EPS werden verworfen. - */ -export function subtractRect(base: Rect, cutter: Rect): Rect[] { - const oMinU = Math.max(base.uMin, cutter.uMin); - const oMaxU = Math.min(base.uMax, cutter.uMax); - const oMinV = Math.max(base.vMin, cutter.vMin); - const oMaxV = Math.min(base.vMax, cutter.vMax); - // Kein (nennenswerter) Überlapp — `base` unverändert. - if (oMaxU - oMinU <= RECT_EPS || oMaxV - oMinV <= RECT_EPS) return [base]; - - const out: Rect[] = []; - const push = (r: Rect) => { - if (r.uMax - r.uMin > RECT_EPS && r.vMax - r.vMin > RECT_EPS) out.push(r); - }; - // Links / rechts der Überlappung, jeweils über die volle Basis-Höhe. - push({ uMin: base.uMin, uMax: oMinU, vMin: base.vMin, vMax: base.vMax }); - push({ uMin: oMaxU, uMax: base.uMax, vMin: base.vMin, vMax: base.vMax }); - // Unten / oben im mittleren u-Streifen (nur der von der Überlappung befreite Rest). - push({ uMin: oMinU, uMax: oMaxU, vMin: base.vMin, vMax: oMinV }); - push({ uMin: oMinU, uMax: oMaxU, vMin: oMaxV, vMax: base.vMax }); - return out; -} - /** * Globale Schnitt-Dominanz: für jedes Band wird die Rechteck-Überlappung ALLER * Bänder mit STRIKT höherer `joinPriority` subtrahiert (elementübergreifend — * z. B. schneidet ein Decken-Beton-Band 100 ein überlappendes Wand-Putz-Band 10 - * weg). Gleiche Priorität schneidet NICHT (koexistiert → durchgehende Fläche). - * Bänder ohne `joinPriority` (unauflösbares Bauteil) nehmen weder als Basis noch - * als Cutter teil und bleiben unverändert erhalten. - * - * Kanten: jedes emittierte Rest-Rechteck erhält in `generateSectionPlan` seine - * eigene Schnitt-Umrisslinie (unverändert). An der Schnittkante fällt die - * Rest-Rechteck-Kante mit der Kante des stärkeren Bands zusammen — das ist die - * gewünschte Material-/Fugenlinie zwischen den Schichten; im Inneren einer - * Schicht entstehen durch die überlappungsfreie Zerlegung keine falschen Kanten. + * weg). Gleiche Priorität schneidet NICHT. Bänder ohne `joinPriority` nehmen + * weder als Basis noch als Cutter teil. Danach verschmelzen angrenzende Bänder + * gleicher `componentId` + Priorität zu einem Körper (keine innere Trennlinie). + * Die Rechenarbeit liegt im Rust-Kern (`plan_section.rs`, [K3c]); hier nur + * Ein-/Ausgabe der Bänder samt Stil. */ export function subtractDominantBands(bands: SectionCutPolygon[]): SectionCutPolygon[] { - const rects = bands.map(rectOfBand); + const ids = new Map(); + const b: number[] = [bands.length]; + for (const band of bands) { + const r = rectOfBand(band); + let comp = -1; + if (band.componentId !== undefined) { + comp = ids.get(band.componentId) ?? ids.size; + ids.set(band.componentId, comp); + } + b.push(r ? 1 : 0, r?.uMin ?? 0, r?.uMax ?? 0, r?.vMin ?? 0, r?.vMax ?? 0, + band.joinPriority ?? Number.NaN, comp); + } + const f = core().section_dominant_bands_flat(Float64Array.from(b)); const out: SectionCutPolygon[] = []; - for (let i = 0; i < bands.length; i++) { - const band = bands[i]; - const base = rects[i]; - const prio = band.joinPriority; - // Nicht-rechteckig oder ohne Priorität: unverändert durchreichen. - if (base === null || prio === undefined) { - out.push(band); - continue; - } - let pieces: Rect[] = [base]; - for (let j = 0; j < bands.length && pieces.length > 0; j++) { - if (j === i) continue; - const otherPrio = bands[j].joinPriority; - const cutter = rects[j]; - if (cutter === null || otherPrio === undefined || otherPrio <= prio) continue; - const next: Rect[] = []; - for (const p of pieces) next.push(...subtractRect(p, cutter)); - pieces = next; - } - for (const p of pieces) out.push(bandFromRect(band, p)); - } - // MERGE-Regel: nach der Dominanz-Subtraktion angrenzende/überlappende Bänder - // gleicher Komponente + Priorität zu einem Körper verschmelzen (keine innere - // Trennlinie durch gleichartiges Material). Die Subtraktion oben bleibt davon - // unberührt (bit-identisch) — hier werden nur gleichartige Reste vereinigt. - return mergeSameComponentBands(out); -} - -/** - * Union zweier achsparalleler Rechtecke, ABER NUR wenn das Ergebnis EXAKT wieder - * ein Rechteck ist — sonst `null`. Zwei Fälle liefern eine rechteckige Union - * (jeweils mit `RECT_EPS`-Toleranz): - * • Enthaltensein: eines liegt vollständig im anderen ⇒ das umschließende. - * • Achs-Deckung + Berührung: in einer Achse deckungsgleich (gleiche min/max) - * UND in der anderen berührend/überlappend (kein Spalt) ⇒ Bounding-Box. - * Teil-/Eck-Überlappungen (Union wäre L-förmig) und Bänder mit Spalt liefern - * `null` — sie dürfen NICHT verschmolzen werden (die Bounding-Box deckte sonst - * leere Fläche ab). Genau die im Schnitt vorkommenden bündigen Rechtecke. - */ -function rectUnionIfRect(a: Rect, b: Rect): Rect | null { - const E = RECT_EPS; - // Enthaltensein (inkl. Deckungsgleichheit): Union = umschließendes Rechteck. - const aInB = - b.uMin - a.uMin <= E && a.uMax - b.uMax <= E && b.vMin - a.vMin <= E && a.vMax - b.vMax <= E; - if (aInB) return { uMin: b.uMin, uMax: b.uMax, vMin: b.vMin, vMax: b.vMax }; - const bInA = - a.uMin - b.uMin <= E && b.uMax - a.uMax <= E && a.vMin - b.vMin <= E && b.vMax - a.vMax <= E; - if (bInA) return { uMin: a.uMin, uMax: a.uMax, vMin: a.vMin, vMax: a.vMax }; - - const uAligned = Math.abs(a.uMin - b.uMin) <= E && Math.abs(a.uMax - b.uMax) <= E; - const vAligned = Math.abs(a.vMin - b.vMin) <= E && Math.abs(a.vMax - b.vMax) <= E; - // Berührung/Überlappung in der jeweils ANDEREN Achse (kein Spalt größer EPS). - const vTouch = a.vMax >= b.vMin - E && b.vMax >= a.vMin - E; - const uTouch = a.uMax >= b.uMin - E && b.uMax >= a.uMin - E; - if ((uAligned && vTouch) || (vAligned && uTouch)) { - return { - uMin: Math.min(a.uMin, b.uMin), - uMax: Math.max(a.uMax, b.uMax), - vMin: Math.min(a.vMin, b.vMin), - vMax: Math.max(a.vMax, b.vMax), - }; - } - return null; -} - -/** - * MERGE-Phase der Schnitt-Dominanz (vgl. `resolveJoinPriority` "merge", - * src/model/joins.ts): Bänder mit GLEICHER `componentId` UND gleicher - * `joinPriority`, deren achsparallele Rechtecke sich berühren/überlappen und - * eine rechteckige Union bilden (`rectUnionIfRect`), werden zu EINEM Band - * zusammengefasst — so entsteht an der Berührkante keine innere Trennlinie durch - * gleichartiges Material (z. B. zwei Backstein-Kerne, Beton-Decke an Beton-Wand). - * - * Bänder VERSCHIEDENER Komponenten (auch bei gleicher Priorität) bleiben - * getrennt (coexist). Bänder ohne `componentId`/`joinPriority` oder ohne - * Rechteck-Form nehmen nicht teil und werden unverändert durchgereicht — daher - * ist die Phase für die bestehenden Dominanz-Tests (keine `componentId`) ein - * No-op. Iterativ bis zum Fixpunkt (Ketten aus ≥3 Rechtecken verschmelzen - * schrittweise); die Reihenfolge bleibt erhalten (das verschmolzene Rechteck - * ersetzt das erste Band an seiner Position). - */ -function mergeSameComponentBands(bands: SectionCutPolygon[]): SectionCutPolygon[] { - const out = bands.slice(); - for (let merged = true; merged; ) { - merged = false; - for (let i = 0; i < out.length && !merged; i++) { - const bi = out[i]; - if (bi.componentId === undefined || bi.joinPriority === undefined) continue; - const ri = rectOfBand(bi); - if (!ri) continue; - for (let j = i + 1; j < out.length; j++) { - const bj = out[j]; - if (bj.componentId !== bi.componentId || bj.joinPriority !== bi.joinPriority) continue; - const rj = rectOfBand(bj); - if (!rj) continue; - const u = rectUnionIfRect(ri, rj); - if (!u) continue; - out[i] = bandFromRect(bi, u); - out.splice(j, 1); - merged = true; // Fixpunkt-Neustart: neu entstandene Nachbarschaften erfassen - break; - } - } + for (let k = 0, i = 1; k < f[0]; k++, i += 6) { + const src = bands[f[i]]; + out.push(f[i + 1] === 0 ? src : { + component: src.component, + color: src.color, + pts: [ + [f[i + 2], f[i + 5]], + [f[i + 3], f[i + 5]], + [f[i + 3], f[i + 4]], + [f[i + 2], f[i + 4]], + ], + fill: src.fill, + hatch: src.hatch, + joinPriority: src.joinPriority, + componentId: src.componentId, + sourceId: src.sourceId, + }); } return out; } -/** Erzeugt aus einem Rest-`Rect` ein Cut-Band, das Stil/Referenz von `src` erbt. */ -function bandFromRect(src: SectionCutPolygon, r: Rect): SectionCutPolygon { - return { - component: src.component, - color: src.color, - pts: [ - [r.uMin, r.vMax], - [r.uMax, r.vMax], - [r.uMax, r.vMin], - [r.uMin, r.vMin], - ], - fill: src.fill, - hatch: src.hatch, - joinPriority: src.joinPriority, - componentId: src.componentId, - sourceId: src.sourceId, - }; -} - /** * Zerlegt das EINE geschnittene Deckenrechteck (`cp`, vier Ecken in u/v-Metern) * in liegende Teil-Rechtecke je Schicht des Deckentyps `wt` — das Schnitt- @@ -1384,69 +1258,19 @@ export function mergeMonolithCuts( /** * Äussere Umrisse der Vereinigung achsparalleler Rechtecke (Raster über alle * Kanten-Koordinaten, Randkanten verketten). Liefert je zusammenhängender - * Fläche den Aussenring (CCW); Innenringe (Löcher) entfallen. + * Fläche den Aussenring (CCW); Innenringe (Löcher) entfallen. Rechnet der Kern. */ export function unionRectOutlines(rects: Rect[]): Array> { - const xs = [...new Set(rects.flatMap((r) => [r.uMin, r.uMax]))].sort((a, b) => a - b); - const ys = [...new Set(rects.flatMap((r) => [r.vMin, r.vMax]))].sort((a, b) => a - b); - const nx = xs.length - 1; - const ny = ys.length - 1; - if (nx < 1 || ny < 1) return []; - const filled = (i: number, j: number): boolean => { - if (i < 0 || j < 0 || i >= nx || j >= ny) return false; - const cx = (xs[i] + xs[i + 1]) / 2; - const cy = (ys[j] + ys[j + 1]) / 2; - return rects.some((r) => cx > r.uMin && cx < r.uMax && cy > r.vMin && cy < r.vMax); - }; - const cell: boolean[][] = []; - for (let i = 0; i < nx; i++) { - cell.push([]); - for (let j = 0; j < ny; j++) cell[i].push(filled(i, j)); - } - const at = (i: number, j: number) => i >= 0 && j >= 0 && i < nx && j < ny && cell[i][j]; - // Gerichtete Randkanten (Fläche links → CCW), als Gitterpunkt-Paare. - const next = new Map(); - const key = (i: number, j: number) => `${i},${j}`; - for (let i = 0; i < nx; i++) { - for (let j = 0; j < ny; j++) { - if (!cell[i][j]) continue; - if (!at(i, j - 1)) next.set(key(i, j), [i + 1, j]); // unten, nach rechts - if (!at(i + 1, j)) next.set(key(i + 1, j), [i + 1, j + 1]); // rechts, nach oben - if (!at(i, j + 1)) next.set(key(i + 1, j + 1), [i, j + 1]); // oben, nach links - if (!at(i - 1, j)) next.set(key(i, j + 1), [i, j]); // links, nach unten - } - } + const b: number[] = [rects.length]; + for (const r of rects) b.push(r.uMin, r.uMax, r.vMin, r.vMax); + const f = core().section_union_outlines_flat(Float64Array.from(b)); const rings: Array> = []; - const used = new Set(); - for (const start of next.keys()) { - if (used.has(start)) continue; + let i = 1; + for (let k = 0; k < (f[0] ?? 0); k++) { + const count = f[i++]; const ring: Array<[number, number]> = []; - let k = start; - while (!used.has(k)) { - used.add(k); - const [i, j] = k.split(",").map(Number); - ring.push([xs[i], ys[j]]); - const n = next.get(k); - if (!n) break; - k = key(n[0], n[1]); - } - // Kollineare Zwischenpunkte entfernen. - const simple = ring.filter((p, idx) => { - const a = ring[(idx + ring.length - 1) % ring.length]; - const b = ring[(idx + 1) % ring.length]; - return !((a[0] === p[0] && p[0] === b[0]) || (a[1] === p[1] && p[1] === b[1])); - }); - if (simple.length >= 4 && signedArea(simple) > 0) rings.push(simple); + for (let j = 0; j < count; j++, i += 2) ring.push([f[i], f[i + 1]]); + rings.push(ring); } return rings; } - -function signedArea(ring: Array<[number, number]>): number { - let a = 0; - for (let i = 0; i < ring.length; i++) { - const [x0, y0] = ring[i]; - const [x1, y1] = ring[(i + 1) % ring.length]; - a += x0 * y1 - x1 * y0; - } - return a / 2; -} From 69ee1d9db6854d12be931a776b93189b950d90a5 Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:10:34 +0100 Subject: [PATCH 07/31] [K3c] Ansicht: Verdeckungs-Clipping, Schlagschatten, XOR-Umriss in Rust (plan_elevation.rs); toElevation buendelt die Anfragen --- TODO.md | 1 + src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/plan_elevation.rs | 410 +++++++++++++++++++++++ src-tauri/core/src/web/mod.rs | 1 + src-tauri/core/src/web/plan_elevation.rs | 27 ++ src/plan/toElevation.ts | 375 ++++++--------------- 6 files changed, 536 insertions(+), 279 deletions(-) create mode 100644 src-tauri/core/src/plan_elevation.rs create mode 100644 src-tauri/core/src/web/plan_elevation.rs diff --git a/TODO.md b/TODO.md index 4c956f28..894f59bf 100644 --- a/TODO.md +++ b/TODO.md @@ -106,6 +106,7 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern nach Rust [K4] — vorher würde ein Rust-`Drawing2D` doppelt gepflegt. Danach: [K3c] Schnitt/Ansicht, [K3d] Aufräumen. - ◐ **[K3c] Schnitt und Ansicht** (`toSection`, `toElevation`, `meshSection`) im selben Puffer-Format. ✅ Schnitt-Bänder: Dominanz-Subtraktion, Verschmelzung, Rechteck-Vereinigung (`plan_section.rs`, 28.10.). + ✅ Ansicht: Verdeckungs-Clipping, Punkt-Verdeckung, Schlagschatten, XOR-Umriss (`plan_elevation.rs`, 28.10.). - ○ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. 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. diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 0bd4953f..81e1462f 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -37,6 +37,7 @@ pub mod plan_stairs; pub mod plan_walls; pub mod opening_geom; pub mod plan_openings; +pub mod plan_elevation; pub mod plan_misc; pub mod plan_section; pub mod curves; diff --git a/src-tauri/core/src/plan_elevation.rs b/src-tauri/core/src/plan_elevation.rs new file mode 100644 index 00000000..bd66c8d9 --- /dev/null +++ b/src-tauri/core/src/plan_elevation.rs @@ -0,0 +1,410 @@ +//! Ansichts-Geometrie ([K3c]): Verdeckungs-Clipping, Punkt-Verdeckung, Schlagschatten und +//! XOR-Umriss frontaler Flächengruppen (`toElevation.ts`: `clipSegmentVisible`, `isPointOccluded`, +//! `buildShadows`, `xorOutlineEdges`). Flächenaufbau, Stil, Painter-Ordnung und Pick-IDs bleiben in +//! TS. Rechenreihenfolge und Zahlsemantik wie dort. +//! +//! ## Verdecker (`occ`) +//! `[n, (tiefe, k, u0, v0 … u(k-1), v(k-1)) × n]`. +//! +//! ## Segmente +//! `clip_segments(occ, segs)` mit `segs = [m, (ax, ay, bx, by, tiefe) × m]` → +//! `[m, (c, (ax, ay, bx, by) × c) × m]` (sichtbare Teilstücke je Segment, c = 0 ganz verdeckt). +//! +//! ## Punkte +//! `occluded_points(occ, pts)` mit `pts = [m, (u, v, tiefe) × m]` → `[m, 0/1 × m]`. +//! +//! ## Schatten +//! `shadows(walls, slabs)`, je `[n, (tiefe, tiefeMin, k, u, v …) × n]` (Wände: tiefeMin ungenutzt) → +//! `[r, (tiefe, k, u, v …) × r]`. +//! +//! ## XOR-Umriss +//! `xor_outline(polys)` mit `[n, (k, u, v …) × n]` → `[e, (ax, ay, bx, by) × e]`. + +use crate::jsnum::{max, min, round}; +use std::collections::HashMap; + +const OCC_MARGIN: f64 = 2e-3; +const EPS: f64 = 1e-6; +const MAX_SHADOW_DELTA: f64 = 1.2; +const SUN_U: f64 = 1.0; +const SUN_V: f64 = -1.0; + +type P = (f64, f64); + +struct Occ { + poly: Vec

, + bbox: [f64; 4], // uMin, uMax, vMin, vMax + depth: f64, +} + +fn bbox_of(pts: &[P]) -> [f64; 4] { + let (mut u_min, mut u_max, mut v_min, mut v_max) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY); + for &(u, v) in pts { + if u < u_min { + u_min = u; + } + if u > u_max { + u_max = u; + } + if v < v_min { + v_min = v; + } + if v > v_max { + v_max = v; + } + } + [u_min, u_max, v_min, v_max] +} + +/// Liest `[n, (kopf…, k, pts…) × n]`; `head` = Zahl der Kopfwerte je Eintrag. `None` bei Unsinn. +fn read_polys(f: &[f64], head: usize) -> Option, Vec

)>> { + if f.is_empty() || f.iter().any(|v| !v.is_finite()) || f[0] < 0.0 { + return None; + } + let n = f[0] as usize; + let mut i = 1; + let mut out = Vec::with_capacity(n); + for _ in 0..n { + if i + head >= f.len() { + return None; + } + let h = f[i..i + head].to_vec(); + let k = f[i + head]; + if k < 0.0 { + return None; + } + let k = k as usize; + i += head + 1; + if i + 2 * k > f.len() { + return None; + } + out.push((h, (0..k).map(|j| (f[i + 2 * j], f[i + 2 * j + 1])).collect())); + i += 2 * k; + } + (i == f.len()).then_some(out) +} + +fn read_occ(f: &[f64]) -> Option> { + Some( + read_polys(f, 1)? + .into_iter() + .map(|(h, poly)| Occ { bbox: bbox_of(&poly), poly, depth: h[0] }) + .collect(), + ) +} + +fn segment_inside_poly_interval(a: P, b: P, poly: &[P]) -> Option<(f64, f64)> { + let n = poly.len(); + if n < 3 { + return None; + } + let mut area = 0.0; + for i in 0..n { + let p = poly[i]; + let q = poly[(i + 1) % n]; + area += p.0 * q.1 - q.0 * p.1; + } + let sign = if area >= 0.0 { 1.0 } else { -1.0 }; + let dx = b.0 - a.0; + let dy = b.1 - a.1; + let (mut t0, mut t1) = (0.0, 1.0); + for i in 0..n { + let p = poly[i]; + let q = poly[(i + 1) % n]; + let ex = q.0 - p.0; + let ey = q.1 - p.1; + let c0 = sign * (ex * (a.1 - p.1) - ey * (a.0 - p.0)); + let cd = sign * (ex * dy - ey * dx); + if cd.abs() < 1e-12 { + if c0 < 0.0 { + return None; + } + } else { + let t_hit = -c0 / cd; + if cd > 0.0 { + t0 = max(t0, t_hit); + } else { + t1 = min(t1, t_hit); + } + if t0 > t1 { + return None; + } + } + } + (t0 <= t1).then_some((t0, t1)) +} + +fn clip_segment_visible(a: P, b: P, depth: f64, occ: &[Occ]) -> Vec<(P, P)> { + let mut cuts: Vec<(f64, f64)> = Vec::new(); + let seg_min = (min(a.0, b.0), min(a.1, b.1)); + let seg_max = (max(a.0, b.0), max(a.1, b.1)); + for o in occ { + if o.depth >= depth - OCC_MARGIN { + continue; + } + if o.bbox[1] < seg_min.0 || o.bbox[0] > seg_max.0 { + continue; + } + if o.bbox[3] < seg_min.1 || o.bbox[2] > seg_max.1 { + continue; + } + if let Some(iv) = segment_inside_poly_interval(a, b, &o.poly) { + if iv.1 - iv.0 > 1e-6 { + cuts.push(iv); + } + } + } + if cuts.is_empty() { + return vec![(a, b)]; + } + cuts.sort_by(|x, y| x.0.partial_cmp(&y.0).unwrap_or(std::cmp::Ordering::Equal)); + let at = |t: f64| -> P { (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t) }; + let mut out = Vec::new(); + let mut cursor = 0.0; + for (s, e) in cuts { + if s > cursor + 1e-6 { + out.push((at(cursor), at(min(s, 1.0)))); + } + cursor = max(cursor, e); + if cursor >= 1.0 { + break; + } + } + if cursor < 1.0 - 1e-6 { + out.push((at(cursor), at(1.0))); + } + out +} + +pub fn clip_segments(occ: &[f64], segs: &[f64]) -> Vec { + let Some(occ) = read_occ(occ) else { return Vec::new() }; + if segs.is_empty() || segs.iter().any(|v| !v.is_finite()) || segs[0] < 0.0 || segs.len() != 1 + 5 * segs[0] as usize { + return Vec::new(); + } + let m = segs[0] as usize; + let mut f = vec![m as f64]; + for k in 0..m { + let s = &segs[1 + 5 * k..6 + 5 * k]; + let parts = clip_segment_visible((s[0], s[1]), (s[2], s[3]), s[4], &occ); + f.push(parts.len() as f64); + for (a, b) in parts { + f.extend([a.0, a.1, b.0, b.1]); + } + } + f +} + +fn point_in_poly(pt: P, poly: &[P]) -> bool { + let mut inside = false; + let mut j = poly.len().wrapping_sub(1); + for i in 0..poly.len() { + let (xi, yi) = poly[i]; + let (xj, yj) = poly[j]; + if (yi > pt.1) != (yj > pt.1) && pt.0 < ((xj - xi) * (pt.1 - yi)) / (yj - yi) + xi { + inside = !inside; + } + j = i; + } + inside +} + +pub fn occluded_points(occ: &[f64], pts: &[f64]) -> Vec { + let Some(occ) = read_occ(occ) else { return Vec::new() }; + if pts.is_empty() || pts.iter().any(|v| !v.is_finite()) || pts[0] < 0.0 || pts.len() != 1 + 3 * pts[0] as usize { + return Vec::new(); + } + let m = pts[0] as usize; + let mut f = vec![m as f64]; + for k in 0..m { + let (u, v, depth) = (pts[1 + 3 * k], pts[2 + 3 * k], pts[3 + 3 * k]); + let hit = occ.iter().any(|o| { + o.depth < depth - OCC_MARGIN + && !(u < o.bbox[0] || u > o.bbox[1] || v < o.bbox[2] || v > o.bbox[3]) + && point_in_poly((u, v), &o.poly) + }); + f.push(if hit { 1.0 } else { 0.0 }); + } + f +} + +fn clip_polygon_to_rect(poly: &[P], r: [f64; 4]) -> Vec

{ + fn clip(input: &[P], inside: impl Fn(P) -> bool, intersect: impl Fn(P, P) -> P) -> Vec

{ + let mut out = Vec::new(); + for i in 0..input.len() { + let a = input[i]; + let b = input[(i + 1) % input.len()]; + let (ain, bin) = (inside(a), inside(b)); + if ain { + out.push(a); + } + if ain != bin { + out.push(intersect(a, b)); + } + } + out + } + let lerp = |a: P, b: P, t: f64| -> P { (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t) }; + let (u_min, u_max, v_min, v_max) = (r[0], r[1], r[2], r[3]); + let mut p = poly.to_vec(); + p = clip(&p, |q| q.0 >= u_min, |a, b| lerp(a, b, (u_min - a.0) / (b.0 - a.0))); + if p.len() < 3 { + return Vec::new(); + } + p = clip(&p, |q| q.0 <= u_max, |a, b| lerp(a, b, (u_max - a.0) / (b.0 - a.0))); + if p.len() < 3 { + return Vec::new(); + } + p = clip(&p, |q| q.1 >= v_min, |a, b| lerp(a, b, (v_min - a.1) / (b.1 - a.1))); + if p.len() < 3 { + return Vec::new(); + } + p = clip(&p, |q| q.1 <= v_max, |a, b| lerp(a, b, (v_max - a.1) / (b.1 - a.1))); + if p.len() < 3 { + return Vec::new(); + } + p +} + +pub fn shadows(walls: &[f64], slabs: &[f64]) -> Vec { + let (Some(walls), Some(slabs)) = (read_polys(walls, 2), read_polys(slabs, 2)) else { + return Vec::new(); + }; + let mut res: Vec<(f64, Vec

)> = Vec::new(); + for (sh, spts) in &slabs { + let so = bbox_of(spts); + for (wh, wpts) in &walls { + let wo = bbox_of(wpts); + let delta = wh[0] - sh[1]; + if delta <= EPS || delta > MAX_SHADOW_DELTA { + continue; + } + if so[1] <= wo[0] + EPS || so[0] >= wo[1] - EPS { + continue; + } + let v_top = so[2]; + let par = [ + (so[0], v_top), + (so[1], v_top), + (so[1] + delta * SUN_U, v_top + delta * SUN_V), + (so[0] + delta * SUN_U, v_top + delta * SUN_V), + ]; + let clipped = clip_polygon_to_rect(&par, wo); + if clipped.len() >= 3 { + res.push((wh[0], clipped)); + } + } + } + let mut f = vec![res.len() as f64]; + for (d, pts) in res { + f.push(d); + f.push(pts.len() as f64); + for p in pts { + f.extend([p.0, p.1]); + } + } + f +} + +pub fn xor_outline(polys: &[f64]) -> Vec { + let Some(polys) = read_polys(polys, 0) else { return Vec::new() }; + const EPS_AX: f64 = 1e-6; + let key_of = |x: f64| round(x * 1e5); + // Gruppen in Einfügereihenfolge (wie `Map`; -0 und 0 sind derselbe Schlüssel). + let mut horiz: Vec<(f64, Vec<(f64, f64)>)> = Vec::new(); + let mut vert: Vec<(f64, Vec<(f64, f64)>)> = Vec::new(); + let mut hidx: HashMap = HashMap::new(); + let mut vidx: HashMap = HashMap::new(); + let mut out: Vec<(P, P)> = Vec::new(); + fn add(list: &mut Vec<(f64, Vec<(f64, f64)>)>, idx: &mut HashMap, k: f64, iv: (f64, f64)) { + let slot = *idx.entry(k as i64).or_insert_with(|| { + list.push((k, Vec::new())); + list.len() - 1 + }); + list[slot].1.push(iv); + } + for (_, poly) in &polys { + for i in 0..poly.len() { + let a = poly[i]; + let b = poly[(i + 1) % poly.len()]; + if (a.1 - b.1).abs() < EPS_AX { + add(&mut horiz, &mut hidx, key_of(a.1), (min(a.0, b.0), max(a.0, b.0))); + } else if (a.0 - b.0).abs() < EPS_AX { + add(&mut vert, &mut vidx, key_of(a.0), (min(a.1, b.1), max(a.1, b.1))); + } else { + out.push((a, b)); + } + } + } + let sweep = |m: &Vec<(f64, Vec<(f64, f64)>)>, emit: &mut dyn FnMut(f64, f64, f64)| { + for (k, ivs) in m { + let mut evs: Vec<(f64, i32)> = Vec::new(); + for &(s, e) in ivs { + if e - s < 1e-9 { + continue; + } + evs.push((s, 1)); + evs.push((e, -1)); + } + evs.sort_by(|p, q| { + let d = p.0 - q.0; + let c = if d != 0.0 { d } else { (q.1 - p.1) as f64 }; + c.partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal) + }); + let mut count = 0i32; + let mut start = 0.0; + let coord = k / 1e5; + for (x, d) in evs { + let was_odd = count % 2 == 1; + count += d; + let is_odd = count % 2 == 1; + if !was_odd && is_odd { + start = x; + } else if was_odd && !is_odd && x - start > 1e-9 { + emit(coord, start, x); + } + } + } + }; + sweep(&horiz, &mut |v, s, e| out.push(((s, v), (e, v)))); + sweep(&vert, &mut |u, s, e| out.push(((u, s), (u, e)))); + let mut f = vec![out.len() as f64]; + for (a, b) in out { + f.extend([a.0, a.1, b.0, b.1]); + } + f +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn verdecktes_segment_wird_zerschnitten() { + // Verdecker [1,2]×[-1,1] vor einer Linie bei v=0 von u=0..3. + let occ = [1.0, 0.0, 4.0, 1.0, -1.0, 2.0, -1.0, 2.0, 1.0, 1.0, 1.0]; + let f = clip_segments(&occ, &[1.0, 0.0, 0.0, 3.0, 0.0, 1.0]); + assert_eq!(f, vec![1.0, 2.0, 0.0, 0.0, 1.0, 0.0, 2.0, 0.0, 3.0, 0.0]); + // Tiefer als die Linie: kein Effekt. + let f = clip_segments(&occ, &[1.0, 0.0, 0.0, 3.0, 0.0, -1.0]); + assert_eq!(f, vec![1.0, 1.0, 0.0, 0.0, 3.0, 0.0]); + } + + #[test] + fn xor_hebt_innenkante_auf() { + let sq = |x0: f64, x1: f64| [4.0, x0, 0.0, x1, 0.0, x1, 1.0, x0, 1.0]; + let mut inp = vec![2.0]; + inp.extend(sq(0.0, 1.0)); + inp.extend(sq(1.0, 2.0)); + let f = xor_outline(&inp); + // Oben/unten je 2 Teilstücke (an der Naht nicht verschmolzen) + 2 senkrechte Aussenkanten; + // die Innenkante bei u=1 hebt sich auf. + assert_eq!(f[0], 6.0); + } + + #[test] + fn unsinn_ist_leer() { + assert!(clip_segments(&[f64::NAN], &[0.0]).is_empty()); + assert!(shadows(&[1.0], &[0.0]).is_empty()); + assert!(xor_outline(&[1.0, 5.0, 0.0]).is_empty()); + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 9ab6f102..8d406547 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -28,6 +28,7 @@ mod gpu_compile; mod plan_stairs; mod plan_walls; mod plan_openings; +mod plan_elevation; mod plan_misc; mod plan_section; mod curves; diff --git a/src-tauri/core/src/web/plan_elevation.rs b/src-tauri/core/src/web/plan_elevation.rs new file mode 100644 index 00000000..4234203a --- /dev/null +++ b/src-tauri/core/src/web/plan_elevation.rs @@ -0,0 +1,27 @@ +//! Bindungen der Ansichts-Geometrie (`crate::plan_elevation`). Layouts s. dort. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Sichtbare Teilstücke von Segmenten gegen nähere Verdecker; Unsinn → leer. +#[wasm_bindgen] +pub fn elevation_clip_segments_flat(occ: &[f64], segs: &[f64]) -> Vec { + crate::plan_elevation::clip_segments(occ, segs) +} + +/// Ob Punkte hinter einem näheren Verdecker liegen; Unsinn → leer. +#[wasm_bindgen] +pub fn elevation_occluded_points_flat(occ: &[f64], pts: &[f64]) -> Vec { + crate::plan_elevation::occluded_points(occ, pts) +} + +/// Schlagschatten auskragender Flächen auf Fassaden; Unsinn → leer. +#[wasm_bindgen] +pub fn elevation_shadows_flat(walls: &[f64], slabs: &[f64]) -> Vec { + crate::plan_elevation::shadows(walls, slabs) +} + +/// XOR-Umrisskanten frontaler Rechteckgruppen; Unsinn → leer. +#[wasm_bindgen] +pub fn elevation_xor_outline_flat(polys: &[f64]) -> Vec { + crate::plan_elevation::xor_outline(polys) +} diff --git a/src/plan/toElevation.ts b/src/plan/toElevation.ts index 9bebceae..9c056000 100644 --- a/src/plan/toElevation.ts +++ b/src/plan/toElevation.ts @@ -31,6 +31,7 @@ // v = absolute Höhe (Welt-Y). Die PlanView zeichnet Y nach oben → Ansicht steht // aufrecht. +import { core } from "../engine/coreWasm"; import type { DrawingLevel, Project, Vec2, Wall } from "../model/types"; import { getComponent, @@ -122,11 +123,6 @@ function rgbToHex(c: RRgb): string { return `#${b(c[0])}${b(c[1])}${b(c[2])}`; } -/** Sonnenrichtung als (u, v)-Schattenversatz je Tiefeneinheit: 45° von links - * oben ⇒ Schatten fällt nach rechts unten (+u, −v). */ -const SUN_U = 1; -const SUN_V = -1; - /** Numerisches Rauschen (Meter) für Tiefen-/Flächenvergleiche. */ const EPS = 1e-6; /** Grazing-Schwelle: Flächen fast parallel zur Blickrichtung gelten als nicht @@ -900,161 +896,28 @@ function collectOpenings(project: Project, frame: ElevationFrame): ProjectedOpen // ── Schlagschatten (45°, klassische Architektur-Konvention) ───────────────── -/** Achsparalleles (u, v)-Rechteck. */ -interface UVRect { - uMin: number; - uMax: number; - vMin: number; - vMax: number; -} - -function bboxOf(pts: Array<[number, number]>): UVRect { - let uMin = Infinity, uMax = -Infinity, vMin = Infinity, vMax = -Infinity; - for (const [u, v] of pts) { - if (u < uMin) uMin = u; - if (u > uMax) uMax = u; - if (v < vMin) vMin = v; - if (v > vMax) vMax = v; - } - return { uMin, uMax, vMin, vMax }; -} - /** * Ein opakes Verdeckungs-Polygon (projizierte Fläche) mit seiner FERNSTEN Tiefe - * (`depthMax`): eine Linie/Fläche gilt nur dann als verdeckt, wenn sie hinter - * dem gesamten Occluder liegt (`> depthMax`) — konservativ, damit gekippte - * Flächen (Dach) keine sichtbaren Kanten fälschlich wegschneiden. + * (`depth` = `depthMax`): eine Linie/Fläche gilt nur dann als verdeckt, wenn sie hinter + * dem gesamten Occluder liegt — konservativ, damit gekippte Flächen (Dach) keine + * sichtbaren Kanten fälschlich wegschneiden. Das Clipping selbst rechnet der Kern + * (`plan_elevation.rs`, [K3c]): warum überhaupt clippen — die GL-Ansicht zeichnet ALLE + * Linien in einem EIGENEN Stift-Durchgang ÜBER allen Füllungen (s. `glPlan/glPlanCompile.ts`); + * eine reine Painter-Tiefensortierung der Flächen verdeckt Linien also NICHT. */ interface Occluder { poly: Array<[number, number]>; - bbox: UVRect; depth: number; } -/** Warum überhaupt clippen: die GL-Ansicht zeichnet ALLE Linien in einem - * EIGENEN Stift-Durchgang ÜBER allen Füllungen (s. `glPlan/glPlanCompile.ts`); - * eine reine Painter-Tiefensortierung der Flächen verdeckt Linien also NICHT. - * Verdeckte Linienstücke werden darum hier, beim Planaufbau, exakt entfernt. */ -const OCC_MARGIN = 2e-3; - -/** - * Teilintervall `[t0,t1] ⊆ [0,1]` des Segments A→B, das INNERHALB des konvexen - * Polygons liegt (Halbebenen-Schnitt auf dem Parameter t), oder `null`. Die - * Polygon-Windung wird aus der Signfläche bestimmt, sodass die Innen-Seite jeder - * Kante korrekt orientiert ist (kein Vorwissen über CW/CCW nötig). - */ -function segmentInsidePolyInterval( - a: [number, number], - b: [number, number], - poly: Array<[number, number]>, -): [number, number] | null { - const n = poly.length; - if (n < 3) return null; - let area = 0; - for (let i = 0; i < n; i++) { - const p = poly[i]; - const q = poly[(i + 1) % n]; - area += p[0] * q[1] - q[0] * p[1]; +/** Verdecker flach für den Kern (`[n, (tiefe, k, u, v …) × n]`). */ +function encodeOccluders(occ: Occluder[]): Float64Array { + const b: number[] = [occ.length]; + for (const o of occ) { + b.push(o.depth, o.poly.length); + for (const [u, v] of o.poly) b.push(u, v); } - const sign = area >= 0 ? 1 : -1; - const dx = b[0] - a[0]; - const dy = b[1] - a[1]; - let t0 = 0; - let t1 = 1; - for (let i = 0; i < n; i++) { - const p = poly[i]; - const q = poly[(i + 1) % n]; - const ex = q[0] - p[0]; - const ey = q[1] - p[1]; - // Innen: sign·cross(edge, X−p) ≥ 0. f(t) = c0 + cd·t. - const c0 = sign * (ex * (a[1] - p[1]) - ey * (a[0] - p[0])); - const cd = sign * (ex * dy - ey * dx); - if (Math.abs(cd) < 1e-12) { - if (c0 < 0) return null; // Segment komplett ausserhalb dieser Kante - } else { - const tHit = -c0 / cd; - if (cd > 0) t0 = Math.max(t0, tHit); - else t1 = Math.min(t1, tHit); - if (t0 > t1) return null; - } - } - return t0 <= t1 ? [t0, t1] : null; -} - -/** - * Sichtbare Teilstücke eines Segments A→B (Tiefe `depth`): entfernt alle Anteile, - * die innerhalb eines NÄHEREN opaken Occluders (`o.depth < depth − margin`) - * liegen. Liefert die verbleibenden Segmente (leer, wenn ganz verdeckt). Exakt - * (Polygon-Halbebenen), nicht die frühere Bounding-Box-Näherung. - */ -function clipSegmentVisible( - a: [number, number], - b: [number, number], - depth: number, - occluders: Occluder[], -): Array<[[number, number], [number, number]]> { - const cuts: Array<[number, number]> = []; - const segMin: [number, number] = [Math.min(a[0], b[0]), Math.min(a[1], b[1])]; - const segMax: [number, number] = [Math.max(a[0], b[0]), Math.max(a[1], b[1])]; - for (const o of occluders) { - if (o.depth >= depth - OCC_MARGIN) continue; // nicht echt näher - // Billiger Bounding-Box-Vorabtest. - if (o.bbox.uMax < segMin[0] || o.bbox.uMin > segMax[0]) continue; - if (o.bbox.vMax < segMin[1] || o.bbox.vMin > segMax[1]) continue; - const iv = segmentInsidePolyInterval(a, b, o.poly); - if (iv && iv[1] - iv[0] > 1e-6) cuts.push(iv); - } - if (cuts.length === 0) return [[a, b]]; - cuts.sort((x, y) => x[0] - y[0]); - const at = (t: number): [number, number] => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]; - const out: Array<[[number, number], [number, number]]> = []; - let cursor = 0; - for (const [s, e] of cuts) { - if (s > cursor + 1e-6) out.push([at(cursor), at(Math.min(s, 1))]); - cursor = Math.max(cursor, e); - if (cursor >= 1) break; - } - if (cursor < 1 - 1e-6) out.push([at(cursor), at(1)]); - return out; -} - -/** - * Clippt ein Polygon an ein achsparalleles Rechteck (Sutherland–Hodgman, vier - * Halbebenen). Liefert das (konvexe) Restpolygon oder [] bei leerem Schnitt. - */ -function clipPolygonToRect(poly: Array<[number, number]>, r: UVRect): Array<[number, number]> { - type Pt = [number, number]; - const clip = ( - input: Pt[], - inside: (p: Pt) => boolean, - intersect: (a: Pt, b: Pt) => Pt, - ): Pt[] => { - const out: Pt[] = []; - for (let i = 0; i < input.length; i++) { - const a = input[i]; - const b = input[(i + 1) % input.length]; - const ain = inside(a); - const bin = inside(b); - if (ain) out.push(a); - if (ain !== bin) out.push(intersect(a, b)); - } - return out; - }; - let p: Pt[] = poly.slice(); - const lerp = (a: Pt, b: Pt, t: number): Pt => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]; - // links (u >= uMin) - p = clip(p, (q) => q[0] >= r.uMin, (a, b) => lerp(a, b, (r.uMin - a[0]) / (b[0] - a[0]))); - if (p.length < 3) return []; - // rechts (u <= uMax) - p = clip(p, (q) => q[0] <= r.uMax, (a, b) => lerp(a, b, (r.uMax - a[0]) / (b[0] - a[0]))); - if (p.length < 3) return []; - // unten (v >= vMin) - p = clip(p, (q) => q[1] >= r.vMin, (a, b) => lerp(a, b, (r.vMin - a[1]) / (b[1] - a[1]))); - if (p.length < 3) return []; - // oben (v <= vMax) - p = clip(p, (q) => q[1] <= r.vMax, (a, b) => lerp(a, b, (r.vMax - a[1]) / (b[1] - a[1]))); - if (p.length < 3) return []; - return p; + return Float64Array.from(b); } /** Ein Schatten-Polygon mit der Tiefe der Empfängerfläche (für die Painter-Ordnung). */ @@ -1063,51 +926,35 @@ interface ShadowPoly { depth: number; } +function encodeShadowFaces(faces: ProjectedFace[]): Float64Array { + const b: number[] = [faces.length]; + for (const f of faces) { + b.push(f.depth, f.depthMin, f.pts.length); + for (const [u, v] of f.pts) b.push(u, v); + } + return Float64Array.from(b); +} + /** * Baut die Schlagschatten auskragender Decken/Balkone (Slabs) auf die dahinter * liegenden Fassaden (Wände). KLASSISCHE ARCHITEKTUR-KONVENTION: Sonne 45° von * links oben ⇒ die Unterkante des Überstands wirft einen Schatten, dessen - * horizontaler Versatz UND vertikaler Abfall der Auskragungstiefe entspricht - * (Δ = Tiefendifferenz Empfänger − Überstand). Der Schatten ist ein Parallelo- - * gramm unter der Überstand-Unterkante (Höhe/Breite ∝ Δ), geclippt auf die - * Empfänger-Fassade. - * - * NÄHERUNG (dokumentiert): Überstand-Silhouette = (u, v)-Bounding-Box der Slab- - * Fläche; Empfänger = Bounding-Box der Wandfläche. Nur Slab→Wand-Paare mit - * echtem Tiefen-Vorsprung (Slab näher) und u-Überlapp erzeugen Schatten. Deckt - * die geforderten Fälle (Dachüberstand/Traufe, auskragende Decke/Balkon) ab; - * schräge Auskragungen werden als achsparalleles Band angenähert. + * horizontaler Versatz UND vertikaler Abfall der Auskragungstiefe entspricht. + * Rechnet der Kern (`plan_elevation.rs`): Näherung Überstand-Silhouette = (u, v)- + * Bounding-Box der Slab-Fläche, Empfänger = Bounding-Box der Wandfläche; nur Paare mit + * echtem Tiefen-Vorsprung (höchstens 1,2 m) und u-Überlapp. */ -/** Maximale Schatten-Tiefendifferenz (Meter): tiefer liegende Empfänger (ferne - * Innen-/Rückwände) bekämen sonst raumhohe Schatten-Parallelogramme — - * gezeichnet wird der klassische Bauteil-Schlagschatten (Traufe, Balkon), - * nicht die globale Verschattung. */ -const MAX_SHADOW_DELTA = 1.2; - export function buildShadows(walls: ProjectedFace[], slabs: ProjectedFace[]): ShadowPoly[] { + const f = core().elevation_shadows_flat(encodeShadowFaces(walls), encodeShadowFaces(slabs)); const out: ShadowPoly[] = []; - for (const slab of slabs) { - const so = bboxOf(slab.pts); - for (const wall of walls) { - const wo = bboxOf(wall.pts); - // Werfer-Tiefe = NÄCHSTE Kante (depthMin): bei geneigten Dachflächen ist - // das die auskragende Traufe — der Bezug für die Schattentiefe. - const delta = wall.depth - slab.depthMin; // Wand hinter dem Überstand? - if (delta <= EPS || delta > MAX_SHADOW_DELTA) continue; - // u-Überlapp Überstand/Wand? - if (so.uMax <= wo.uMin + EPS || so.uMin >= wo.uMax - EPS) continue; - // Der Schatten hängt an der Slab-Unterkante (so.vMin) und fällt um Δ nach - // unten, versetzt um Δ nach rechts (Sonne von links oben). - const vTop = so.vMin; - const parallelogram: Array<[number, number]> = [ - [so.uMin, vTop], - [so.uMax, vTop], - [so.uMax + delta * SUN_U, vTop + delta * SUN_V], - [so.uMin + delta * SUN_U, vTop + delta * SUN_V], - ]; - const clipped = clipPolygonToRect(parallelogram, wo); - if (clipped.length >= 3) out.push({ pts: clipped, depth: wall.depth }); - } + let i = 1; + for (let k = 0; k < (f[0] ?? 0); k++) { + const depth = f[i]; + const count = f[i + 1]; + i += 2; + const pts = new Array<[number, number]>(count); + for (let j = 0; j < count; j++, i += 2) pts[j] = [f[i], f[i + 1]]; + out.push({ pts, depth }); } return out; } @@ -1116,62 +963,22 @@ export function buildShadows(walls: ProjectedFace[], slabs: ProjectedFace[]): Sh /** * Vereinigungs-UMRISS einer Gruppe achsparalleler (u,v)-Rechteckflächen über - * Kanten-XOR: jede Kante wird als Intervall auf ihrer Trägerlinie gesammelt; - * Bereiche mit GERADER Überdeckung (geteilte Innenkanten zweier Teilboxen) - * heben sich auf, ungerade Bereiche bilden die Silhouette — inklusive der - * Fensterlöcher (die Teilboxen um eine Öffnung lassen genau deren Rand übrig). - * Nicht-achsparallele Kanten werden unverändert durchgereicht. + * Kanten-XOR: Bereiche mit GERADER Überdeckung (geteilte Innenkanten zweier + * Teilboxen) heben sich auf, ungerade Bereiche bilden die Silhouette — inklusive der + * Fensterlöcher. Nicht-achsparallele Kanten werden unverändert durchgereicht. + * Rechnet der Kern (`plan_elevation.rs`). */ export function xorOutlineEdges( polys: Array>, ): Array<[[number, number], [number, number]]> { - const EPS_AX = 1e-6; - const keyOf = (x: number): number => Math.round(x * 1e5); - const horiz = new Map>(); - const vert = new Map>(); - const out: Array<[[number, number], [number, number]]> = []; + const b: number[] = [polys.length]; for (const poly of polys) { - for (let i = 0; i < poly.length; i++) { - const a = poly[i]; - const b = poly[(i + 1) % poly.length]; - if (Math.abs(a[1] - b[1]) < EPS_AX) { - const k = keyOf(a[1]); - if (!horiz.has(k)) horiz.set(k, []); - horiz.get(k)!.push([Math.min(a[0], b[0]), Math.max(a[0], b[0])]); - } else if (Math.abs(a[0] - b[0]) < EPS_AX) { - const k = keyOf(a[0]); - if (!vert.has(k)) vert.set(k, []); - vert.get(k)!.push([Math.min(a[1], b[1]), Math.max(a[1], b[1])]); - } else { - out.push([a, b]); - } - } + b.push(poly.length); + for (const [u, v] of poly) b.push(u, v); } - const sweep = ( - m: Map>, - emit: (coord: number, s: number, e: number) => void, - ): void => { - for (const [k, ivs] of m) { - const evs: Array<[number, number]> = []; - for (const [s, e] of ivs) { - if (e - s < 1e-9) continue; - evs.push([s, 1], [e, -1]); - } - evs.sort((p, q) => p[0] - q[0] || q[1] - p[1]); - let count = 0; - let start = 0; - const coord = k / 1e5; - for (const [x, d] of evs) { - const wasOdd = count % 2 === 1; - count += d; - const isOdd = count % 2 === 1; - if (!wasOdd && isOdd) start = x; - else if (wasOdd && !isOdd && x - start > 1e-9) emit(coord, start, x); - } - } - }; - sweep(horiz, (v, s, e) => out.push([[s, v], [e, v]])); - sweep(vert, (u, s, e) => out.push([[u, s], [u, e]])); + const f = core().elevation_xor_outline_flat(Float64Array.from(b)); + const out: Array<[[number, number], [number, number]]> = []; + for (let k = 0, i = 1; k < (f[0] ?? 0); k++, i += 4) out.push([[f[i], f[i + 1]], [f[i + 2], f[i + 3]]]); return out; } @@ -1263,32 +1070,21 @@ export function generateElevationPlan( // Fassade). Linien HINTER einem Occluder werden exakt herausgeschnitten — // nötig, weil die GL-Pipeline alle Linien in einem eigenen Durchgang über die // Füllungen legt. - const occluders: Occluder[] = faces.map((f) => ({ - poly: f.pts, - bbox: bboxOf(f.pts), - depth: f.depthMax, - })); - for (const op of openings) { - occluders.push({ poly: op.pts, bbox: bboxOf(op.pts), depth: op.depth }); - } - // Ist ein Punkt hinter einer näheren opaken Fläche verborgen? (Ganz-Öffnung-Cull.) - const pointInPoly = (pt: [number, number], poly: Array<[number, number]>): boolean => { - let inside = false; - for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { - const [xi, yi] = poly[i]; - const [xj, yj] = poly[j]; - if ((yi > pt[1]) !== (yj > pt[1]) && pt[0] < ((xj - xi) * (pt[1] - yi)) / (yj - yi) + xi) inside = !inside; + const occluders: Occluder[] = faces.map((f) => ({ poly: f.pts, depth: f.depthMax })); + for (const op of openings) occluders.push({ poly: op.pts, depth: op.depth }); + const occFlat = encodeOccluders(occluders); + // Ganz-Öffnung-Cull: liegt der Öffnungs-Mittelpunkt hinter einer näheren opaken Fläche? + const openingOccluded = (() => { + const b: number[] = [openings.length]; + for (const op of openings) { + b.push( + (op.pts[0][0] + op.pts[1][0] + op.pts[2][0] + op.pts[3][0]) / 4, + (op.pts[0][1] + op.pts[1][1] + op.pts[2][1] + op.pts[3][1]) / 4, + op.depth, + ); } - return inside; - }; - const isPointOccluded = (pt: [number, number], depth: number): boolean => { - for (const o of occluders) { - if (o.depth >= depth - OCC_MARGIN) continue; - if (pt[0] < o.bbox.uMin || pt[0] > o.bbox.uMax || pt[1] < o.bbox.vMin || pt[1] > o.bbox.vMax) continue; - if (pointInPoly(pt, o.poly)) return true; - } - return false; - }; + return core().elevation_occluded_points_flat(occFlat, Float64Array.from(b)); + })(); const primitives: Primitive[] = []; let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; @@ -1322,19 +1118,43 @@ export function generateElevationPlan( const items: Item[] = []; let seq = 0; - // Emittiert ein Linien-Segment, exakt gegen nähere Occluder geclippt (verdeckte - // Teilstücke entfallen). `depth` = Tiefe der Linie (leicht vor ihrer Trägerfläche). + // Linien-Segmente werden exakt gegen nähere Occluder geclippt (verdeckte Teilstücke + // entfallen). Die Anforderungen sammeln sich in Zeichenreihenfolge und gehen gebündelt + // an den Kern (`flushPending`); `depth` = Tiefe der Linie (leicht vor ihrer Trägerfläche). + type Pending = + | { a: [number, number]; b: [number, number]; depth: number; prim: (a: [number, number], b: [number, number]) => Primitive } + | { item: Omit }; + const pending: Pending[] = []; const pushClippedLine = ( a: [number, number], b: [number, number], depth: number, prim: (a: [number, number], b: [number, number]) => Primitive, ): void => { - for (const [sa, sb] of clipSegmentVisible(a, b, depth, occluders)) { - acc(sa[0], sa[1]); - acc(sb[0], sb[1]); - items.push({ depth, seq: seq++, prim: prim(sa, sb) }); + pending.push({ a, b, depth, prim }); + }; + const flushPending = (): void => { + const lines = pending.filter((p): p is Extract => "a" in p); + const q: number[] = [lines.length]; + for (const l of lines) q.push(l.a[0], l.a[1], l.b[0], l.b[1], l.depth); + const r = core().elevation_clip_segments_flat(occFlat, Float64Array.from(q)); + let i = 1; + for (const p of pending) { + if ("item" in p) { + items.push({ ...p.item, seq: seq++ }); + continue; + } + const c = r.length === 0 ? 1 : r[i++]; + for (let k = 0; k < c; k++) { + const sa: [number, number] = r.length === 0 ? p.a : [r[i], r[i + 1]]; + const sb: [number, number] = r.length === 0 ? p.b : [r[i + 2], r[i + 3]]; + if (r.length !== 0) i += 4; + acc(sa[0], sa[1]); + acc(sb[0], sb[1]); + items.push({ depth: p.depth, seq: seq++, prim: p.prim(sa, sb) }); + } } + pending.length = 0; }; // Frontale Wand-/Deckenflächen (alle Ecken auf gleicher Tiefe) werden je @@ -1400,9 +1220,8 @@ export function generateElevationPlan( })); } } - items.push({ + pending.push({ item: { depth: f.depth, - seq: seq++, // Painter-Gleichstand (bündige Flächen, z. B. Decken-Stirn in der // Fassadenebene): Decke vor Wand vor Dach zeichnen, damit die Wand die // Stirnstreifen überdeckt. @@ -1421,7 +1240,7 @@ export function generateElevationPlan( ...(f.ceilingId ? { ceilingId: f.ceilingId } : {}), ...(f.roofId ? { roofId: f.roofId } : {}), }, - }); + } }); } for (const g of frontalGroups.values()) { // Der XOR-Silhouetten-Umriss der Gruppe, JEDE Kante exakt gegen nähere @@ -1440,6 +1259,8 @@ export function generateElevationPlan( } } + flushPending(); + // Schatten (leicht VOR der Empfängertiefe, damit sie direkt nach der Fassade, // aber unter den Öffnungen/Kanten näherer Flächen liegen). if (shadows) { @@ -1468,12 +1289,8 @@ export function generateElevationPlan( // Ganz verdeckte Öffnungen (Mittelpunkt hinter einer näheren opaken Fläche) // werden gar nicht erst emittiert — sonst scheinen ihre Symbol-/Sprossen-Linien // (eigener Linien-Durchgang, s. Occluder-Kommentar oben) durch die Vorderwand. - for (const op of openings) { - const opCenter: [number, number] = [ - (op.pts[0][0] + op.pts[1][0] + op.pts[2][0] + op.pts[3][0]) / 4, - (op.pts[0][1] + op.pts[1][1] + op.pts[2][1] + op.pts[3][1]) / 4, - ]; - if (isPointOccluded(opCenter, op.depth)) continue; + for (const [openingIndex, op] of openings.entries()) { + if (openingOccluded[1 + openingIndex] === 1) continue; const toVec = (q: Array<[number, number]>): Vec2[] => q.map(([u, v]) => { acc(u, v); From 873deb75c2242bcc6bd2d22869a55839f006167c Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:14:04 +0100 Subject: [PATCH 08/31] [K3c] Ansicht: Flaechen-Projektion (Waende, Decken, Daecher) und Eck-Verlaengerung in Rust; Weltflaechen-Funktionen in TS entfernt --- TODO.md | 1 + src-tauri/core/src/plan_elevation.rs | 361 ++++++++++++++++ src-tauri/core/src/web/plan_elevation.rs | 12 + src/plan/toElevation.test.ts | 36 +- src/plan/toElevation.ts | 514 ++++++----------------- 5 files changed, 521 insertions(+), 403 deletions(-) diff --git a/TODO.md b/TODO.md index 894f59bf..2a4fa896 100644 --- a/TODO.md +++ b/TODO.md @@ -107,6 +107,7 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern - ◐ **[K3c] Schnitt und Ansicht** (`toSection`, `toElevation`, `meshSection`) im selben Puffer-Format. ✅ Schnitt-Bänder: Dominanz-Subtraktion, Verschmelzung, Rechteck-Vereinigung (`plan_section.rs`, 28.10.). ✅ Ansicht: Verdeckungs-Clipping, Punkt-Verdeckung, Schlagschatten, XOR-Umriss (`plan_elevation.rs`, 28.10.). + ✅ Ansicht: Flächen (Wand-Quader, Decken-Prismen, Dach/Giebel) projizieren + Rückseiten-Culling, Eck-Verlängerung (`plan_elevation.rs`). - ○ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. 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. diff --git a/src-tauri/core/src/plan_elevation.rs b/src-tauri/core/src/plan_elevation.rs index bd66c8d9..8a4c978f 100644 --- a/src-tauri/core/src/plan_elevation.rs +++ b/src-tauri/core/src/plan_elevation.rs @@ -19,7 +19,24 @@ //! //! ## XOR-Umriss //! `xor_outline(polys)` mit `[n, (k, u, v …) × n]` → `[e, (ax, ay, bx, by) × e]`. +//! +//! ## Flächen +//! `faces(frame, walls, slabs, roofs)`; `frame = [Px,Py,Pz, Nx,Ny,Nz, Ux,Uy,Uz]` (Welt, Y oben). +//! ```text +//! walls [n, (sx, sz, ex, ez, dicke, hoehe, basis) × n] +//! slabs [n, (zUnten, zOben, k, x, z …) × n] +//! roofs [n, (nFl, nGiebel, (k, x, y, z …) × nFl, (k, x, y, z …) × nGiebel) × n] Modell [x, y, Höhe] +//! → [m, (rolle 0 Wand|1 Decke|2 Dach, quelle, tiefe, tiefeMin, tiefeMax, nx, ny, nz, k, u, v …) × m] +//! ``` +//! Reihenfolge: Wände, Decken, Dächer (je Quelle in Modellreihenfolge); nur sichtbare Flächen +//! (Rückseiten-Culling, Tiefe > 0). +//! +//! ## Eck-Verlängerung +//! `wall_extensions(in)` mit `in = [n, (geschoss, sx, sy, ex, ey, halbe dicke) × n]` → +//! `[n, (verlStart, verlEnde) × n]`: Wandenden bis zur Aussenfläche der dicksten anstossenden Wand +//! desselben Geschosses (`wallCornerExtensions`). +use crate::jsmath::{hypot, hypot2}; use crate::jsnum::{max, min, round}; use std::collections::HashMap; @@ -374,6 +391,325 @@ pub fn xor_outline(polys: &[f64]) -> Vec { f } +// ── Flächen ──────────────────────────────────────────────────────────────── + +const FACING_EPS: f64 = 1e-4; +type V3 = [f64; 3]; + +struct Frame { + p: V3, + n: V3, + u: V3, +} + +struct Projected { + role: u8, + src: usize, + depth: f64, + depth_min: f64, + depth_max: f64, + normal: V3, + pts: Vec

, +} + +fn normalize3(a: V3) -> V3 { + let l = hypot(&a); + let l = if l == 0.0 || l.is_nan() { 1.0 } else { l }; + [a[0] / l, a[1] / l, a[2] / l] +} + +fn neg(a: V3) -> V3 { + [-a[0], -a[1], -a[2]] +} + +fn project_point(f: &Frame, w: V3) -> (f64, f64, f64) { + let rx = w[0] - f.p[0]; + let ry = w[1] - f.p[1]; + let rz = w[2] - f.p[2]; + ( + rx * f.u[0] + ry * f.u[1] + rz * f.u[2], + w[1], + rx * f.n[0] + ry * f.n[1] + rz * f.n[2], + ) +} + +fn project_face(f: &Frame, poly: &[V3], normal: V3, role: u8, src: usize) -> Option { + let facing = f.n[0] * normal[0] + f.n[1] * normal[1] + f.n[2] * normal[2]; + if facing >= -FACING_EPS { + return None; + } + let mut pts = Vec::with_capacity(poly.len()); + let (mut sum, mut dmin, mut dmax) = (0.0, f64::INFINITY, f64::NEG_INFINITY); + for &w in poly { + let (u, v, d) = project_point(f, w); + pts.push((u, v)); + sum += d; + dmin = min(dmin, d); + dmax = max(dmax, d); + } + let depth = sum / poly.len() as f64; + if depth <= EPS { + return None; + } + Some(Projected { role, src, depth, depth_min: dmin, depth_max: dmax, normal, pts }) +} + +fn wall_faces(f: &Frame, w: &[f64], src: usize, out: &mut Vec) { + let (sx, sz, ex, ez) = (w[0], w[1], w[2], w[3]); + let ax = ex - sx; + let az = ez - sz; + let len = hypot2(ax, az); + if len < 1e-9 || w[5] <= EPS { + return; + } + let a_hat: V3 = [ax / len, 0.0, az / len]; + let n_hat: V3 = [az / len, 0.0, -ax / len]; + let ht = w[4] / 2.0; + let zb = w[6]; + let zt = w[6] + w[5]; + let corner = |s_along: f64, t_off: f64, y: f64| -> V3 { + [sx + a_hat[0] * s_along + n_hat[0] * t_off, y, sz + a_hat[2] * s_along + n_hat[2] * t_off] + }; + let faces: [(V3, [V3; 4]); 6] = [ + (n_hat, [corner(0.0, ht, zb), corner(len, ht, zb), corner(len, ht, zt), corner(0.0, ht, zt)]), + (neg(n_hat), [corner(0.0, -ht, zb), corner(0.0, -ht, zt), corner(len, -ht, zt), corner(len, -ht, zb)]), + (neg(a_hat), [corner(0.0, -ht, zb), corner(0.0, ht, zb), corner(0.0, ht, zt), corner(0.0, -ht, zt)]), + (a_hat, [corner(len, -ht, zb), corner(len, -ht, zt), corner(len, ht, zt), corner(len, ht, zb)]), + ([0.0, 1.0, 0.0], [corner(0.0, -ht, zt), corner(0.0, ht, zt), corner(len, ht, zt), corner(len, -ht, zt)]), + ([0.0, -1.0, 0.0], [corner(0.0, -ht, zb), corner(len, -ht, zb), corner(len, ht, zb), corner(0.0, ht, zb)]), + ]; + for (normal, poly) in faces { + if let Some(p) = project_face(f, &poly, normal, 0, src) { + out.push(p); + } + } +} + +fn slab_faces(f: &Frame, z_bottom: f64, z_top: f64, outline: &[P], src: usize, out: &mut Vec) { + let n = outline.len(); + if n < 3 || z_top - z_bottom <= EPS { + return; + } + let (mut cx, mut cz) = (0.0, 0.0); + for p in outline { + cx += p.0; + cz += p.1; + } + cx /= n as f64; + cz /= n as f64; + let bottom: Vec = outline.iter().map(|p| [p.0, z_bottom, p.1]).collect(); + let top: Vec = outline.iter().map(|p| [p.0, z_top, p.1]).collect(); + let mut push = |poly: &[V3], normal: V3| { + if let Some(p) = project_face(f, poly, normal, 1, src) { + out.push(p); + } + }; + push(&top, [0.0, 1.0, 0.0]); + let rev: Vec = bottom.iter().rev().copied().collect(); + push(&rev, [0.0, -1.0, 0.0]); + for i in 0..n { + let j = (i + 1) % n; + let ex = outline[j].0 - outline[i].0; + let ez = outline[j].1 - outline[i].1; + let mut m = normalize3([ez, 0.0, -ex]); + let mid_x = (outline[i].0 + outline[j].0) / 2.0; + let mid_z = (outline[i].1 + outline[j].1) / 2.0; + if m[0] * (mid_x - cx) + m[2] * (mid_z - cz) < 0.0 { + m = neg(m); + } + push(&[bottom[i], bottom[j], top[j], top[i]], m); + } +} + +fn newell(poly: &[V3]) -> V3 { + let (mut nx, mut ny, mut nz) = (0.0, 0.0, 0.0); + for i in 0..poly.len() { + let a = poly[i]; + let b = poly[(i + 1) % poly.len()]; + nx += (a[1] - b[1]) * (a[2] + b[2]); + ny += (a[2] - b[2]) * (a[0] + b[0]); + nz += (a[0] - b[0]) * (a[1] + b[1]); + } + normalize3([nx, ny, nz]) +} + +/// Liest `k, (x, y, z) × k` ab `i`; Modell [x, y, Höhe] → Welt [x, Höhe, y]. +fn read_world_poly(f: &[f64], i: &mut usize) -> Option> { + let k = *f.get(*i)?; + if k < 0.0 || k.fract() != 0.0 { + return None; + } + let k = k as usize; + *i += 1; + if *i + 3 * k > f.len() { + return None; + } + let poly = (0..k).map(|j| [f[*i + 3 * j], f[*i + 3 * j + 2], f[*i + 3 * j + 1]]).collect(); + *i += 3 * k; + Some(poly) +} + +fn roof_faces(f: &Frame, planes: &[Vec], gables: &[Vec], src: usize, out: &mut Vec) { + let (mut cx, mut cy, mut cz, mut cn) = (0.0, 0.0, 0.0, 0usize); + for pl in planes { + for p in pl { + // Welt [x, Höhe, y] → Modell-Reihenfolge der TS-Summen: p[0], p[2], p[1]. + cx += p[0]; + cy += p[1]; + cz += p[2]; + cn += 1; + } + } + if cn == 0 { + return; + } + let cnf = cn as f64; + cx /= cnf; + cy /= cnf; + cz /= cnf; + for poly in planes { + let mut n = newell(poly); + if n[1] < 0.0 { + n = neg(n); + } + if let Some(p) = project_face(f, poly, n, 2, src) { + out.push(p); + } + } + for poly in gables { + if poly.len() < 3 { + continue; + } + let mut n = newell(poly); + let to_c = [cx - poly[0][0], cy - poly[0][1], cz - poly[0][2]]; + if n[0] * to_c[0] + n[1] * to_c[1] + n[2] * to_c[2] > 0.0 { + n = neg(n); + } + if let Some(p) = project_face(f, poly, n, 2, src) { + out.push(p); + } + } +} + +fn counted(f: &[f64]) -> Option { + let n = *f.first()?; + (n >= 0.0 && n.fract() == 0.0 && f.iter().all(|v| v.is_finite())).then_some(n as usize) +} + +pub fn faces(frame: &[f64], walls: &[f64], slabs: &[f64], roofs: &[f64]) -> Vec { + if frame.len() != 9 || frame.iter().any(|v| !v.is_finite()) { + return Vec::new(); + } + let fr = Frame { + p: [frame[0], frame[1], frame[2]], + n: [frame[3], frame[4], frame[5]], + u: [frame[6], frame[7], frame[8]], + }; + let (Some(nw), Some(ns), Some(nr)) = (counted(walls), counted(slabs), counted(roofs)) else { + return Vec::new(); + }; + if walls.len() != 1 + 7 * nw { + return Vec::new(); + } + let mut out: Vec = Vec::new(); + for k in 0..nw { + wall_faces(&fr, &walls[1 + 7 * k..8 + 7 * k], k, &mut out); + } + let mut i = 1; + for k in 0..ns { + let Some(&kk) = slabs.get(i + 2) else { return Vec::new() }; + if kk < 0.0 || kk.fract() != 0.0 || i + 3 + 2 * kk as usize > slabs.len() { + return Vec::new(); + } + let kk = kk as usize; + let outline: Vec

= (0..kk).map(|j| (slabs[i + 3 + 2 * j], slabs[i + 4 + 2 * j])).collect(); + slab_faces(&fr, slabs[i], slabs[i + 1], &outline, k, &mut out); + i += 3 + 2 * kk; + } + if i != slabs.len() { + return Vec::new(); + } + let mut i = 1; + for k in 0..nr { + let (Some(&nf), Some(&ng)) = (roofs.get(i), roofs.get(i + 1)) else { return Vec::new() }; + if nf < 0.0 || ng < 0.0 || nf.fract() != 0.0 || ng.fract() != 0.0 { + return Vec::new(); + } + i += 2; + let mut planes = Vec::new(); + for _ in 0..nf as usize { + let Some(p) = read_world_poly(roofs, &mut i) else { return Vec::new() }; + planes.push(p); + } + let mut gables = Vec::new(); + for _ in 0..ng as usize { + let Some(p) = read_world_poly(roofs, &mut i) else { return Vec::new() }; + gables.push(p); + } + roof_faces(&fr, &planes, &gables, k, &mut out); + } + if i != roofs.len() { + return Vec::new(); + } + let mut f = vec![out.len() as f64]; + for p in &out { + f.extend([ + p.role as f64, p.src as f64, p.depth, p.depth_min, p.depth_max, + p.normal[0], p.normal[1], p.normal[2], p.pts.len() as f64, + ]); + for q in &p.pts { + f.extend([q.0, q.1]); + } + } + f +} + +// ── Eck-Verlängerung ─────────────────────────────────────────────────────── + +fn body_contains(w: &[f64], half: f64, p: P) -> bool { + let dx = w[3] - w[1]; + let dy = w[4] - w[2]; + let len = hypot2(dx, dy); + if len < 1e-9 { + return false; + } + let ux = dx / len; + let uy = dy / len; + let rx = p.0 - w[1]; + let ry = p.1 - w[2]; + let along = rx * ux + ry * uy; + let perp = (-uy * rx + ux * ry).abs(); + along >= -1e-6 && along <= len + 1e-6 && perp <= half + 1e-6 +} + +pub fn wall_extensions(inp: &[f64]) -> Vec { + let Some(n) = counted(inp) else { return Vec::new() }; + if inp.len() != 1 + 6 * n { + return Vec::new(); + } + let w = |k: usize| &inp[1 + 6 * k..7 + 6 * k]; + let mut f = vec![n as f64]; + for k in 0..n { + let me = w(k); + let ext_at = |p: P| -> f64 { + let mut max_other = 0.0; + for o in 0..n { + let other = w(o); + if o == k || other[0] != me[0] { + continue; + } + if body_contains(other, other[5], p) { + max_other = max(max_other, other[5]); + } + } + max_other + }; + f.push(ext_at((me[1], me[2]))); + f.push(ext_at((me[3], me[4]))); + } + f +} + #[cfg(test)] mod tests { use super::*; @@ -401,6 +737,31 @@ mod tests { assert_eq!(f[0], 6.0); } + #[test] + fn wand_sichtbar_nur_aus_der_sueden() { + // Betrachter bei z = -2, Blick +z; Wand 4 m lang bei z = 0, 3 m hoch. + let frame = [-1.0, 0.0, -2.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0]; + let walls = [1.0, 0.0, 0.0, 4.0, 0.0, 0.2, 3.0, 0.0]; + let f = faces(&frame, &walls, &[0.0], &[0.0]); + assert_eq!(f[0], 1.0); + assert_eq!((f[1], f[2]), (0.0, 0.0)); // Rolle Wand, Quelle 0 + assert!((f[3] - 1.9).abs() < 1e-9); // Südseite bei z = -0.1 + // hinter dem Betrachter: nichts + let walls = [1.0, 0.0, -5.0, 4.0, -5.0, 0.2, 3.0, 0.0]; + assert_eq!(faces(&frame, &walls, &[0.0], &[0.0]), vec![0.0]); + } + + #[test] + fn t_stoss_verlaengert_das_ende() { + // Wand 0 endet an der Seite von Wand 1 (Dicke 0.4): Verlängerung = halbe Dicke 0.2. + let f = wall_extensions(&[ + 2.0, // + 0.0, 0.0, 0.0, 3.0, 0.0, 0.1, // Wand 0 endet bei (3, 0) + 0.0, 3.0, -2.0, 3.0, 2.0, 0.2, // Wand 1 läuft durch (3, 0) + ]); + assert_eq!(f, vec![2.0, 0.0, 0.2, 0.0, 0.0]); + } + #[test] fn unsinn_ist_leer() { assert!(clip_segments(&[f64::NAN], &[0.0]).is_empty()); diff --git a/src-tauri/core/src/web/plan_elevation.rs b/src-tauri/core/src/web/plan_elevation.rs index 4234203a..047d4718 100644 --- a/src-tauri/core/src/web/plan_elevation.rs +++ b/src-tauri/core/src/web/plan_elevation.rs @@ -25,3 +25,15 @@ pub fn elevation_shadows_flat(walls: &[f64], slabs: &[f64]) -> Vec { pub fn elevation_xor_outline_flat(polys: &[f64]) -> Vec { crate::plan_elevation::xor_outline(polys) } + +/// Sichtbare Wand-, Decken- und Dachflächen in Ansichts-Koordinaten; Unsinn → leer. +#[wasm_bindgen] +pub fn elevation_faces_flat(frame: &[f64], walls: &[f64], slabs: &[f64], roofs: &[f64]) -> Vec { + crate::plan_elevation::faces(frame, walls, slabs, roofs) +} + +/// Eck-Verlängerung der Wandenden für die Ansicht; Unsinn → leer. +#[wasm_bindgen] +pub fn elevation_wall_extensions_flat(input: &[f64]) -> Vec { + crate::plan_elevation::wall_extensions(input) +} diff --git a/src/plan/toElevation.test.ts b/src/plan/toElevation.test.ts index 9a4e6838..f57637d2 100644 --- a/src/plan/toElevation.test.ts +++ b/src/plan/toElevation.test.ts @@ -16,9 +16,6 @@ import { collectElevationFaces, elevationFrame, generateElevationPlan, - projectFace, - projectPoint, - wallWorldFaces, } from "./toElevation"; // Betrachter im Süden (world z = −2), Blick nach +Z (in die Szene). Damit liegt @@ -41,44 +38,29 @@ function wall(over: Partial = {}): RWall { } describe("toElevation — Projektion + Culling", () => { - it("projiziert einen Weltpunkt auf (u, v, depth)", () => { - const frame = elevationFrame(PLANE_SOUTH); - // Punkt auf der Süd-Fassade (z ≈ −0.1), x = 4, Höhe 3. - const p = projectPoint(frame, [4, 3, -0.1]); - expect(p.v).toBeCloseTo(3, 6); // v = absolute Höhe - expect(p.depth).toBeCloseTo(1.9, 6); // −0.1 − (−2) = 1.9 hinter der Ebene - // u = dot(rel, U); U (entspiegelt, Blick +z ⇒ rechts = +x) = [1, 0, 0], - // P.x = −1 → u = 4 − (−1) = 5. - expect(p.u).toBeCloseTo(5, 6); - }); - it("Süd-Langseite einer Wand: erwartetes (u, v)-Rechteck + Tiefe, Rückseite gecullt", () => { const frame = elevationFrame(PLANE_SOUTH); - const faces = wallWorldFaces(wall()); - const projected = faces.map((f) => projectFace(frame, f)); + const model: RModel3d = { walls: [wall()], slabs: [], meshes: [], roofLayers: [] }; + const visible = collectElevationFaces(model, frame); // Genau EINE sichtbare Fläche (die Süd-Langseite); alle anderen sind // Rückseiten oder streifend (Deckel/Boden/Stirnkappen). - const visible = projected.filter((p) => p !== null); expect(visible.length).toBe(1); - const face = visible[0]!; + const face = visible[0]; expect(face.wallId).toBe("W"); const us = face.pts.map((p) => p[0]); const vs = face.pts.map((p) => p[1]); - expect(Math.min(...us)).toBeCloseTo(1, 6); // x=0 → u=1 (P.x=−1) + // U (entspiegelt, Blick +z ⇒ rechts = +x) = [1, 0, 0], P.x = −1. + expect(Math.min(...us)).toBeCloseTo(1, 6); // x=0 → u=1 expect(Math.max(...us)).toBeCloseTo(5, 6); // x=4 → u=5 expect(Math.min(...vs)).toBeCloseTo(0, 6); expect(Math.max(...vs)).toBeCloseTo(3, 6); - expect(face.depth).toBeCloseTo(1.9, 6); + expect(face.depth).toBeCloseTo(1.9, 6); // z ≈ −0.1 − (−2) }); - it("Rückseiten-Culling: eine Fläche mit Normale VON der Ebene weg erscheint nicht", () => { + it("Rückseiten-Culling: eine Wand hinter dem Betrachter erscheint nicht", () => { const frame = elevationFrame(PLANE_SOUTH); - const faces = wallWorldFaces(wall()); - // Die +Quer-Fläche (Nord-Langseite, Normale [0,0,−1]·N = −1 … eigentlich die - // Süd-Seite ist sichtbar) — hier prüfen wir explizit die Rückseite: - const north = faces.find((f) => f.normal[2] > 0.5); // Normale zeigt +Z (= mit N) - expect(north).toBeDefined(); - expect(projectFace(frame, north!)).toBeNull(); + const model: RModel3d = { walls: [wall({ start: [0, -5], end: [4, -5] })], slabs: [], meshes: [], roofLayers: [] }; + expect(collectElevationFaces(model, frame)).toEqual([]); }); }); diff --git a/src/plan/toElevation.ts b/src/plan/toElevation.ts index 9c056000..fa23d785 100644 --- a/src/plan/toElevation.ts +++ b/src/plan/toElevation.ts @@ -76,7 +76,7 @@ const FRAME_MM = 0.18; * zeichnungs-Look) bleibt alles weiss — nur Kontur trägt Information. Im * FARBIG-Modus tragen die Flächen echte Bauteilfarbe: Wand/Dach die dominante * Schicht (s. {@link WorldFace.fill}, gesetzt in {@link wallWorldFaces}/ - * {@link roofWorldFacesAll}), Fenster/Türen feste, an `toWalls3d.ts` + * {@link collectRoofFaces}), Fenster/Türen feste, an `toWalls3d.ts` * (FRAME_RGB/GLASS_RGB/SILL_RGB/DOOR_LEAF_RGB) angelehnte Töne, damit Ansicht * und 3D konsistent wirken. */ @@ -179,271 +179,11 @@ export function projectPoint( }; } -// ── Welt-Flächen aus dem geflachten Modell ───────────────────────────────── +// ── Flächen aus dem geflachten Modell ────────────────────────────────────── /** Rolle einer Fläche (steuert Füllung/Stil in der Ansicht). */ export type FaceRole = "wall" | "slab" | "roof"; -/** Eine orientierte Welt-Fläche (konvexes Polygon + Aussennormale). */ -export interface WorldFace { - poly: V3[]; - normal: V3; - role: FaceRole; - /** Ursprungs-Wand (nur role "wall") — für Auswahl/Painter-Identität. */ - wallId?: string; - /** Ursprungs-Decke (nur role "slab"). */ - ceilingId?: string; - /** Ursprungs-Dach (nur role "roof"). */ - roofId?: string; - /** - * Bauteil-Farbe (dominante Wandschicht bzw. äusserste Dach-/Eindeckungs- - * schicht) für den Farbig-Modus (s. {@link ElevationOptions.mono}). Fehlt - * ⇒ Fallback auf die neutrale Rollen-Füllung. - */ - fill?: RRgb; -} - -function normalize3(a: V3): V3 { - const l = Math.hypot(a[0], a[1], a[2]) || 1; - return [a[0] / l, a[1] / l, a[2] / l]; -} - -/** - * Die sechs Quader-Flächen EINER Wand-Box (RWall) in Weltkoordinaten mit - * Aussennormalen: zwei Langseiten (Fassaden-Aussenflächen, Normale horizontal - * quer zur Wand), zwei Stirnkappen (Normale entlang der Achse), Deckel/Boden. - */ -export function wallWorldFaces(w: RWall): WorldFace[] { - const sx = w.start[0]; - const sz = w.start[1]; - const ex = w.end[0]; - const ez = w.end[1]; - const ax = ex - sx; - const az = ez - sz; - const len = Math.hypot(ax, az); - if (len < 1e-9 || w.height <= EPS) return []; - const aHat: V3 = [ax / len, 0, az / len]; - const nHat: V3 = [az / len, 0, -ax / len]; // horizontale Quer-Normale - const ht = w.thickness / 2; - const zb = w.baseElevation; - const zt = w.baseElevation + w.height; - // Ecke bei (Achsen-Meter sAlong, Quer-Versatz tOff, Höhe y). - const corner = (sAlong: number, tOff: number, y: number): V3 => [ - sx + aHat[0] * sAlong + nHat[0] * tOff, - y, - sz + aHat[2] * sAlong + nHat[2] * tOff, - ]; - const faces: WorldFace[] = []; - // +Quer (Aussenfläche A) - faces.push({ - role: "wall", - normal: nHat, - poly: [corner(0, ht, zb), corner(len, ht, zb), corner(len, ht, zt), corner(0, ht, zt)], - }); - // −Quer (Aussenfläche B) - faces.push({ - role: "wall", - normal: [-nHat[0], -nHat[1], -nHat[2]], - poly: [corner(0, -ht, zb), corner(0, -ht, zt), corner(len, -ht, zt), corner(len, -ht, zb)], - }); - // Stirn Start (−Achse) - faces.push({ - role: "wall", - normal: [-aHat[0], -aHat[1], -aHat[2]], - poly: [corner(0, -ht, zb), corner(0, ht, zb), corner(0, ht, zt), corner(0, -ht, zt)], - }); - // Stirn Ende (+Achse) - faces.push({ - role: "wall", - normal: aHat, - poly: [corner(len, -ht, zb), corner(len, -ht, zt), corner(len, ht, zt), corner(len, ht, zb)], - }); - // Deckel (+Höhe) - faces.push({ - role: "wall", - normal: [0, 1, 0], - poly: [corner(0, -ht, zt), corner(0, ht, zt), corner(len, ht, zt), corner(len, -ht, zt)], - }); - // Boden (−Höhe) - faces.push({ - role: "wall", - normal: [0, -1, 0], - poly: [corner(0, -ht, zb), corner(len, -ht, zb), corner(len, ht, zb), corner(0, ht, zb)], - }); - for (const f of faces) { - f.wallId = w.wallId; - f.fill = w.color; - } - return faces; -} - -/** - * Enthält der Wandkörper von `w` (Achse ± `half`) den Punkt `p`? Perpendikular- - * abstand ≤ half UND Projektion innerhalb der Achsenlänge (mit half-Toleranz an - * den Enden). Basis der T-/L-/X-Stoss-Erkennung für die Eckverlängerung. - */ -function wallBodyContains(w: Wall, half: number, p: Vec2): boolean { - const dx = w.end.x - w.start.x; - const dy = w.end.y - w.start.y; - const len = Math.hypot(dx, dy); - if (len < 1e-9) return false; - const ux = dx / len; - const uy = dy / len; - const rx = p.x - w.start.x; - const ry = p.y - w.start.y; - const along = rx * ux + ry * uy; - const perp = Math.abs(-uy * rx + ux * ry); - return along >= -1e-6 && along <= len + 1e-6 && perp <= half + 1e-6; -} - -/** - * Achsen-Verlängerung je Wandende (Meter, ≥0) für die ANSICHT: axis-zu-axis - * gebaute Wandboxen (s. {@link wallWorldFaces}) decken einen Eckknoten nicht - * voll ab — an jeder Ecke bleibt ein dreieckiger Spalt der Grösse der halben - * Dicke der anschliessenden Wand (sichtbar als Kerbe in der Silhouette bzw. als - * Lücke im Schlagschatten). Jedes Wandende wird darum bis zur AUSSENFLÄCHE der - * dicksten anstossenden anderen Wand verlängert — die Boxen überlappen dann im - * Eckbereich vollständig. - * - * Erfasst L-Ecken (Endpunkt teilt sich mit anderem Endpunkt), T-Stösse (Ende - * trifft die SEITE/Achse einer durchlaufenden Wand) UND versetzte Stösse — über - * {@link wallBodyContains} statt exakter Endpunkt-Gleichheit. Bewusst eine - * EIGENE, tolerante Näherung statt der Gehrungs-Logik aus `model/joins.ts` (die - * bedient 2D-Grundriss/3D-Viewer und bleibt unangetastet): die Ansicht ist ein - * Painter-Silhouetten-Verfahren, dem eine leichte Eck-Überlappung nichts - * ausmacht — anders als Grundriss-Poché/Schnitt-Dominanz, die exakte Gehrung - * brauchen. - */ -function wallCornerExtensions(project: Project, walls: Wall[]): Map { - const thicknessOf = (w: Wall): number => { - try { - return wallTypeThickness(getWallType(project, w)); - } catch { - return 0.2; - } - }; - const halves = new Map(); - for (const w of walls) halves.set(w.id, thicknessOf(w) / 2); - const extAt = (w: Wall, p: Vec2): number => { - let maxOther = 0; - for (const other of walls) { - if (other.id === w.id) continue; - const ho = halves.get(other.id) ?? 0.1; - if (wallBodyContains(other, ho, p)) maxOther = Math.max(maxOther, ho); - } - return maxOther; - }; - const out = new Map(); - for (const w of walls) out.set(w.id, { start: extAt(w, w.start), end: extAt(w, w.end) }); - return out; -} - -/** - * Verlängert die (offset-freien, s. {@link resolveWallBands} `layered:false`) - * Wand-Boxen des Ansichts-Modells an gemeinsamen Eck-Knoten (s. - * {@link wallCornerExtensions}), damit Fassaden-Ecken in der Ansicht ohne - * dreieckige Kerbe/Schattenlücke erscheinen. Wirkt PRO GESCHOSS (`floorId`), - * damit sich nur Wände desselben Grundrisses zu Ecken verbinden. Mutiert die - * `start`/`end`-Koordinaten der jeweils äussersten Teilstücke (Pfeiler vor der - * ersten bzw. nach der letzten Öffnung) in-place. - * - * WICHTIG — nur Wände verlängern, die etwa PARALLEL zur Ansichtsebene laufen - * (Fassaden-Silhouette): eine facaden-SENKRECHTE Wand (Innenwand quer zur - * Blickrichtung) würde sonst entlang ihrer Achse in die Tiefe — u. U. VOR die - * Fassade auf den Betrachter zu — geschoben und erschiene als störender - * Balken. `uModel` ist die Ansichts-u-Achse in Grundriss-Koordinaten (Modell - * x,y = Welt x,z), gegen die die Wandachse projiziert wird. - */ -function extendWallCornersForElevation(project: Project, rwalls: RWall[], uModel: Vec2): void { - const byFloor = new Map(); - for (const w of project.walls) { - const key = w.floorId ?? ""; - const list = byFloor.get(key); - if (list) list.push(w); - else byFloor.set(key, [w]); - } - const byWallId = new Map(); - for (const rw of rwalls) { - const list = byWallId.get(rw.wallId); - if (list) list.push(rw); - else byWallId.set(rw.wallId, [rw]); - } - const closeTo = (a: RVec2, b: Vec2): boolean => Math.abs(a[0] - b.x) < 1e-6 && Math.abs(a[1] - b.y) < 1e-6; - for (const floorWalls of byFloor.values()) { - const ext = wallCornerExtensions(project, floorWalls); - for (const w of floorWalls) { - const e = ext.get(w.id); - if (!e || (e.start <= EPS && e.end <= EPS)) continue; - const pieces = byWallId.get(w.id); - if (!pieces) continue; - const dx = w.end.x - w.start.x; - const dz = w.end.y - w.start.y; - const len = Math.hypot(dx, dz); - if (len < 1e-9) continue; - const ux = dx / len; - const uz = dz / len; - // Parallelität zur Ansichtsebene: |Achse · u| ≈ 1 (parallel) … 0 (senkrecht). - // Facaden-senkrechte Wände NICHT verlängern (sonst Tiefen-Protrusion). - if (Math.abs(ux * uModel.x + uz * uModel.y) < 0.35) continue; - if (e.start > EPS) { - const first = pieces.find((p) => closeTo(p.start, w.start)); - if (first) first.start = [first.start[0] - ux * e.start, first.start[1] - uz * e.start]; - } - if (e.end > EPS) { - const last = pieces.find((p) => closeTo(p.end, w.end)); - if (last) last.end = [last.end[0] + ux * e.end, last.end[1] + uz * e.end]; - } - } - } -} - -/** - * Die Flächen EINER Deckenplatte (RSlab): Deckel + Boden (Umriss bei zTop/zBottom) - * und je Umrisskante eine Seitenfläche (Stirn). Die Seitennormalen werden über - * den Grundriss-Schwerpunkt nach AUSSEN orientiert (unabhängig von der Umriss- - * Windung). Der Umriss (Modell x,y) wird als Welt (x, y=Höhe, z=y) gehoben. - */ -export function slabWorldFaces(s: RSlab): WorldFace[] { - const n = s.outline.length; - if (n < 3 || s.zTop - s.zBottom <= EPS) return []; - // Grundriss-Schwerpunkt (für die Aussen-Orientierung der Seitenflächen). - let cx = 0; - let cz = 0; - for (const p of s.outline) { - cx += p[0]; - cz += p[1]; - } - cx /= n; - cz /= n; - const bottom: V3[] = s.outline.map((p) => [p[0], s.zBottom, p[1]]); - const top: V3[] = s.outline.map((p) => [p[0], s.zTop, p[1]]); - const faces: WorldFace[] = []; - faces.push({ role: "slab", normal: [0, 1, 0], poly: top.slice() }); - faces.push({ role: "slab", normal: [0, -1, 0], poly: bottom.slice().reverse() }); - for (let i = 0; i < n; i++) { - const j = (i + 1) % n; - const ex = s.outline[j][0] - s.outline[i][0]; - const ez = s.outline[j][1] - s.outline[i][1]; - // Kandidat-Normale horizontal quer zur Kante; nach aussen orientieren. - let m: V3 = normalize3([ez, 0, -ex]); - const midX = (s.outline[i][0] + s.outline[j][0]) / 2; - const midZ = (s.outline[i][1] + s.outline[j][1]) / 2; - if (m[0] * (midX - cx) + m[2] * (midZ - cz) < 0) m = [-m[0], -m[1], -m[2]]; - faces.push({ - role: "slab", - normal: m, - poly: [bottom[i], bottom[j], top[j], top[i]], - }); - } - for (const f of faces) { - f.ceilingId = s.ceilingId; - f.fill = s.color; - } - return faces; -} - -// ── Projektion + Sichtbarkeit ────────────────────────────────────────────── - /** Eine in die Ansicht projizierte, sichtbare Fläche. */ export interface ProjectedFace { pts: Array<[number, number]>; @@ -462,137 +202,164 @@ export interface ProjectedFace { normal?: V3; } -/** - * Projiziert eine Welt-Fläche und entscheidet die Sichtbarkeit: - * • Rückseiten-Culling: Normale muss GEGEN die Blickrichtung zeigen (N·Nf < 0). - * • Vor/Hinter: die mittlere Tiefe muss hinter der Ebene liegen (depth > 0). - * Sonst `null` (Fläche erscheint nicht). - */ -export function projectFace(frame: ElevationFrame, face: WorldFace): ProjectedFace | null { - const facing = frame.N[0] * face.normal[0] + frame.N[1] * face.normal[1] + frame.N[2] * face.normal[2]; - if (facing >= -FACING_EPS) return null; // Rückseite oder streifend → unsichtbar - const pts: Array<[number, number]> = []; - let depthSum = 0; - let depthMin = Infinity; - let depthMax = -Infinity; - for (const w of face.poly) { - const p = projectPoint(frame, w); - pts.push([p.u, p.v]); - depthSum += p.depth; - depthMin = Math.min(depthMin, p.depth); - depthMax = Math.max(depthMax, p.depth); - } - const depth = depthSum / face.poly.length; - if (depth <= EPS) return null; // vor der Ebene → ignorieren - return { - pts, - depth, - depthMin, - depthMax, - role: face.role, - wallId: face.wallId, - ceilingId: face.ceilingId, - roofId: face.roofId, - fill: face.fill, - normal: face.normal, - }; +const ROLES: FaceRole[] = ["wall", "slab", "roof"]; + +/** Ansichts-Frame flach für den Kern (`[P, N, U]`). */ +function encodeFrame(frame: ElevationFrame): Float64Array { + return Float64Array.from([...frame.P, ...frame.N, ...frame.U]); } /** - * Sammelt alle sichtbaren, projizierten Flächen des Modells (Wände + Decken), - * bereits rückseiten-gecullt und vor der Ebene verworfen. Reihenfolge = Emissions- - * reihenfolge des Modells (NICHT tiefensortiert) — die Painter-Sortierung macht - * der Aufrufer. + * Projiziert Wand-Quader (sechs Flächen je Wand-Box, Aussennormalen), Decken-Prismen (Deckel, + * Boden, Stirnflächen) und Dachflächen/Giebel in die Ansicht und behält die sichtbaren + * (Rückseiten-Culling: Normale gegen die Blickrichtung, mittlere Tiefe hinter der Ebene). + * Rechnet der Kern (`plan_elevation.rs`, [K3c]); hier nur Ein-/Ausgabe samt Herkunft (IDs, Farbe). + * Reihenfolge = Emissionsreihenfolge des Modells (NICHT tiefensortiert) — die Painter-Sortierung + * macht der Aufrufer. */ -export function collectElevationFaces(model: RModel3d, frame: ElevationFrame): ProjectedFace[] { - const out: ProjectedFace[] = []; - for (const w of model.walls) { - for (const f of wallWorldFaces(w)) { - const pf = projectFace(frame, f); - if (pf) out.push(pf); +function projectFaces( + frame: ElevationFrame, + walls: RWall[], + slabs: RSlab[], + roofs: Array<{ id: string; fill: RRgb; planes: V3[][]; gables: V3[][] }>, +): ProjectedFace[] { + const w: number[] = [walls.length]; + for (const x of walls) w.push(x.start[0], x.start[1], x.end[0], x.end[1], x.thickness, x.height, x.baseElevation); + const sl: number[] = [slabs.length]; + for (const x of slabs) { + sl.push(x.zBottom, x.zTop, x.outline.length); + for (const p of x.outline) sl.push(p[0], p[1]); + } + const r: number[] = [roofs.length]; + for (const roof of roofs) { + r.push(roof.planes.length, roof.gables.length); + for (const poly of [...roof.planes, ...roof.gables]) { + r.push(poly.length); + for (const p of poly) r.push(p[0], p[1], p[2]); } } - for (const s of model.slabs) { - for (const f of slabWorldFaces(s)) { - const pf = projectFace(frame, f); - if (pf) out.push(pf); + const f = core().elevation_faces_flat(encodeFrame(frame), Float64Array.from(w), Float64Array.from(sl), Float64Array.from(r)); + const out: ProjectedFace[] = []; + for (let k = 0, i = 1; k < (f[0] ?? 0); k++) { + const role = ROLES[f[i]]; + const src = f[i + 1]; + const count = f[i + 8]; + const pts = new Array<[number, number]>(count); + for (let j = 0; j < count; j++) pts[j] = [f[i + 9 + 2 * j], f[i + 10 + 2 * j]]; + const face: ProjectedFace = { + pts, + depth: f[i + 2], + depthMin: f[i + 3], + depthMax: f[i + 4], + role, + normal: [f[i + 5], f[i + 6], f[i + 7]], + }; + if (role === "wall") { + face.wallId = walls[src].wallId; + face.fill = walls[src].color; + } else if (role === "slab") { + face.ceilingId = slabs[src].ceilingId; + face.fill = slabs[src].color; + } else { + face.roofId = roofs[src].id; + face.fill = roofs[src].fill; } + out.push(face); + i += 9 + 2 * count; } return out; } -// ── Dächer ────────────────────────────────────────────────────────────────── +/** + * Sammelt alle sichtbaren, projizierten Flächen des Modells (Wände + Decken), bereits + * rückseiten-gecullt und vor der Ebene verworfen. + */ +export function collectElevationFaces(model: RModel3d, frame: ElevationFrame): ProjectedFace[] { + return projectFaces(frame, model.walls, model.slabs, []); +} /** - * Die Welt-Flächen ALLER Dächer des Projekts: Dachflächen (Aufsicht-Polygone der - * roofGeometry, Normale aufwärts orientiert) + Giebel (vertikale Endflächen, - * Normale vom Dach-Schwerpunkt weg nach aussen). Modell [x,y,z=Höhe] → Welt - * (x, y=Höhe, z=y), dieselbe Konvention wie emitRoofs/pickGeometry. Die - * Materialdicke bleibt für die Ansicht unberücksichtigt (Silhouette genügt — - * die Untersicht ist rückseiten-gecullt ohnehin unsichtbar). + * Dachflächen (Aufsicht-Polygone der roofGeometry) und Giebel ALLER Dächer, projiziert. Modell + * [x, y, Höhe]; die Eindeckungsfarbe (äusserste Schicht bzw. `roof.color`) entspricht `emitRoofs` + * des 3D-Viewers. Die Materialdicke bleibt unberücksichtigt (Silhouette genügt). */ -export function roofWorldFacesAll(project: Project): WorldFace[] { - const out: WorldFace[] = []; - for (const roof of project.roofs ?? []) { - const eavesZ = roofBaseElevation(project, roof); - const g = roofGeometry(roof, eavesZ); - // Äusserste Schicht (Eindeckung) bzw. `roof.color`-Übersteuerung — dieselbe - // Farbwahl wie {@link emitRoofs} (3D-Viewer), damit Ansicht/3D konsistent - // wirken. Ohne auflösbare Schicht der neutrale Dach-Fallback. +function collectRoofFaces(project: Project, frame: ElevationFrame): ProjectedFace[] { + const roofs = (project.roofs ?? []).map((roof) => { + const g = roofGeometry(roof, roofBaseElevation(project, roof)); const outer = roofLayers(project, roof)[0]; const fill: RRgb = roof.color ? hexToRgb(roof.color, ROOF_RGB_FALLBACK) : outer?.componentId ? hexToRgb(getComponent(project, outer.componentId).color, ROOF_RGB_FALLBACK) : ROOF_RGB_FALLBACK; - // Dach-Schwerpunkt (Welt) für die Aussen-Orientierung der Giebel. - let cx = 0; - let cy = 0; - let cz = 0; - let cn = 0; - for (const pl of g.planes) { - for (const p of pl.pts) { - cx += p[0]; - cy += p[2]; - cz += p[1]; - cn++; - } - } - if (cn === 0) continue; - cx /= cn; - cy /= cn; - cz /= cn; - const newell = (poly: V3[]): V3 => { - let nx = 0; - let ny = 0; - let nz = 0; - for (let i = 0; i < poly.length; i++) { - const a = poly[i]; - const b = poly[(i + 1) % poly.length]; - nx += (a[1] - b[1]) * (a[2] + b[2]); - ny += (a[2] - b[2]) * (a[0] + b[0]); - nz += (a[0] - b[0]) * (a[1] + b[1]); - } - return normalize3([nx, ny, nz]); + return { + id: roof.id, + fill, + planes: g.planes.map((pl) => pl.pts.map((p) => [p[0], p[1], p[2]] as V3)), + gables: g.gables.map((gb) => gb.map((p) => [p[0], p[1], p[2]] as V3)), }; - for (const pl of g.planes) { - const poly: V3[] = pl.pts.map((p) => [p[0], p[2], p[1]]); - let n = newell(poly); - // Dachflächen zeigen aufwärts (Welt-Y). - if (n[1] < 0) n = [-n[0], -n[1], -n[2]]; - out.push({ role: "roof", normal: n, poly, roofId: roof.id, fill }); - } - for (const gable of g.gables) { - const poly: V3[] = gable.map((p) => [p[0], p[2], p[1]]); - if (poly.length < 3) continue; - let n = newell(poly); - // Giebel zeigen vom Dach-Schwerpunkt weg nach aussen. - const toC: V3 = [cx - poly[0][0], cy - poly[0][1], cz - poly[0][2]]; - if (n[0] * toC[0] + n[1] * toC[1] + n[2] * toC[2] > 0) n = [-n[0], -n[1], -n[2]]; - out.push({ role: "roof", normal: n, poly, roofId: roof.id, fill }); + }); + return projectFaces(frame, [], [], roofs); +} + +/** + * Verlängert die (offset-freien) Wand-Boxen des Ansichts-Modells an gemeinsamen Eck-Knoten, damit + * Fassaden-Ecken in der Ansicht ohne dreieckige Kerbe/Schattenlücke erscheinen: jedes Wandende + * reicht bis zur AUSSENFLÄCHE der dicksten anstossenden anderen Wand desselben Geschosses (L-Ecken, + * T-Stösse, versetzte Stösse). Bewusst eine EIGENE, tolerante Näherung statt der Gehrungs-Logik aus + * `model/joins.ts`; die Mengen rechnet der Kern (`plan_elevation.rs`). + * + * Nur Wände etwa PARALLEL zur Ansichtsebene werden verlängert (Fassaden-Silhouette): eine + * fassaden-SENKRECHTE Wand würde sonst entlang ihrer Achse in die Tiefe geschoben. `uModel` ist die + * Ansichts-u-Achse in Grundriss-Koordinaten. Mutiert `start`/`end` der jeweils äussersten + * Teilstücke (Pfeiler vor der ersten bzw. nach der letzten Öffnung) in-place. + */ +function extendWallCornersForElevation(project: Project, rwalls: RWall[], uModel: Vec2): void { + const floors = new Map(); + const b: number[] = [project.walls.length]; + for (const w of project.walls) { + const key = w.floorId ?? ""; + if (!floors.has(key)) floors.set(key, floors.size); + let thickness = 0.2; + try { + thickness = wallTypeThickness(getWallType(project, w)); + } catch { + thickness = 0.2; } + b.push(floors.get(key)!, w.start.x, w.start.y, w.end.x, w.end.y, thickness / 2); } - return out; + const ext = core().elevation_wall_extensions_flat(Float64Array.from(b)); + if (ext.length === 0) return; + const byWallId = new Map(); + for (const rw of rwalls) { + const list = byWallId.get(rw.wallId); + if (list) list.push(rw); + else byWallId.set(rw.wallId, [rw]); + } + const closeTo = (a: RVec2, v: Vec2): boolean => Math.abs(a[0] - v.x) < 1e-6 && Math.abs(a[1] - v.y) < 1e-6; + project.walls.forEach((w, k) => { + const eStart = ext[1 + 2 * k]; + const eEnd = ext[2 + 2 * k]; + if (eStart <= EPS && eEnd <= EPS) return; + const pieces = byWallId.get(w.id); + if (!pieces) return; + const dx = w.end.x - w.start.x; + const dz = w.end.y - w.start.y; + const len = Math.hypot(dx, dz); + if (len < 1e-9) return; + const ux = dx / len; + const uz = dz / len; + // Parallelität zur Ansichtsebene: |Achse · u| ≈ 1 (parallel) … 0 (senkrecht). + if (Math.abs(ux * uModel.x + uz * uModel.y) < 0.35) return; + if (eStart > EPS) { + const first = pieces.find((p) => closeTo(p.start, w.start)); + if (first) first.start = [first.start[0] - ux * eStart, first.start[1] - uz * eStart]; + } + if (eEnd > EPS) { + const last = pieces.find((p) => closeTo(p.end, w.end)); + if (last) last.end = [last.end[0] + ux * eEnd, last.end[1] + uz * eEnd]; + } + }); } // ── Fenster/Türen ─────────────────────────────────────────────────────────── @@ -1022,12 +789,7 @@ export function generateElevationPlan( const model = projectToModel3d(project, { layeredWalls: false }); // Ansichts-u-Achse in Grundriss-Koordinaten (Welt x,z = Modell x,y). extendWallCornersForElevation(project, model.walls, { x: frame.U[0], y: frame.U[2] }); - let faces = collectElevationFaces(model, frame); - // Dächer analytisch (roofGeometry) — nicht Teil von RModel3d walls/slabs. - for (const rf of roofWorldFacesAll(project)) { - const pf = projectFace(frame, rf); - if (pf) faces.push(pf); - } + let faces = [...collectElevationFaces(model, frame), ...collectRoofFaces(project, frame)]; // Grafik-Kategorie einer projizierten Fläche (Quell-Wand/-Decke/-Dach) — für // Ebenen-Panel-Sichtbarkeit UND -Dimmen (s. u.). const categoryCodeOfFace = (f: ProjectedFace): string | undefined => { From 7aa6d394ec452a497efb836bc690d8d1494c043d Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:16:33 +0100 Subject: [PATCH 09/31] [K3c] Ansicht: Oeffnungen (Rahmen, Glas, Sprossen, Sims, Symbol) in Rust; collectOpenings loest nur noch Typen auf --- TODO.md | 2 +- src-tauri/core/src/plan_elevation.rs | 291 ++++++++++++++++++++ src-tauri/core/src/web/plan_elevation.rs | 6 + src/plan/toElevation.ts | 327 +++++------------------ 4 files changed, 358 insertions(+), 268 deletions(-) diff --git a/TODO.md b/TODO.md index 2a4fa896..ceaec3b3 100644 --- a/TODO.md +++ b/TODO.md @@ -107,7 +107,7 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern - ◐ **[K3c] Schnitt und Ansicht** (`toSection`, `toElevation`, `meshSection`) im selben Puffer-Format. ✅ Schnitt-Bänder: Dominanz-Subtraktion, Verschmelzung, Rechteck-Vereinigung (`plan_section.rs`, 28.10.). ✅ Ansicht: Verdeckungs-Clipping, Punkt-Verdeckung, Schlagschatten, XOR-Umriss (`plan_elevation.rs`, 28.10.). - ✅ Ansicht: Flächen (Wand-Quader, Decken-Prismen, Dach/Giebel) projizieren + Rückseiten-Culling, Eck-Verlängerung (`plan_elevation.rs`). + ✅ Ansicht: Flächen (Wand-Quader, Decken-Prismen, Dach/Giebel) projizieren + Rückseiten-Culling, Eck-Verlängerung, Öffnungen (Rahmen, Glasfelder, Sprossen, Sims, SIA-Symbol) (`plan_elevation.rs`). - ○ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. 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. diff --git a/src-tauri/core/src/plan_elevation.rs b/src-tauri/core/src/plan_elevation.rs index 8a4c978f..82379ce5 100644 --- a/src-tauri/core/src/plan_elevation.rs +++ b/src-tauri/core/src/plan_elevation.rs @@ -31,6 +31,19 @@ //! Reihenfolge: Wände, Decken, Dächer (je Quelle in Modellreihenfolge); nur sichtbare Flächen //! (Rückseiten-Culling, Tiefe > 0). //! +//! ## Öffnungen +//! `openings(frame, in)` mit `in = [n, Öffnung × n]`, Öffnung = +//! ```text +//! sx, sz, ex, ez, dicke, von, bis, zUnten, zOben, +//! istTuer, glasBlatt, glasAnteil (NaN = 1), +//! rahmenbreite, kaempferHoehe, sprossenZeilen (NaN = 1), sprossenSpalten (NaN = 1), +//! bankAn, typArt (0 fest, 1 dreh, 2 kipp, 3 drehkipp, 4 schiebe), +//! nFluegel, (pfosten, pfostenBreite (NaN), autoBreite (0/1), breite (NaN), art (-1 = typArt), bandLinks) × nFluegel +//! ``` +//! → `[n, (ok, tiefe, istTuer, 8 Ecken, Listen) × n]`; `ok` 0 = nicht sichtbar (sonst nichts mehr). +//! Listen in dieser Reihenfolge, je `[anzahl, Einträge]`: glas, tuerblatt (Vierecke à 8 Werte), +//! teilungen (Linien à 4), fluegel (Vierecke), bank (Vierecke), symbol (Linien). +//! //! ## Eck-Verlängerung //! `wall_extensions(in)` mit `in = [n, (geschoss, sx, sy, ex, ey, halbe dicke) × n]` → //! `[n, (verlStart, verlEnde) × n]`: Wandenden bis zur Aussenfläche der dicksten anstossenden Wand @@ -710,6 +723,284 @@ pub fn wall_extensions(inp: &[f64]) -> Vec { f } +// ── Öffnungen ────────────────────────────────────────────────────────────── + +type Quad = [P; 4]; +type Line = (P, P); + +#[derive(Default)] +struct OpeningOut { + glass: Vec, + door_leaf: Vec, + divisions: Vec, + sash_rects: Vec, + sill: Vec, + symbol: Vec, +} + +fn lerp(a: P, b: P, t: f64) -> P { + (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t) +} + +fn quad_at(q: &Quad, fa: f64, fz: f64) -> P { + lerp(lerp(q[0], q[1], fa), lerp(q[3], q[2], fa), fz) +} + +fn rect(q: &Quad, fa0: f64, fa1: f64, fz0: f64, fz1: f64) -> Quad { + [quad_at(q, fa0, fz0), quad_at(q, fa1, fz0), quad_at(q, fa1, fz1), quad_at(q, fa0, fz1)] +} + +/// Projiziert die zum Betrachter zeigende Wand-Langseite der Öffnung; `None` ohne sichtbare Seite. +fn project_opening_rect(f: &Frame, o: &[f64]) -> Option<(Quad, f64)> { + let (sx, sz) = (o[0], o[1]); + let ax = o[2] - o[0]; + let az = o[3] - o[1]; + let len = hypot2(ax, az); + let (from, to, z_bottom, z_top) = (o[5], o[6], o[7], o[8]); + if len < 1e-9 || to - from <= EPS || z_top - z_bottom <= EPS { + return None; + } + let a_hat: V3 = [ax / len, 0.0, az / len]; + let n_hat: V3 = [az / len, 0.0, -ax / len]; + let ht = o[4] / 2.0; + for side in [ht, -ht] { + let normal = if side > 0.0 { n_hat } else { neg(n_hat) }; + let facing = f.n[0] * normal[0] + f.n[1] * normal[1] + f.n[2] * normal[2]; + if facing >= -FACING_EPS { + continue; + } + let corner = |s_along: f64, y: f64| -> V3 { + [sx + a_hat[0] * s_along + n_hat[0] * side, y, sz + a_hat[2] * s_along + n_hat[2] * side] + }; + let world = [corner(from, z_bottom), corner(to, z_bottom), corner(to, z_top), corner(from, z_top)]; + let mut pts = [(0.0, 0.0); 4]; + let mut depth_sum = 0.0; + for (k, w) in world.iter().enumerate() { + let (u, v, d) = project_point(f, *w); + pts[k] = (u, v); + depth_sum += d; + } + let depth = depth_sum / 4.0; + if depth <= EPS { + continue; + } + return Some((pts, depth)); + } + None +} + +fn layout_opening(o: &[f64], sashes: &[f64], pts: &Quad) -> OpeningOut { + let mut out = OpeningOut::default(); + let (from, to, z_bottom, z_top) = (o[5], o[6], o[7], o[8]); + let w = to - from; + let h = z_top - z_bottom; + if o[9] != 0.0 { + // Tür: Blatt-Fläche, bei Glasblatt mit Teilverglasung (Kämpferhöhe von OBEN). + if o[10] != 0.0 { + let ratio = max(0.05, min(1.0, if o[11].is_nan() { 1.0 } else { o[11] })); + if ratio >= 1.0 - EPS { + out.glass.push(rect(pts, 0.04, 0.96, 0.0, 0.97)); + } else { + let split_z = 0.97 * (1.0 - ratio); + out.glass.push(rect(pts, 0.04, 0.96, split_z, 0.97)); + out.door_leaf.push(rect(pts, 0.04, 0.96, 0.0, split_z)); + out.divisions.push((quad_at(pts, 0.04, split_z), quad_at(pts, 0.96, split_z))); + } + } else { + out.door_leaf.push(rect(pts, 0.04, 0.96, 0.0, 0.97)); + } + return out; + } + let fw = o[12]; + let fa = min(0.45, fw / max(w, 1e-6)); + let fz = min(0.45, fw / max(h, 1e-6)); + let transom = max(0.0, o[13]); + let f_tr = if transom > EPS && transom < h - fw { 1.0 - transom / h } else { 0.0 }; + let field_top = if f_tr > 0.0 { f_tr - fz / 2.0 } else { 1.0 - fz }; + let inner_w = max(1e-6, w * (1.0 - 2.0 * fa)); + let n_sashes = sashes.len() / 6; + let sash = |k: usize| &sashes[6 * k..6 * k + 6]; + let (mut fixed_sum, mut auto_count) = (0.0, 0usize); + for k in 0..n_sashes { + let sd = sash(k); + if sd[0] != 0.0 { + fixed_sum += max(0.0, if sd[1].is_nan() { 0.06 } else { sd[1] }); + } else if sd[2] == 0.0 { + fixed_sum += max(0.0, if sd[3].is_nan() { 0.0 } else { sd[3] }); + } else { + auto_count += 1; + } + } + let auto_w = if auto_count > 0 { max(0.02, (inner_w - fixed_sum) / auto_count as f64) } else { 0.0 }; + let mut cursor = fa; + for k in 0..n_sashes { + let sd = sash(k); + let sw = if sd[0] != 0.0 { + max(0.0, if sd[1].is_nan() { 0.06 } else { sd[1] }) + } else if sd[2] == 0.0 { + max(0.0, if sd[3].is_nan() { auto_w } else { sd[3] }) + } else { + auto_w + }; + let fa0 = cursor; + let fa1 = cursor + sw / w; + cursor = fa1; + if sd[0] != 0.0 { + let fm = (fa0 + fa1) / 2.0; + out.divisions.push((quad_at(pts, fm, fz), quad_at(pts, fm, field_top))); + continue; + } + out.sash_rects.push(rect(pts, fa0, fa1, fz, field_top)); + let spw = min(0.06, max(0.03, fw)); + let g_u = spw / max(w, 1e-6); + let g_v = spw / max(h, 1e-6); + let g_a = fa0 + g_u; + let g_b = fa1 - g_u; + let gz0 = fz + g_v; + let gz1 = field_top - g_v; + let rows = max(1.0, round(if o[14].is_nan() { 1.0 } else { o[14] })) as usize; + let cols = max(1.0, round(if o[15].is_nan() { 1.0 } else { o[15] })) as usize; + if g_b - g_a > 1e-6 && gz1 - gz0 > 1e-6 { + for r in 0..rows { + let rf = r as f64; + let rows_f = rows as f64; + let rz0 = gz0 + ((gz1 - gz0) * rf) / rows_f + if r > 0 { g_v / 2.0 } else { 0.0 }; + let rz1 = gz0 + ((gz1 - gz0) * (rf + 1.0)) / rows_f - if r < rows - 1 { g_v / 2.0 } else { 0.0 }; + if rz1 - rz0 <= 1e-6 { + continue; + } + for c in 0..cols { + let cf = c as f64; + let cols_f = cols as f64; + let ca0 = g_a + ((g_b - g_a) * cf) / cols_f + if c > 0 { g_u / 2.0 } else { 0.0 }; + let ca1 = g_a + ((g_b - g_a) * (cf + 1.0)) / cols_f - if c < cols - 1 { g_u / 2.0 } else { 0.0 }; + if ca1 - ca0 > 1e-6 { + out.glass.push(rect(pts, ca0, ca1, rz0, rz1)); + } + } + } + for r in 1..rows { + let rz = gz0 + ((gz1 - gz0) * r as f64) / rows as f64; + out.divisions.push((quad_at(pts, g_a, rz), quad_at(pts, g_b, rz))); + } + for c in 1..cols { + let ca = g_a + ((g_b - g_a) * c as f64) / cols as f64; + out.divisions.push((quad_at(pts, ca, gz0), quad_at(pts, ca, gz1))); + } + } + if fa1 < 1.0 - fa - 1e-6 { + out.divisions.push((quad_at(pts, fa1, fz), quad_at(pts, fa1, field_top))); + } + let kind = if sd[4] >= 0.0 { sd[4] as i64 } else { o[17] as i64 }; + let hinge_left = sd[5] != 0.0; + if kind == 1 || kind == 3 { + let apex = quad_at(pts, if hinge_left { g_a } else { g_b }, (gz0 + gz1) / 2.0); + let far_u = if hinge_left { g_b } else { g_a }; + out.symbol.push((quad_at(pts, far_u, gz0), apex)); + out.symbol.push((quad_at(pts, far_u, gz1), apex)); + } + if kind == 2 || kind == 3 { + let apex = quad_at(pts, (g_a + g_b) / 2.0, gz1); + out.symbol.push((quad_at(pts, g_a, gz0), apex)); + out.symbol.push((quad_at(pts, g_b, gz0), apex)); + } + if kind == 4 { + let zc = (gz0 + gz1) / 2.0; + let to_right = hinge_left; + let tail = if to_right { g_a } else { g_b }; + let head = if to_right { g_b } else { g_a }; + let barb = (head - tail) * 0.22; + let head_pt = quad_at(pts, head, zc); + out.symbol.push((quad_at(pts, tail, zc), head_pt)); + out.symbol.push((quad_at(pts, head - barb, gz0 + (gz1 - gz0) * 0.32), head_pt)); + out.symbol.push((quad_at(pts, head - barb, gz0 + (gz1 - gz0) * 0.68), head_pt)); + } + } + if o[16] != 0.0 { + let ov1 = 0.02 / max(w, 1e-6); + let ov2 = 0.05 / max(w, 1e-6); + let h1 = 0.035 / max(h, 1e-6); + let h2 = 0.025 / max(h, 1e-6); + out.sill.push(rect(pts, -ov1, 1.0 + ov1, -h1, 0.0)); + out.sill.push(rect(pts, -ov2, 1.0 + ov2, -(h1 + h2), -h1)); + } + if f_tr > 0.0 { + out.glass.push(rect(pts, fa, 1.0 - fa, f_tr + fz / 2.0, 1.0 - fz)); + out.divisions.push((quad_at(pts, 0.0, f_tr), quad_at(pts, 1.0, f_tr))); + } + out +} + +fn push_quads(f: &mut Vec, list: &[Quad]) { + f.push(list.len() as f64); + for q in list { + for p in q { + f.extend([p.0, p.1]); + } + } +} + +fn push_lines(f: &mut Vec, list: &[Line]) { + f.push(list.len() as f64); + for (a, b) in list { + f.extend([a.0, a.1, b.0, b.1]); + } +} + +pub fn openings(frame: &[f64], inp: &[f64]) -> Vec { + if frame.len() != 9 || frame.iter().any(|v| !v.is_finite()) { + return Vec::new(); + } + let fr = Frame { + p: [frame[0], frame[1], frame[2]], + n: [frame[3], frame[4], frame[5]], + u: [frame[6], frame[7], frame[8]], + }; + // Werte dürfen NaN tragen (= „fehlt"); sonst nur endliche. + let Some(n) = inp.first().copied().filter(|n| *n >= 0.0 && n.fract() == 0.0).map(|n| n as usize) else { + return Vec::new(); + }; + let mut f = vec![n as f64]; + let mut i = 1; + for _ in 0..n { + if i + 19 > inp.len() { + return Vec::new(); + } + let o = &inp[i..i + 19]; + let ns = o[18]; + if !(ns >= 0.0) || ns.fract() != 0.0 || i + 19 + 6 * ns as usize > inp.len() { + return Vec::new(); + } + let ns = ns as usize; + let sashes = &inp[i + 19..i + 19 + 6 * ns]; + i += 19 + 6 * ns; + let geo = &o[..9]; + if geo.iter().any(|v| !v.is_finite()) { + return Vec::new(); + } + match project_opening_rect(&fr, o) { + None => f.push(0.0), + Some((pts, depth)) => { + f.extend([1.0, depth, o[9]]); + for p in &pts { + f.extend([p.0, p.1]); + } + let out = layout_opening(o, sashes, &pts); + push_quads(&mut f, &out.glass); + push_quads(&mut f, &out.door_leaf); + push_lines(&mut f, &out.divisions); + push_quads(&mut f, &out.sash_rects); + push_quads(&mut f, &out.sill); + push_lines(&mut f, &out.symbol); + } + } + } + if i != inp.len() { + return Vec::new(); + } + f +} + #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/core/src/web/plan_elevation.rs b/src-tauri/core/src/web/plan_elevation.rs index 047d4718..a9be6172 100644 --- a/src-tauri/core/src/web/plan_elevation.rs +++ b/src-tauri/core/src/web/plan_elevation.rs @@ -37,3 +37,9 @@ pub fn elevation_faces_flat(frame: &[f64], walls: &[f64], slabs: &[f64], roofs: pub fn elevation_wall_extensions_flat(input: &[f64]) -> Vec { crate::plan_elevation::wall_extensions(input) } + +/// Projektion und Aufteilung (Glas, Flügel, Sprossen, Bank, Symbol) der Öffnungen; Unsinn → leer. +#[wasm_bindgen] +pub fn elevation_openings_flat(frame: &[f64], input: &[f64]) -> Vec { + crate::plan_elevation::openings(frame, input) +} diff --git a/src/plan/toElevation.ts b/src/plan/toElevation.ts index fa23d785..d3c6c487 100644 --- a/src/plan/toElevation.ts +++ b/src/plan/toElevation.ts @@ -32,7 +32,7 @@ // aufrecht. import { core } from "../engine/coreWasm"; -import type { DrawingLevel, Project, Vec2, Wall } from "../model/types"; +import type { DrawingLevel, Project, Vec2 } from "../model/types"; import { getComponent, getDoorType, @@ -125,9 +125,6 @@ function rgbToHex(c: RRgb): string { /** Numerisches Rauschen (Meter) für Tiefen-/Flächenvergleiche. */ const EPS = 1e-6; -/** Grazing-Schwelle: Flächen fast parallel zur Blickrichtung gelten als nicht - * sichtbar (Kanten-an, keine Fläche) — vermeidet Z-Rauschen an Laibungen. */ -const FACING_EPS = 1e-4; // ── Ebenen-Frame ──────────────────────────────────────────────────────────── @@ -164,21 +161,6 @@ export function elevationFrame(plane: SectionPlaneSpec): ElevationFrame { return { P: plane.point, N, U }; } -/** Projektion eines Weltpunkts in die Ansicht: u, v (Höhe) und Tiefe hinter der Ebene. */ -export function projectPoint( - frame: ElevationFrame, - w: V3, -): { u: number; v: number; depth: number } { - const rx = w[0] - frame.P[0]; - const ry = w[1] - frame.P[1]; - const rz = w[2] - frame.P[2]; - return { - u: rx * frame.U[0] + ry * frame.U[1] + rz * frame.U[2], - v: w[1], // absolute Höhe, wie die Schnitt-v-Konvention - depth: rx * frame.N[0] + ry * frame.N[1] + rz * frame.N[2], - }; -} - // ── Flächen aus dem geflachten Modell ────────────────────────────────────── /** Rolle einer Fläche (steuert Füllung/Stil in der Ansicht). */ @@ -392,90 +374,20 @@ interface ProjectedOpening { openingId?: string; } -/** - * Projiziert die Aussenfläche EINER Öffnung (Fenster/Tür) der Wirtswand: das - * Rechteck [from..to] × [zBottom..zTop] auf der zum Betrachter zeigenden - * Wand-Langseite (±T/2). Näherung: die Öffnung wird als planare Glasfläche BÜNDIG - * in der Aussenwandebene dargestellt (keine Laibungstiefe) — genügt für die - * Fassaden-Lesbarkeit. `null`, wenn keine Seite front-/hinter-Ebene liegt. - */ -function projectOpeningRect( - frame: ElevationFrame, - wall: Wall, - from: number, - to: number, - zBottom: number, - zTop: number, - thickness: number, -): ProjectedOpening | null { - const sx = wall.start.x; - const sz = wall.start.y; - const ax = wall.end.x - wall.start.x; - const az = wall.end.y - wall.start.y; - const len = Math.hypot(ax, az); - if (len < 1e-9 || to - from <= EPS || zTop - zBottom <= EPS) return null; - const aHat: V3 = [ax / len, 0, az / len]; - const nHat: V3 = [az / len, 0, -ax / len]; - const ht = thickness / 2; - // Kandidaten-Seiten (±T/2): die front-facing + hinter der Ebene liegende nehmen. - for (const side of [ht, -ht]) { - const normal: V3 = side > 0 ? nHat : [-nHat[0], -nHat[1], -nHat[2]]; - const facing = frame.N[0] * normal[0] + frame.N[1] * normal[1] + frame.N[2] * normal[2]; - if (facing >= -FACING_EPS) continue; - const corner = (sAlong: number, y: number): V3 => [ - sx + aHat[0] * sAlong + nHat[0] * side, - y, - sz + aHat[2] * sAlong + nHat[2] * side, - ]; - const world = [corner(from, zBottom), corner(to, zBottom), corner(to, zTop), corner(from, zTop)]; - const pts: Array<[number, number]> = []; - let depthSum = 0; - for (const w of world) { - const p = projectPoint(frame, w); - pts.push([p.u, p.v]); - depthSum += p.depth; - } - const depth = depthSum / world.length; - if (depth <= EPS) continue; - // pts-Reihenfolge: [unten-von, unten-bis, oben-bis, oben-von] — Basis für - // die (fa, fz)-Interpolation der Flügel-/Glasfelder in collectOpenings. - return { pts, depth, glass: [], doorLeaf: [], divisions: [], sashRects: [], sill: [], symbol: [], isDoor: false }; - } - return null; -} +/** Öffnungsart (`WindowSash.opening`/`WindowType.kind`) in der Kern-Kodierung. */ +const SASH_KIND: Record = { dreh: 1, kipp: 2, drehkipp: 3, schiebe: 4 }; /** - * Alle Öffnungs-Flächen (Fenster/Türen inkl. Legacy-Türen) des Projekts, auf die - * jeweilige Wand-Aussenseite projiziert. Thickness = WallType-Dicke (Fallback - * 0.2 m). Rein aus dem Projekt (nicht aus dem geflachten Modell), damit Rahmen+Glas - * unabhängig von der Segment-Aussparung der Wand-Box gezeichnet werden können. + * Alle Öffnungs-Flächen (Fenster/Türen inkl. Legacy-Türen) des Projekts, auf die jeweilige + * Wand-Aussenseite projiziert (Rahmen, Glasfelder je Flügel/Sprossenraster, Kämpfer, Sims, + * Öffnungssymbol nach SIA). Thickness = WallType-Dicke (Fallback 0.2 m). Rein aus dem Projekt + * (nicht aus dem geflachten Modell), damit Rahmen+Glas unabhängig von der Segment-Aussparung der + * Wand-Box gezeichnet werden können. Die Geometrie rechnet der Kern (`plan_elevation.rs`, [K3c]); + * hier die Auflösung aus dem Modell (Typ-Bibliothek) und die Übersetzung. */ function collectOpenings(project: Project, frame: ElevationFrame): ProjectedOpening[] { - const out: ProjectedOpening[] = []; - const lerp = ( - a: [number, number], - b: [number, number], - t: number, - ): [number, number] => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]; - // Punkt im Öffnungs-Quad: fa = Anteil entlang der Wandachse, fz = Höhenanteil. - const quadAt = ( - q: Array<[number, number]>, - fa: number, - fz: number, - ): [number, number] => lerp(lerp(q[0], q[1], fa), lerp(q[3], q[2], fa), fz); - const rect = ( - q: Array<[number, number]>, - fa0: number, - fa1: number, - fz0: number, - fz1: number, - ): Array<[number, number]> => [ - quadAt(q, fa0, fz0), - quadAt(q, fa1, fz0), - quadAt(q, fa1, fz1), - quadAt(q, fa0, fz1), - ]; - + const b: number[] = [0]; + const ids: string[] = []; for (const wall of project.walls) { let thickness = 0.2; try { @@ -487,177 +399,58 @@ function collectOpenings(project: Project, frame: ElevationFrame): ProjectedOpen const iv = openingInterval(wall, op); if (!iv) continue; const v = openingVerticalExtent(project, wall, op); - const pr = projectOpeningRect(frame, wall, iv.from, iv.to, v.zBottom, v.zTop, thickness); - if (!pr) continue; - pr.openingId = op.id; - const w = iv.to - iv.from; - const h = v.zTop - v.zBottom; - if (op.kind === "door") { - // Türen im Projekt-`openings`-Array: Blatt-Fläche, bei Glasblatt mit - // Teilverglasung (`glazingRatio`, Kämpferhöhe von OBEN gemessen wie - // beim Fenster-Oberlicht) — Glasanteil oben (`glass`), blinder Rest - // unten (`doorLeaf`), Trennlinie dazwischen ab Kämpfer. - pr.isDoor = true; - const dt = getDoorType(project, op); - if (dt?.leafStyle === "glas") { - const ratio = Math.max(0.05, Math.min(1, dt.glazingRatio ?? 1)); - if (ratio >= 1 - EPS) { - pr.glass.push(rect(pr.pts, 0.04, 0.96, 0, 0.97)); - } else { - const splitZ = 0.97 * (1 - ratio); - pr.glass.push(rect(pr.pts, 0.04, 0.96, splitZ, 0.97)); - pr.doorLeaf.push(rect(pr.pts, 0.04, 0.96, 0, splitZ)); - pr.divisions.push([quadAt(pr.pts, 0.04, splitZ), quadAt(pr.pts, 0.96, splitZ)]); - } - } else { - pr.doorLeaf.push(rect(pr.pts, 0.04, 0.96, 0, 0.97)); - } - out.push(pr); - continue; + const door = op.kind === "door"; + const dt = door ? getDoorType(project, op) : undefined; + const wt = door ? undefined : getWindowType(project, op); + const sashes = door ? [] : wt ? sashesOfWindowType(wt) : [{ kind: "fluegel" as const }]; + b.push( + wall.start.x, wall.start.y, wall.end.x, wall.end.y, thickness, iv.from, iv.to, v.zBottom, v.zTop, + door ? 1 : 0, dt?.leafStyle === "glas" ? 1 : 0, dt?.glazingRatio ?? Number.NaN, + wt?.frameWidth ?? 0.06, wt?.transomHeight ?? 0, wt?.mullionRows ?? Number.NaN, wt?.mullionCols ?? Number.NaN, + wt?.sillBoard !== "keine" && wt?.sillBoard !== "innen" ? 1 : 0, + SASH_KIND[wt?.kind ?? "fest"] ?? 0, + sashes.length, + ); + for (const sd of sashes as Array<{ kind: string; postWidth?: number; autoWidth?: boolean; width?: number; opening?: string; hingeSide?: string }>) { + b.push( + sd.kind === "pfosten" ? 1 : 0, sd.postWidth ?? Number.NaN, sd.autoWidth === false ? 0 : 1, sd.width ?? Number.NaN, + sd.opening === undefined ? -1 : SASH_KIND[sd.opening] ?? 0, (sd.hingeSide ?? "left") === "left" ? 1 : 0, + ); } - // Fenster: Blendrahmen → Flügelfelder → Glas (+ Kämpfer/Oberlicht) aus dem - // Fenstertyp; ohne Typ ein einzelnes Glasfeld im Default-Rahmen. - const wt = getWindowType(project, op); - const fw = wt?.frameWidth ?? 0.06; - const fa = Math.min(0.45, fw / Math.max(w, 1e-6)); - const fz = Math.min(0.45, fw / Math.max(h, 1e-6)); - const transom = Math.max(0, wt?.transomHeight ?? 0); - // Oberlicht-Trennung als Höhenanteil (0 = keins). - const fTr = transom > EPS && transom < h - fw ? 1 - transom / h : 0; - const fieldTop = fTr > 0 ? fTr - fz / 2 : 1 - fz; - // Flügel-Spannen über die innere Breite (autoWidth gleichmässig). - const sashes = wt ? sashesOfWindowType(wt) : [{ kind: "fluegel" as const }]; - const innerW = Math.max(1e-6, w * (1 - 2 * fa)); - let fixedSum = 0; - let autoCount = 0; - for (const sd of sashes) { - if (sd.kind === "pfosten") fixedSum += Math.max(0, sd.postWidth ?? 0.06); - else if (sd.autoWidth === false) fixedSum += Math.max(0, sd.width ?? 0); - else autoCount++; - } - const autoW = autoCount > 0 ? Math.max(0.02, (innerW - fixedSum) / autoCount) : 0; - let cursor = fa; - for (const sd of sashes) { - const sw = - sd.kind === "pfosten" - ? Math.max(0, sd.postWidth ?? 0.06) - : sd.autoWidth === false - ? Math.max(0, sd.width ?? autoW) - : autoW; - const fa0 = cursor; - const fa1 = cursor + sw / w; - cursor = fa1; - if (sd.kind === "pfosten") { - // Pfosten als Teilungslinie (Mitte). - const fm = (fa0 + fa1) / 2; - pr.divisions.push([quadAt(pr.pts, fm, fz), quadAt(pr.pts, fm, fieldTop)]); - continue; - } - // Flügelrahmen (Kontur) + Glas darin eingerückt (VW: Blendrahmen → - // Flügelprofil → Glas als drei ablesbare Konturen). - pr.sashRects.push(rect(pr.pts, fa0, fa1, fz, fieldTop)); - const spw = Math.min(0.06, Math.max(0.03, fw)); // Flügelprofil (m) - const gU = spw / Math.max(w, 1e-6); - const gV = spw / Math.max(h, 1e-6); - const gA = fa0 + gU; - const gB = fa1 - gU; - const gz0 = fz + gV; - const gz1 = fieldTop - gV; - // Kämpfer-/Sprossen-Zeilen (mullionRows): das Glasfeld wird in `rows` - // horizontale Scheiben geteilt (analog zum 3D, s. toWalls3d), mit einer - // Trennlinie je Zeilengrenze über die Glasbreite. 1 = ungeteilt (bisher). - const rows = Math.max(1, Math.round(wt?.mullionRows ?? 1)); - // Sprossen-Spalten (mullionCols): das Glasfeld wird in `cols` vertikale - // Scheiben geteilt (analog zum 3D, s. toWalls3d), mit einer - // Trennlinie je Spaltengrenze über die Glasscheibenhöhe. - const cols = Math.max(1, Math.round(wt?.mullionCols ?? 1)); - if (gB - gA > 1e-6 && gz1 - gz0 > 1e-6) { - // Glasfelder: rows × cols Gitter aus Einzelscheiben. - for (let r = 0; r < rows; r++) { - const rz0 = gz0 + ((gz1 - gz0) * r) / rows + (r > 0 ? gV / 2 : 0); - const rz1 = gz0 + ((gz1 - gz0) * (r + 1)) / rows - (r < rows - 1 ? gV / 2 : 0); - if (rz1 - rz0 <= 1e-6) continue; - for (let c = 0; c < cols; c++) { - const ca0 = gA + ((gB - gA) * c) / cols + (c > 0 ? gU / 2 : 0); - const ca1 = gA + ((gB - gA) * (c + 1)) / cols - (c < cols - 1 ? gU / 2 : 0); - if (ca1 - ca0 > 1e-6) pr.glass.push(rect(pr.pts, ca0, ca1, rz0, rz1)); - } - } - // Horizontale Trennlinien (Kämpfer) - for (let r = 1; r < rows; r++) { - const rz = gz0 + ((gz1 - gz0) * r) / rows; - pr.divisions.push([quadAt(pr.pts, gA, rz), quadAt(pr.pts, gB, rz)]); - } - // Vertikale Trennlinien (Sprossen-Spalten) - for (let c = 1; c < cols; c++) { - const ca = gA + ((gB - gA) * c) / cols; - pr.divisions.push([quadAt(pr.pts, ca, gz0), quadAt(pr.pts, ca, gz1)]); - } - } - // Trennlinie zum nächsten Feld (ausser am Rand). - if (fa1 < 1 - fa - 1e-6) { - pr.divisions.push([quadAt(pr.pts, fa1, fz), quadAt(pr.pts, fa1, fieldTop)]); - } - // Öffnungssymbol (SIA B.9.1.3): Linien starten/enden EXAKT auf den - // Glasfeld-Ecken (Nutzer-Report: Anker waren daneben). Dreh/Drehkipp: - // Spitze zeigt zur Bandseite (Anschlag), Basis zur Griffseite — SIA- - // Konvention. Kipp: Spitze oben Mitte (VW). - const kind = sd.opening ?? wt?.kind ?? "fest"; - if (kind === "dreh" || kind === "drehkipp") { - const hingeLeft = (sd.hingeSide ?? "left") === "left"; - const apex = quadAt(pr.pts, hingeLeft ? gA : gB, (gz0 + gz1) / 2); - const farU = hingeLeft ? gB : gA; - pr.symbol.push( - [quadAt(pr.pts, farU, gz0), apex], - [quadAt(pr.pts, farU, gz1), apex], - ); - } - if (kind === "kipp" || kind === "drehkipp") { - const apex = quadAt(pr.pts, (gA + gB) / 2, gz1); - pr.symbol.push( - [quadAt(pr.pts, gA, gz0), apex], - [quadAt(pr.pts, gB, gz0), apex], - ); - } - if (kind === "schiebe") { - // Schiebeflügel (SIA: „vertikales/horizontales Schiebefenster"): - // KEIN Dreieck (keine Bandseite), sondern ein Pfeil in Laufrichtung - // (horizontal) auf halber Glashöhe — die Griffseite (hingeSide) - // bestimmt die Pfeilrichtung. - const zc = (gz0 + gz1) / 2; - const toRight = (sd.hingeSide ?? "left") === "left"; // Griff links ⇒ schiebt nach rechts - const tail = toRight ? gA : gB; - const head = toRight ? gB : gA; - const barb = (head - tail) * 0.22; // Pfeilspitzen-Rücksprung (Glasbreite-Anteil) - const headPt = quadAt(pr.pts, head, zc); - pr.symbol.push( - [quadAt(pr.pts, tail, zc), headPt], // Schaft - [quadAt(pr.pts, head - barb, gz0 + (gz1 - gz0) * 0.32), headPt], // obere Spitze - [quadAt(pr.pts, head - barb, gz0 + (gz1 - gz0) * 0.68), headPt], // untere Spitze - ); - } - } - // Fensterbank (Sims, VW): Bank + Tropfkante als zwei Bänder unter dem - // Rahmen, seitlich leicht überstehend. Default AN (sillBoard fehlt), - // aus bei "keine"/"innen". - const sb = wt?.sillBoard; - if (sb !== "keine" && sb !== "innen") { - const ov1 = 0.02 / Math.max(w, 1e-6); - const ov2 = 0.05 / Math.max(w, 1e-6); - const h1 = 0.035 / Math.max(h, 1e-6); - const h2 = 0.025 / Math.max(h, 1e-6); - pr.sill.push(rect(pr.pts, -ov1, 1 + ov1, -h1, 0)); - pr.sill.push(rect(pr.pts, -ov2, 1 + ov2, -(h1 + h2), -h1)); - } - - // Oberlicht: eigenes Glasfeld + Kämpferlinie. - if (fTr > 0) { - pr.glass.push(rect(pr.pts, fa, 1 - fa, fTr + fz / 2, 1 - fz)); - pr.divisions.push([quadAt(pr.pts, 0, fTr), quadAt(pr.pts, 1, fTr)]); - } - out.push(pr); + ids.push(op.id); + b[0]++; } } + const f = core().elevation_openings_flat(encodeFrame(frame), Float64Array.from(b)); + const out: ProjectedOpening[] = []; + if (f.length === 0) return out; + let i = 1; + const quads = (): Array> => { + const list: Array> = []; + for (let k = 0, n = f[i++]; k < n; k++, i += 8) { + list.push([[f[i], f[i + 1]], [f[i + 2], f[i + 3]], [f[i + 4], f[i + 5]], [f[i + 6], f[i + 7]]]); + } + return list; + }; + const lines = (): Array<[[number, number], [number, number]]> => { + const list: Array<[[number, number], [number, number]]> = []; + for (let k = 0, n = f[i++]; k < n; k++, i += 4) list.push([[f[i], f[i + 1]], [f[i + 2], f[i + 3]]]); + return list; + }; + for (let k = 0; k < f[0]; k++) { + if (f[i++] === 0) continue; + const depth = f[i]; + const isDoor = f[i + 1] === 1; + const pts: Array<[number, number]> = [[f[i + 2], f[i + 3]], [f[i + 4], f[i + 5]], [f[i + 6], f[i + 7]], [f[i + 8], f[i + 9]]]; + i += 10; + const glass = quads(); + const doorLeaf = quads(); + const divisions = lines(); + const sashRects = quads(); + const sill = quads(); + const symbol = lines(); + out.push({ pts, depth, glass, doorLeaf, divisions, sashRects, sill, symbol, isDoor, openingId: ids[k] }); + } return out; } From 759e7d70a55e43b21279a99c6a1729759313a2cb Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:18:46 +0100 Subject: [PATCH 10/31] [K3c] Netz-Ebenenschnitt (Koerper, Gelaende) in Rust (mesh_section.rs); meshSection.ts Fassade; rueckwaerts geschlossene Ringe gehen nicht mehr verloren --- TODO.md | 1 + src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/mesh_section.rs | 299 +++++++++++++++++++++++++ src-tauri/core/src/web/mesh_section.rs | 15 ++ src-tauri/core/src/web/mod.rs | 1 + src/plan/meshSection.test.ts | 12 +- src/plan/meshSection.ts | 209 ++++------------- 7 files changed, 369 insertions(+), 169 deletions(-) create mode 100644 src-tauri/core/src/mesh_section.rs create mode 100644 src-tauri/core/src/web/mesh_section.rs diff --git a/TODO.md b/TODO.md index ceaec3b3..dec15804 100644 --- a/TODO.md +++ b/TODO.md @@ -108,6 +108,7 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern ✅ Schnitt-Bänder: Dominanz-Subtraktion, Verschmelzung, Rechteck-Vereinigung (`plan_section.rs`, 28.10.). ✅ Ansicht: Verdeckungs-Clipping, Punkt-Verdeckung, Schlagschatten, XOR-Umriss (`plan_elevation.rs`, 28.10.). ✅ Ansicht: Flächen (Wand-Quader, Decken-Prismen, Dach/Giebel) projizieren + Rückseiten-Culling, Eck-Verlängerung, Öffnungen (Rahmen, Glasfelder, Sprossen, Sims, SIA-Symbol) (`plan_elevation.rs`). + ✅ Netz-Ebenenschnitt (Körper/Gelände) + Ringe→Flächen (`mesh_section.rs`; behebt nebenbei: rückwärts geschlossene Ringe gingen verloren). - ○ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. 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. diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 81e1462f..58f1fbb7 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -37,6 +37,7 @@ pub mod plan_stairs; pub mod plan_walls; pub mod opening_geom; pub mod plan_openings; +pub mod mesh_section; pub mod plan_elevation; pub mod plan_misc; pub mod plan_section; diff --git a/src-tauri/core/src/mesh_section.rs b/src-tauri/core/src/mesh_section.rs new file mode 100644 index 00000000..19a4acad --- /dev/null +++ b/src-tauri/core/src/mesh_section.rs @@ -0,0 +1,299 @@ +//! Ebenenschnitt beliebiger Dreiecksnetze ([K3c], vorher `plan/meshSection.ts`): senkrechte Ebene +//! (Schnitt: u entlang der Ebene, v = Höhe) oder waagrechte (Grundriss auf Schnitthöhe). Geschlossene +//! Netze ergeben Ringe, offene (Gelände) Linienzüge. Ecken exakt auf der Ebene werden der „hinteren" +//! Seite zugeschlagen (`d > 0` = vorn), damit sich die Segmente schliessen. Rechenreihenfolge wie in +//! TS (Punkt-Schlüssel auf 1e-6 gerundet mit `Math.round`). +//! +//! ## Schnitt +//! `cut(positions, indices, plane)` mit `plane = [0, px, py, dx, dy]` (senkrecht) oder `[1, z]` +//! (waagrecht) → `[nRinge, (k, u, v …) × nRinge, nZüge, (k, u, v …) × nZüge]`; leer bei Unsinn. +//! +//! ## Ringe → Flächen +//! `rings_to_polygons(in)` mit `in = [n, (k, u, v …) × n]` → `[p, (r, (k, u, v …) × r) × p]` +//! (Aussenring zuerst, dann Löcher; Schachtelungstiefe gerade = aussen). + +use crate::jsnum::round; +use std::collections::{HashMap, VecDeque}; + +type P = (f64, f64); +const QUANT: f64 = 1e6; + +fn key(p: P) -> (i64, i64) { + (round(p.0 * QUANT) as i64, round(p.1 * QUANT) as i64) +} + +fn chain(segs: &[(P, P)]) -> (Vec>, Vec>) { + let mut by_start: HashMap<(i64, i64), Vec> = HashMap::new(); + let mut by_end: HashMap<(i64, i64), Vec> = HashMap::new(); + for (i, s) in segs.iter().enumerate() { + by_start.entry(key(s.0)).or_default().push(i); + by_end.entry(key(s.1)).or_default().push(i); + } + let mut used = vec![false; segs.len()]; + fn take(m: &mut HashMap<(i64, i64), Vec>, k: (i64, i64), used: &[bool]) -> Option { + let l = m.get_mut(&k)?; + while let Some(i) = l.pop() { + if !used[i] { + return Some(i); + } + } + None + } + let mut rings = Vec::new(); + let mut lines = Vec::new(); + for i in 0..segs.len() { + if used[i] { + continue; + } + used[i] = true; + let mut pts: VecDeque

= VecDeque::from([segs[i].0, segs[i].1]); + let start_key = key(pts[0]); + loop { + let k = key(*pts.back().unwrap()); + if k == start_key && pts.len() > 2 { + break; + } + let Some(n) = take(&mut by_start, k, &used) else { break }; + used[n] = true; + pts.push_back(segs[n].1); + } + if key(*pts.back().unwrap()) == start_key && pts.len() > 3 { + pts.pop_back(); + rings.push(pts.into_iter().collect()); + continue; + } + let mut closed = false; + loop { + let k = key(pts[0]); + let Some(n) = take(&mut by_end, k, &used) else { break }; + used[n] = true; + pts.push_front(segs[n].0); + if key(pts[0]) == key(*pts.back().unwrap()) { + pts.pop_front(); + rings.push(pts.iter().copied().collect()); + closed = true; + break; + } + } + if !closed && pts.len() >= 2 { + lines.push(pts.into_iter().collect()); + } + } + (rings, lines) +} + +pub fn cut(positions: &[f64], indices: &[f64], plane: &[f64]) -> Vec { + let nv = positions.len() / 3; + let vertical = match plane.first() { + Some(&k) if k == 0.0 && plane.len() == 5 => true, + Some(&k) if k == 1.0 && plane.len() == 2 => false, + _ => return Vec::new(), + }; + if positions.iter().chain(indices).chain(plane).any(|v| !v.is_finite()) + || indices.iter().any(|&i| i < 0.0 || i.fract() != 0.0 || i as usize >= nv) + { + return Vec::new(); + } + let mut dist = vec![0.0; nv]; + let mut c0 = vec![0.0; nv]; + let mut c1 = vec![0.0; nv]; + for i in 0..nv { + let (x, y, z) = (positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]); + if vertical { + let (px, py, dx, dy) = (plane[1], plane[2], plane[3], plane[4]); + dist[i] = (x - px) * dy - (y - py) * dx; + c0[i] = (x - px) * dx + (y - py) * dy; + c1[i] = z; + } else { + dist[i] = z - plane[1]; + c0[i] = x; + c1[i] = y; + } + } + let mut edge_pt: HashMap<(usize, usize), P> = HashMap::new(); + let mut crossing = |a: usize, b: usize| -> P { + let k = if a < b { (a, b) } else { (b, a) }; + *edge_pt.entry(k).or_insert_with(|| { + let t = dist[a] / (dist[a] - dist[b]); + (c0[a] + (c0[b] - c0[a]) * t, c1[a] + (c1[b] - c1[a]) * t) + }) + }; + let mut segs: Vec<(P, P)> = Vec::new(); + let mut t = 0; + while t + 2 < indices.len() { + let (a, b, c) = (indices[t] as usize, indices[t + 1] as usize, indices[t + 2] as usize); + t += 3; + let (sa, sb, sc) = (dist[a] > 0.0, dist[b] > 0.0, dist[c] > 0.0); + if sa == sb && sb == sc { + continue; + } + let odd = if sa != sb && sa != sc { a } else if sb != sa && sb != sc { b } else { c }; + let o1 = if odd == a { b } else if odd == b { c } else { a }; + let o2 = if odd == a { c } else if odd == b { a } else { b }; + let p = crossing(odd, o1); + let q = crossing(odd, o2); + if (p.0 - q.0).abs() < 1e-9 && (p.1 - q.1).abs() < 1e-9 { + continue; + } + segs.push(if dist[odd] > 0.0 { (q, p) } else { (p, q) }); + } + let (rings, lines) = chain(&segs); + let mut f = vec![rings.len() as f64]; + for r in &rings { + push_ring(&mut f, r); + } + f.push(lines.len() as f64); + for l in &lines { + push_ring(&mut f, l); + } + f +} + +fn push_ring(f: &mut Vec, r: &[P]) { + f.push(r.len() as f64); + for p in r { + f.extend([p.0, p.1]); + } +} + +fn ring_area(r: &[P]) -> f64 { + let mut a = 0.0; + for i in 0..r.len() { + let p = r[i]; + let q = r[(i + 1) % r.len()]; + a += p.0 * q.1 - q.0 * p.1; + } + a / 2.0 +} + +fn point_in_ring(p: P, r: &[P]) -> bool { + let mut inside = false; + let mut j = r.len() - 1; + for i in 0..r.len() { + let (xi, yi) = r[i]; + let (xj, yj) = r[j]; + if (yi > p.1) != (yj > p.1) && p.0 < ((xj - xi) * (p.1 - yi)) / (yj - yi) + xi { + inside = !inside; + } + j = i; + } + inside +} + +pub fn rings_to_polygons(inp: &[f64]) -> Vec { + if inp.is_empty() || inp.iter().any(|v| !v.is_finite()) || inp[0] < 0.0 { + return Vec::new(); + } + let n = inp[0] as usize; + let mut rings: Vec> = Vec::with_capacity(n); + let mut i = 1; + for _ in 0..n { + let Some(&k) = inp.get(i) else { return Vec::new() }; + if k < 0.0 || i + 1 + 2 * k as usize > inp.len() { + return Vec::new(); + } + let k = k as usize; + rings.push((0..k).map(|j| (inp[i + 1 + 2 * j], inp[i + 2 + 2 * j])).collect()); + i += 1 + 2 * k; + } + if i != inp.len() { + return Vec::new(); + } + let mut items: Vec<(Vec

, f64)> = rings + .into_iter() + .filter(|r| r.len() >= 3 && ring_area(r).abs() > 1e-12) + .map(|r| { + let a = ring_area(&r).abs(); + (r, a) + }) + .collect(); + items.sort_by(|a, b| (b.1 - a.1).partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal)); + let mut depth = vec![0usize; items.len()]; + let mut parent: Vec> = vec![None; items.len()]; + for i in 0..items.len() { + for j in (0..i).rev() { + if point_in_ring(items[i].0[0], &items[j].0) { + parent[i] = Some(j); + depth[i] = depth[j] + 1; + break; + } + } + } + let mut out: Vec> = Vec::new(); + let mut idx: HashMap = HashMap::new(); + for i in 0..items.len() { + if depth[i] % 2 == 0 { + idx.insert(i, out.len()); + out.push(vec![i]); + } + } + for i in 0..items.len() { + if depth[i] % 2 == 1 { + if let Some(owner) = parent[i].and_then(|p| idx.get(&p)) { + out[*owner].push(i); + } + } + } + let mut f = vec![out.len() as f64]; + for poly in &out { + f.push(poly.len() as f64); + for &r in poly { + push_ring(&mut f, &items[r].0); + } + } + f +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Würfel 0..2 (12 Dreiecke, nach aussen gewunden). + fn cube() -> (Vec, Vec) { + let mut p = Vec::new(); + for z in [0.0, 2.0] { + for y in [0.0, 2.0] { + for x in [0.0, 2.0] { + p.extend([x, y, z]); + } + } + } + let f = [ + 0, 2, 1, 1, 2, 3, 4, 5, 6, 5, 7, 6, 0, 1, 4, 1, 5, 4, 2, 6, 3, 3, 6, 7, 0, 4, 2, 2, 4, 6, 1, 3, 5, 3, 7, 5, + ]; + (p, f.iter().map(|&i| i as f64).collect()) + } + + #[test] + fn waagrechter_schnitt_ergibt_einen_ring() { + let (p, f) = cube(); + let r = cut(&p, &f, &[1.0, 1.0]); + assert_eq!(r[0], 1.0); + // Die Diagonalen der Seitenflächen liefern Zwischenpunkte: 4 Ecken + 4 Mitten. + assert_eq!(r[1], 8.0); + assert_eq!(r[2 + 16], 0.0); // keine Linienzüge + } + + #[test] + fn ebene_ausserhalb_ist_leer_aber_gueltig() { + let (p, f) = cube(); + assert_eq!(cut(&p, &f, &[1.0, 10.0]), vec![0.0, 0.0]); + } + + #[test] + fn unsinn_ist_leer() { + assert!(cut(&[0.0, 0.0, 0.0], &[0.0, 1.0, 2.0], &[1.0, 0.0]).is_empty()); + assert!(cut(&[0.0; 9], &[0.0, 1.0, 2.0], &[7.0]).is_empty()); + } + + #[test] + fn loch_gehoert_zum_aussenring() { + let outer = [4.0, 0.0, 0.0, 10.0, 0.0, 10.0, 10.0, 0.0, 10.0]; + let hole = [4.0, 4.0, 4.0, 6.0, 4.0, 6.0, 6.0, 4.0, 6.0]; + let mut inp = vec![2.0]; + inp.extend(outer); + inp.extend(hole); + let f = rings_to_polygons(&inp); + assert_eq!(&f[..3], &[1.0, 2.0, 4.0]); + } +} diff --git a/src-tauri/core/src/web/mesh_section.rs b/src-tauri/core/src/web/mesh_section.rs new file mode 100644 index 00000000..f0e1e297 --- /dev/null +++ b/src-tauri/core/src/web/mesh_section.rs @@ -0,0 +1,15 @@ +//! Bindungen des Netz-Ebenenschnitts (`crate::mesh_section`). Layouts s. dort. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Schnitt eines Dreiecksnetzes mit einer Ebene; Unsinn → leer. +#[wasm_bindgen] +pub fn mesh_section_cut_flat(positions: &[f64], indices: &[f64], plane: &[f64]) -> Vec { + crate::mesh_section::cut(positions, indices, plane) +} + +/// Ringe → Flächen mit Löchern; Unsinn → leer. +#[wasm_bindgen] +pub fn mesh_section_polygons_flat(input: &[f64]) -> Vec { + crate::mesh_section::rings_to_polygons(input) +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 8d406547..4a75e16a 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -28,6 +28,7 @@ mod gpu_compile; mod plan_stairs; mod plan_walls; mod plan_openings; +mod mesh_section; mod plan_elevation; mod plan_misc; mod plan_section; diff --git a/src/plan/meshSection.test.ts b/src/plan/meshSection.test.ts index c5365bbd..9fecb082 100644 --- a/src/plan/meshSection.test.ts +++ b/src/plan/meshSection.test.ts @@ -1,5 +1,15 @@ import { describe, expect, it } from "vitest"; -import { cutMeshWithPlane, ringArea, ringsToPolygons } from "./meshSection"; +import { cutMeshWithPlane, ringsToPolygons, type Pt2 } from "./meshSection"; + +const ringArea = (r: Pt2[]): number => { + let a = 0; + for (let i = 0; i < r.length; i++) { + const p = r[i]; + const q = r[(i + 1) % r.length]; + a += p[0] * q[1] - q[0] * p[1]; + } + return a / 2; +}; /** Quader als geschlossenes Netz (12 Dreiecke, aussen orientiert). `inward` kehrt um (Hohlraum). */ function box(x0: number, y0: number, z0: number, x1: number, y1: number, z1: number, inward = false) { diff --git a/src/plan/meshSection.ts b/src/plan/meshSection.ts index 15d85815..7e4efffb 100644 --- a/src/plan/meshSection.ts +++ b/src/plan/meshSection.ts @@ -8,9 +8,10 @@ // Geschlossene Netze (Körper) ergeben geschlossene Ringe → Polygone mit Löchern; offene Netze // (Gelände) ergeben offene Linienzüge (Geländelinie im Schnitt). // -// Robustheit: Ecken exakt AUF der Ebene werden einheitlich der „hinteren" Seite zugeschlagen -// (symbolische Störung, `d > 0` ⇒ vorn) — so schliessen sich die Segmente auch bei Netzen, deren -// Ecken genau auf der Schnittlinie liegen (Achsen im Raster!). +// Die Rechnung liegt im Rust-Kern (`src-tauri/core/src/mesh_section.rs`, [K3c]); hier nur die +// Fassade mit unveränderter Signatur. + +import { core } from "../engine/coreWasm"; export type Pt2 = [number, number]; @@ -34,153 +35,35 @@ export interface HorizontalPlane { } export type CutPlane = VerticalPlane | HorizontalPlane; -const QUANT = 1e6; -const key = (p: Pt2): string => `${Math.round(p[0] * QUANT)},${Math.round(p[1] * QUANT)}`; +/** Liest `[n, (k, u, v …) × n]` ab `i` (Index wandert mit). */ +function readRings(f: Float64Array, at: { i: number }): Pt2[][] { + const out: Pt2[][] = []; + for (let k = 0, n = f[at.i++]; k < n; k++) { + const count = f[at.i++]; + const ring = new Array(count); + for (let j = 0; j < count; j++, at.i += 2) ring[j] = [f[at.i], f[at.i + 1]]; + out.push(ring); + } + return out; +} /** * Schneidet das Netz mit `plane`. `positions` flach [x,y,z,…], `indices` je 3 ein Dreieck. * Entartete Segmente (Länge ~0) werden verworfen. */ export function cutMeshWithPlane(positions: ArrayLike, indices: ArrayLike, plane: CutPlane): CutResult { - const nv = Math.floor(positions.length / 3); - // Signierter Abstand + 2D-Koordinate je Vertex. - const dist = new Float64Array(nv); - const c0 = new Float64Array(nv); - const c1 = new Float64Array(nv); - for (let i = 0; i < nv; i++) { - const x = positions[i * 3]; - const y = positions[i * 3 + 1]; - const z = positions[i * 3 + 2]; - if (plane.kind === "vertical") { - // Normale der Ebene (im Grundriss): n = (dir.y, −dir.x); u = Position entlang dir. - dist[i] = (x - plane.point.x) * plane.dir.y - (y - plane.point.y) * plane.dir.x; - c0[i] = (x - plane.point.x) * plane.dir.x + (y - plane.point.y) * plane.dir.y; - c1[i] = z; - } else { - dist[i] = z - plane.z; - c0[i] = x; - c1[i] = y; - } - } - - // Kanten-Schnittpunkte cachen (jede Kante gehört zu bis zu 2 Dreiecken → gleicher Punkt). - const edgePt = new Map(); - const edgeKey = (a: number, b: number): number => (a < b ? a * nv + b : b * nv + a); - const crossing = (a: number, b: number): Pt2 => { - const k = edgeKey(a, b); - let p = edgePt.get(k); - if (!p) { - const t = dist[a] / (dist[a] - dist[b]); - p = [c0[a] + (c0[b] - c0[a]) * t, c1[a] + (c1[b] - c1[a]) * t]; - edgePt.set(k, p); - } - return p; - }; - - const segs: Array<[Pt2, Pt2]> = []; - for (let t = 0; t + 2 < indices.length; t += 3) { - const a = indices[t]; - const b = indices[t + 1]; - const c = indices[t + 2]; - const sa = dist[a] > 0; - const sb = dist[b] > 0; - const sc = dist[c] > 0; - if (sa === sb && sb === sc) continue; - // Genau eine Ecke steht allein auf ihrer Seite: die beiden Kanten dort bilden das Segment. - const odd = sa !== sb && sa !== sc ? a : sb !== sa && sb !== sc ? b : c; - const o1 = odd === a ? b : odd === b ? c : a; - const o2 = odd === a ? c : odd === b ? a : b; - const p = crossing(odd, o1); - const q = crossing(odd, o2); - if (Math.abs(p[0] - q[0]) < 1e-9 && Math.abs(p[1] - q[1]) < 1e-9) continue; - // Einheitlicher Umlaufsinn je Seite der Einzelecke → Segmente benachbarter Dreiecke fügen - // sich bei gleichsinnig orientiertem Netz zu gleichsinnigen Ketten. - segs.push(dist[odd] > 0 ? [q, p] : [p, q]); - } - return chain(segs); -} - -/** Verkettet Segmente zu Ringen und Linienzügen. */ -function chain(segs: Array<[Pt2, Pt2]>): CutResult { - // Start-/Endpunkt-Index. - const byStart = new Map(); - const byEnd = new Map(); - segs.forEach((s, i) => { - const ks = key(s[0]); - const ke = key(s[1]); - (byStart.get(ks) ?? byStart.set(ks, []).get(ks)!).push(i); - (byEnd.get(ke) ?? byEnd.set(ke, []).get(ke)!).push(i); - }); - const used = new Array(segs.length).fill(false); - const take = (m: Map, k: string): number => { - const l = m.get(k); - if (!l) return -1; - while (l.length) { - const i = l.pop()!; - if (!used[i]) return i; - } - return -1; - }; - const rings: Pt2[][] = []; - const lines: Pt2[][] = []; - for (let i = 0; i < segs.length; i++) { - if (used[i]) continue; - used[i] = true; - const pts: Pt2[] = [segs[i][0], segs[i][1]]; - const startKey = key(pts[0]); - // vorwärts - for (;;) { - const k = key(pts[pts.length - 1]); - if (k === startKey && pts.length > 2) break; - const n = take(byStart, k); - if (n < 0) break; - used[n] = true; - pts.push(segs[n][1]); - } - if (key(pts[pts.length - 1]) === startKey && pts.length > 3) { - pts.pop(); - rings.push(pts); - continue; - } - // rückwärts verlängern (offener Zug) - for (;;) { - const k = key(pts[0]); - const n = take(byEnd, k); - if (n < 0) break; - used[n] = true; - pts.unshift(segs[n][0]); - if (key(pts[0]) === key(pts[pts.length - 1])) { - pts.shift(); - rings.push(pts); - pts.length = 0; - break; - } - } - if (pts.length >= 2) lines.push(pts); - } + const pl = + plane.kind === "vertical" + ? [0, plane.point.x, plane.point.y, plane.dir.x, plane.dir.y] + : [1, plane.z]; + const f = core().mesh_section_cut_flat(Float64Array.from(positions), Float64Array.from(indices), Float64Array.from(pl)); + if (f.length === 0) return { rings: [], lines: [] }; + const at = { i: 0 }; + const rings = readRings(f, at); + const lines = readRings(f, at); return { rings, lines }; } -export const ringArea = (r: Pt2[]): number => { - let a = 0; - for (let i = 0; i < r.length; i++) { - const p = r[i]; - const q = r[(i + 1) % r.length]; - a += p[0] * q[1] - q[0] * p[1]; - } - return a / 2; -}; - -function pointInRing(p: Pt2, r: Pt2[]): boolean { - let inside = false; - for (let i = 0, j = r.length - 1; i < r.length; j = i++) { - const [xi, yi] = r[i]; - const [xj, yj] = r[j]; - if (yi > p[1] !== yj > p[1] && p[0] < ((xj - xi) * (p[1] - yi)) / (yj - yi) + xi) inside = !inside; - } - return inside; -} - /** Ring mit Löchern (Aussenring zuerst, dann Löcher). */ export type RingSet = Pt2[][]; @@ -189,35 +72,25 @@ export type RingSet = Pt2[][]; * Loch). Unabhängig vom Umlaufsinn. Aussenringe zuerst-gross; Löcher folgen ihrem Aussenring. */ export function ringsToPolygons(rings: Pt2[][]): RingSet[] { - const items = rings - .filter((r) => r.length >= 3 && Math.abs(ringArea(r)) > 1e-12) - .map((r) => ({ r, area: Math.abs(ringArea(r)) })) - .sort((a, b) => b.area - a.area); - const depth: number[] = items.map(() => 0); - const parent: number[] = items.map(() => -1); - for (let i = 0; i < items.length; i++) { - for (let j = i - 1; j >= 0; j--) { - // Kandidat j (grösser) enthält i? Test mit einem Punkt von i (nicht auf dem Rand von j). - if (pointInRing(items[i].r[0], items[j].r)) { - parent[i] = j; - depth[i] = depth[j] + 1; - break; - } - } + const b: number[] = [rings.length]; + for (const r of rings) { + b.push(r.length); + for (const p of r) b.push(p[0], p[1]); } + const f = core().mesh_section_polygons_flat(Float64Array.from(b)); + if (f.length === 0) return []; + const at = { i: 1 }; const out: RingSet[] = []; - const idx = new Map(); - items.forEach((it, i) => { - if (depth[i] % 2 === 0) { - idx.set(i, out.length); - out.push([it.r]); + for (let k = 0; k < f[0]; k++) { + const nr = f[at.i++]; + const set: RingSet = []; + for (let r = 0; r < nr; r++) { + const count = f[at.i++]; + const ring = new Array(count); + for (let j = 0; j < count; j++, at.i += 2) ring[j] = [f[at.i], f[at.i + 1]]; + set.push(ring); } - }); - items.forEach((it, i) => { - if (depth[i] % 2 === 1) { - const owner = idx.get(parent[i]); - if (owner !== undefined) out[owner].push(it.r); - } - }); + out.push(set); + } return out; } From 89b8f7b1c39900d9fa58d803da00f1ee37f56a8b Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:20:08 +0100 Subject: [PATCH 11/31] [K3c] Dach-Schnittspur (appendRoofSections) in Rust (plan_section.rs); TS nur noch Schichtbaender --- TODO.md | 1 + src-tauri/core/src/plan_section.rs | 134 +++++++++++++++++++++++++ src-tauri/core/src/web/plan_section.rs | 6 ++ src/plan/toSection.ts | 106 +++---------------- 4 files changed, 153 insertions(+), 94 deletions(-) diff --git a/TODO.md b/TODO.md index dec15804..3fe4dec6 100644 --- a/TODO.md +++ b/TODO.md @@ -109,6 +109,7 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern ✅ Ansicht: Verdeckungs-Clipping, Punkt-Verdeckung, Schlagschatten, XOR-Umriss (`plan_elevation.rs`, 28.10.). ✅ Ansicht: Flächen (Wand-Quader, Decken-Prismen, Dach/Giebel) projizieren + Rückseiten-Culling, Eck-Verlängerung, Öffnungen (Rahmen, Glasfelder, Sprossen, Sims, SIA-Symbol) (`plan_elevation.rs`). ✅ Netz-Ebenenschnitt (Körper/Gelände) + Ringe→Flächen (`mesh_section.rs`; behebt nebenbei: rückwärts geschlossene Ringe gingen verloren). + ✅ Dach-Schnittspur (Cyrus–Beck, lineare Oberkante, Verschmelzen) in `plan_section.rs`. - ○ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. 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. diff --git a/src-tauri/core/src/plan_section.rs b/src-tauri/core/src/plan_section.rs index 76f8bf2d..453292cf 100644 --- a/src-tauri/core/src/plan_section.rs +++ b/src-tauri/core/src/plan_section.rs @@ -9,6 +9,12 @@ //! `[m, Eintrag × m]`, Eintrag = `[quelle, istRechteck, uMin, uMax, vMin, vMax]`. `istRechteck` 0 = //! Quellband unverändert übernehmen, sonst neues Rechteck mit Stil von `quelle`. //! +//! ## Dach-Schnittspur +//! `roof_segments(base_x, base_y, u_x, u_y, planes)` mit `planes = [n, (k, x, y, z …) × n]` (Modell +//! [x, y, Höhe], konvexe Aufsicht-Polygone) → `[m, (tLo, tHi, zOben0, zOben1, cosNeigung) × m]`: die +//! Spur der senkrechten Schnittebene (Gerade `base + t·u`) je Dachfläche, nach `tLo` sortiert und +//! gleich geneigte, anstossende Teile verschmolzen (`appendRoofSections`). +//! //! ## Umrisse //! `union_outlines(in)` mit `in = [n, (uMin, uMax, vMin, vMax) × n]` → `[r, (k, x, y × k) × r]`. @@ -302,6 +308,123 @@ pub fn union_outlines(inp: &[f64]) -> Vec { f } +/// Spur-Abschnitt auf einer Dachfläche. +#[derive(Clone, Copy)] +struct RoofSeg { + t_lo: f64, + t_hi: f64, + z_top0: f64, + z_top1: f64, + cos_theta: f64, +} + +pub fn roof_segments(bx: f64, by: f64, ux: f64, uy: f64, planes: &[f64]) -> Vec { + if [bx, by, ux, uy].iter().any(|v| !v.is_finite()) || planes.iter().any(|v| !v.is_finite()) { + return Vec::new(); + } + let Some(&n) = planes.first() else { return Vec::new() }; + if n < 0.0 || n.fract() != 0.0 { + return Vec::new(); + } + let mut segs: Vec = Vec::new(); + let mut i = 1; + for _ in 0..n as usize { + let Some(&k) = planes.get(i) else { return Vec::new() }; + if k < 0.0 || k.fract() != 0.0 || i + 1 + 3 * k as usize > planes.len() { + return Vec::new(); + } + let k = k as usize; + let pts: Vec<[f64; 3]> = (0..k).map(|j| [planes[i + 1 + 3 * j], planes[i + 2 + 3 * j], planes[i + 3 + 3 * j]]).collect(); + i += 1 + 3 * k; + if k < 3 { + continue; + } + let (mut a, mut b, mut c) = (0.0, 0.0, 0.0); + for q in 0..k { + let cc = pts[q]; + let d = pts[(q + 1) % k]; + a += (cc[1] - d[1]) * (cc[2] + d[2]); + b += (cc[2] - d[2]) * (cc[0] + d[0]); + c += (cc[0] - d[0]) * (cc[1] + d[1]); + } + if c.abs() < 1e-9 { + continue; + } + let n_len = crate::jsmath::hypot(&[a, b, c]); + let cos_theta = c.abs() / if n_len == 0.0 || n_len.is_nan() { 1.0 } else { n_len }; + let z_at = |x: f64, y: f64| -> f64 { pts[0][2] - (a * (x - pts[0][0]) + b * (y - pts[0][1])) / c }; + let (mut cx, mut cy) = (0.0, 0.0); + for p in &pts { + cx += p[0]; + cy += p[1]; + } + cx /= k as f64; + cy /= k as f64; + let (mut t_lo, mut t_hi) = (f64::NEG_INFINITY, f64::INFINITY); + let mut outside = false; + let mut q = 0; + while q < k && !outside { + let pa = pts[q]; + let pb = pts[(q + 1) % k]; + let mut ex = -(pb[1] - pa[1]); + let mut ey = pb[0] - pa[0]; + if ex * (cx - pa[0]) + ey * (cy - pa[1]) < 0.0 { + ex = -ex; + ey = -ey; + } + let denom = ex * ux + ey * uy; + let dist = ex * (bx - pa[0]) + ey * (by - pa[1]); + q += 1; + if denom.abs() < 1e-12 { + if dist < -1e-9 { + outside = true; + } + continue; + } + let t = -dist / denom; + if denom > 0.0 { + t_lo = max(t_lo, t); + } else { + t_hi = min(t_hi, t); + } + } + if outside || t_hi - t_lo <= 1e-6 { + continue; + } + let (x0, y0) = (bx + t_lo * ux, by + t_lo * uy); + let (x1, y1) = (bx + t_hi * ux, by + t_hi * uy); + segs.push(RoofSeg { t_lo, t_hi, z_top0: z_at(x0, y0), z_top1: z_at(x1, y1), cos_theta }); + } + if i != planes.len() { + return Vec::new(); + } + segs.sort_by(|p, q| (p.t_lo - q.t_lo).partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal)); + let slope = |x: &RoofSeg| (x.z_top1 - x.z_top0) / max(x.t_hi - x.t_lo, 1e-12); + let line_z = |x: &RoofSeg, t: f64| x.z_top0 + slope(x) * (t - x.t_lo); + let mut merged: Vec = Vec::new(); + for sg in segs { + if let Some(last) = merged.last_mut() { + if sg.t_lo <= last.t_hi + 1e-6 + && (line_z(last, sg.t_lo) - sg.z_top0).abs() < 1e-6 + && (slope(&sg) - slope(last)).abs() < 1e-6 + && (sg.cos_theta - last.cos_theta).abs() < 1e-6 + { + let hi = max(last.t_hi, sg.t_hi); + let z1 = line_z(last, hi); + last.z_top1 = z1; + last.t_hi = hi; + continue; + } + } + merged.push(sg); + } + let mut f = vec![merged.len() as f64]; + for m in &merged { + f.extend([m.t_lo, m.t_hi, m.z_top0, m.z_top1, m.cos_theta]); + } + f +} + #[cfg(test)] mod tests { use super::*; @@ -356,8 +479,19 @@ mod tests { assert_eq!(f[1], 6.0); } + #[test] + fn pultdach_spur() { + // Fläche 0..4 × 0..3, Höhe steigt in x von 3 auf 4 (Neigung 1/4); Schnitt entlang x bei y = 1. + let planes = [1.0, 4.0, 0.0, 0.0, 3.0, 4.0, 0.0, 4.0, 4.0, 3.0, 4.0, 0.0, 3.0, 3.0]; + let f = roof_segments(-1.0, 1.0, 1.0, 0.0, &planes); + assert_eq!(f[0], 1.0); + assert_eq!((f[1], f[2]), (1.0, 5.0)); + assert!((f[3] - 3.0).abs() < 1e-12 && (f[4] - 4.0).abs() < 1e-12); + } + #[test] fn unsinn_ist_leer() { + assert!(roof_segments(f64::NAN, 0.0, 1.0, 0.0, &[0.0]).is_empty()); assert!(dominant_bands(&[f64::NAN]).is_empty()); assert!(dominant_bands(&[2.0, 1.0]).is_empty()); assert!(union_outlines(&[1.0, f64::NAN, 1.0, 0.0, 1.0]).is_empty()); diff --git a/src-tauri/core/src/web/plan_section.rs b/src-tauri/core/src/web/plan_section.rs index 9d696f8f..508ea06e 100644 --- a/src-tauri/core/src/web/plan_section.rs +++ b/src-tauri/core/src/web/plan_section.rs @@ -13,3 +13,9 @@ pub fn section_dominant_bands_flat(input: &[f64]) -> Vec { pub fn section_union_outlines_flat(input: &[f64]) -> Vec { crate::plan_section::union_outlines(input) } + +/// Spur der senkrechten Schnittebene auf den Dachflächen eines Dachs; Unsinn → leer. +#[wasm_bindgen] +pub fn section_roof_segments_flat(base_x: f64, base_y: f64, u_x: f64, u_y: f64, planes: &[f64]) -> Vec { + crate::plan_section::roof_segments(base_x, base_y, u_x, u_y, planes) +} diff --git a/src/plan/toSection.ts b/src/plan/toSection.ts index dd551428..a87c4329 100644 --- a/src/plan/toSection.ts +++ b/src/plan/toSection.ts @@ -875,7 +875,6 @@ export function appendRoofSections( // plane.point[0]=x, plane.point[2]=y; u-Achse = (−nz, nx) (s. section.rs). const base: Vec2 = { x: plane.point[0], y: plane.point[2] }; const uDir = sectionUAxisModel(plane); - const EPS_U = 1e-6; roofs.forEach((roof, index) => { const eavesZ = roofBaseElevation(project, roof); @@ -884,100 +883,19 @@ export function appendRoofSections( const totalT = layers.reduce((s, l) => s + Math.max(0, l.thickness), 0); if (totalT <= 1e-9) return; - const segs: Array<{ tLo: number; tHi: number; zTop0: number; zTop1: number; cosTheta: number }> = []; - for (const pl of geo.planes) { - const pts = pl.pts; - if (pts.length < 3) continue; - // Ebenengleichung z = z0 − (A(x−x0)+B(y−y0))/C über die Newell-Normale. - let A = 0; - let B = 0; - let C = 0; - for (let i = 0; i < pts.length; i++) { - const c = pts[i]; - const d = pts[(i + 1) % pts.length]; - A += (c[1] - d[1]) * (c[2] + d[2]); - B += (c[2] - d[2]) * (c[0] + d[0]); - C += (c[0] - d[0]) * (c[1] + d[1]); - } - if (Math.abs(C) < 1e-9) continue; // (nahezu) vertikale Fläche — kein Flächenschnitt - const nLen = Math.hypot(A, B, C); - const cosTheta = Math.abs(C) / (nLen || 1); - const zAt = (x: number, y: number): number => - pts[0][2] - (A * (x - pts[0][0]) + B * (y - pts[0][1])) / C; - - // Cyrus–Beck: Gerade base + t·uDir gegen das konvexe Aufsichts-Polygon. - // Orientierungsunabhängig: Innenseite je Kante über den Polygon-Schwerpunkt. - let cx = 0; - let cy = 0; - for (const p of pts) { - cx += p[0]; - cy += p[1]; - } - cx /= pts.length; - cy /= pts.length; - let tLo = -Infinity; - let tHi = Infinity; - let outside = false; - for (let i = 0; i < pts.length && !outside; i++) { - const a = pts[i]; - const b = pts[(i + 1) % pts.length]; - // Kanten-Normale, zum Schwerpunkt orientiert (Innenseite). - let ex = -(b[1] - a[1]); - let ey = b[0] - a[0]; - if (ex * (cx - a[0]) + ey * (cy - a[1]) < 0) { - ex = -ex; - ey = -ey; - } - const denom = ex * uDir.x + ey * uDir.y; - const dist = ex * (base.x - a[0]) + ey * (base.y - a[1]); - if (Math.abs(denom) < 1e-12) { - if (dist < -1e-9) outside = true; // parallel ausserhalb - continue; - } - const t = -dist / denom; - if (denom > 0) tLo = Math.max(tLo, t); - else tHi = Math.min(tHi, t); - } - if (outside || tHi - tLo <= EPS_U) continue; - - const q = (t: number): Vec2 => ({ x: base.x + t * uDir.x, y: base.y + t * uDir.y }); - const p0 = q(tLo); - const p1 = q(tHi); - const zTop0 = zAt(p0.x, p0.y); - const zTop1 = zAt(p1.x, p1.y); - - segs.push({ - tLo, - tHi, - zTop0, - zTop1, - cosTheta, - }); + // Spur der Schnittebene auf den Dachflächen (Cyrus–Beck gegen die konvexen Aufsichten, lineare + // Oberkante), gleich geneigte anstossende Teile zu EINEM Band vereint — sonst stünde an der + // Naht eine senkrechte Linie. Rechnet der Kern (`plan_section.rs`). + const pl: number[] = [geo.planes.length]; + for (const plane of geo.planes) { + pl.push(plane.pts.length); + for (const p of plane.pts) pl.push(p[0], p[1], p[2]); } - - // Aneinanderstossende/überlappende Bänder, deren Oberkante in einer Geraden weiterläuft und die gleiche - // Dicke haben (z. B. Teilflächen EINER Ebene aus der konvexen Zerlegung, oder zwei - // Flächen, die genau an der Schnittspur anstossen), zu EINEM Band vereinen — sonst - // steht an der Naht eine senkrechte Linie. - segs.sort((p, q) => p.tLo - q.tLo); - const merged: typeof segs = []; - for (const sg of segs) { - const last = merged[merged.length - 1]; - const slope = (x: typeof sg) => (x.zTop1 - x.zTop0) / Math.max(x.tHi - x.tLo, 1e-12); - const lineZ = (x: typeof sg, t: number) => x.zTop0 + slope(x) * (t - x.tLo); - if ( - last && - sg.tLo <= last.tHi + 1e-6 && // anstossend ODER überlappend - Math.abs(lineZ(last, sg.tLo) - sg.zTop0) < 1e-6 && - Math.abs(slope(sg) - slope(last)) < 1e-6 && - Math.abs(sg.cosTheta - last.cosTheta) < 1e-6 - ) { - const hi = Math.max(last.tHi, sg.tHi); - last.zTop1 = lineZ(last, hi); - last.tHi = hi; - } else { - merged.push({ ...sg }); - } + const sg = core().section_roof_segments_flat(base.x, base.y, uDir.x, uDir.y, Float64Array.from(pl)); + const merged: Array<{ tLo: number; tHi: number; zTop0: number; zTop1: number; cosTheta: number }> = []; + for (let k = 0; k < (sg[0] ?? 0); k++) { + const o = 1 + 5 * k; + merged.push({ tLo: sg[o], tHi: sg[o + 1], zTop0: sg[o + 2], zTop1: sg[o + 3], cosTheta: sg[o + 4] }); } for (const { tLo, tHi, zTop0, zTop1, cosTheta } of merged) { From 96205efd868b940994cc252aacb735654aa8676e Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:29:44 +0100 Subject: [PATCH 12/31] [K1] Delaunay-Triangulierung in Rust (delaunay.rs, Port von delaunator mit exaktem orient2d); Gelaende und Kontext nutzen den Kern; Abhaengigkeit delaunator entfernt --- TODO.md | 2 +- package-lock.json | 16 - package.json | 1 - src-tauri/core/src/delaunay.rs | 538 +++++++++++++++++++++++++++++ src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/web/delaunay.rs | 9 + src-tauri/core/src/web/mod.rs | 1 + src/io/geoContext.ts | 9 +- src/model/terrain.ts | 17 +- 9 files changed, 558 insertions(+), 36 deletions(-) create mode 100644 src-tauri/core/src/delaunay.rs create mode 100644 src-tauri/core/src/web/delaunay.rs diff --git a/TODO.md b/TODO.md index 3fe4dec6..f58b068a 100644 --- a/TODO.md +++ b/TODO.md @@ -28,7 +28,7 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern langsamer). Schatten, Baurecht (exakter Puffer statt Kapsel), Aussenbemassung, Kennzahlen in Rust; die `checkRoomProgram` bleibt vorerst TS (SIA-416-Zuordnung: seit [K2] `room_area.rs`). `bulge.ts` ist Fassade über den Rust-Kern (`bulge_polyline_points` für ganze Polylinien; `hasRealBulge`/`pointOnCircle` bleiben TS, - Einzeiler). Offen: Triangulierung, Straight Skeleton [B2]. · M + Einzeiler). Delaunay-Triangulierung (`delaunay.rs`, Port von delaunator inkl. exaktem `orient2d`; bitgleich zu JS über Zufalls-/Raster-/kozirkulare/fast-kollineare Punkte; `delaunator` aus den Abhängigkeiten entfernt, 28.10.): Gelände-TIN und Kontext-Gebäude. Offen: Straight Skeleton [B2]. · M - ✅ **Mac-Test 27.10.** (Maintainer): App startet mit dem Rust-Kern, Darstellung sieht gut aus — Stand `5b72069` (K0–K2, render2d binär); zweiter Test mit GPU-Kompilierung [K3b] (`7a8af4f`) ebenfalls bestanden. - ✅ **[K2] Geometrie-Ableitungen.** (27.10.) Dachgeometrie in Rust (`roof.rs`, `roof_skeleton.rs`; diff --git a/package-lock.json b/package-lock.json index dfe79507..94aa3826 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,7 +17,6 @@ "@tauri-apps/plugin-process": "^2.3.1", "@tauri-apps/plugin-shell": "^2.3.5", "@tauri-apps/plugin-updater": "^2.10.1", - "delaunator": "^5.1.0", "dxf-parser": "^1.1.2", "jspdf": "^4.2.1", "jszip": "^3.10.1", @@ -2978,15 +2977,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/delaunator": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.1.0.tgz", - "integrity": "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==", - "license": "ISC", - "dependencies": { - "robust-predicates": "^3.0.2" - } - }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -5194,12 +5184,6 @@ "node": ">= 0.8.15" } }, - "node_modules/robust-predicates": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz", - "integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==", - "license": "Unlicense" - }, "node_modules/rolldown": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.4.tgz", diff --git a/package.json b/package.json index cba3e081..232b60fd 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,6 @@ "@tauri-apps/plugin-process": "^2.3.1", "@tauri-apps/plugin-shell": "^2.3.5", "@tauri-apps/plugin-updater": "^2.10.1", - "delaunator": "^5.1.0", "dxf-parser": "^1.1.2", "jspdf": "^4.2.1", "jszip": "^3.10.1", diff --git a/src-tauri/core/src/delaunay.rs b/src-tauri/core/src/delaunay.rs new file mode 100644 index 00000000..0345ffc5 --- /dev/null +++ b/src-tauri/core/src/delaunay.rs @@ -0,0 +1,538 @@ +//! Delaunay-Triangulierung ([K1]): Port von `delaunator` 5.1.0 (Volodymyr Agafonkin / Mapbox, ISC-Lizenz, +//! https://github.com/mapbox/delaunator) samt exaktem +//! `orient2d` (robust-predicates). Dieselbe Reihenfolge der Schritte wie in JS, damit Dreiecke und +//! deren Indizes bitgleich herauskommen — auch bei kozirkulären Punkten (Raster). Verwendet vom +//! Gelände-TIN (`model/terrain.ts`) und den Kontext-Gebäuden (`io/geoContext.ts`). +//! +//! `triangulate(coords)` mit `coords = [x0, y0, x1, y1 …]` → Dreiecks-Indizes (je drei, gegen den +//! Uhrzeigersinn); leer bei < 3 Punkten, nur kollinearen Punkten oder nicht endlichen Werten. + +const EPSILON: f64 = 1.0 / 4503599627370496.0; // 2^-52 +const EDGE_STACK_LEN: usize = 512; + +// ── exaktes orient2d ─────────────────────────────────────────────────────── + +fn two_sum(a: f64, b: f64) -> (f64, f64) { + let x = a + b; + let bv = x - a; + let av = x - bv; + (x, (a - av) + (b - bv)) +} + +fn two_product(a: f64, b: f64) -> (f64, f64) { + let x = a * b; + (x, a.mul_add(b, -x)) +} + +/// Summe einer Expansion (aufsteigend, nicht überlappend) und eines Doubles. +fn grow(e: &[f64], b: f64) -> Vec { + let mut out = Vec::with_capacity(e.len() + 1); + let mut q = b; + for &x in e { + let (s, t) = two_sum(q, x); + q = s; + if t != 0.0 { + out.push(t); + } + } + if q != 0.0 || out.is_empty() { + out.push(q); + } + out +} + +fn scale(e: &[f64], b: f64) -> Vec { + let mut out = Vec::with_capacity(2 * e.len()); + let (mut q, h) = two_product(e[0], b); + if h != 0.0 { + out.push(h); + } + for &x in &e[1..] { + let (p1, p0) = two_product(x, b); + let (sum, h) = two_sum(q, p0); + if h != 0.0 { + out.push(h); + } + let (q2, h2) = two_sum(p1, sum); + q = q2; + if h2 != 0.0 { + out.push(h2); + } + } + if q != 0.0 || out.is_empty() { + out.push(q); + } + out +} + +fn sum(e: &[f64], f: &[f64]) -> Vec { + let mut out = e.to_vec(); + for &x in f { + out = grow(&out, x); + } + out +} + +fn estimate_sign(e: &[f64]) -> f64 { + for &x in e.iter().rev() { + if x != 0.0 { + return x; + } + } + 0.0 +} + +/// Wie `orient2d` aus `robust-predicates`: Vorzeichen exakt (negativ, wenn a, b, c gegen den +/// Uhrzeigersinn liegen — Konvention dieses Pakets), Betrag nur die schnelle Näherung. +pub fn orient2d(ax: f64, ay: f64, bx: f64, by: f64, cx: f64, cy: f64) -> f64 { + const EPS: f64 = 1.1102230246251565e-16; // 2^-53 + const CCW_ERR_BOUND_A: f64 = (3.0 + 16.0 * EPS) * EPS; + let detleft = (ay - cy) * (bx - cx); + let detright = (ax - cx) * (by - cy); + let det = detleft - detright; + let detsum = (detleft + detright).abs(); + if det.abs() >= CCW_ERR_BOUND_A * detsum { + return det; + } + // exakt: (ay-cy)(bx-cx) - (ax-cx)(by-cy); jede Differenz als 2-Term-Expansion + let (acx, acx_t) = two_sum(ax, -cx); + let (bcx, bcx_t) = two_sum(bx, -cx); + let (acy, acy_t) = two_sum(ay, -cy); + let (bcy, bcy_t) = two_sum(by, -cy); + let prod = |a: &[f64; 2], b: &[f64; 2]| -> Vec { sum(&scale(a, b[0]), &scale(a, b[1])) }; + let left = prod(&[acy_t, acy], &[bcx_t, bcx]); + let right = prod(&[acx_t, acx], &[bcy_t, bcy]); + let neg: Vec = right.iter().map(|v| -v).collect(); + estimate_sign(&sum(&left, &neg)) +} + +// ── Delaunator ───────────────────────────────────────────────────────────── + +fn dist(ax: f64, ay: f64, bx: f64, by: f64) -> f64 { + let dx = ax - bx; + let dy = ay - by; + dx * dx + dy * dy +} + +fn in_circle(ax: f64, ay: f64, bx: f64, by: f64, cx: f64, cy: f64, px: f64, py: f64) -> bool { + let dx = ax - px; + let dy = ay - py; + let ex = bx - px; + let ey = by - py; + let fx = cx - px; + let fy = cy - py; + let ap = dx * dx + dy * dy; + let bp = ex * ex + ey * ey; + let cp = fx * fx + fy * fy; + dx * (ey * cp - bp * fy) - dy * (ex * cp - bp * fx) + ap * (ex * fy - ey * fx) < 0.0 +} + +fn circumradius(ax: f64, ay: f64, bx: f64, by: f64, cx: f64, cy: f64) -> f64 { + let dx = bx - ax; + let dy = by - ay; + let ex = cx - ax; + let ey = cy - ay; + let bl = dx * dx + dy * dy; + let cl = ex * ex + ey * ey; + let d = 0.5 / (dx * ey - dy * ex); + let x = (ey * bl - dy * cl) * d; + let y = (dx * cl - ex * bl) * d; + x * x + y * y +} + +fn circumcenter(ax: f64, ay: f64, bx: f64, by: f64, cx: f64, cy: f64) -> (f64, f64) { + let dx = bx - ax; + let dy = by - ay; + let ex = cx - ax; + let ey = cy - ay; + let bl = dx * dx + dy * dy; + let cl = ex * ex + ey * ey; + let d = 0.5 / (dx * ey - dy * ex); + (ax + (ey * bl - dy * cl) * d, ay + (dx * cl - ex * bl) * d) +} + +fn pseudo_angle(dx: f64, dy: f64) -> f64 { + let p = dx / (dx.abs() + dy.abs()); + (if dy > 0.0 { 3.0 - p } else { 1.0 + p }) / 4.0 +} + +fn quicksort(ids: &mut [u32], dists: &[f64], left: isize, right: isize) { + if right - left <= 20 { + for i in left + 1..=right { + let temp = ids[i as usize]; + let temp_dist = dists[temp as usize]; + let mut j = i - 1; + while j >= left && dists[ids[j as usize] as usize] > temp_dist { + ids[(j + 1) as usize] = ids[j as usize]; + j -= 1; + } + ids[(j + 1) as usize] = temp; + } + } else { + let median = (left + right) >> 1; + let mut i = left + 1; + let mut j = right; + ids.swap(median as usize, i as usize); + if dists[ids[left as usize] as usize] > dists[ids[right as usize] as usize] { + ids.swap(left as usize, right as usize); + } + if dists[ids[i as usize] as usize] > dists[ids[right as usize] as usize] { + ids.swap(i as usize, right as usize); + } + if dists[ids[left as usize] as usize] > dists[ids[i as usize] as usize] { + ids.swap(left as usize, i as usize); + } + let temp = ids[i as usize]; + let temp_dist = dists[temp as usize]; + loop { + loop { + i += 1; + if !(dists[ids[i as usize] as usize] < temp_dist) { + break; + } + } + loop { + j -= 1; + if !(dists[ids[j as usize] as usize] > temp_dist) { + break; + } + } + if j < i { + break; + } + ids.swap(i as usize, j as usize); + } + ids[(left + 1) as usize] = ids[j as usize]; + ids[j as usize] = temp; + if right - i + 1 >= j - left { + quicksort(ids, dists, i, right); + quicksort(ids, dists, left, j - 1); + } else { + quicksort(ids, dists, left, j - 1); + quicksort(ids, dists, i, right); + } + } +} + +struct State<'a> { + coords: &'a [f64], + triangles: Vec, + halfedges: Vec, + hull_prev: Vec, + hull_tri: Vec, + hull_start: usize, + edge_stack: [u32; EDGE_STACK_LEN], +} + +impl State<'_> { + fn link(&mut self, a: usize, b: i32) { + self.halfedges[a] = b; + if b != -1 { + self.halfedges[b as usize] = a as i32; + } + } + + fn add_triangle(&mut self, i0: u32, i1: u32, i2: u32, a: i32, b: i32, c: i32) -> usize { + let t = self.triangles.len(); + self.triangles.extend([i0, i1, i2]); + self.halfedges.extend([-1, -1, -1]); + self.link(t, a); + self.link(t + 1, b); + self.link(t + 2, c); + t + } + + fn legalize(&mut self, a_in: usize) -> usize { + let mut a = a_in; + let mut i = 0usize; + let mut ar; + loop { + let b = self.halfedges[a]; + let a0 = a - a % 3; + ar = a0 + (a + 2) % 3; + if b == -1 { + if i == 0 { + break; + } + i -= 1; + a = self.edge_stack[i] as usize; + continue; + } + let b = b as usize; + let b0 = b - b % 3; + let al = a0 + (a + 1) % 3; + let bl = b0 + (b + 2) % 3; + let p0 = self.triangles[ar] as usize; + let pr = self.triangles[a] as usize; + let pl = self.triangles[al] as usize; + let p1 = self.triangles[bl] as usize; + let c = self.coords; + let illegal = in_circle( + c[2 * p0], c[2 * p0 + 1], c[2 * pr], c[2 * pr + 1], c[2 * pl], c[2 * pl + 1], c[2 * p1], c[2 * p1 + 1], + ); + if illegal { + self.triangles[a] = p1 as u32; + self.triangles[b] = p0 as u32; + let hbl = self.halfedges[bl]; + if hbl == -1 { + let mut e = self.hull_start; + loop { + if self.hull_tri[e] as usize == bl { + self.hull_tri[e] = a as u32; + break; + } + e = self.hull_prev[e] as usize; + if e == self.hull_start { + break; + } + } + } + self.link(a, hbl); + let har = self.halfedges[ar]; + self.link(b, har); + self.link(ar, bl as i32); + let br = b0 + (b + 1) % 3; + if i < EDGE_STACK_LEN { + self.edge_stack[i] = br as u32; + i += 1; + } + } else { + if i == 0 { + break; + } + i -= 1; + a = self.edge_stack[i] as usize; + } + } + ar + } +} + +pub fn triangulate(coords: &[f64]) -> Vec { + let n = coords.len() >> 1; + if n < 3 || coords.len() != 2 * n || coords.iter().any(|v| !v.is_finite()) { + return Vec::new(); + } + let max_triangles = if n * 2 >= 5 { 2 * n - 5 } else { 0 }; + let hash_size = (n as f64).sqrt().ceil() as usize; + let mut hull_next = vec![0u32; n]; + let mut hull_hash = vec![-1i32; hash_size]; + let mut st = State { + coords, + triangles: Vec::with_capacity(max_triangles * 3), + halfedges: Vec::with_capacity(max_triangles * 3), + hull_prev: vec![0u32; n], + hull_tri: vec![0u32; n], + hull_start: 0, + edge_stack: [0; EDGE_STACK_LEN], + }; + let mut ids: Vec = (0..n as u32).collect(); + let mut dists = vec![0.0f64; n]; + + let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for i in 0..n { + let x = coords[2 * i]; + let y = coords[2 * i + 1]; + if x < min_x { + min_x = x; + } + if y < min_y { + min_y = y; + } + if x > max_x { + max_x = x; + } + if y > max_y { + max_y = y; + } + } + let cx = (min_x + max_x) / 2.0; + let cy = (min_y + max_y) / 2.0; + + let (mut i0, mut i1, mut i2) = (0usize, 0usize, 0usize); + let mut min_dist = f64::INFINITY; + for i in 0..n { + let d = dist(cx, cy, coords[2 * i], coords[2 * i + 1]); + if d < min_dist { + i0 = i; + min_dist = d; + } + } + let i0x = coords[2 * i0]; + let i0y = coords[2 * i0 + 1]; + let mut min_dist = f64::INFINITY; + for i in 0..n { + if i == i0 { + continue; + } + let d = dist(i0x, i0y, coords[2 * i], coords[2 * i + 1]); + if d < min_dist && d > 0.0 { + i1 = i; + min_dist = d; + } + } + let mut i1x = coords[2 * i1]; + let mut i1y = coords[2 * i1 + 1]; + let mut min_radius = f64::INFINITY; + for i in 0..n { + if i == i0 || i == i1 { + continue; + } + let r = circumradius(i0x, i0y, i1x, i1y, coords[2 * i], coords[2 * i + 1]); + if r < min_radius { + i2 = i; + min_radius = r; + } + } + let mut i2x = coords[2 * i2]; + let mut i2y = coords[2 * i2 + 1]; + if min_radius == f64::INFINITY { + return Vec::new(); // alle Punkte kollinear: keine Dreiecke + } + if orient2d(i0x, i0y, i1x, i1y, i2x, i2y) < 0.0 { + std::mem::swap(&mut i1, &mut i2); + std::mem::swap(&mut i1x, &mut i2x); + std::mem::swap(&mut i1y, &mut i2y); + } + let (ccx, ccy) = circumcenter(i0x, i0y, i1x, i1y, i2x, i2y); + for i in 0..n { + dists[i] = dist(coords[2 * i], coords[2 * i + 1], ccx, ccy); + } + quicksort(&mut ids, &dists, 0, n as isize - 1); + + let hash_key = |x: f64, y: f64| -> usize { + let v = (pseudo_angle(x - ccx, y - ccy) * hash_size as f64).floor(); + if v.is_nan() { + 0 + } else { + (v as i64).rem_euclid(hash_size as i64) as usize + } + }; + + st.hull_start = i0; + hull_next[i0] = i1 as u32; + st.hull_prev[i2] = i1 as u32; + hull_next[i1] = i2 as u32; + st.hull_prev[i0] = i2 as u32; + hull_next[i2] = i0 as u32; + st.hull_prev[i1] = i0 as u32; + st.hull_tri[i0] = 0; + st.hull_tri[i1] = 1; + st.hull_tri[i2] = 2; + hull_hash[hash_key(i0x, i0y)] = i0 as i32; + hull_hash[hash_key(i1x, i1y)] = i1 as i32; + hull_hash[hash_key(i2x, i2y)] = i2 as i32; + st.add_triangle(i0 as u32, i1 as u32, i2 as u32, -1, -1, -1); + + let (mut xp, mut yp) = (0.0f64, 0.0f64); + for k in 0..n { + let i = ids[k] as usize; + let x = coords[2 * i]; + let y = coords[2 * i + 1]; + if k > 0 && (x - xp).abs() <= EPSILON && (y - yp).abs() <= EPSILON { + continue; + } + xp = x; + yp = y; + if i == i0 || i == i1 || i == i2 { + continue; + } + let mut start = 0usize; + let key = hash_key(x, y); + for j in 0..hash_size { + let s = hull_hash[(key + j) % hash_size]; + start = if s < 0 { usize::MAX } else { s as usize }; + if s != -1 && start != hull_next[start] as usize { + break; + } + } + if start == usize::MAX { + continue; + } + start = st.hull_prev[start] as usize; + let mut e = start; + let mut found = true; + loop { + let q = hull_next[e] as usize; + if orient2d(x, y, coords[2 * e], coords[2 * e + 1], coords[2 * q], coords[2 * q + 1]) >= 0.0 { + e = q; + if e == start { + found = false; + break; + } + } else { + break; + } + } + if !found { + continue; + } + let mut t = st.add_triangle(e as u32, i as u32, hull_next[e], -1, -1, st.hull_tri[e] as i32); + st.hull_tri[i] = st.legalize(t + 2) as u32; + st.hull_tri[e] = t as u32; + + let mut nn = hull_next[e] as usize; + loop { + let q = hull_next[nn] as usize; + if orient2d(x, y, coords[2 * nn], coords[2 * nn + 1], coords[2 * q], coords[2 * q + 1]) < 0.0 { + t = st.add_triangle(nn as u32, i as u32, q as u32, st.hull_tri[i] as i32, -1, st.hull_tri[nn] as i32); + st.hull_tri[i] = st.legalize(t + 2) as u32; + hull_next[nn] = nn as u32; + nn = q; + } else { + break; + } + } + if e == start { + loop { + let q = st.hull_prev[e] as usize; + if orient2d(x, y, coords[2 * q], coords[2 * q + 1], coords[2 * e], coords[2 * e + 1]) < 0.0 { + t = st.add_triangle(q as u32, i as u32, e as u32, -1, st.hull_tri[e] as i32, st.hull_tri[q] as i32); + st.legalize(t + 2); + st.hull_tri[q] = t as u32; + hull_next[e] = e as u32; + e = q; + } else { + break; + } + } + } + st.hull_start = e; + st.hull_prev[i] = e as u32; + hull_next[e] = i as u32; + st.hull_prev[nn] = i as u32; + hull_next[i] = nn as u32; + hull_hash[hash_key(x, y)] = i as i32; + hull_hash[hash_key(coords[2 * e], coords[2 * e + 1])] = e as i32; + } + st.triangles +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn quadrat_ergibt_zwei_dreiecke() { + let t = triangulate(&[0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]); + assert_eq!(t.len(), 6); + } + + #[test] + fn kollinear_und_zu_wenig_sind_leer() { + assert!(triangulate(&[0.0, 0.0, 1.0, 1.0, 2.0, 2.0]).is_empty()); + assert!(triangulate(&[0.0, 0.0, 1.0, 1.0]).is_empty()); + assert!(triangulate(&[0.0, f64::NAN, 1.0, 1.0, 2.0, 5.0]).is_empty()); + } + + #[test] + fn orient_ist_exakt() { + // fast kollinear: nur mit exakter Arithmetik korrekt + let a = (0.5, 0.5); + let b = (12.0, 12.0); + let c = (24.0, 24.0); + assert_eq!(orient2d(a.0, a.1, b.0, b.1, c.0, c.1), 0.0); + assert!(orient2d(0.0, 0.0, 1.0, 0.0, 0.0, 1.0) < 0.0); + assert!(orient2d(0.0, 0.0, 0.0, 1.0, 1.0, 0.0) > 0.0); + } +} diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 58f1fbb7..3a0b0adc 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -37,6 +37,7 @@ pub mod plan_stairs; pub mod plan_walls; pub mod opening_geom; pub mod plan_openings; +pub mod delaunay; pub mod mesh_section; pub mod plan_elevation; pub mod plan_misc; diff --git a/src-tauri/core/src/web/delaunay.rs b/src-tauri/core/src/web/delaunay.rs new file mode 100644 index 00000000..b936ed86 --- /dev/null +++ b/src-tauri/core/src/web/delaunay.rs @@ -0,0 +1,9 @@ +//! Bindung der Delaunay-Triangulierung (`crate::delaunay`). + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Delaunay-Dreiecke zu `[x0, y0, x1, y1 …]`; Indizes je drei; leer bei < 3 oder kollinearen Punkten. +#[wasm_bindgen] +pub fn delaunay_flat(coords: &[f64]) -> Vec { + crate::delaunay::triangulate(coords).into_iter().map(f64::from).collect() +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 4a75e16a..db426be7 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -28,6 +28,7 @@ mod gpu_compile; mod plan_stairs; mod plan_walls; mod plan_openings; +mod delaunay; mod mesh_section; mod plan_elevation; mod plan_misc; diff --git a/src/io/geoContext.ts b/src/io/geoContext.ts index a16e839f..2059d353 100644 --- a/src/io/geoContext.ts +++ b/src/io/geoContext.ts @@ -8,7 +8,7 @@ // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import { allowHost } from "../net/net"; -import Delaunator from "delaunator"; +import { core } from "../engine/coreWasm"; import type { ContextObject, Contour, ImportedMesh } from "../model/types"; import { GEO_CATEGORY_DEFS } from "../model/contextCategories"; @@ -228,12 +228,7 @@ function triangulateRing(ring: { x: number; y: number }[]): number[] { coords[i * 2] = ring[i].x; coords[i * 2 + 1] = ring[i].y; } - let tri: Uint32Array; - try { - tri = new Delaunator(coords).triangles; - } catch { - return fanTriangulate(n); - } + const tri = core().delaunay_flat(coords); const out: number[] = []; for (let t = 0; t < tri.length; t += 3) { const a = tri[t], b = tri[t + 1], c = tri[t + 2]; diff --git a/src/model/terrain.ts b/src/model/terrain.ts index a1082226..60ddd585 100644 --- a/src/model/terrain.ts +++ b/src/model/terrain.ts @@ -8,7 +8,7 @@ // // Gelände ist NICHT semantisch — es ist Kontext-Geometrie (Project.context). -import Delaunator from "delaunator"; +import { core } from "../engine/coreWasm"; import type { Contour, TerrainMesh } from "./types"; import { TERRAIN_CATEGORY } from "./contextCategories"; @@ -25,7 +25,7 @@ export const TERRAIN_LAYER = "Terrain"; * z = Kontur-Höhe. Es wird KEIN zusätzliches Resampling betrieben — die * Kontur-Vertices selbst sind die Breaklines. * 2. Delaunay: 2D-Triangulation über die (x,y)-Projektion aller Vertices - * (Delaunator). Die Z-Höhe je Vertex bleibt erhalten → echtes Gelände-TIN. + * (Rust-Kern, `delaunay.rs`). Die Z-Höhe je Vertex bleibt erhalten → echtes Gelände-TIN. * 3. Degenerate-Filter: Dreiecke mit (nahezu) null Fläche in der (x,y)-Ebene * bzw. mit nicht-endlichen Koordinaten werden verworfen. * @@ -59,21 +59,16 @@ export function generateTerrainFromContours(contours: Contour[]): TerrainMesh { return { id, type: "terrainMesh", name, categoryCode: TERRAIN_CATEGORY.code, positions: [], indices: [] }; } - // 2. Delaunay über die (x,y)-Projektion. Delaunator erwartet ein flaches + // 2. Delaunay über die (x,y)-Projektion. der Kern erwartet ein flaches // [x0,y0, x1,y1, …]-Koordinatenarray. const coords2d = new Float64Array(xs.length * 2); for (let i = 0; i < xs.length; i++) { coords2d[i * 2] = xs[i]; coords2d[i * 2 + 1] = ys[i]; } - // Bei kollinearen Punkten liefert Delaunator eine leere Triangulation — das ist - // korrekt (kein Crash). Trotzdem schützen wir gegen einen möglichen Wurf. - let triangles: Uint32Array; - try { - triangles = new Delaunator(coords2d).triangles; - } catch { - return { id, type: "terrainMesh", name, categoryCode: TERRAIN_CATEGORY.code, positions: [], indices: [] }; - } + // Der Kern (`delaunay.rs`, Port von delaunator) liefert bei kollinearen Punkten eine leere + // Triangulation — das ist korrekt. + const triangles = core().delaunay_flat(coords2d); // 3. positions (x,y,z) aufbauen; Z aus zs je Vertex. const positions: number[] = new Array(xs.length * 3); From 72ef7b770ea5d5d88f21f34d5799f98067d622fd Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:32:33 +0100 Subject: [PATCH 13/31] [K3c] Abzugskoerper-Geometrie (Schluesselloch, Subtraktion, Strecke, Schnitt-Rechtecke) in Rust (voids.rs); mehrere getrennte Aussparungen wirken jetzt alle --- TODO.md | 1 + src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/voids.rs | 385 ++++++++++++++++++++++++++++++++ src-tauri/core/src/web/mod.rs | 1 + src-tauri/core/src/web/voids.rs | 27 +++ src/plan/voids.test.ts | 5 + src/plan/voids.ts | 205 ++++------------- 7 files changed, 462 insertions(+), 163 deletions(-) create mode 100644 src-tauri/core/src/voids.rs create mode 100644 src-tauri/core/src/web/voids.rs diff --git a/TODO.md b/TODO.md index f58b068a..fa4c0401 100644 --- a/TODO.md +++ b/TODO.md @@ -110,6 +110,7 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern ✅ Ansicht: Flächen (Wand-Quader, Decken-Prismen, Dach/Giebel) projizieren + Rückseiten-Culling, Eck-Verlängerung, Öffnungen (Rahmen, Glasfelder, Sprossen, Sims, SIA-Symbol) (`plan_elevation.rs`). ✅ Netz-Ebenenschnitt (Körper/Gelände) + Ringe→Flächen (`mesh_section.rs`; behebt nebenbei: rückwärts geschlossene Ringe gingen verloren). ✅ Dach-Schnittspur (Cyrus–Beck, lineare Oberkante, Verschmelzen) in `plan_section.rs`. + ✅ Abzugskörper-Geometrie (`voids.rs`: Polygon minus Schneider mit Schlüsselloch-Stegen, Strecke ausserhalb, Schnitt-Rechtecke); behebt: bei mehreren getrennten Aussparungen wurde nichts abgezogen. - ○ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. 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. diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 3a0b0adc..ade3dffd 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -42,6 +42,7 @@ pub mod mesh_section; pub mod plan_elevation; pub mod plan_misc; pub mod plan_section; +pub mod voids; pub mod curves; #[cfg(feature = "web")] diff --git a/src-tauri/core/src/voids.rs b/src-tauri/core/src/voids.rs new file mode 100644 index 00000000..27fb260a --- /dev/null +++ b/src-tauri/core/src/voids.rs @@ -0,0 +1,385 @@ +//! Abzugskörper in Grundriss und Schnitt ([K3c], vorher `plan/voids.ts`): Polygon minus Schneider mit +//! Schlüsselloch-Stegen für Löcher, nicht gestrichene Kanten, Strecke ausserhalb von Ringen und die +//! Schnitt-Rechtecke eines senkrechten Prismas. Die Auswahl, welche Körper welches Bauteil treffen, +//! bleibt in TS (Modell). Rechenreihenfolge wie dort. +//! +//! ## Flaches Format +//! Ringliste `[n, (k, x, y …) × n]`. +//! - `keyhole(ringe)` → `[k, x, y …, nStege, i …]` (Ringe offen oder geschlossen). +//! - `subtract_rings(pts, schneider, nicht_gestrichen)`: `pts = [k, x, y …]`, `schneider = Ringliste`, +//! `nicht_gestrichen = [m, i …]` → `[-1]` (keine Überschneidung — Original unverändert) oder +//! `[n, (k, x, y …, m, i …) × n]`. +//! - `segment_outside(ax, ay, bx, by, schneider)` → `[n, (t0, t1) × n]`. +//! - `section_rects(pts, base_x, base_y, u_x, u_y)` → `[n, (u0, u1) × n]`. +//! +//! Abweichung zur TS-Fassung: der Überschneidungstest nahm den Schnitt mit ALLEN Schneidern +//! gleichzeitig; mit zwei getrennten Aussparungen fiel dann jede Subtraktion weg. Jetzt gilt die +//! Vereinigung der Schneider. + +use crate::flat_read::{signed_area, Reader}; +use crate::jsmath::hypot2; +use crate::jsnum::max; +use crate::polygon_bool; + +type Pair = [f64; 2]; +const EPS: f64 = 1e-7; + +fn open_ring(r: &[Pair]) -> Vec { + if r.len() > 1 { + let a = r[0]; + let b = r[r.len() - 1]; + if (a[0] - b[0]).abs() < EPS && (a[1] - b[1]).abs() < EPS { + return r[..r.len() - 1].to_vec(); + } + } + r.to_vec() +} + +/// Löcher per Steg in den Aussenring einhängen; liefert Punkte und Stegkanten-Indizes. +pub fn keyhole(poly: &[Vec]) -> (Vec, Vec) { + let mut outer = open_ring(&poly[0]); + let mut bridges: Vec = Vec::new(); + let mut holes: Vec> = poly[1..].iter().map(|h| open_ring(h)).filter(|h| h.len() >= 3).collect(); + let max_x = |h: &Vec| h.iter().fold(f64::NEG_INFINITY, |m, p| max(m, p[0])); + holes.sort_by(|a, b| (max_x(b) - max_x(a)).partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal)); + for hole in holes { + let mut hi = 0; + for i in 1..hole.len() { + if hole[i][0] > hole[hi][0] { + hi = i; + } + } + let h = hole[hi]; + let mut oi = 0; + let mut best = f64::INFINITY; + for (i, p) in outer.iter().enumerate() { + let d = hypot2(p[0] - h[0], p[1] - h[1]); + if d < best { + best = d; + oi = i; + } + } + let mut hole_seq: Vec = hole[hi..].to_vec(); + hole_seq.extend_from_slice(&hole[..hi]); + hole_seq.push(h); + let mut next: Vec = outer[..=oi].to_vec(); + next.extend_from_slice(&hole_seq); + next.push(outer[oi]); + next.extend_from_slice(&outer[oi + 1..]); + let shift = hole_seq.len() + 1; + for b in bridges.iter_mut() { + if *b > oi { + *b += shift; + } + } + bridges.push(oi); + bridges.push(oi + hole_seq.len()); + outer = next; + } + (outer, bridges) +} + +fn on_segment(a: Pair, b: Pair, p: Pair, q: Pair) -> bool { + let tol = 1e-6; + let dx = q[0] - p[0]; + let dy = q[1] - p[1]; + let len = hypot2(dx, dy); + if len < EPS { + return false; + } + let dist = |r: Pair| ((r[0] - p[0]) * dy - (r[1] - p[1]) * dx).abs() / len; + let t = |r: Pair| ((r[0] - p[0]) * dx + (r[1] - p[1]) * dy) / (len * len); + dist(a) < tol && dist(b) < tol && t(a) > -tol && t(a) < 1.0 + tol && t(b) > -tol && t(b) < 1.0 + tol +} + +/// Math.sign: NaN bleibt NaN, ±0 bleibt 0. +fn js_sign(x: f64) -> f64 { + if x.is_nan() || x == 0.0 { + x + } else { + x.signum() + } +} + +pub struct Piece { + pub pts: Vec, + pub no_stroke: Vec, +} + +/// `None` = keine Überschneidung (Original unverändert lassen). +pub fn subtract_rings(pts: &[Pair], cutters: &[Vec], no_stroke: &[usize]) -> Option> { + if pts.len() < 3 || cutters.is_empty() { + return None; + } + let subject = vec![pts.to_vec()]; + let clips: Vec>> = cutters.iter().filter(|c| c.len() >= 3).map(|c| vec![c.clone()]).collect(); + if clips.is_empty() { + return None; + } + let all_clips = polygon_bool::union(&clips); + if polygon_bool::intersection(&[subject.clone()], &all_clips).is_empty() { + return None; + } + let diff = polygon_bool::difference(&[subject], &clips); + let area0 = signed_area(pts).abs(); + let mut out = Vec::new(); + for poly in &diff { + // Ringe wie im TS-Pfad geschlossen übergeben (der Kern liefert offene Ringe). + let closed: Vec> = poly + .iter() + .map(|r| { + let mut c = r.clone(); + if let Some(&f) = r.first() { + c.push(f); + } + c + }) + .collect(); + let (kp, bridges) = keyhole(&closed); + if kp.len() < 3 || signed_area(&open_ring(&closed[0])).abs() < area0 * 1e-9 { + continue; + } + let same_dir = js_sign(signed_area(&kp)) == js_sign(signed_area(pts)) || signed_area(pts) == 0.0; + let ring_pts: Vec = if same_dir { kp } else { kp.into_iter().rev().collect() }; + let n = ring_pts.len(); + let bridge_set: std::collections::HashSet = if same_dir { + bridges.iter().copied().collect() + } else { + bridges.iter().map(|&i| (n + n - 2 - i.min(n + n - 2)) % n).collect() + }; + let mut ns = Vec::new(); + for i in 0..n { + let a = ring_pts[i]; + let b = ring_pts[(i + 1) % n]; + if bridge_set.contains(&i) { + ns.push(i); + continue; + } + for &e in no_stroke { + if e < pts.len() { + let p = pts[e]; + let q = pts[(e + 1) % pts.len()]; + if on_segment(a, b, p, q) { + ns.push(i); + break; + } + } + } + } + out.push(Piece { pts: ring_pts, no_stroke: ns }); + } + Some(out) +} + +fn point_in_ring(x: f64, y: f64, r: &[Pair]) -> bool { + let mut inside = false; + let mut j = r.len().wrapping_sub(1); + for i in 0..r.len() { + let [xi, yi] = r[i]; + let [xj, yj] = r[j]; + if (yi > y) != (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi { + inside = !inside; + } + j = i; + } + inside +} + +/// Teile der Strecke a→b ausserhalb aller Ringe, als Parameter-Intervalle. +pub fn segment_outside(a: Pair, b: Pair, cutters: &[Vec]) -> Vec<(f64, f64)> { + let mut ts = vec![0.0, 1.0]; + let dx = b[0] - a[0]; + let dy = b[1] - a[1]; + for r in cutters { + for i in 0..r.len() { + let p = r[i]; + let q = r[(i + 1) % r.len()]; + let ex = q[0] - p[0]; + let ey = q[1] - p[1]; + let den = dx * ey - dy * ex; + if den.abs() < 1e-14 { + continue; + } + let t = ((p[0] - a[0]) * ey - (p[1] - a[1]) * ex) / den; + let u = ((p[0] - a[0]) * dy - (p[1] - a[1]) * dx) / den; + if t > 0.0 && t < 1.0 && u >= -1e-9 && u <= 1.0 + 1e-9 { + ts.push(t); + } + } + } + ts.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal)); + let mut out: Vec<(f64, f64)> = Vec::new(); + for i in 0..ts.len() - 1 { + let (t0, t1) = (ts[i], ts[i + 1]); + if t1 - t0 < 1e-9 { + continue; + } + let tm = (t0 + t1) / 2.0; + let mx = a[0] + dx * tm; + let my = a[1] + dy * tm; + if cutters.iter().any(|r| point_in_ring(mx, my, r)) { + continue; + } + match out.last_mut() { + Some(last) if (last.1 - t0).abs() < 1e-9 => last.1 = t1, + _ => out.push((t0, t1)), + } + } + out +} + +/// u-Intervalle der Schnittspur durch ein senkrechtes Prisma (`pts` = Grundriss). +pub fn section_rects(pts: &[Pair], base: Pair, u_dir: Pair) -> Vec<(f64, f64)> { + let n = pts.len(); + let side = |p: Pair| (p[0] - base[0]) * u_dir[1] - (p[1] - base[1]) * u_dir[0]; + let mut ts: Vec = Vec::new(); + for i in 0..n { + let a = pts[i]; + let b = pts[(i + 1) % n]; + let sa = side(a); + let sb = side(b); + if (sa > 0.0) == (sb > 0.0) { + continue; + } + let t = sa / (sa - sb); + let px = a[0] + (b[0] - a[0]) * t; + let py = a[1] + (b[1] - a[1]) * t; + ts.push((px - base[0]) * u_dir[0] + (py - base[1]) * u_dir[1]); + } + ts.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + let mut out = Vec::new(); + let mut i = 0; + while i + 1 < ts.len() { + let (u0, u1) = (ts[i], ts[i + 1]); + i += 2; + if u1 - u0 < 1e-6 { + continue; + } + out.push((u0, u1)); + } + out +} + +// ── Bindungen (flach) ────────────────────────────────────────────────────── + +fn read_rings(r: &mut Reader) -> Option>> { + let n = r.count()?; + (0..n).map(|_| r.ring()).collect() +} + +fn finite(rings: &[Vec]) -> bool { + rings.iter().all(|r| r.iter().all(|p| p[0].is_finite() && p[1].is_finite())) +} + +fn push_ring(f: &mut Vec, r: &[Pair]) { + f.push(r.len() as f64); + for p in r { + f.extend(*p); + } +} + +pub fn keyhole_flat(inp: &[f64]) -> Vec { + let mut r = Reader::new(inp); + let Some(rings) = read_rings(&mut r) else { return Vec::new() }; + if rings.is_empty() || !finite(&rings) || rings[0].is_empty() { + return Vec::new(); + } + let (pts, bridges) = keyhole(&rings); + let mut f = Vec::new(); + push_ring(&mut f, &pts); + f.push(bridges.len() as f64); + f.extend(bridges.iter().map(|&b| b as f64)); + f +} + +pub fn subtract_rings_flat(pts: &[f64], cutters: &[f64], no_stroke: &[f64]) -> Vec { + let (mut rp, mut rc, mut rn) = (Reader::new(pts), Reader::new(cutters), Reader::new(no_stroke)); + let (Some(p), Some(c)) = (rp.ring(), read_rings(&mut rc)) else { return Vec::new() }; + let Some(m) = rn.count() else { return Vec::new() }; + let Some(ns) = (0..m).map(|_| rn.count()).collect::>>() else { return Vec::new() }; + if !finite(&c) || !finite(&[p.clone()]) { + return Vec::new(); + } + match subtract_rings(&p, &c, &ns) { + None => vec![-1.0], + Some(pieces) => { + let mut f = vec![pieces.len() as f64]; + for pc in &pieces { + push_ring(&mut f, &pc.pts); + f.push(pc.no_stroke.len() as f64); + f.extend(pc.no_stroke.iter().map(|&i| i as f64)); + } + f + } + } +} + +pub fn segment_outside_flat(a: &[f64], cutters: &[f64]) -> Vec { + let mut rc = Reader::new(cutters); + let Some(c) = read_rings(&mut rc) else { return Vec::new() }; + if a.len() != 4 || a.iter().any(|v| !v.is_finite()) || !finite(&c) { + return Vec::new(); + } + let parts = segment_outside([a[0], a[1]], [a[2], a[3]], &c); + let mut f = vec![parts.len() as f64]; + for (t0, t1) in parts { + f.extend([t0, t1]); + } + f +} + +pub fn section_rects_flat(pts: &[f64], base_u: &[f64]) -> Vec { + let mut r = Reader::new(pts); + let Some(p) = r.ring() else { return Vec::new() }; + if base_u.len() != 4 || base_u.iter().any(|v| !v.is_finite()) || !finite(&[p.clone()]) || p.is_empty() { + return Vec::new(); + } + let rects = section_rects(&p, [base_u[0], base_u[1]], [base_u[2], base_u[3]]); + let mut f = vec![rects.len() as f64]; + for (u0, u1) in rects { + f.extend([u0, u1]); + } + f +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sq(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec { + vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]] + } + + #[test] + fn loch_wird_per_steg_eingehaengt() { + let r = subtract_rings(&sq(0.0, 0.0, 4.0, 2.0), &[sq(1.0, 0.5, 2.0, 1.5)], &[]).unwrap(); + assert_eq!(r.len(), 1); + assert_eq!(r[0].pts.len(), 10); + assert_eq!(r[0].no_stroke.len(), 2); + } + + #[test] + fn ohne_ueberschneidung_none() { + assert!(subtract_rings(&sq(0.0, 0.0, 1.0, 1.0), &[sq(5.0, 5.0, 6.0, 6.0)], &[]).is_none()); + } + + #[test] + fn zwei_getrennte_aussparungen_wirken_beide() { + let r = subtract_rings(&sq(0.0, 0.0, 10.0, 2.0), &[sq(1.0, -1.0, 2.0, 3.0), sq(6.0, -1.0, 7.0, 3.0)], &[]).unwrap(); + assert_eq!(r.len(), 3); + } + + #[test] + fn strecke_wird_geteilt() { + let parts = segment_outside([0.0, 0.5], [4.0, 0.5], &[sq(1.0, 0.0, 2.0, 1.0)]); + assert_eq!(parts.len(), 2); + assert!((parts[0].1 - 0.25).abs() < 1e-12 && (parts[1].0 - 0.5).abs() < 1e-12); + } + + #[test] + fn unsinn_ist_leer() { + assert!(keyhole_flat(&[f64::NAN]).is_empty()); + assert!(subtract_rings_flat(&[3.0, 0.0], &[0.0], &[0.0]).is_empty()); + assert!(section_rects_flat(&[3.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0], &[0.0]).is_empty()); + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index db426be7..0a26d665 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -33,6 +33,7 @@ mod mesh_section; mod plan_elevation; mod plan_misc; mod plan_section; +mod voids; mod curves; mod hatch; diff --git a/src-tauri/core/src/web/voids.rs b/src-tauri/core/src/web/voids.rs new file mode 100644 index 00000000..6b33f1fb --- /dev/null +++ b/src-tauri/core/src/web/voids.rs @@ -0,0 +1,27 @@ +//! Bindungen der Abzugskörper-Geometrie (`crate::voids`). Layouts s. dort. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Löcher als Schlüsselloch-Stege in den Aussenring; Unsinn → leer. +#[wasm_bindgen] +pub fn voids_keyhole_flat(rings: &[f64]) -> Vec { + crate::voids::keyhole_flat(rings) +} + +/// Polygon minus Schneider (mit nicht gestrichenen Kanten); `[-1]` = keine Überschneidung. +#[wasm_bindgen] +pub fn voids_subtract_rings_flat(pts: &[f64], cutters: &[f64], no_stroke: &[f64]) -> Vec { + crate::voids::subtract_rings_flat(pts, cutters, no_stroke) +} + +/// Teile einer Strecke ausserhalb aller Ringe; Unsinn → leer. +#[wasm_bindgen] +pub fn voids_segment_outside_flat(seg: &[f64], cutters: &[f64]) -> Vec { + crate::voids::segment_outside_flat(seg, cutters) +} + +/// Schnitt-Intervalle eines Prismas mit einer senkrechten Ebene; Unsinn → leer. +#[wasm_bindgen] +pub fn voids_section_rects_flat(pts: &[f64], base_u: &[f64]) -> Vec { + crate::voids::section_rects_flat(pts, base_u) +} diff --git a/src/plan/voids.test.ts b/src/plan/voids.test.ts index 95725702..10ab1836 100644 --- a/src/plan/voids.test.ts +++ b/src/plan/voids.test.ts @@ -29,6 +29,11 @@ describe("Abzugskoerper — Polygon-Kern", () => { it("ohne Ueberschneidung: null (Original bleibt)", () => { expect(subtractRings(sq(0, 0, 1, 1), [sq(5, 5, 6, 6)])).toBeNull(); }); + it("zwei getrennte Aussparungen wirken beide (drei Restteile)", () => { + // Früher: der Überschneidungstest schnitt mit ALLEN Schneidern zugleich → keine Subtraktion. + const r = subtractRings(sq(0, 0, 10, 2), [sq(1, -1, 2, 3), sq(6, -1, 7, 3)])!; + expect(r).toHaveLength(3); + }); it("ungestrichene Originalkanten bleiben ungestrichen", () => { // Kante 1 (rechts, x=4) ungestrichen; der Schnitt links lässt sie unberührt. const r = subtractRings(sq(0, 0, 4, 2), [sq(-1, -1, 1, 3)], [1])!; diff --git a/src/plan/voids.ts b/src/plan/voids.ts index fd0150e8..940eec1a 100644 --- a/src/plan/voids.ts +++ b/src/plan/voids.ts @@ -15,8 +15,8 @@ // Polygone mit Loch (Körper ganz im Bauteil) werden über einen Steg an den Aussenring // gehängt (Schlüsselloch); die beiden Stegkanten sind nicht gestrichen (`noStrokeEdges`). -import * as polygonClipping from "../geometry/polygonBool"; -import type { Pair, Polygon as PcPolygon, MultiPolygon } from "../geometry/polygonBool"; +import type { Pair } from "../geometry/polygonBool"; +import { core } from "../engine/coreWasm"; import type { ExtrudedSolid, Project, Vec2 } from "../model/types"; import { getFloor } from "../model/types"; import { ceilingVerticalExtent, columnVerticalExtent } from "../model/wall"; @@ -60,29 +60,18 @@ export function voidPrisms(project: Project): VoidPrism[] { return out; } -// ── Polygon-Booleans ───────────────────────────────────────────────────────── +// ── Polygon-Booleans (Rust-Kern, `voids.rs`) ───────────────────────────────── const ring = (pts: Vec2[]): Pair[] => pts.map((p) => [p.x, p.y] as Pair); -/** Fläche (vorzeichenbehaftet) eines Rings. */ -function signedArea(r: Pair[]): number { - let a = 0; - for (let i = 0; i < r.length; i++) { - const p = r[i]; - const q = r[(i + 1) % r.length]; - a += p[0] * q[1] - q[0] * p[1]; +/** Ringliste flach für den Kern (`[n, (k, x, y …) × n]`). */ +function encodeRings(rings: Pair[][]): Float64Array { + const b: number[] = [rings.length]; + for (const r of rings) { + b.push(r.length); + for (const p of r) b.push(p[0], p[1]); } - return a / 2; -} - -/** Ring ohne doppelten Schlusspunkt (der Polygon-Kern liefert geschlossene Ringe). */ -function openRing(r: Pair[]): Pair[] { - if (r.length > 1) { - const a = r[0]; - const b = r[r.length - 1]; - if (Math.abs(a[0] - b[0]) < EPS && Math.abs(a[1] - b[1]) < EPS) return r.slice(0, -1); - } - return r; + return Float64Array.from(b); } /** @@ -90,45 +79,14 @@ function openRing(r: Pair[]): Pair[] { * Indizes der Stegkanten (Kante i = pts[i] → pts[i+1]). */ export function keyhole(poly: Pair[][]): { pts: Pair[]; bridges: number[] } { - let outer = openRing(poly[0]); - const bridges: number[] = []; - const holes = poly.slice(1).map(openRing).filter((h) => h.length >= 3); - // Löcher von rechts nach links einhängen (Stege kreuzen sich so nicht). - holes.sort((a, b) => Math.max(...b.map((p) => p[0])) - Math.max(...a.map((p) => p[0]))); - for (const hole of holes) { - // Lochpunkt mit grösstem x, nächster Aussenring-Punkt dazu. - let hi = 0; - for (let i = 1; i < hole.length; i++) if (hole[i][0] > hole[hi][0]) hi = i; - const h = hole[hi]; - let oi = 0; - let best = Infinity; - for (let i = 0; i < outer.length; i++) { - const d = Math.hypot(outer[i][0] - h[0], outer[i][1] - h[1]); - if (d < best) { - best = d; - oi = i; - } - } - const holeSeq = [...hole.slice(hi), ...hole.slice(0, hi), h]; - const next: Pair[] = [...outer.slice(0, oi + 1), ...holeSeq, outer[oi], ...outer.slice(oi + 1)]; - // Indizes der beiden Stegkanten (alte Stegindizes hinter oi verschieben sich). - const shift = holeSeq.length + 1; - for (let k = 0; k < bridges.length; k++) if (bridges[k] > oi) bridges[k] += shift; - bridges.push(oi, oi + holeSeq.length); - outer = next; - } - return { pts: outer, bridges }; -} - -/** Liegt Segment a→b auf Segment p→q (kollinear, innerhalb)? */ -function onSegment(a: Pair, b: Pair, p: Pair, q: Pair, tol = 1e-6): boolean { - const dx = q[0] - p[0]; - const dy = q[1] - p[1]; - const len = Math.hypot(dx, dy); - if (len < EPS) return false; - const dist = (r: Pair) => Math.abs((r[0] - p[0]) * dy - (r[1] - p[1]) * dx) / len; - const t = (r: Pair) => ((r[0] - p[0]) * dx + (r[1] - p[1]) * dy) / (len * len); - return dist(a) < tol && dist(b) < tol && t(a) > -tol && t(a) < 1 + tol && t(b) > -tol && t(b) < 1 + tol; + const f = core().voids_keyhole_flat(encodeRings(poly)); + const n = f[0]; + const pts = new Array(n); + for (let i = 0; i < n; i++) pts[i] = [f[1 + 2 * i], f[2 + 2 * i]]; + const nb = f[1 + 2 * n]; + const bridges = new Array(nb); + for (let i = 0; i < nb; i++) bridges[i] = f[2 + 2 * n + i]; + return { pts, bridges }; } /** @@ -143,99 +101,33 @@ export function subtractRings( noStroke: number[] = [], ): Array<{ pts: Pair[]; noStrokeEdges: number[] }> | null { if (pts.length < 3 || cutters.length === 0) return null; - const subject: PcPolygon = [pts]; - const clips: MultiPolygon = cutters.filter((c) => c.length >= 3).map((c) => [c] as PcPolygon); - if (clips.length === 0) return null; - // Schnell-Test: überlappen die Hüllen überhaupt? - let hit = false; - try { - hit = polygonClipping.intersection(subject, ...clips).length > 0; - } catch { - return null; - } - if (!hit) return null; - let diff: MultiPolygon; - try { - diff = polygonClipping.difference(subject, ...clips); - } catch { - return null; - } - const area0 = Math.abs(signedArea(pts)); + const f = core().voids_subtract_rings_flat( + encodeRings([pts]).subarray(1), + encodeRings(cutters), + Float64Array.from([noStroke.length, ...noStroke]), + ); + if (f.length === 0 || f[0] < 0) return null; const out: Array<{ pts: Pair[]; noStrokeEdges: number[] }> = []; - for (const poly of diff) { - const { pts: kp, bridges } = keyhole(poly); - if (kp.length < 3 || Math.abs(signedArea(openRing(poly[0]))) < area0 * 1e-9) continue; - // Orientierung des Originals beibehalten (Schraffur-/Strich-Logik ist orientierungsfrei, - // aber Tests und Nachbearbeitungen erwarten den Umlaufsinn). - const sameDir = Math.sign(signedArea(kp)) === Math.sign(signedArea(pts)) || signedArea(pts) === 0; - const ringPts = sameDir ? kp : [...kp].reverse(); - const n = ringPts.length; - const bridgeSet = new Set(sameDir ? bridges : bridges.map((i) => (n - 2 - i + n) % n)); - const ns: number[] = []; - for (let i = 0; i < n; i++) { - const a = ringPts[i]; - const b = ringPts[(i + 1) % n]; - if (bridgeSet.has(i)) { - ns.push(i); - continue; - } - for (const e of noStroke) { - const p = pts[e]; - const q = pts[(e + 1) % pts.length]; - if (p && q && onSegment(a, b, p, q)) { - ns.push(i); - break; - } - } - } - out.push({ pts: ringPts, noStrokeEdges: ns }); + let i = 1; + for (let k = 0; k < f[0]; k++) { + const n = f[i++]; + const rp = new Array(n); + for (let j = 0; j < n; j++, i += 2) rp[j] = [f[i], f[i + 1]]; + const m = f[i++]; + const ns = new Array(m); + for (let j = 0; j < m; j++) ns[j] = f[i++]; + out.push({ pts: rp, noStrokeEdges: ns }); } return out; } // ── Grundriss ──────────────────────────────────────────────────────────────── -function pointInRing(x: number, y: number, r: Pair[]): boolean { - let inside = false; - for (let i = 0, j = r.length - 1; i < r.length; j = i++) { - const [xi, yi] = r[i]; - const [xj, yj] = r[j]; - if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside; - } - return inside; -} - /** Teile der Strecke a→b ausserhalb aller Ringe, als Parameter-Intervalle [t0, t1]. */ export function segmentOutside(a: Vec2, b: Vec2, cutters: Pair[][]): Array<[number, number]> { - const ts = [0, 1]; - const dx = b.x - a.x; - const dy = b.y - a.y; - for (const r of cutters) { - for (let i = 0; i < r.length; i++) { - const p = r[i]; - const q = r[(i + 1) % r.length]; - const ex = q[0] - p[0]; - const ey = q[1] - p[1]; - const den = dx * ey - dy * ex; - if (Math.abs(den) < 1e-14) continue; - const t = ((p[0] - a.x) * ey - (p[1] - a.y) * ex) / den; - const u = ((p[0] - a.x) * dy - (p[1] - a.y) * dx) / den; - if (t > 0 && t < 1 && u >= -1e-9 && u <= 1 + 1e-9) ts.push(t); - } - } - ts.sort((x, y) => x - y); + const f = core().voids_segment_outside_flat(Float64Array.from([a.x, a.y, b.x, b.y]), encodeRings(cutters)); const out: Array<[number, number]> = []; - for (let i = 0; i + 1 < ts.length; i++) { - const [t0, t1] = [ts[i], ts[i + 1]]; - if (t1 - t0 < 1e-9) continue; - const tm = (t0 + t1) / 2; - const mx = a.x + dx * tm; - const my = a.y + dy * tm; - if (cutters.some((r) => pointInRing(mx, my, r))) continue; - const last = out[out.length - 1]; - if (last && Math.abs(last[1] - t0) < 1e-9) last[1] = t1; - else out.push([t0, t1]); - } + for (let k = 0; k < (f[0] ?? 0); k++) out.push([f[1 + 2 * k], f[2 + 2 * k]]); return out; } @@ -315,27 +207,14 @@ export function subtractVoidsInPlan(prims: Primitive[], project: Project, cutZ: * Richtung `uDir` (Einheitsvektor; u = Abstand entlang uDir ab `base`). */ export function voidSectionRects(v: VoidPrism, base: Vec2, uDir: Vec2): Pair[][] { - const ts: number[] = []; - const n = v.pts.length; - // Normale der Schnittspur: Punkt-Seite über das Kreuzprodukt. - const side = (p: Vec2) => (p.x - base.x) * uDir.y - (p.y - base.y) * uDir.x; - for (let i = 0; i < n; i++) { - const a = v.pts[i]; - const b = v.pts[(i + 1) % n]; - const sa = side(a); - const sb = side(b); - // Halboffene Regel (eine Ecke auf der Spur zählt nur einmal). - if ((sa > 0) === (sb > 0)) continue; - const t = sa / (sa - sb); - const px = a.x + (b.x - a.x) * t; - const py = a.y + (b.y - a.y) * t; - ts.push((px - base.x) * uDir.x + (py - base.y) * uDir.y); - } - ts.sort((a, b) => a - b); + const f = core().voids_section_rects_flat( + Float64Array.from([v.pts.length, ...v.pts.flatMap((p) => [p.x, p.y])]), + Float64Array.from([base.x, base.y, uDir.x, uDir.y]), + ); const rects: Pair[][] = []; - for (let i = 0; i + 1 < ts.length; i += 2) { - const [u0, u1] = [ts[i], ts[i + 1]]; - if (u1 - u0 < 1e-6) continue; + for (let k = 0; k < (f[0] ?? 0); k++) { + const u0 = f[1 + 2 * k]; + const u1 = f[2 + 2 * k]; rects.push([ [u0, v.z0], [u1, v.z0], From 1c3f38e9abdcb30e31c87034b24314b110e1684a Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:35:02 +0100 Subject: [PATCH 14/31] [K3] TODO: Stand K3c, was in TS bleibt und warum K3d an K4 haengt --- TODO.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/TODO.md b/TODO.md index fa4c0401..a8ed41ac 100644 --- a/TODO.md +++ b/TODO.md @@ -111,7 +111,12 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern ✅ Netz-Ebenenschnitt (Körper/Gelände) + Ringe→Flächen (`mesh_section.rs`; behebt nebenbei: rückwärts geschlossene Ringe gingen verloren). ✅ Dach-Schnittspur (Cyrus–Beck, lineare Oberkante, Verschmelzen) in `plan_section.rs`. ✅ Abzugskörper-Geometrie (`voids.rs`: Polygon minus Schneider mit Schlüsselloch-Stegen, Strecke ausserhalb, Schnitt-Rechtecke); behebt: bei mehreren getrennten Aussparungen wurde nichts abgezogen. - - ○ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. + Rest in TS (28.10.): Stil-Auflösung (Bauteil, Schraffur, Farbe, Linienstil, Pick-IDs, Painter-Reihenfolge) in `generatePlan*.ts`, + `toSection.ts` (Besitzer-Zuordnung, Schichtbänder), `toElevation.ts` (Orchestrierung), `sectionOpenings.ts`, `planUnderlay.ts`, + `drawing2d.ts`. Das ist kein Rechenanteil mehr, sondern liest das Modell; es zieht mit [K4] um. + - ○ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. Hängt an [K4]: Rust braucht das + typisierte Modell (Bauteil-Typen, Schraffuren, Linienstile, Kategorien) und einen Plan-Puffer v2 mit Pick-IDs + vollem `Primitive`-Umfang + (Text, Schraffur-Optionen, Zickzack/Motiv); die Verbraucher von `Primitive[]` (SVG/PDF/DXF, Auswahl, Overlay) lesen dann den Puffer. 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 From 8a120329ee2f9fa2a8041b1e5a1566fd51bdf69c Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:41:02 +0100 Subject: [PATCH 15/31] [K4] S1: Projekt-Dokument im Rust-Kern (document.rs), TS-Spiegel ueber Ops (core/document.ts), Store haelt es aktuell --- TODO.md | 16 +- src-tauri/core/Cargo.lock | 62 +++++++ src-tauri/core/Cargo.toml | 1 + src-tauri/core/src/document.rs | 267 +++++++++++++++++++++++++++++ src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/web/document.rs | 63 +++++++ src-tauri/core/src/web/mod.rs | 1 + src/core/document.test.ts | 56 ++++++ src/core/document.ts | 57 ++++++ src/state/appStore.ts | 23 +++ 10 files changed, 546 insertions(+), 1 deletion(-) create mode 100644 src-tauri/core/src/document.rs create mode 100644 src-tauri/core/src/web/document.rs create mode 100644 src/core/document.test.ts create mode 100644 src/core/document.ts diff --git a/TODO.md b/TODO.md index a8ed41ac..7a10a607 100644 --- a/TODO.md +++ b/TODO.md @@ -119,7 +119,21 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern (Text, Schraffur-Optionen, Zickzack/Motiv); die Verbraucher von `Primitive[]` (SVG/PDF/DXF, Auswahl, Overlay) lesen dann den Puffer. 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 +- ◐ **[K4] Modell und Ops in Rust** [2]; TS bekommt die Typen generiert (z. B. `ts-rs`). · XL + Ziel (Entscheid 28.10., Maintainer): nur die UI bleibt TS, alles andere Rust. Vorgehen in Stufen, jede verdrahtet und mit + Gleichheitstest gegen die TS-Fassung, die im selben Schritt verschwindet: + - ✅ **S1 Dokument im Kern** (28.10.): `document.rs` hält das Projekt als JSON-Baum, `core/document.ts` spiegelt jede + Änderung von `store.project` (setProject, Laden, Undo/Redo) als Ops (`diffToOps` → `doc_apply`); Selbstheilung durch Neuöffnen. + Test: 300 Zufallsänderungen, Kern-JSON == TS-Projekt. (Spiegel, TS ist noch Quelle der Änderungen.) + - ○ **S2 Ableitungen lesen das Dokument**: typisierte Sicht (serde) je Domäne; Plan/Schnitt/Ansicht, 3D, Kennzahlen, Export + rechnen mit `doc`-Handle statt mit flach gesammelten Arrays; TS-Sammler/-Adapter werden gelöscht ([K3d] hängt hier dran: + Plan-Puffer v2 mit Pick-IDs und vollem Primitive-Umfang). + - ○ **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. + - ○ **S4 Typen aus Rust**: `types.ts` wird aus den Rust-Strukturen erzeugt (ts-rs); Datei-I/O (`projectFormat`, Migration, IFC/DXF/ + STEP-Ex- und -Import) im Kern. + Offene Entscheide/Risiken: Kosten der JSON-Übergabe bei grossen Projekten (Teil-Updates statt Neuaufbau), Struktur-Sharing im + React-Store (TS-Spiegel bleibt bis S3), Befehls-Zustandsautomaten sind viel Code (`src/commands/cmds/*`). - **Fertig wenn** (je Etappe): TS-Fassung gelöscht, `npm run check` grün, App/CLI/IFC unverändert. ## Was die Analyse übersieht (Ergänzungen zum Vergleich) diff --git a/src-tauri/core/Cargo.lock b/src-tauri/core/Cargo.lock index 1595493a..6351b1f9 100644 --- a/src-tauri/core/Cargo.lock +++ b/src-tauri/core/Cargo.lock @@ -31,9 +31,28 @@ dependencies = [ "console_error_panic_hook", "i_overlay", "kernel2d", + "serde_json", "wasm-bindgen", ] +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + [[package]] name = "i_float" version = "5.0.0" @@ -76,6 +95,22 @@ version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "048af31de955890c62a8506fec511335a5089e91e1c516537add16f96c507d84" +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + [[package]] name = "kernel2d" version = "0.1.0" @@ -89,6 +124,12 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + [[package]] name = "once_cell" version = "1.21.4" @@ -149,6 +190,21 @@ dependencies = [ "syn", ] +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + [[package]] name = "syn" version = "3.0.9" @@ -210,3 +266,9 @@ checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" dependencies = [ "unicode-ident", ] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/src-tauri/core/Cargo.toml b/src-tauri/core/Cargo.toml index 85a0ffb7..a9167209 100644 --- a/src-tauri/core/Cargo.toml +++ b/src-tauri/core/Cargo.toml @@ -19,6 +19,7 @@ web = ["dep:wasm-bindgen", "dep:console_error_panic_hook"] [dependencies] i_overlay = { version = "9.1", default-features = false } +serde_json = { version = "1", features = ["preserve_order", "float_roundtrip"] } kernel2d = { path = "../kernel2d" } wasm-bindgen = { version = "0.2", optional = true } console_error_panic_hook = { version = "0.1", optional = true } diff --git a/src-tauri/core/src/document.rs b/src-tauri/core/src/document.rs new file mode 100644 index 00000000..fb7a74d3 --- /dev/null +++ b/src-tauri/core/src/document.rs @@ -0,0 +1,267 @@ +//! Projekt-Dokument und Ops ([K4], Stufe S1): Rust hält das Projekt als JSON-Baum und wendet die +//! Op-Folgen an, die TS aus `core/ops.ts` erzeugt (`setField`/`add`/`replace`/`remove`/`reorder`). +//! Die Ops werden atomar angewendet und geprüft (doppelte ids); bei Verstoss bleibt das Dokument +//! unverändert. Später lesen die Ableitungen (Plan, Schnitt, 3D, Kennzahlen, Export) direkt dieses +//! Dokument statt flacher TS-Sammler. +//! +//! JSON kennt weder `undefined` noch NaN: fehlende Felder fehlen, nicht endliche Zahlen prüft TS +//! vor dem Senden (`validateOps`). + +use serde_json::{Map, Value}; +use std::collections::HashSet; + +/// Eine Änderung am Projekt (Spiegel von `CoreOp` in `core/ops.ts`). +#[derive(Clone, Debug, PartialEq)] +pub enum Op { + Add { collection: String, items: Vec, at: Option }, + Replace { collection: String, entity: Value }, + Remove { collection: String, ids: Vec }, + Reorder { collection: String, ids: Vec }, + SetField { key: String, value: Option }, +} + +fn id_of(v: &Value) -> Option<&str> { + v.get("id").and_then(Value::as_str) +} + +impl Op { + pub fn from_json(v: &Value) -> Result { + let kind = v.get("kind").and_then(Value::as_str).ok_or("Op ohne kind")?; + let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_owned).ok_or(format!("Op {kind}: {k} fehlt")); + let ids = |k: &str| -> Result, String> { + v.get(k) + .and_then(Value::as_array) + .ok_or(format!("Op {kind}: {k} fehlt"))? + .iter() + .map(|x| x.as_str().map(str::to_owned).ok_or(format!("Op {kind}: {k} enthält Nicht-Text"))) + .collect() + }; + Ok(match kind { + "add" => { + let items = v.get("items").and_then(Value::as_array).ok_or("Op add: items fehlt")?.clone(); + if items.iter().any(|e| id_of(e).is_none()) { + return Err("Op add: Element ohne id".into()); + } + let at = match v.get("at") { + None | Some(Value::Null) => None, + Some(a) => Some(a.as_f64().filter(|x| x.is_finite()).map(|x| x.max(0.0) as usize).ok_or("Op add: at ungültig")?), + }; + Op::Add { collection: s("collection")?, items, at } + } + "replace" => { + let entity = v.get("entity").cloned().ok_or("Op replace: entity fehlt")?; + if id_of(&entity).is_none() { + return Err("Op replace: Element ohne id".into()); + } + Op::Replace { collection: s("collection")?, entity } + } + "remove" => Op::Remove { collection: s("collection")?, ids: ids("ids")? }, + "reorder" => Op::Reorder { collection: s("collection")?, ids: ids("ids")? }, + "setField" => Op::SetField { key: s("key")?, value: v.get("value").filter(|x| !x.is_null()).cloned() }, + other => return Err(format!("Unbekannte Op: {other}")), + }) + } + + fn key(&self) -> &str { + match self { + Op::Add { collection, .. } | Op::Replace { collection, .. } | Op::Remove { collection, .. } | Op::Reorder { collection, .. } => collection, + Op::SetField { key, .. } => key, + } + } +} + +/// Liste mit lauter `id`-tragenden Elementen (leer zählt mit). +fn is_id_list(v: &Value) -> bool { + v.as_array().is_some_and(|a| a.iter().all(|e| id_of(e).is_some())) +} + +fn unique_ids(list: &[Value]) -> bool { + let mut seen = HashSet::new(); + list.iter().all(|e| seen.insert(id_of(e).unwrap_or(""))) +} + +fn has_dup(v: Option<&Value>) -> bool { + match v { + Some(v) if is_id_list(v) => !unique_ids(v.as_array().unwrap()), + _ => false, + } +} + +#[derive(Clone, Debug, Default)] +pub struct Document { + root: Map, +} + +impl Document { + pub fn from_json(text: &str) -> Result { + match serde_json::from_str::(text) { + Ok(Value::Object(root)) => Ok(Document { root }), + Ok(_) => Err("Projekt ist kein JSON-Objekt".into()), + Err(e) => Err(e.to_string()), + } + } + + pub fn to_json(&self) -> String { + serde_json::to_string(&self.root).unwrap_or_default() + } + + pub fn field(&self, key: &str) -> Option<&Value> { + self.root.get(key) + } + + fn list_mut(&mut self, collection: &str) -> &mut Vec { + let slot = self.root.entry(collection.to_owned()).or_insert_with(|| Value::Array(vec![])); + if !slot.is_array() { + *slot = Value::Array(vec![]); + } + slot.as_array_mut().unwrap() + } + + fn apply_one(&mut self, op: &Op) { + match op { + Op::SetField { key, value } => match value { + Some(v) => { + self.root.insert(key.clone(), v.clone()); + } + None => { + self.root.shift_remove(key); + } + }, + Op::Add { collection, items, at } => { + let list = self.list_mut(collection); + let at = at.map_or(list.len(), |a| a.min(list.len())); + list.splice(at..at, items.iter().cloned()); + } + Op::Replace { collection, entity } => { + let list = self.list_mut(collection); + let id = id_of(entity); + match list.iter().position(|e| id_of(e) == id) { + Some(i) => list[i] = entity.clone(), + None => list.push(entity.clone()), + } + } + Op::Remove { collection, ids } => { + let drop: HashSet<&str> = ids.iter().map(String::as_str).collect(); + self.list_mut(collection).retain(|e| !id_of(e).is_some_and(|i| drop.contains(i))); + } + Op::Reorder { collection, ids } => { + let list = std::mem::take(self.list_mut(collection)); + let mut ordered = Vec::with_capacity(list.len()); + let mut rest = Vec::new(); + let listed: HashSet<&str> = ids.iter().map(String::as_str).collect(); + for id in ids { + if let Some(e) = list.iter().find(|e| id_of(e) == Some(id.as_str())) { + ordered.push(e.clone()); + } + } + for e in &list { + if !id_of(e).is_some_and(|i| listed.contains(i)) { + rest.push(e.clone()); + } + } + ordered.extend(rest); + *self.list_mut(collection) = ordered; + } + } + } + + /// Wendet `ops` atomar an. Verstösse (neue doppelte ids) → `Err(Meldungen)`, Dokument unverändert. + pub fn apply(&mut self, ops: &[Op]) -> Result<(), Vec> { + // Zustand der berührten Felder sichern (Rücknahme) und Alt-Doppelungen merken. + let mut saved: Vec<(String, Option)> = Vec::new(); + let mut had_dup: HashSet = HashSet::new(); + for op in ops { + let k = op.key().to_owned(); + if !saved.iter().any(|(s, _)| *s == k) { + if has_dup(self.root.get(&k)) { + had_dup.insert(k.clone()); + } + saved.push((k.clone(), self.root.get(&k).cloned())); + } + } + for op in ops { + self.apply_one(op); + } + let mut problems = Vec::new(); + let mut checked: HashSet<&str> = HashSet::new(); + for op in ops { + let (key, is_add, is_set) = match op { + Op::Add { collection, .. } => (collection.as_str(), true, false), + Op::SetField { key, .. } => (key.as_str(), false, true), + _ => continue, + }; + if (is_add || is_set) && checked.insert(key) && !had_dup.contains(key) { + if let Some(v) = self.root.get(key) { + let relevant = is_add || v.as_array().is_some_and(|a| !a.is_empty()) && is_id_list(v); + if relevant && is_id_list(v) && !unique_ids(v.as_array().unwrap()) { + problems.push(format!("Doppelte ids in „{key}\".")); + } + } + } + } + if problems.is_empty() { + return Ok(()); + } + for (k, old) in saved { + match old { + Some(v) => { + self.root.insert(k, v); + } + None => { + self.root.shift_remove(&k); + } + } + } + Err(problems) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn doc() -> Document { + Document::from_json(r#"{"id":"p","walls":[{"id":"a","x":1},{"id":"b","x":2}],"name":"N"}"#).unwrap() + } + fn ops(v: Value) -> Vec { + v.as_array().unwrap().iter().map(|o| Op::from_json(o).unwrap()).collect() + } + + #[test] + fn ops_wirken_wie_in_ts() { + let mut d = doc(); + d.apply(&ops(json!([ + {"kind":"replace","collection":"walls","entity":{"id":"b","x":9}}, + {"kind":"add","collection":"walls","items":[{"id":"c"}],"at":0}, + {"kind":"remove","collection":"walls","ids":["a"]}, + {"kind":"setField","key":"name","value":"M"}, + {"kind":"setField","key":"id"}, + ]))) + .unwrap(); + assert_eq!(d.to_json(), r#"{"name":"M","walls":[{"id":"c"},{"id":"b","x":9}]}"#.replace(r#"{"name":"M","walls""#, r#"{"walls""#).replace("}]}", r#"}],"name":"M"}"#)); + d.apply(&ops(json!([{"kind":"reorder","collection":"walls","ids":["b"]}]))).unwrap(); + assert_eq!(d.field("walls").unwrap()[0]["id"], "b"); + } + + #[test] + fn doppelte_ids_werden_zurueckgenommen() { + let mut d = doc(); + let before = d.to_json(); + let e = d.apply(&ops(json!([{"kind":"add","collection":"walls","items":[{"id":"a"}]}]))).unwrap_err(); + assert_eq!(e, vec!["Doppelte ids in „walls\".".to_string()]); + assert_eq!(d.to_json(), before); + } + + #[test] + fn alt_doppelungen_bleiben_aenderbar() { + let mut d = Document::from_json(r#"{"walls":[{"id":"a"},{"id":"a"}]}"#).unwrap(); + d.apply(&ops(json!([{"kind":"add","collection":"walls","items":[{"id":"z"}]}]))).unwrap(); + } + + #[test] + fn kaputte_ops_sind_fehler() { + assert!(Op::from_json(&json!({"kind":"add","collection":"w","items":[{"x":1}]})).is_err()); + assert!(Op::from_json(&json!({"kind":"nope"})).is_err()); + } +} diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index ade3dffd..678fcff5 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -38,6 +38,7 @@ pub mod plan_walls; pub mod opening_geom; pub mod plan_openings; pub mod delaunay; +pub mod document; pub mod mesh_section; pub mod plan_elevation; pub mod plan_misc; diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs new file mode 100644 index 00000000..d5517149 --- /dev/null +++ b/src-tauri/core/src/web/document.rs @@ -0,0 +1,63 @@ +//! Bindungen des Projekt-Dokuments (`crate::document`): Handles in einer Tabelle, damit TS das +//! Projekt nicht bei jedem Aufruf neu übergeben muss. + +use crate::document::{Document, Op}; +use serde_json::Value; +use std::cell::RefCell; +use wasm_bindgen::prelude::wasm_bindgen; + +thread_local! { + static DOCS: RefCell>> = const { RefCell::new(Vec::new()) }; +} + +fn with_doc(h: u32, f: impl FnOnce(&mut Document) -> R) -> Option { + DOCS.with(|d| d.borrow_mut().get_mut((h as usize).checked_sub(1)?)?.as_mut().map(f)) +} + +/// Öffnet ein Dokument aus Projekt-JSON; Handle ≥ 1, 0 bei Fehler. +#[wasm_bindgen] +pub fn doc_open(json: &str) -> u32 { + let Ok(doc) = Document::from_json(json) else { return 0 }; + DOCS.with(|d| { + let mut d = d.borrow_mut(); + if let Some(i) = d.iter().position(Option::is_none) { + d[i] = Some(doc); + i as u32 + 1 + } else { + d.push(Some(doc)); + d.len() as u32 + } + }) +} + +#[wasm_bindgen] +pub fn doc_close(h: u32) { + DOCS.with(|d| { + if let Some(slot) = (h as usize).checked_sub(1).and_then(|i| d.borrow_mut().get_mut(i).map(|s| s.take())) { + drop(slot); + } + }); +} + +/// Wendet eine Op-Folge (JSON-Array) an. Leerer Text = ok, sonst JSON-Array der Meldungen. +#[wasm_bindgen] +pub fn doc_apply(h: u32, ops_json: &str) -> String { + let parsed: Result, String> = serde_json::from_str::(ops_json) + .map_err(|e| e.to_string()) + .and_then(|v| v.as_array().ok_or("Ops sind kein Array".to_string()).and_then(|a| a.iter().map(Op::from_json).collect())); + let problems = match parsed { + Err(e) => vec![e], + Ok(ops) => match with_doc(h, |d| d.apply(&ops)) { + None => vec!["Dokument nicht offen".to_string()], + Some(Ok(())) => return String::new(), + Some(Err(p)) => p, + }, + }; + Value::from(problems).to_string() +} + +/// Das ganze Dokument als JSON (leer, wenn nicht offen). +#[wasm_bindgen] +pub fn doc_json(h: u32) -> String { + with_doc(h, |d| d.to_json()).unwrap_or_default() +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 0a26d665..d05dd9e1 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -29,6 +29,7 @@ mod plan_stairs; mod plan_walls; mod plan_openings; mod delaunay; +mod document; mod mesh_section; mod plan_elevation; mod plan_misc; diff --git a/src/core/document.test.ts b/src/core/document.test.ts new file mode 100644 index 00000000..1af01e3d --- /dev/null +++ b/src/core/document.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "vitest"; +import { ProjectDocument } from "./document"; +import { sampleProject } from "../model/sampleProject"; +import type { Project } from "../model/types"; + +const plain = (p: Project): unknown => JSON.parse(JSON.stringify(p)); + +function mutate(p: Project, seed: number): Project { + let x = seed; + const rnd = () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296); + let out = { ...p }; + const walls = [...out.walls]; + if (rnd() < 0.5 && walls.length) walls.splice(Math.floor(rnd() * walls.length), 1); + if (rnd() < 0.7 && walls.length) { + const i = Math.floor(rnd() * walls.length); + walls[i] = { ...walls[i], height: (walls[i].height ?? 2.6) + rnd() }; + } + if (rnd() < 0.6) walls.splice(Math.floor(rnd() * (walls.length + 1)), 0, { ...p.walls[0], id: `new-${seed}-a` }, { ...p.walls[0], id: `new-${seed}-b` }); + if (rnd() < 0.4) walls.reverse(); + out = { ...out, walls }; + if (rnd() < 0.5) out = { ...out, name: `n${seed}` }; + if (rnd() < 0.3) out = { ...out, referenceElevationMasl: rnd() * 500 }; + if (rnd() < 0.3) out = { ...out, geoAnchor: undefined }; + if (rnd() < 0.5) out = { ...out, drawings2d: [] }; + return out; +} + +describe("ProjectDocument (Kern-Spiegel)", () => { + it("öffnet das Projekt unverändert", () => { + const d = new ProjectDocument(sampleProject); + expect(JSON.parse(d.json())).toEqual(plain(sampleProject)); + d.close(); + }); + + it("folgt beliebigen Änderungen über Ops", () => { + const d = new ProjectDocument(sampleProject); + let cur = sampleProject; + for (let seed = 1; seed <= 300; seed++) { + cur = mutate(cur, seed); + d.sync(cur); + const got = JSON.parse(d.json()) as Record; + const want = plain(cur) as Record; + const bad = [...new Set([...Object.keys(got), ...Object.keys(want)])].filter((k) => JSON.stringify(got[k]) !== JSON.stringify(want[k])); + expect(bad, `seed ${seed}`).toEqual([]); + } + d.close(); + }); + + it("heilt sich bei doppelten ids (Neuöffnen)", () => { + const d = new ProjectDocument(sampleProject); + const dup = { ...sampleProject, walls: [...sampleProject.walls, sampleProject.walls[0]] }; + d.sync(dup); + expect(JSON.parse(d.json())).toEqual(plain(dup)); + d.close(); + }); +}); diff --git a/src/core/document.ts b/src/core/document.ts new file mode 100644 index 00000000..f1573072 --- /dev/null +++ b/src/core/document.ts @@ -0,0 +1,57 @@ +// Projekt-Dokument im Rust-Kern ([K4], Stufe S1): spiegelt das TS-Projekt über Ops nach Rust +// (`document.rs`). TS bleibt vorerst Quelle der Änderungen (`setProject` → `diffToOps`); Rust hält +// den Stand, auf dem die Ableitungen später direkt rechnen, ohne dass TS das Projekt je Aufruf +// flach neu sammeln muss. Bei jedem Widerspruch (abgelehnte Ops, Fehler) wird das Dokument aus dem +// vollen Projekt neu geöffnet — der Spiegel heilt sich selbst. + +import type { Project } from "../model/types"; +import { core } from "../engine/coreWasm"; +import { diffToOps } from "./ops"; + +export class ProjectDocument { + private handle = 0; + private mirror: Project; + + constructor(project: Project) { + this.mirror = project; + this.reopen(project); + } + + /** Handle im Kern (0 = nicht offen). */ + get id(): number { + return this.handle; + } + + private reopen(project: Project): void { + if (this.handle) core().doc_close(this.handle); + this.handle = core().doc_open(JSON.stringify(project)); + if (!this.handle) console.warn("Projekt-Dokument im Kern konnte nicht geöffnet werden."); + } + + /** Bringt das Dokument auf den Stand `next` (über die Differenz als Ops). */ + sync(next: Project): void { + if (next === this.mirror) return; + const ops = diffToOps(this.mirror, next); + this.mirror = next; + if (ops.length === 0) return; + if (!this.handle) { + this.reopen(next); + return; + } + const problems = core().doc_apply(this.handle, JSON.stringify(ops)); + if (problems) { + console.warn("Kern-Dokument weicht ab, wird neu geöffnet:", problems); + this.reopen(next); + } + } + + /** Das Dokument als JSON-Text (Test, Export). */ + json(): string { + return this.handle ? core().doc_json(this.handle) : ""; + } + + close(): void { + if (this.handle) core().doc_close(this.handle); + this.handle = 0; + } +} diff --git a/src/state/appStore.ts b/src/state/appStore.ts index af64cf45..49aba7df 100644 --- a/src/state/appStore.ts +++ b/src/state/appStore.ts @@ -7,6 +7,7 @@ // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import { createStore } from "./store"; +import { ProjectDocument } from "../core/document"; import type { StoreApi } from "./store"; import { createProjectSlice } from "./projectSlice"; import type { ProjectSlice } from "./projectSlice"; @@ -63,3 +64,25 @@ const store = createStore((api) => ({ export const useStore = store.useStore; export const getState = store.getState; export const setState = store.setState; + +// Kern-Dokument ([K4] S1): spiegelt jede Änderung von `project` (Setzen, Laden, Undo/Redo) als Ops +// in den Rust-Kern. Ohne geladenen Kern (Start, manche Tests) bleibt es aus und holt sich beim +// nächsten Zugriff den vollen Stand. +let coreDoc: ProjectDocument | null = null; + +/** Das Rust-Dokument zum aktuellen Projekt (synchron nachgezogen); `null`, solange der Kern fehlt. */ +export function projectDocument(): ProjectDocument | null { + try { + const p = store.getState().project; + if (!coreDoc) coreDoc = new ProjectDocument(p); + else coreDoc.sync(p); + return coreDoc; + } catch { + coreDoc = null; + return null; + } +} + +store.subscribe(() => { + void projectDocument(); +}); From 8d4952e5d0d1cc3ac10d52f3b2d94eb9d427de30 Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:47:21 +0100 Subject: [PATCH 16/31] [K4] S2: typisiertes Rust-Modell (generiert aus TS-Typen), Document::project(), Kennzahlen rechnen auf dem Dokument; TS-Sammler entfernt --- TODO.md | 10 +- scripts/gen-rust-model.py | 259 +++ src-tauri/core/Cargo.lock | 1 + src-tauri/core/Cargo.toml | 1 + src-tauri/core/src/document.rs | 36 +- src-tauri/core/src/kennzahlen.rs | 119 + src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/model/generated.rs | 1991 +++++++++++++++++ src-tauri/core/src/model/manual.rs | 273 +++ src-tauri/core/src/model/mod.rs | 38 + src-tauri/core/src/web/document.rs | 8 + src-tauri/core/src/web/kennzahlen.rs | 41 +- .../core/tests/fixtures/sample_project.json | 936 ++++++++ src/analysis/kennzahlen.ts | 62 +- src/core/document.ts | 21 + src/state/appStore.ts | 22 - 16 files changed, 3700 insertions(+), 119 deletions(-) create mode 100644 scripts/gen-rust-model.py create mode 100644 src-tauri/core/src/model/generated.rs create mode 100644 src-tauri/core/src/model/manual.rs create mode 100644 src-tauri/core/src/model/mod.rs create mode 100644 src-tauri/core/tests/fixtures/sample_project.json diff --git a/TODO.md b/TODO.md index 7a10a607..a9cd051e 100644 --- a/TODO.md +++ b/TODO.md @@ -125,9 +125,13 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern - ✅ **S1 Dokument im Kern** (28.10.): `document.rs` hält das Projekt als JSON-Baum, `core/document.ts` spiegelt jede Änderung von `store.project` (setProject, Laden, Undo/Redo) als Ops (`diffToOps` → `doc_apply`); Selbstheilung durch Neuöffnen. Test: 300 Zufallsänderungen, Kern-JSON == TS-Projekt. (Spiegel, TS ist noch Quelle der Änderungen.) - - ○ **S2 Ableitungen lesen das Dokument**: typisierte Sicht (serde) je Domäne; Plan/Schnitt/Ansicht, 3D, Kennzahlen, Export - rechnen mit `doc`-Handle statt mit flach gesammelten Arrays; TS-Sammler/-Adapter werden gelöscht ([K3d] hängt hier dran: - Plan-Puffer v2 mit Pick-IDs und vollem Primitive-Umfang). + - ◐ **S2 Ableitungen lesen das Dokument** (28.10.): typisiertes Rust-Modell `model/` (`generated.rs` aus den TS-Typen per + `scripts/gen-rust-model.py`, `manual.rs` für getaggte Unions; Hin-und-zurück-Test gegen das Beispielprojekt mit + `deny_unknown_fields`), `Document::project()` als gecachte typisierte Sicht, `documentFor(project)` (TS) hält ein gemeinsames + Dokument per Differenz aktuell. Erster Verbraucher: Kennzahlen (`kennzahlen.rs::compute`, TS-Sammler gelöscht). + Nächste: Baurecht/Footprint, Sonnenstand, Raumprogramm, danach Plan/Schnitt/Ansicht, 3D, Export. + 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). - ○ **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. - ○ **S4 Typen aus Rust**: `types.ts` wird aus den Rust-Strukturen erzeugt (ts-rs); Datei-I/O (`projectFormat`, Migration, IFC/DXF/ diff --git a/scripts/gen-rust-model.py b/scripts/gen-rust-model.py new file mode 100644 index 00000000..6c2f7649 --- /dev/null +++ b/scripts/gen-rust-model.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +"""Einmaliger Übersetzer: TS-Modelltypen -> Rust-Strukturen (serde) für src-tauri/core/src/model/generated.rs. + +Zweck: Startpunkt für [K4] S2/S4. Danach gehört die Rust-Datei dem Kern (von Hand gepflegt, TS-Typen +kommen künftig aus Rust). Nicht für den Dauerbetrieb gedacht. +""" +import re, sys, json + +SRC = [ + "src/model/types.ts", "src/model/viewTypes.ts", "src/text/richText.ts", "src/geometry/roomArea.ts", +] +# Typen, die von Hand geschrieben sind (diskriminierte Unions o. ä.) oder ersetzt werden +MANUAL = {"Vec2", "Drawing2DGeom", "VerticalAnchor", "ColumnProfile", "LayoutAnnotation", "ParametricRule", + "LayoutAnnotationPatch", "ContextObject", "BuiltinPaletteBank", "SiaKey", "SiaAggregate", + "BoolMark", "TextRange"} +TAGGED = {"GridRule", "ModuleRule", "ConditionalThicknessRule", "ReferenceLineRule", "SequenceRule", "ImportedMesh", "ContourSet", "TerrainMesh", "ContextImage"} +ONLY = None # alle Interfaces aus SRC, die erreichbar sind + +def strip_comments(s): + s = re.sub(r"/\*.*?\*/", "", s, flags=re.S) + s = re.sub(r"(?m)//.*$", "", s) + return s + +TOK = re.compile(r'\s*(?:(?P"(?:[^"\\]|\\.)*")|(?P-?\d+(?:\.\d+)?)|(?P[A-Za-z_$][\w$]*)|(?P

=>|[{}\[\]()<>;:,|?=&*.]))') + +def tokenize(s): + pos = 0; out = [] + while pos < len(s): + m = TOK.match(s, pos) + if not m: + if s[pos:].strip() == "": break + pos += 1; continue + pos = m.end() + for k in ("str", "num", "id", "p"): + if m.group(k) is not None: + out.append((k, m.group(k))); break + return out + +class P: + def __init__(self, toks): self.t = toks; self.i = 0 + def peek(self, o=0): return self.t[self.i + o] if self.i + o < len(self.t) else (None, None) + def next(self): v = self.t[self.i]; self.i += 1; return v + def eat(self, v): + if self.peek()[1] == v: self.i += 1; return True + return False + +def parse_type(p): + alts = [] + p.eat("|") + while True: + alts.append(parse_primary(p)) + if not p.eat("|"): break + return alts[0] if len(alts) == 1 else ("union", alts) + +def parse_primary(p): + k, v = p.peek() + if v == "(": + p.next(); t = parse_type(p); p.eat(")"); base = t + elif k == "str": + p.next(); base = ("lit", json.loads(v)) + elif k == "num": + p.next(); base = ("numlit", float(v)) + elif v == "{": + p.next(); fields = parse_fields(p); p.eat("}"); base = ("obj", fields) + elif v == "[": + p.next(); items = [parse_type(p)] + while p.eat(","): items.append(parse_type(p)) + p.eat("]"); base = ("tuple", items) + elif k == "id": + p.next() + if v == "keyof": + parse_primary(p); base = ("keyof",) + else: + args = [] + if p.peek()[1] == "<": + p.next(); args.append(parse_type(p)) + while p.eat(","): args.append(parse_type(p)) + p.eat(">") + base = ("ref", v, args) + else: + raise SyntaxError(f"unerwartet {p.peek()} @ {p.i}") + while p.peek()[1] == "[" and p.peek(1)[1] == "]": + p.next(); p.next(); base = ("array", base) + return base + +def parse_fields(p): + fields = [] + while p.peek()[1] not in ("}", None): + k, name = p.next() + if k == "str": name = json.loads(name) + opt = p.eat("?") + p.eat(":") + t = parse_type(p) + p.eat(";") or p.eat(",") + fields.append((name, opt, t)) + return fields + +def parse_file(path): + text = strip_comments(open(path).read()) + toks = tokenize(text) + out = {} + i = 0 + while i < len(toks): + if toks[i][1] == "export" and toks[i+1][1] in ("interface", "type") and toks[i+2][0] == "id": + kind = toks[i+1][1]; name = toks[i+2][1] + j = i + 3 + try: + p = P(toks); p.i = j + if kind == "interface": + while p.peek()[1] != "{": p.next() + p.next(); fields = parse_fields(p); p.eat("}") + out[name] = ("interface", fields) + else: + if p.peek()[1] == "<": + i += 1; continue + p.eat("=") + out[name] = ("alias", parse_type(p)) + i = p.i + continue + except Exception as e: + sys.stderr.write(f"skip {name}: {e}\n") + i += 1 + return out + +def snake(n): + s = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", n).lower() + kw = {"type", "match", "ref", "box", "move", "in", "loop", "impl", "fn", "use", "mod", "as", "where", "for", "if", "else", "while", "static", "const", "struct", "enum", "trait", "pub", "let", "mut", "return", "break", "continue", "dyn", "async", "await", "try", "yield", "unsafe", "extern", "abstract", "final", "override", "macro", "typeof", "virtual", "become", "do", "priv", "unsized"} + if s in ("super", "self", "crate", "Self"): + return s + "_" + return "r#" + s if s in kw else s + +def pascal(v): + parts = re.split(r"[^A-Za-z0-9]+", v) + s = "".join(x[:1].upper() + x[1:] for x in parts if x) + if not s or s[0].isdigit(): s = "V" + s + return s + +decls = {} +for f in SRC: + decls.update(parse_file(f)) + +out_items = [] # generated rust texts +emitted = set() +enum_counter = {} +enum_lits = {} + +PRIM = {"string": "String", "number": "f64", "boolean": "bool", "unknown": "serde_json::Value", "any": "serde_json::Value", "null": "()"} + +def rust_enum(name, lits): + seen = set(); lines = [] + for l in lits: + v = pascal(l) + base = v; n = 2 + while v in seen: v = f"{base}{n}"; n += 1 + seen.add(v) + lines.append(f' #[serde(rename = {json.dumps(l, ensure_ascii=False)})]\n {v},') + return ("#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]\n" + f"pub enum {name} {{\n" + "\n".join(lines) + "\n}\n") + +def rtype(t, ctx): + """-> (rust_type, is_option)""" + k = t[0] + if k == "ref": + n, args = t[1], t[2] + if n in PRIM: return PRIM[n], False + if n == "Record": return f"std::collections::BTreeMap", False + if n == "Partial": return "serde_json::Value", False + if n == "Array": return f"Vec<{rtype(args[0], ctx)[0]}>", False + if n == "Date": return "String", False + ensure(n) + return n, False + if k == "array": + return f"Vec<{rtype(t[1], ctx)[0]}>", False + if k == "tuple": + if len(t[1]) == 2 and t[1][0] == t[1][1]: + return f"[{rtype(t[1][0], ctx)[0]}; 2]", False + return "serde_json::Value", False + if k == "lit": return "String", False + if k == "numlit": return "f64", False + if k == "keyof": return "String", False + if k == "obj": + name = ctx + emit_struct(name, t[1]) + return name, False + if k == "union": + alts = [a for a in t[1] if not (a[0] == "ref" and a[1] in ("undefined",))] + had_undef = len(alts) != len(t[1]) + nulls = [a for a in alts if a[0] == "ref" and a[1] == "null"] + alts = [a for a in alts if not (a[0] == "ref" and a[1] == "null")] + opt = had_undef or bool(nulls) + if len(alts) == 1: + r, _ = rtype(alts[0], ctx); return (f"Option<{r}>" if nulls else r), had_undef + if all(a[0] == "lit" for a in alts): + lits = [a[1] for a in alts] + ename = ctx + n = 1 + while ename in enum_lits and enum_lits[ename] != lits: + n += 1; ename = f"{ctx}{n}" + if ename not in emitted: + emitted.add(ename); enum_lits[ename] = lits; out_items.append(rust_enum(ename, lits)) + return ename, opt + if all(a[0] == "numlit" for a in alts): return "f64", opt + return "serde_json::Value", opt + raise ValueError(t) + +def emit_struct(name, fields): + if name in emitted: return + emitted.add(name) + lines = [] + for fname, opt, t in fields: + if fname == "type" and name in TAGGED: + continue # Tag steckt im umgebenden Enum (model/manual.rs) + sub = name + pascal(fname) + r, uopt = rtype(t, sub) + is_opt = opt or uopt + rn = snake(fname) + attrs = [] + if rn.replace("r#", "") != fname: + attrs.append(f'rename = {json.dumps(fname)}') + if r.startswith("Option<"): + attrs.append('default') + if is_opt: + attrs.append('skip_serializing_if = "Option::is_none"') + # sonst `T | null` ohne `?`: Feld ist da, darf null sein -> beim Schreiben `null` ausgeben + elif is_opt: + attrs.append('default'); attrs.append('skip_serializing_if = "Option::is_none"') + r = f"Option<{r}>" + a = f" #[serde({', '.join(attrs)})]\n" if attrs else "" + lines.append(f"{a} pub {rn}: {r},") + out_items.append("#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n" + + '#[cfg_attr(test, serde(deny_unknown_fields))]\n' + + f"pub struct {name} {{\n" + "\n".join(lines) + "\n}\n") + +def ensure(n): + if n in emitted or n in MANUAL: return + d = decls.get(n) + if d is None: + sys.stderr.write(f"unbekannt: {n}\n"); return + if d[0] == "interface": + emit_struct(n, d[1]) + else: + t = d[1] + if t[0] == "union" and all(a[0] == "lit" for a in t[1]): + emitted.add(n); enum_lits[n] = [a[1] for a in t[1]]; out_items.append(rust_enum(n, [a[1] for a in t[1]])) + elif t[0] == "lit": + emitted.add(n); out_items.append(rust_enum(n, [t[1]])) + else: + emitted.add(n) + r, _ = rtype(t, n) + out_items.append(f"pub type {n} = {r};\n") + +for root in sys.argv[1:] or ["Project"]: + ensure(root) + +print("// GENERIERT von scripts/gen-rust-model.py aus den TS-Typen (Stand 28.10.), danach von Hand gepflegt.\n" + "// Rust-Gegenstück zu src/model/types.ts ([K4] S2). Union-Typen mit Tag stehen in model/manual.rs.\n" + "#![allow(clippy::large_enum_variant)]\n" + "use super::manual::*;\nuse serde::{Deserialize, Serialize};\n") +print("\n".join(out_items)) diff --git a/src-tauri/core/Cargo.lock b/src-tauri/core/Cargo.lock index 6351b1f9..b96d6972 100644 --- a/src-tauri/core/Cargo.lock +++ b/src-tauri/core/Cargo.lock @@ -31,6 +31,7 @@ dependencies = [ "console_error_panic_hook", "i_overlay", "kernel2d", + "serde", "serde_json", "wasm-bindgen", ] diff --git a/src-tauri/core/Cargo.toml b/src-tauri/core/Cargo.toml index a9167209..5b039c65 100644 --- a/src-tauri/core/Cargo.toml +++ b/src-tauri/core/Cargo.toml @@ -19,6 +19,7 @@ web = ["dep:wasm-bindgen", "dep:console_error_panic_hook"] [dependencies] i_overlay = { version = "9.1", default-features = false } +serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order", "float_roundtrip"] } kernel2d = { path = "../kernel2d" } wasm-bindgen = { version = "0.2", optional = true } diff --git a/src-tauri/core/src/document.rs b/src-tauri/core/src/document.rs index fb7a74d3..4c649296 100644 --- a/src-tauri/core/src/document.rs +++ b/src-tauri/core/src/document.rs @@ -7,8 +7,11 @@ //! JSON kennt weder `undefined` noch NaN: fehlende Felder fehlen, nicht endliche Zahlen prüft TS //! vor dem Senden (`validateOps`). +use crate::model::Project; +use serde::Deserialize; use serde_json::{Map, Value}; use std::collections::HashSet; +use std::rc::Rc; /// Eine Änderung am Projekt (Spiegel von `CoreOp` in `core/ops.ts`). #[derive(Clone, Debug, PartialEq)] @@ -90,12 +93,14 @@ fn has_dup(v: Option<&Value>) -> bool { #[derive(Clone, Debug, Default)] pub struct Document { root: Map, + /// Typisierte Sicht (Cache); jede Änderung verwirft sie. + typed: Option>, } impl Document { pub fn from_json(text: &str) -> Result { match serde_json::from_str::(text) { - Ok(Value::Object(root)) => Ok(Document { root }), + Ok(Value::Object(root)) => Ok(Document { root, typed: None }), Ok(_) => Err("Projekt ist kein JSON-Objekt".into()), Err(e) => Err(e.to_string()), } @@ -105,6 +110,23 @@ impl Document { serde_json::to_string(&self.root).unwrap_or_default() } + /// Typisierte Sicht des Projekts (gecacht bis zur nächsten Änderung). Fehler = Feld, das dem + /// Modell widerspricht (Meldung von serde). + pub fn project(&mut self) -> Result, String> { + if let Some(p) = &self.typed { + return Ok(p.clone()); + } + // Die Map wird nur ausgeliehen: `Value::Object` braucht Besitz, daher temporär herausnehmen. + let value = Value::Object(std::mem::take(&mut self.root)); + let parsed = Project::deserialize(&value).map_err(|e| e.to_string()); + if let Value::Object(m) = value { + self.root = m; + } + let p = Rc::new(parsed?); + self.typed = Some(p.clone()); + Ok(p) + } + pub fn field(&self, key: &str) -> Option<&Value> { self.root.get(key) } @@ -167,6 +189,7 @@ impl Document { /// Wendet `ops` atomar an. Verstösse (neue doppelte ids) → `Err(Meldungen)`, Dokument unverändert. pub fn apply(&mut self, ops: &[Op]) -> Result<(), Vec> { + self.typed = None; // Zustand der berührten Felder sichern (Rücknahme) und Alt-Doppelungen merken. let mut saved: Vec<(String, Option)> = Vec::new(); let mut had_dup: HashSet = HashSet::new(); @@ -259,6 +282,17 @@ mod tests { d.apply(&ops(json!([{"kind":"add","collection":"walls","items":[{"id":"z"}]}]))).unwrap(); } + #[test] + fn typisierte_sicht_folgt_den_ops() { + let text = include_str!("../tests/fixtures/sample_project.json"); + let mut d = Document::from_json(text).unwrap(); + let n = d.project().unwrap().walls.len(); + assert!(n > 0); + let id = d.project().unwrap().walls[0].id.clone(); + d.apply(&ops(json!([{"kind":"remove","collection":"walls","ids":[id]}]))).unwrap(); + assert_eq!(d.project().unwrap().walls.len(), n - 1); + } + #[test] fn kaputte_ops_sind_fehler() { assert!(Op::from_json(&json!({"kind":"add","collection":"w","items":[{"x":1}]})).is_err()); diff --git a/src-tauri/core/src/kennzahlen.rs b/src-tauri/core/src/kennzahlen.rs index 025b0f94..7c2e6f0c 100644 --- a/src-tauri/core/src/kennzahlen.rs +++ b/src-tauri/core/src/kennzahlen.rs @@ -133,3 +133,122 @@ mod tests { assert_eq!(area_sums(0, &[], &[], f64::NAN, &[]), AreaSums { by_level: vec![], gv: 0.0, parcel: None }); } } + +// ── Kennzahlen aus dem Projekt-Dokument ([K4] S2) ─────────────────────────── + +use crate::model::{DrawingLevelKind, Project, SiaCategory}; +use serde::Serialize; + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LevelKennzahlen { + pub level_id: String, + pub name: String, + /// Geschossfläche (SIA 416 GF) aus den Räumen. + pub gf: f64, + /// Anrechenbare Fläche ≈ Nettogeschossfläche NGF. + pub agf: f64, + pub rooms: usize, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Kennzahlen { + pub levels: Vec, + pub gf: f64, + pub agf: f64, + pub gv: f64, + pub footprint: f64, + pub az: Option, + pub uez: Option, +} + +fn category_index(c: SiaCategory) -> usize { + match c { + SiaCategory::HNF => 0, + SiaCategory::NNF => 1, + SiaCategory::VF => 2, + SiaCategory::FF => 3, + SiaCategory::KGF => 4, + SiaCategory::AGF => 5, + } +} + +/// Flächen je Geschoss (SIA 416), Gebäudevolumen, Ausnützungs- und Überbauungsziffer. +pub fn compute(p: &Project) -> Kennzahlen { + let mut floors: Vec<&crate::model::DrawingLevel> = p.drawing_levels.iter().filter(|l| l.kind == DrawingLevelKind::Floor).collect(); + floors.sort_by(|a, b| a.base_elevation.unwrap_or(0.0).partial_cmp(&b.base_elevation.unwrap_or(0.0)).unwrap_or(std::cmp::Ordering::Equal)); + let mut level_index: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for (i, l) in floors.iter().enumerate() { + level_index.entry(l.id.as_str()).or_insert(i); + } + let all_rooms = p.rooms.as_deref().unwrap_or(&[]); + let rooms: Vec<&crate::model::Room> = all_rooms.iter().filter(|r| level_index.contains_key(r.floor_id.as_str())).collect(); + let rooms_in: Vec = rooms + .iter() + .map(|r| RoomIn { + level: level_index[r.floor_id.as_str()], + category: category_index(r.sia_category), + boundary: r.boundary.iter().map(|v| [v.x, v.y]).collect(), + }) + .collect(); + let solids: Vec = p + .extruded_solids + .as_deref() + .unwrap_or(&[]) + .iter() + .map(|s| SolidIn { + subtract: s.operation.as_deref() == Some("subtract"), + points: if s.circle.is_some() { vec![] } else { s.points.iter().map(|v| [v.x, v.y]).collect() }, + circle_r: s.circle.as_ref().map_or(f64::NAN, |c| c.r), + height: s.height, + taper: s.taper.unwrap_or(0.0), + }) + .collect(); + let parcel_ring: Vec<[f64; 2]> = p.site_rules.as_ref().map(|r| r.parcel.iter().map(|v| [v.x, v.y]).collect()).unwrap_or_default(); + let sums = area_sums(floors.len(), &rooms_in, &solids, p.parcel_area.unwrap_or(f64::NAN), &parcel_ring); + let levels: Vec = floors + .iter() + .enumerate() + .map(|(i, l)| { + let entries: Vec<(usize, f64)> = (0..CATEGORIES).map(|k| (k, sums.by_level[i][k])).collect(); + let b = crate::room_area::balance(&entries); + LevelKennzahlen { + level_id: l.id.clone(), + name: l.name.clone(), + gf: b.agg_area[2], + agf: b.agg_area[1], + rooms: rooms.iter().filter(|r| r.floor_id == l.id).count(), + } + }) + .collect(); + let gf: f64 = levels.iter().map(|l| l.gf).sum(); + let agf: f64 = levels.iter().map(|l| l.agf).sum(); + let footprint = levels.iter().find(|l| l.gf > 0.0).map_or(0.0, |l| l.gf); + Kennzahlen { + levels, + gf, + agf, + gv: sums.gv, + footprint, + az: sums.parcel.filter(|x| *x != 0.0).map(|x| agf / x), + uez: sums.parcel.filter(|x| *x != 0.0).map(|x| footprint / x), + } +} + +#[cfg(test)] +mod doc_tests { + use super::*; + + #[test] + fn kennzahlen_des_beispielprojekts() { + let p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap(); + let k = compute(&p); + assert!(!k.levels.is_empty()); + let sum: f64 = k.levels.iter().map(|l| l.gf).sum(); + assert!((k.gf - sum).abs() < 1e-9); + assert!(k.az.is_none() && k.uez.is_none()); + let with_parcel = Project { parcel_area: Some(1000.0), ..p }; + let k2 = compute(&with_parcel); + assert!((k2.az.unwrap() - k2.agf / 1000.0).abs() < 1e-12); + } +} diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 678fcff5..4d29f885 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -40,6 +40,7 @@ pub mod plan_openings; pub mod delaunay; pub mod document; pub mod mesh_section; +pub mod model; pub mod plan_elevation; pub mod plan_misc; pub mod plan_section; diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs new file mode 100644 index 00000000..0495ba60 --- /dev/null +++ b/src-tauri/core/src/model/generated.rs @@ -0,0 +1,1991 @@ +// GENERIERT von scripts/gen-rust-model.py aus den TS-Typen (Stand 28.10.), danach von Hand gepflegt. +// Rust-Gegenstück zu src/model/types.ts ([K4] S2). Union-Typen mit Tag stehen in model/manual.rs. +#![allow(clippy::large_enum_variant)] +use super::manual::*; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum LineStyleKind { + #[serde(rename = "dash")] + Dash, + #[serde(rename = "zigzag")] + Zigzag, + #[serde(rename = "custom")] + Custom, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct LineStyleZigzag { + pub amplitude: f64, + pub wavelength: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct LineStyleMotif { + pub points: Vec, + pub length: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct LineStyle { + pub id: String, + pub name: String, + pub weight: f64, + pub color: String, + #[serde(default)] + pub dash: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub kind: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub zigzag: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub motif: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Marks { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bold: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub italic: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub underline: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub strike: Option, + #[serde(rename = "super", default, skip_serializing_if = "Option::is_none")] + pub super_: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sub: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub font: Option, + #[serde(rename = "sizePt", default, skip_serializing_if = "Option::is_none")] + pub size_pt: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct TextStylePreset { + pub id: String, + pub label: String, + pub marks: Marks, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum HatchStyleKind { + #[serde(rename = "vector")] + Vector, + #[serde(rename = "image")] + Image, + #[serde(rename = "gradient")] + Gradient, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum HatchStyleLines { + #[serde(rename = "parallel")] + Parallel, + #[serde(rename = "random")] + Random, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct HatchStyleImage { + pub src: String, + #[serde(rename = "scaleX")] + pub scale_x: f64, + #[serde(rename = "scaleY")] + pub scale_y: f64, + pub rotation: f64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum HatchStyleGradientType { + #[serde(rename = "linear")] + Linear, + #[serde(rename = "radial")] + Radial, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct HatchStyleGradient { + pub color1: String, + pub color2: String, + pub angle: f64, + pub r#type: HatchStyleGradientType, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum HatchPattern { + #[serde(rename = "none")] + None, + #[serde(rename = "solid")] + Solid, + #[serde(rename = "insulation")] + Insulation, + #[serde(rename = "diagonal")] + Diagonal, + #[serde(rename = "crosshatch")] + Crosshatch, + #[serde(rename = "custom")] + Custom, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct HatchStyleMotif { + pub points: Vec, + pub length: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct HatchStyle { + pub id: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub kind: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub lines: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub image: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub gradient: Option, + pub pattern: HatchPattern, + pub scale: f64, + pub angle: f64, + #[serde(rename = "relativeToWall", default, skip_serializing_if = "Option::is_none")] + pub relative_to_wall: Option, + pub color: String, + #[serde(rename = "lineStyleId", default, skip_serializing_if = "Option::is_none")] + pub line_style_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub seed: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub density: Option, + #[serde(rename = "lengthMin", default, skip_serializing_if = "Option::is_none")] + pub length_min: Option, + #[serde(rename = "lengthMax", default, skip_serializing_if = "Option::is_none")] + pub length_max: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub motif: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ComponentMaterial { + #[serde(rename = "libraryId", default, skip_serializing_if = "Option::is_none")] + pub library_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub normal: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub roughness: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metalness: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub displacement: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ao: Option, + #[serde(rename = "sizeM", default, skip_serializing_if = "Option::is_none")] + pub size_m: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Component { + pub id: String, + pub name: String, + pub color: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub foreground: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub background: Option, + #[serde(rename = "colorPenId", default, skip_serializing_if = "Option::is_none")] + pub color_pen_id: Option, + #[serde(rename = "foregroundPenId", default, skip_serializing_if = "Option::is_none")] + pub foreground_pen_id: Option, + #[serde(rename = "backgroundPenId", default, skip_serializing_if = "Option::is_none")] + pub background_pen_id: Option, + #[serde(rename = "hatchId")] + pub hatch_id: String, + #[serde(rename = "viewHatchId", default, skip_serializing_if = "Option::is_none")] + pub view_hatch_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub texture3d: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub material: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub abbrev: Option, + #[serde(rename = "joinPriority")] + pub join_priority: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Layer { + #[serde(rename = "componentId")] + pub component_id: String, + pub thickness: f64, + #[serde(rename = "jointLineStyleId", default, skip_serializing_if = "Option::is_none")] + pub joint_line_style_id: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct WallType { + pub id: String, + pub name: String, + pub layers: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct CeilingType { + pub id: String, + pub name: String, + pub layers: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct RoofType { + pub id: String, + pub name: String, + pub layers: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct BlockDef { + pub id: String, + pub name: String, + pub geom2d: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum DoorTypeKind { + #[serde(rename = "dreh")] + Dreh, + #[serde(rename = "schiebe")] + Schiebe, + #[serde(rename = "wandoeffnung")] + Wandoeffnung, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum DoorTypeLeafStyle { + #[serde(rename = "glatt")] + Glatt, + #[serde(rename = "kassette")] + Kassette, + #[serde(rename = "glas")] + Glas, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum DoorTypeFrameKind { + #[serde(rename = "zarge")] + Zarge, + #[serde(rename = "blockrahmen")] + Blockrahmen, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum FrameCornerJoin { + #[serde(rename = "vertikal")] + Vertikal, + #[serde(rename = "horizontal")] + Horizontal, + #[serde(rename = "gehrung")] + Gehrung, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum DoorTypeInsetFace { + #[serde(rename = "aussen")] + Aussen, + #[serde(rename = "innen")] + Innen, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct DoorType { + pub id: String, + pub name: String, + pub kind: DoorTypeKind, + #[serde(rename = "leafCount")] + pub leaf_count: f64, + #[serde(rename = "leafStyle")] + pub leaf_style: DoorTypeLeafStyle, + #[serde(rename = "glazingRatio", default, skip_serializing_if = "Option::is_none")] + pub glazing_ratio: Option, + #[serde(rename = "panelCols", default, skip_serializing_if = "Option::is_none")] + pub panel_cols: Option, + #[serde(rename = "panelRows", default, skip_serializing_if = "Option::is_none")] + pub panel_rows: Option, + #[serde(rename = "frameThickness")] + pub frame_thickness: f64, + #[serde(rename = "frameDepth", default, skip_serializing_if = "Option::is_none")] + pub frame_depth: Option, + #[serde(rename = "frameKind", default, skip_serializing_if = "Option::is_none")] + pub frame_kind: Option, + #[serde(rename = "frameWidth", default, skip_serializing_if = "Option::is_none")] + pub frame_width: Option, + #[serde(rename = "frameCornerJoin", default, skip_serializing_if = "Option::is_none")] + pub frame_corner_join: Option, + #[serde(rename = "insetFromFace", default, skip_serializing_if = "Option::is_none")] + pub inset_from_face: Option, + #[serde(rename = "insetFace", default, skip_serializing_if = "Option::is_none")] + pub inset_face: Option, + #[serde(rename = "transomHeight", default, skip_serializing_if = "Option::is_none")] + pub transom_height: Option, + #[serde(rename = "defaultWidth")] + pub default_width: f64, + #[serde(rename = "defaultHeight")] + pub default_height: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub threshold: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum OpeningKind { + #[serde(rename = "dreh")] + Dreh, + #[serde(rename = "kipp")] + Kipp, + #[serde(rename = "drehkipp")] + Drehkipp, + #[serde(rename = "fest")] + Fest, + #[serde(rename = "schiebe")] + Schiebe, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum SashDefKind { + #[serde(rename = "fluegel")] + Fluegel, + #[serde(rename = "pfosten")] + Pfosten, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum SashDefHingeSide { + #[serde(rename = "left")] + Left, + #[serde(rename = "right")] + Right, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct SashDef { + pub kind: SashDefKind, + #[serde(rename = "autoWidth", default, skip_serializing_if = "Option::is_none")] + pub auto_width: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub width: Option, + #[serde(rename = "postWidth", default, skip_serializing_if = "Option::is_none")] + pub post_width: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub opening: Option, + #[serde(rename = "hingeSide", default, skip_serializing_if = "Option::is_none")] + pub hinge_side: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum WindowShadingKind { + #[serde(rename = "rollladen")] + Rollladen, + #[serde(rename = "raffstore")] + Raffstore, + #[serde(rename = "markise")] + Markise, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct WindowShadingBox { + pub width: f64, + pub height: f64, + pub depth: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct WindowShading { + pub create: bool, + pub kind: WindowShadingKind, + pub r#box: WindowShadingBox, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum WindowTypeGlazing { + #[serde(rename = "einfach")] + Einfach, + #[serde(rename = "zweifach")] + Zweifach, + #[serde(rename = "dreifach")] + Dreifach, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum WindowTypeInsetFace { + #[serde(rename = "aussen")] + Aussen, + #[serde(rename = "innen")] + Innen, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum WindowTypeSillLineFaces { + #[serde(rename = "aussen")] + Aussen, + #[serde(rename = "innen")] + Innen, + #[serde(rename = "beide")] + Beide, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum WindowTypeSillLineView { + #[serde(rename = "auf")] + Auf, + #[serde(rename = "unter")] + Unter, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct WindowTypeSillLine { + pub faces: WindowTypeSillLineFaces, + pub view: WindowTypeSillLineView, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum WindowTypeSillBoard { + #[serde(rename = "keine")] + Keine, + #[serde(rename = "innen")] + Innen, + #[serde(rename = "aussen")] + Aussen, + #[serde(rename = "beide")] + Beide, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct WindowType { + pub id: String, + pub name: String, + pub kind: OpeningKind, + #[serde(rename = "wingCount")] + pub wing_count: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sashes: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub shading: Option, + #[serde(rename = "glazingPanes", default, skip_serializing_if = "Option::is_none")] + pub glazing_panes: Option, + #[serde(rename = "mullionRows", default, skip_serializing_if = "Option::is_none")] + pub mullion_rows: Option, + #[serde(rename = "mullionCols", default, skip_serializing_if = "Option::is_none")] + pub mullion_cols: Option, + pub glazing: WindowTypeGlazing, + #[serde(rename = "frameThickness")] + pub frame_thickness: f64, + #[serde(rename = "frameDepth", default, skip_serializing_if = "Option::is_none")] + pub frame_depth: Option, + #[serde(rename = "frameWidth", default, skip_serializing_if = "Option::is_none")] + pub frame_width: Option, + #[serde(rename = "frameCornerJoin", default, skip_serializing_if = "Option::is_none")] + pub frame_corner_join: Option, + #[serde(rename = "insetFromFace", default, skip_serializing_if = "Option::is_none")] + pub inset_from_face: Option, + #[serde(rename = "insetFace", default, skip_serializing_if = "Option::is_none")] + pub inset_face: Option, + #[serde(rename = "innerLayerRecess", default, skip_serializing_if = "Option::is_none")] + pub inner_layer_recess: Option, + #[serde(rename = "transomHeight", default, skip_serializing_if = "Option::is_none")] + pub transom_height: Option, + #[serde(rename = "sillLine", default, skip_serializing_if = "Option::is_none")] + pub sill_line: Option, + #[serde(rename = "defaultSillHeight")] + pub default_sill_height: f64, + #[serde(rename = "defaultWidth")] + pub default_width: f64, + #[serde(rename = "defaultHeight")] + pub default_height: f64, + #[serde(rename = "sillBoard", default, skip_serializing_if = "Option::is_none")] + pub sill_board: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum StairTypeStructure { + #[serde(rename = "massiv")] + Massiv, + #[serde(rename = "beton")] + Beton, + #[serde(rename = "wange")] + Wange, + #[serde(rename = "aufgesattelt")] + Aufgesattelt, + #[serde(rename = "spindel")] + Spindel, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum StairTypeRailing { + #[serde(rename = "keine")] + Keine, + #[serde(rename = "links")] + Links, + #[serde(rename = "rechts")] + Rechts, + #[serde(rename = "beide")] + Beide, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct StairType { + pub id: String, + pub name: String, + pub structure: StairTypeStructure, + #[serde(rename = "closedRisers")] + pub closed_risers: bool, + #[serde(rename = "treadThickness")] + pub tread_thickness: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub nosing: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub railing: Option, + #[serde(rename = "defaultWidth")] + pub default_width: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ColorPen { + pub id: String, + pub name: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct PenStyle { + pub color: String, + pub weight: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct PenSet { + pub id: String, + pub name: String, + pub pens: std::collections::BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct CustomPalette { + pub id: String, + pub name: String, + pub colors: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub visible: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct BuiltinPaletteBanks { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub simple: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tango: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub material: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ral: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum DrawingLevelKind { + #[serde(rename = "floor")] + Floor, + #[serde(rename = "section")] + Section, + #[serde(rename = "elevation")] + Elevation, + #[serde(rename = "drawing")] + Drawing, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct DrawingLevel { + pub id: String, + pub name: String, + pub kind: DrawingLevelKind, + pub visible: bool, + pub locked: bool, + #[serde(rename = "floorHeight", default, skip_serializing_if = "Option::is_none")] + pub floor_height: Option, + #[serde(rename = "cutHeight", default, skip_serializing_if = "Option::is_none")] + pub cut_height: Option, + #[serde(rename = "baseElevation", default, skip_serializing_if = "Option::is_none")] + pub base_elevation: Option, + #[serde(rename = "linePoints", default, skip_serializing_if = "Option::is_none")] + pub line_points: Option<[Vec2; 2]>, + #[serde(rename = "directionSign", default, skip_serializing_if = "Option::is_none")] + pub direction_sign: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub shadows: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub depth: Option, + #[serde(rename = "hiddenLines", default, skip_serializing_if = "Option::is_none")] + pub hidden_lines: Option, + #[serde(rename = "planUnderlayId", default, skip_serializing_if = "Option::is_none")] + pub plan_underlay_id: Option, + #[serde(rename = "levelMarks", default, skip_serializing_if = "Option::is_none")] + pub level_marks: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum SiaCategory { + #[serde(rename = "HNF")] + HNF, + #[serde(rename = "NNF")] + NNF, + #[serde(rename = "VF")] + VF, + #[serde(rename = "FF")] + FF, + #[serde(rename = "KGF")] + KGF, + #[serde(rename = "AGF")] + AGF, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct RoomProgramRow { + pub name: String, + #[serde(rename = "siaCategory", default, skip_serializing_if = "Option::is_none")] + pub sia_category: Option, + pub area: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub count: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct SunStudy { + pub when: String, + pub show: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct SiteRulesBuildingLines { + pub a: Vec2, + pub b: Vec2, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct SiteRules { + pub parcel: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub setbacks: Option>, + #[serde(rename = "defaultSetback")] + pub default_setback: f64, + #[serde(rename = "buildingLines", default, skip_serializing_if = "Option::is_none")] + pub building_lines: Option>, + #[serde(rename = "maxHeight", default, skip_serializing_if = "Option::is_none")] + pub max_height: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub show: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct LayerCategory { + pub code: String, + pub name: String, + pub color: String, + #[serde(rename = "colorPenId", default, skip_serializing_if = "Option::is_none")] + pub color_pen_id: Option, + pub lw: f64, + pub visible: bool, + pub locked: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hatch: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub children: Option>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum AttributeSource { + #[serde(rename = "layer")] + Layer, + #[serde(rename = "object")] + Object, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum WallReferenceLine { + #[serde(rename = "left")] + Left, + #[serde(rename = "center")] + Center, + #[serde(rename = "right")] + Right, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum SliceTermination { + #[serde(rename = "both")] + Both, + #[serde(rename = "below")] + Below, + #[serde(rename = "above")] + Above, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Wall { + pub id: String, + pub r#type: String, + #[serde(rename = "floorId")] + pub floor_id: String, + #[serde(rename = "categoryCode")] + pub category_code: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub locked: Option, + pub start: Vec2, + pub end: Vec2, + #[serde(rename = "wallTypeId")] + pub wall_type_id: String, + pub height: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + #[serde(rename = "colorPenId", default, skip_serializing_if = "Option::is_none")] + pub color_pen_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub foreground: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub background: Option, + #[serde(rename = "foregroundPenId", default, skip_serializing_if = "Option::is_none")] + pub foreground_pen_id: Option, + #[serde(rename = "backgroundPenId", default, skip_serializing_if = "Option::is_none")] + pub background_pen_id: Option, + #[serde(rename = "strokeWeight", default, skip_serializing_if = "Option::is_none")] + pub stroke_weight: Option, + #[serde(rename = "hatchId", default, skip_serializing_if = "Option::is_none")] + pub hatch_id: Option, + #[serde(rename = "foregroundSource", default, skip_serializing_if = "Option::is_none")] + pub foreground_source: Option, + #[serde(rename = "backgroundSource", default, skip_serializing_if = "Option::is_none")] + pub background_source: Option, + #[serde(rename = "strokeWeightSource", default, skip_serializing_if = "Option::is_none")] + pub stroke_weight_source: Option, + #[serde(rename = "hatchSource", default, skip_serializing_if = "Option::is_none")] + pub hatch_source: Option, + #[serde(rename = "referenceLine", default, skip_serializing_if = "Option::is_none")] + pub reference_line: Option, + #[serde(rename = "referenceOffset", default, skip_serializing_if = "Option::is_none")] + pub reference_offset: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bottom: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub top: Option, + #[serde(rename = "sliceTermination", default, skip_serializing_if = "Option::is_none")] + pub slice_termination: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Ceiling { + pub id: String, + pub r#type: String, + #[serde(rename = "floorId")] + pub floor_id: String, + #[serde(rename = "categoryCode")] + pub category_code: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub locked: Option, + pub outline: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub openings: Option>>, + #[serde(rename = "wallTypeId")] + pub wall_type_id: String, + #[serde(rename = "ceilingTypeId", default, skip_serializing_if = "Option::is_none")] + pub ceiling_type_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thickness: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + #[serde(rename = "colorPenId", default, skip_serializing_if = "Option::is_none")] + pub color_pen_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub foreground: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub background: Option, + #[serde(rename = "foregroundPenId", default, skip_serializing_if = "Option::is_none")] + pub foreground_pen_id: Option, + #[serde(rename = "backgroundPenId", default, skip_serializing_if = "Option::is_none")] + pub background_pen_id: Option, + #[serde(rename = "strokeWeight", default, skip_serializing_if = "Option::is_none")] + pub stroke_weight: Option, + #[serde(rename = "hatchId", default, skip_serializing_if = "Option::is_none")] + pub hatch_id: Option, + #[serde(rename = "foregroundSource", default, skip_serializing_if = "Option::is_none")] + pub foreground_source: Option, + #[serde(rename = "backgroundSource", default, skip_serializing_if = "Option::is_none")] + pub background_source: Option, + #[serde(rename = "strokeWeightSource", default, skip_serializing_if = "Option::is_none")] + pub stroke_weight_source: Option, + #[serde(rename = "hatchSource", default, skip_serializing_if = "Option::is_none")] + pub hatch_source: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub top: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bottom: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum RoofShape { + #[serde(rename = "flach")] + Flach, + #[serde(rename = "pult")] + Pult, + #[serde(rename = "sattel")] + Sattel, + #[serde(rename = "walm")] + Walm, + #[serde(rename = "mansarde")] + Mansarde, + #[serde(rename = "zelt")] + Zelt, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum RoofMansardType { + #[serde(rename = "giebel")] + Giebel, + #[serde(rename = "walm")] + Walm, + #[serde(rename = "zelt")] + Zelt, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum RoofRidgeAxis { + #[serde(rename = "x")] + X, + #[serde(rename = "y")] + Y, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Roof { + pub id: String, + pub r#type: String, + #[serde(rename = "floorId")] + pub floor_id: String, + #[serde(rename = "categoryCode")] + pub category_code: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub locked: Option, + pub outline: Vec, + pub shape: RoofShape, + #[serde(rename = "pitchDeg")] + pub pitch_deg: f64, + #[serde(rename = "pitchUpperDeg", default, skip_serializing_if = "Option::is_none")] + pub pitch_upper_deg: Option, + #[serde(rename = "mansardType", default, skip_serializing_if = "Option::is_none")] + pub mansard_type: Option, + #[serde(rename = "mansardKneeRatio", default, skip_serializing_if = "Option::is_none")] + pub mansard_knee_ratio: Option, + #[serde(rename = "halfHipRatio", default, skip_serializing_if = "Option::is_none")] + pub half_hip_ratio: Option, + pub overhang: f64, + #[serde(rename = "overhangGable", default, skip_serializing_if = "Option::is_none")] + pub overhang_gable: Option, + #[serde(rename = "ridgeAxis")] + pub ridge_axis: RoofRidgeAxis, + #[serde(rename = "baseElevation", default, skip_serializing_if = "Option::is_none")] + pub base_elevation: Option, + pub thickness: f64, + #[serde(rename = "roofTypeId", default, skip_serializing_if = "Option::is_none")] + pub roof_type_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + #[serde(rename = "colorPenId", default, skip_serializing_if = "Option::is_none")] + pub color_pen_id: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum OpeningKind2 { + #[serde(rename = "window")] + Window, + #[serde(rename = "door")] + Door, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum OpeningDoorType { + #[serde(rename = "normal")] + Normal, + #[serde(rename = "wandoeffnung")] + Wandoeffnung, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum OpeningHinge { + #[serde(rename = "start")] + Start, + #[serde(rename = "end")] + End, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum SwingSide { + #[serde(rename = "left")] + Left, + #[serde(rename = "right")] + Right, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum OpeningOpeningDir { + #[serde(rename = "in")] + In, + #[serde(rename = "out")] + Out, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum OpeningLintelLines { + #[serde(rename = "keine")] + Keine, + #[serde(rename = "innen")] + Innen, + #[serde(rename = "aussen")] + Aussen, + #[serde(rename = "beide")] + Beide, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum DetailLevel { + #[serde(rename = "grob")] + Grob, + #[serde(rename = "mittel")] + Mittel, + #[serde(rename = "fein")] + Fein, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct LineStyleOverride { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub weight: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Opening { + pub id: String, + pub r#type: String, + #[serde(rename = "hostWallId")] + pub host_wall_id: String, + #[serde(rename = "categoryCode")] + pub category_code: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub locked: Option, + pub kind: OpeningKind2, + pub position: f64, + pub width: f64, + pub height: f64, + #[serde(rename = "sillHeight")] + pub sill_height: f64, + #[serde(rename = "wingCount", default, skip_serializing_if = "Option::is_none")] + pub wing_count: Option, + #[serde(rename = "doorType", default, skip_serializing_if = "Option::is_none")] + pub door_type: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hinge: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub swing: Option, + #[serde(rename = "swingAngle", default, skip_serializing_if = "Option::is_none")] + pub swing_angle: Option, + #[serde(rename = "openingDir", default, skip_serializing_if = "Option::is_none")] + pub opening_dir: Option, + #[serde(rename = "frameThickness", default, skip_serializing_if = "Option::is_none")] + pub frame_thickness: Option, + #[serde(rename = "lintelLines", default, skip_serializing_if = "Option::is_none")] + pub lintel_lines: Option, + #[serde(rename = "typeId", default, skip_serializing_if = "Option::is_none")] + pub type_id: Option, + #[serde(rename = "detailLevel", default, skip_serializing_if = "Option::is_none")] + pub detail_level: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + #[serde(rename = "colorPenId", default, skip_serializing_if = "Option::is_none")] + pub color_pen_id: Option, + #[serde(rename = "frameLine", default, skip_serializing_if = "Option::is_none")] + pub frame_line: Option, + #[serde(rename = "frameViewLine", default, skip_serializing_if = "Option::is_none")] + pub frame_view_line: Option, + #[serde(rename = "sashLine", default, skip_serializing_if = "Option::is_none")] + pub sash_line: Option, + #[serde(rename = "sillLineStyle", default, skip_serializing_if = "Option::is_none")] + pub sill_line_style: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum StairShape { + #[serde(rename = "straight")] + Straight, + #[serde(rename = "L")] + L, + #[serde(rename = "spiral")] + Spiral, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum StairReferenz { + #[serde(rename = "links")] + Links, + #[serde(rename = "mitte")] + Mitte, + #[serde(rename = "rechts")] + Rechts, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum StairArrowStyle { + #[serde(rename = "line")] + Line, + #[serde(rename = "filled")] + Filled, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Stair { + pub id: String, + pub r#type: String, + #[serde(rename = "floorId")] + pub floor_id: String, + #[serde(rename = "categoryCode")] + pub category_code: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub locked: Option, + pub shape: StairShape, + pub start: Vec2, + pub dir: Vec2, + #[serde(rename = "runLength")] + pub run_length: f64, + #[serde(rename = "run2Length", default, skip_serializing_if = "Option::is_none")] + pub run2_length: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub turn: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub center: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub radius: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sweep: Option, + pub width: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub referenz: Option, + #[serde(rename = "totalRise", default, skip_serializing_if = "Option::is_none")] + pub total_rise: Option, + #[serde(rename = "stepCount")] + pub step_count: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub up: Option, + #[serde(rename = "typeId", default, skip_serializing_if = "Option::is_none")] + pub type_id: Option, + #[serde(rename = "detailLevel", default, skip_serializing_if = "Option::is_none")] + pub detail_level: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + #[serde(rename = "colorPenId", default, skip_serializing_if = "Option::is_none")] + pub color_pen_id: Option, + #[serde(rename = "arrowStyle", default, skip_serializing_if = "Option::is_none")] + pub arrow_style: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct TextRun { + pub text: String, + pub marks: Marks, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Align { + #[serde(rename = "left")] + Left, + #[serde(rename = "center")] + Center, + #[serde(rename = "right")] + Right, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Paragraph { + pub runs: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub align: Option, + #[serde(rename = "lineHeight", default, skip_serializing_if = "Option::is_none")] + pub line_height: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct RichTextDoc { + pub version: f64, + pub paragraphs: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct RoomStamp { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub number: Option, + pub name: String, + #[serde(rename = "nameLine2", default, skip_serializing_if = "Option::is_none")] + pub name_line2: Option, + #[serde(rename = "showFloorArea")] + pub show_floor_area: bool, + #[serde(rename = "floorAreaPrefix", default, skip_serializing_if = "Option::is_none")] + pub floor_area_prefix: Option, + #[serde(rename = "showUsage")] + pub show_usage: bool, + #[serde(rename = "nameAlign", default, skip_serializing_if = "Option::is_none")] + pub name_align: Option, + #[serde(rename = "line2Align", default, skip_serializing_if = "Option::is_none")] + pub line2_align: Option, + #[serde(rename = "floorAreaAlign", default, skip_serializing_if = "Option::is_none")] + pub floor_area_align: Option, + #[serde(rename = "usageAlign", default, skip_serializing_if = "Option::is_none")] + pub usage_align: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub occupancy: Option, + #[serde(rename = "roundingStep", default, skip_serializing_if = "Option::is_none")] + pub rounding_step: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Room { + pub id: String, + pub r#type: String, + #[serde(rename = "floorId")] + pub floor_id: String, + #[serde(rename = "categoryCode")] + pub category_code: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub locked: Option, + #[serde(rename = "siaCategory")] + pub sia_category: SiaCategory, + pub name: String, + pub boundary: Vec, + pub color: String, + #[serde(rename = "colorPenId", default, skip_serializing_if = "Option::is_none")] + pub color_pen_id: Option, + #[serde(rename = "stampAnchor", default, skip_serializing_if = "Option::is_none")] + pub stamp_anchor: Option, + #[serde(rename = "stampDoc", default, skip_serializing_if = "Option::is_none")] + pub stamp_doc: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stamp: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum EndMark { + #[serde(rename = "none")] + None, + #[serde(rename = "arrow")] + Arrow, + #[serde(rename = "arrowOpen")] + ArrowOpen, + #[serde(rename = "dot")] + Dot, + #[serde(rename = "tick")] + Tick, + #[serde(rename = "square")] + Square, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Drawing2DEndMarks { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end: Option, + #[serde(rename = "sizeMm", default, skip_serializing_if = "Option::is_none")] + pub size_mm: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Drawing2D { + pub id: String, + pub r#type: String, + #[serde(rename = "levelId")] + pub level_id: String, + #[serde(rename = "categoryCode")] + pub category_code: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub locked: Option, + #[serde(rename = "noPrint", default, skip_serializing_if = "Option::is_none")] + pub no_print: Option, + pub geom: Drawing2DGeom, + #[serde(rename = "lineStyleId", default, skip_serializing_if = "Option::is_none")] + pub line_style_id: Option, + #[serde(rename = "hatchId", default, skip_serializing_if = "Option::is_none")] + pub hatch_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub foreground: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub background: Option, + #[serde(rename = "foregroundPenId", default, skip_serializing_if = "Option::is_none")] + pub foreground_pen_id: Option, + #[serde(rename = "backgroundPenId", default, skip_serializing_if = "Option::is_none")] + pub background_pen_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + #[serde(rename = "colorPenId", default, skip_serializing_if = "Option::is_none")] + pub color_pen_id: Option, + #[serde(rename = "dashScale", default, skip_serializing_if = "Option::is_none")] + pub dash_scale: Option, + #[serde(rename = "hatchAngleDeg", default, skip_serializing_if = "Option::is_none")] + pub hatch_angle_deg: Option, + #[serde(rename = "hatchScale", default, skip_serializing_if = "Option::is_none")] + pub hatch_scale: Option, + #[serde(rename = "hatchOrigin", default, skip_serializing_if = "Option::is_none")] + pub hatch_origin: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub opacity: Option, + #[serde(rename = "fillOpacity", default, skip_serializing_if = "Option::is_none")] + pub fill_opacity: Option, + #[serde(rename = "endMarks", default, skip_serializing_if = "Option::is_none")] + pub end_marks: Option, + #[serde(rename = "fillColor", default, skip_serializing_if = "Option::is_none")] + pub fill_color: Option, + #[serde(rename = "weightMm", default, skip_serializing_if = "Option::is_none")] + pub weight_mm: Option, + #[serde(rename = "foregroundSource", default, skip_serializing_if = "Option::is_none")] + pub foreground_source: Option, + #[serde(rename = "backgroundSource", default, skip_serializing_if = "Option::is_none")] + pub background_source: Option, + #[serde(rename = "strokeWeightSource", default, skip_serializing_if = "Option::is_none")] + pub stroke_weight_source: Option, + #[serde(rename = "hatchSource", default, skip_serializing_if = "Option::is_none")] + pub hatch_source: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ExtrudedSolidCircle { + pub center: Vec2, + pub r: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ExtrudedSolidBrep { + pub spec: std::collections::BTreeMap, + pub origin: Vec2, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ExtrudedSolid { + pub id: String, + pub r#type: String, + #[serde(rename = "levelId")] + pub level_id: String, + pub points: Vec, + pub height: f64, + #[serde(rename = "baseOffset", default, skip_serializing_if = "Option::is_none")] + pub base_offset: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub operation: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub circle: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub taper: Option, + #[serde(rename = "cornerRadius", default, skip_serializing_if = "Option::is_none")] + pub corner_radius: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub chamfer: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub brep: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Column { + pub id: String, + pub r#type: String, + #[serde(rename = "floorId")] + pub floor_id: String, + #[serde(rename = "categoryCode")] + pub category_code: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub locked: Option, + pub position: Vec2, + pub profile: ColumnProfile, + pub rotation: f64, + pub height: f64, + #[serde(rename = "componentId", default, skip_serializing_if = "Option::is_none")] + pub component_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bottom: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub top: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + #[serde(rename = "colorPenId", default, skip_serializing_if = "Option::is_none")] + pub color_pen_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub foreground: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub background: Option, + #[serde(rename = "foregroundPenId", default, skip_serializing_if = "Option::is_none")] + pub foreground_pen_id: Option, + #[serde(rename = "backgroundPenId", default, skip_serializing_if = "Option::is_none")] + pub background_pen_id: Option, + #[serde(rename = "strokeWeight", default, skip_serializing_if = "Option::is_none")] + pub stroke_weight: Option, + #[serde(rename = "hatchId", default, skip_serializing_if = "Option::is_none")] + pub hatch_id: Option, + #[serde(rename = "foregroundSource", default, skip_serializing_if = "Option::is_none")] + pub foreground_source: Option, + #[serde(rename = "backgroundSource", default, skip_serializing_if = "Option::is_none")] + pub background_source: Option, + #[serde(rename = "strokeWeightSource", default, skip_serializing_if = "Option::is_none")] + pub stroke_weight_source: Option, + #[serde(rename = "hatchSource", default, skip_serializing_if = "Option::is_none")] + pub hatch_source: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Group { + pub id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(rename = "wallIds")] + pub wall_ids: Vec, + #[serde(rename = "drawingIds")] + pub drawing_ids: Vec, + #[serde(rename = "ceilingIds")] + pub ceiling_ids: Vec, + #[serde(rename = "roomIds")] + pub room_ids: Vec, + #[serde(rename = "stairIds")] + pub stair_ids: Vec, + #[serde(rename = "columnIds")] + pub column_ids: Vec, + #[serde(rename = "roofIds")] + pub roof_ids: Vec, + #[serde(rename = "openingIds")] + pub opening_ids: Vec, + #[serde(rename = "groupIds")] + pub group_ids: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ParametricWall { + pub id: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + pub rules: Vec, + #[serde(rename = "defaultWallTypeId")] + pub default_wall_type_id: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum OverrideConditionType { + #[serde(rename = "layer_name")] + LayerName, + #[serde(rename = "object_name")] + ObjectName, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum OverrideOperator { + #[serde(rename = "equals")] + Equals, + #[serde(rename = "contains")] + Contains, + #[serde(rename = "starts_with")] + StartsWith, + #[serde(rename = "not_equals")] + NotEquals, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct OverrideCondition { + pub r#type: OverrideConditionType, + pub operator: OverrideOperator, + pub value: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct OverrideActions { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub lineweight: Option, + #[serde(rename = "linetypeId", default, skip_serializing_if = "Option::is_none")] + pub linetype_id: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct OverrideRule { + pub id: String, + pub name: String, + pub enabled: bool, + pub condition: OverrideCondition, + pub actions: OverrideActions, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum ViewType { + #[serde(rename = "grundriss")] + Grundriss, + #[serde(rename = "perspektive")] + Perspektive, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum View3d { + #[serde(rename = "front")] + Front, + #[serde(rename = "back")] + Back, + #[serde(rename = "side")] + Side, + #[serde(rename = "left")] + Left, + #[serde(rename = "top")] + Top, + #[serde(rename = "iso")] + Iso, + #[serde(rename = "isoFrontLeft")] + IsoFrontLeft, + #[serde(rename = "isoBackRight")] + IsoBackRight, + #[serde(rename = "isoBackLeft")] + IsoBackLeft, + #[serde(rename = "perspective")] + Perspective, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ViewSnapshot { + pub id: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub folder: Option, + #[serde(rename = "folderId", default, skip_serializing_if = "Option::is_none")] + pub folder_id: Option, + #[serde(rename = "viewType")] + pub view_type: ViewType, + pub view3d: View3d, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fov: Option, + #[serde(rename = "scaleDenominator")] + pub scale_denominator: f64, + pub detail: DetailLevel, + #[serde(rename = "activeLevelId")] + pub active_level_id: String, + #[serde(rename = "layerVisibility")] + pub layer_visibility: std::collections::BTreeMap, + #[serde(rename = "drawingVisibility")] + pub drawing_visibility: std::collections::BTreeMap, + #[serde(rename = "enabledOverrideRuleIds", default, skip_serializing_if = "Option::is_none")] + pub enabled_override_rule_ids: Option>, + #[serde(rename = "cameraCenter", default, skip_serializing_if = "Option::is_none")] + pub camera_center: Option, + #[serde(rename = "cameraPxPerMeter", default, skip_serializing_if = "Option::is_none")] + pub camera_px_per_meter: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ViewSnapshotFolder { + pub id: String, + pub name: String, + #[serde(rename = "parentId", default, skip_serializing_if = "Option::is_none")] + pub parent_id: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum LayoutPaperFormat { + #[serde(rename = "a0")] + A0, + #[serde(rename = "a1")] + A1, + #[serde(rename = "a2")] + A2, + #[serde(rename = "a3")] + A3, + #[serde(rename = "a4")] + A4, + #[serde(rename = "a5")] + A5, + #[serde(rename = "a6")] + A6, + #[serde(rename = "b0")] + B0, + #[serde(rename = "b1")] + B1, + #[serde(rename = "b2")] + B2, + #[serde(rename = "b3")] + B3, + #[serde(rename = "b4")] + B4, + #[serde(rename = "b5")] + B5, + #[serde(rename = "b6")] + B6, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum LayoutOrientation { + #[serde(rename = "portrait")] + Portrait, + #[serde(rename = "landscape")] + Landscape, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct LayoutViewport { + pub id: String, + #[serde(rename = "snapshotId")] + pub snapshot_id: String, + #[serde(rename = "xMm")] + pub x_mm: f64, + #[serde(rename = "yMm")] + pub y_mm: f64, + #[serde(rename = "widthMm")] + pub width_mm: f64, + #[serde(rename = "heightMm")] + pub height_mm: f64, + #[serde(rename = "scaleDenominator", default, skip_serializing_if = "Option::is_none")] + pub scale_denominator: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Layout { + pub id: String, + pub name: String, + pub paper: LayoutPaperFormat, + pub orientation: LayoutOrientation, + #[serde(rename = "planNumber", default, skip_serializing_if = "Option::is_none")] + pub plan_number: Option, + #[serde(rename = "masterId", default, skip_serializing_if = "Option::is_none")] + pub master_id: Option, + #[serde(rename = "folderId", default, skip_serializing_if = "Option::is_none")] + pub folder_id: Option, + #[serde(rename = "customWidthMm", default, skip_serializing_if = "Option::is_none")] + pub custom_width_mm: Option, + #[serde(rename = "customHeightMm", default, skip_serializing_if = "Option::is_none")] + pub custom_height_mm: Option, + pub viewports: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub annotations: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct LayoutTitleBlock { + #[serde(rename = "projectName", default, skip_serializing_if = "Option::is_none")] + pub project_name: Option, + #[serde(rename = "sheetName", default, skip_serializing_if = "Option::is_none")] + pub sheet_name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scale: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub date: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub author: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct MasterLayout { + pub id: String, + pub name: String, + pub paper: LayoutPaperFormat, + pub orientation: LayoutOrientation, + #[serde(rename = "titleBlock")] + pub title_block: LayoutTitleBlock, + #[serde(rename = "folderId", default, skip_serializing_if = "Option::is_none")] + pub folder_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub border: Option, + #[serde(rename = "customWidthMm", default, skip_serializing_if = "Option::is_none")] + pub custom_width_mm: Option, + #[serde(rename = "customHeightMm", default, skip_serializing_if = "Option::is_none")] + pub custom_height_mm: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum LayoutFolderKind { + #[serde(rename = "layout")] + Layout, + #[serde(rename = "master")] + Master, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct LayoutFolder { + pub id: String, + pub name: String, + #[serde(rename = "parentId", default, skip_serializing_if = "Option::is_none")] + pub parent_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub kind: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ProjectGeoAnchorLv95 { + pub e: f64, + pub n: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ProjectGeoAnchor { + pub lv95: ProjectGeoAnchorLv95, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub height: Option, + pub model: Vec2, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Project { + #[serde(rename = "formatVersion", default, skip_serializing_if = "Option::is_none")] + pub format_version: Option, + pub id: String, + pub name: String, + #[serde(rename = "lineStyles")] + pub line_styles: Vec, + #[serde(rename = "textStyles", default, skip_serializing_if = "Option::is_none")] + pub text_styles: Option>, + pub hatches: Vec, + pub components: Vec, + #[serde(rename = "wallTypes")] + pub wall_types: Vec, + #[serde(rename = "ceilingTypes", default, skip_serializing_if = "Option::is_none")] + pub ceiling_types: Option>, + #[serde(rename = "roofTypes", default, skip_serializing_if = "Option::is_none")] + pub roof_types: Option>, + #[serde(rename = "blockDefs", default, skip_serializing_if = "Option::is_none")] + pub block_defs: Option>, + #[serde(rename = "doorTypes", default, skip_serializing_if = "Option::is_none")] + pub door_types: Option>, + #[serde(rename = "windowTypes", default, skip_serializing_if = "Option::is_none")] + pub window_types: Option>, + #[serde(rename = "stairTypes", default, skip_serializing_if = "Option::is_none")] + pub stair_types: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pens: Option>, + #[serde(rename = "penSets", default, skip_serializing_if = "Option::is_none")] + pub pen_sets: Option>, + #[serde(rename = "activePenSetId", default, skip_serializing_if = "Option::is_none")] + pub active_pen_set_id: Option, + #[serde(rename = "customPalettes", default, skip_serializing_if = "Option::is_none")] + pub custom_palettes: Option>, + #[serde(rename = "builtinPaletteBanks", default, skip_serializing_if = "Option::is_none")] + pub builtin_palette_banks: Option, + #[serde(rename = "drawingLevels")] + pub drawing_levels: Vec, + #[serde(rename = "roomProgram", default, skip_serializing_if = "Option::is_none")] + pub room_program: Option>, + #[serde(rename = "parcelArea", default, skip_serializing_if = "Option::is_none")] + pub parcel_area: Option, + #[serde(rename = "sunStudy", default, skip_serializing_if = "Option::is_none")] + pub sun_study: Option, + #[serde(rename = "siteRules", default, skip_serializing_if = "Option::is_none")] + pub site_rules: Option, + #[serde(rename = "scaleLineWeights", default, skip_serializing_if = "Option::is_none")] + pub scale_line_weights: Option, + pub layers: Vec, + pub walls: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ceilings: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub roofs: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub openings: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stairs: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rooms: Option>, + pub drawings2d: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub context: Option>, + #[serde(rename = "extrudedSolids", default, skip_serializing_if = "Option::is_none")] + pub extruded_solids: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub columns: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub groups: Option>, + #[serde(rename = "parametricWalls", default, skip_serializing_if = "Option::is_none")] + pub parametric_walls: Option>, + #[serde(rename = "overrideRules", default, skip_serializing_if = "Option::is_none")] + pub override_rules: Option>, + #[serde(rename = "viewSnapshots", default, skip_serializing_if = "Option::is_none")] + pub view_snapshots: Option>, + #[serde(rename = "viewSnapshotFolders", default, skip_serializing_if = "Option::is_none")] + pub view_snapshot_folders: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub layouts: Option>, + #[serde(rename = "masterLayouts", default, skip_serializing_if = "Option::is_none")] + pub master_layouts: Option>, + #[serde(rename = "layoutFolders", default, skip_serializing_if = "Option::is_none")] + pub layout_folders: Option>, + #[serde(rename = "referenceElevationMasl", default, skip_serializing_if = "Option::is_none")] + pub reference_elevation_masl: Option, + #[serde(rename = "geoAnchor", default, skip_serializing_if = "Option::is_none")] + pub geo_anchor: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum GridRuleDirections { + #[serde(rename = "x")] + X, + #[serde(rename = "y")] + Y, + #[serde(rename = "both")] + Both, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct GridRule { + #[serde(rename = "gridId", default, skip_serializing_if = "Option::is_none")] + pub grid_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub spacing: Option, + pub directions: GridRuleDirections, + #[serde(rename = "boundaryId", default, skip_serializing_if = "Option::is_none")] + pub boundary_id: Option, + #[serde(rename = "wallTypeId", default, skip_serializing_if = "Option::is_none")] + pub wall_type_id: Option, + #[serde(rename = "referenceLine", default, skip_serializing_if = "Option::is_none")] + pub reference_line: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub height: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum ModuleRuleDirection { + #[serde(rename = "x")] + X, + #[serde(rename = "y")] + Y, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ModuleRule { + #[serde(rename = "moduleSize")] + pub module_size: f64, + pub direction: ModuleRuleDirection, + #[serde(rename = "referenceWallId", default, skip_serializing_if = "Option::is_none")] + pub reference_wall_id: Option, + #[serde(rename = "wallTypeId", default, skip_serializing_if = "Option::is_none")] + pub wall_type_id: Option, + #[serde(rename = "referenceLine", default, skip_serializing_if = "Option::is_none")] + pub reference_line: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub height: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum ConditionalThicknessRuleLogic { + #[serde(rename = "and")] + And, + #[serde(rename = "or")] + Or, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ConditionalThicknessRule { + pub condition: serde_json::Value, + #[serde(rename = "wallTypeId")] + pub wall_type_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub logic: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ReferenceLineRule { + #[serde(rename = "referenceLine")] + pub reference_line: WallReferenceLine, + pub target: serde_json::Value, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct SequenceRule { + pub rules: Vec, + #[serde(rename = "stopOnMatch", default, skip_serializing_if = "Option::is_none")] + pub stop_on_match: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ImportedMesh { + pub id: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub layer: Option, + #[serde(rename = "categoryCode", default, skip_serializing_if = "Option::is_none")] + pub category_code: Option, + pub positions: Vec, + pub indices: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum ContourCurveKind { + #[serde(rename = "circle")] + Circle, + #[serde(rename = "arc")] + Arc, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ContourCurve { + pub kind: ContourCurveKind, + pub cx: f64, + pub cy: f64, + pub r: f64, + pub a0: f64, + pub a1: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Contour { + pub z: f64, + pub pts: Vec, + pub closed: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub layer: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub filled: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub curve: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ContourSet { + pub id: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub layer: Option, + #[serde(rename = "categoryCode", default, skip_serializing_if = "Option::is_none")] + pub category_code: Option, + pub contours: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct TerrainMesh { + pub id: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub layer: Option, + #[serde(rename = "categoryCode", default, skip_serializing_if = "Option::is_none")] + pub category_code: Option, + pub positions: Vec, + pub indices: Vec, + #[serde(rename = "vertexColors", default, skip_serializing_if = "Option::is_none")] + pub vertex_colors: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ContextImageFilters { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub saturation: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub brightness: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub contrast: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub grayscale: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct ContextImage { + pub id: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub layer: Option, + #[serde(rename = "categoryCode", default, skip_serializing_if = "Option::is_none")] + pub category_code: Option, + pub src: String, + pub min: Vec2, + pub max: Vec2, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub opacity: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub drape: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub filters: Option, +} + diff --git a/src-tauri/core/src/model/manual.rs b/src-tauri/core/src/model/manual.rs new file mode 100644 index 00000000..0ca1631e --- /dev/null +++ b/src-tauri/core/src/model/manual.rs @@ -0,0 +1,273 @@ +//! Von Hand geschriebene Teile des Modells: Typen mit Tag (diskriminierte Unions) und `Vec2`. +//! Gegenstück zu den entsprechenden Typen in `src/model/types.ts`. + +use super::generated::*; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)] +#[cfg_attr(test, serde(deny_unknown_fields))] +pub struct Vec2 { + pub x: f64, + pub y: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "mode")] +pub enum VerticalAnchor { + #[serde(rename = "floor")] + Floor { + #[serde(rename = "floorId")] + floor_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + offset: Option, + }, + #[serde(rename = "custom")] + Custom { z: f64 }, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind")] +pub enum ColumnProfile { + #[serde(rename = "rect")] + Rect { width: f64, depth: f64 }, + #[serde(rename = "round")] + Round { radius: f64 }, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Offset2 { + pub along: f64, + pub perp: f64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum KoteKind { + #[serde(rename = "okFertig")] + OkFertig, + #[serde(rename = "ukFertig")] + UkFertig, + #[serde(rename = "okRoh")] + OkRoh, + #[serde(rename = "ukRoh")] + UkRoh, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum SplineMode { + Fit, + Control, +} + +/// Geometrie eines 2D-Zeichenelements (Tag `shape`). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "shape")] +pub enum Drawing2DGeom { + #[serde(rename = "line")] + Line { a: Vec2, b: Vec2 }, + #[serde(rename = "xline")] + Xline { a: Vec2, b: Vec2 }, + #[serde(rename = "ray")] + Ray { a: Vec2, b: Vec2 }, + #[serde(rename = "polyline")] + Polyline { + pts: Vec, + closed: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + bulge: Option>, + }, + #[serde(rename = "rect")] + Rect { min: Vec2, max: Vec2 }, + #[serde(rename = "circle")] + Circle { center: Vec2, r: f64 }, + #[serde(rename = "arc")] + Arc { center: Vec2, r: f64, a0: f64, a1: f64 }, + #[serde(rename = "ellipse")] + Ellipse { center: Vec2, rx: f64, ry: f64, rotation: f64 }, + #[serde(rename = "bezier")] + Bezier { pts: Vec }, + #[serde(rename = "spline")] + Spline { + pts: Vec, + closed: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + mode: Option, + }, + #[serde(rename = "dimension")] + Dimension { + pts: Vec, + offset: f64, + #[serde(rename = "gapMm", default, skip_serializing_if = "Option::is_none")] + gap_mm: Option, + #[serde(rename = "overshootMm", default, skip_serializing_if = "Option::is_none")] + overshoot_mm: Option, + #[serde(rename = "tickLenMm", default, skip_serializing_if = "Option::is_none")] + tick_len_mm: Option, + #[serde(rename = "textHeightMm", default, skip_serializing_if = "Option::is_none")] + text_height_mm: Option, + #[serde(rename = "lineWeightMm", default, skip_serializing_if = "Option::is_none")] + line_weight_mm: Option, + #[serde(rename = "extWeightMm", default, skip_serializing_if = "Option::is_none")] + ext_weight_mm: Option, + #[serde(rename = "tickWeightMm", default, skip_serializing_if = "Option::is_none")] + tick_weight_mm: Option, + #[serde(rename = "textOffsetsMm", default, skip_serializing_if = "Option::is_none")] + text_offsets_mm: Option>, + }, + #[serde(rename = "kote")] + Kote { at: Vec2, value: f64, kind: KoteKind, rotation: f64 }, + #[serde(rename = "detailref")] + Detailref { + at: Vec2, + label: String, + #[serde(rename = "sheetLayoutId", default, skip_serializing_if = "Option::is_none")] + sheet_layout_id: Option, + #[serde(rename = "sheetLabel", default, skip_serializing_if = "Option::is_none")] + sheet_label: Option, + }, + #[serde(rename = "scalebar")] + Scalebar { + at: Vec2, + #[serde(rename = "segmentLength")] + segment_length: f64, + segments: f64, + }, + #[serde(rename = "pointmarker")] + Pointmarker { at: Vec2 }, + #[serde(rename = "text")] + Text { + at: Vec2, + text: String, + height: f64, + angle: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + width: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + marks: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + doc: Option, + #[serde(rename = "leaderTarget", default, skip_serializing_if = "Option::is_none")] + leader_target: Option, + #[serde(rename = "leaderBendPoints", default, skip_serializing_if = "Option::is_none")] + leader_bend_points: Option>, + #[serde(rename = "pathPts", default, skip_serializing_if = "Option::is_none")] + path_pts: Option>, + }, + #[serde(rename = "block")] + Block { + #[serde(rename = "blockDefId")] + block_def_id: String, + at: Vec2, + rotation: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + scale: Option, + }, + #[serde(rename = "image")] + Image { + min: Vec2, + max: Vec2, + src: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + opacity: Option, + }, +} + +/// Layout-Beschriftung (Tag `kind`). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind")] +pub enum LayoutAnnotation { + #[serde(rename = "line")] + Line { + id: String, + #[serde(rename = "x1Mm")] + x1_mm: f64, + #[serde(rename = "y1Mm")] + y1_mm: f64, + #[serde(rename = "x2Mm")] + x2_mm: f64, + #[serde(rename = "y2Mm")] + y2_mm: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + color: Option, + #[serde(rename = "weightMm", default, skip_serializing_if = "Option::is_none")] + weight_mm: Option, + }, + #[serde(rename = "rect")] + Rect { + id: String, + #[serde(rename = "xMm")] + x_mm: f64, + #[serde(rename = "yMm")] + y_mm: f64, + #[serde(rename = "widthMm")] + width_mm: f64, + #[serde(rename = "heightMm")] + height_mm: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + color: Option, + #[serde(rename = "weightMm", default, skip_serializing_if = "Option::is_none")] + weight_mm: Option, + }, + #[serde(rename = "text")] + Text { + id: String, + #[serde(rename = "xMm")] + x_mm: f64, + #[serde(rename = "yMm")] + y_mm: f64, + text: String, + #[serde(rename = "heightMm")] + height_mm: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + color: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + doc: Option, + #[serde(rename = "widthMm", default, skip_serializing_if = "Option::is_none")] + width_mm: Option, + }, + #[serde(rename = "image")] + Image { + id: String, + #[serde(rename = "xMm")] + x_mm: f64, + #[serde(rename = "yMm")] + y_mm: f64, + #[serde(rename = "widthMm")] + width_mm: f64, + #[serde(rename = "heightMm")] + height_mm: f64, + src: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + opacity: Option, + }, +} + +/// Parametrische Wandregel (Tag `type`). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type")] +pub enum ParametricRule { + #[serde(rename = "grid")] + Grid(GridRule), + #[serde(rename = "module")] + Module(ModuleRule), + #[serde(rename = "conditional-thickness")] + ConditionalThickness(ConditionalThicknessRule), + #[serde(rename = "reference-line")] + ReferenceLine(ReferenceLineRule), + #[serde(rename = "sequence")] + Sequence(SequenceRule), +} + +/// Kontext-Objekt (Tag `type`). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type")] +pub enum ContextObject { + #[serde(rename = "importedMesh")] + ImportedMesh(ImportedMesh), + #[serde(rename = "contourSet")] + ContourSet(ContourSet), + #[serde(rename = "terrainMesh")] + TerrainMesh(TerrainMesh), + #[serde(rename = "image")] + Image(ContextImage), +} diff --git a/src-tauri/core/src/model/mod.rs b/src-tauri/core/src/model/mod.rs new file mode 100644 index 00000000..a0f73443 --- /dev/null +++ b/src-tauri/core/src/model/mod.rs @@ -0,0 +1,38 @@ +//! Typisiertes Projektmodell ([K4] S2): Rust-Gegenstück zu `src/model/types.ts`. `generated.rs` +//! entstand aus den TS-Typen (`scripts/gen-rust-model.py`) und wird ab jetzt von Hand gepflegt; +//! Typen mit Tag stehen in `manual.rs`. + +pub mod generated; +pub mod manual; + +pub use generated::*; +pub use manual::*; + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::Value; + + /// Zahlen als f64 vergleichbar machen (JS kennt keinen Unterschied zwischen 3 und 3.0). + fn norm(v: &Value) -> Value { + match v { + Value::Number(n) => serde_json::Number::from_f64(n.as_f64().unwrap()).map_or(Value::Null, Value::Number), + Value::Array(a) => Value::Array(a.iter().map(norm).collect()), + Value::Object(o) => Value::Object(o.iter().map(|(k, v)| (k.clone(), norm(v))).collect()), + other => other.clone(), + } + } + + fn roundtrip(name: &str, text: &str) { + let raw: Value = serde_json::from_str(text).unwrap(); + // `deny_unknown_fields` (nur im Test) meldet jedes Feld, das dem Modell fehlt. + let p: Project = serde_json::from_value(raw.clone()).unwrap_or_else(|e| panic!("{name}: {e}")); + let back = serde_json::to_value(&p).unwrap(); + assert_eq!(norm(&back), norm(&raw), "{name}: Hin-und-zurück weicht ab"); + } + + #[test] + fn beispielprojekt_hin_und_zurueck() { + roundtrip("sample_project", include_str!("../../tests/fixtures/sample_project.json")); + } +} diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index d5517149..15c08e25 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -61,3 +61,11 @@ pub fn doc_apply(h: u32, ops_json: &str) -> String { pub fn doc_json(h: u32) -> String { with_doc(h, |d| d.to_json()).unwrap_or_default() } + +/// Kennzahlen des Projekts als JSON (leer bei Fehler: Dokument nicht offen oder Modell passt nicht). +#[wasm_bindgen] +pub fn doc_kennzahlen(h: u32) -> String { + with_doc(h, |d| d.project().ok().map(|p| serde_json::to_string(&crate::kennzahlen::compute(&p)).unwrap_or_default())) + .flatten() + .unwrap_or_default() +} diff --git a/src-tauri/core/src/web/kennzahlen.rs b/src-tauri/core/src/web/kennzahlen.rs index f0f36803..19776c1c 100644 --- a/src-tauri/core/src/web/kennzahlen.rs +++ b/src-tauri/core/src/web/kennzahlen.rs @@ -1,8 +1,7 @@ //! Bindungen der Kennzahlen-Rechenteile (`crate::kennzahlen`). use crate::flat_read::pairs; -use crate::flat_read::Reader; -use crate::kennzahlen::{self, RoomIn, SolidIn}; +use crate::kennzahlen; use wasm_bindgen::prelude::wasm_bindgen; /// Grundriss `[x0, y0, …]`, Kreisradius (NaN = kein Kreis), Höhe, Verjüngung → m³. @@ -10,41 +9,3 @@ use wasm_bindgen::prelude::wasm_bindgen; pub fn kz_solid_volume(points: &[f64], circle_r: f64, height: f64, taper: f64) -> f64 { kennzahlen::solid_volume(&pairs(points), circle_r, height, taper) } - -fn read_rooms(buf: &[f64]) -> Option> { - let mut r = Reader::new(buf); - let n = r.count()?; - let mut out = Vec::with_capacity(n.min(1 << 16)); - for _ in 0..n { - let (level, category) = (r.count()?, r.count()?); - out.push(RoomIn { level, category, boundary: r.ring()? }); - } - Some(out) -} - -fn read_solids(buf: &[f64]) -> Option> { - let mut r = Reader::new(buf); - let n = r.count()?; - let mut out = Vec::with_capacity(n.min(1 << 16)); - for _ in 0..n { - let subtract = r.num()? != 0.0; - let (circle_r, height, taper) = (r.num()?, r.num()?, r.num()?); - out.push(SolidIn { subtract, points: r.ring()?, circle_r, height, taper }); - } - Some(out) -} - -/// Räume `[n, (geschoss, kategorie, nPkt, x, y, …)…]`, Körper -/// `[n, (abzug 0/1, radius|NaN, höhe, verjüngung, nPkt, x, y, …)…]`, Parzellenzahl, Parzellenring -/// `[x0, y0, …]` → `[gv, parzelle|NaN, (6 Kategorie-Summen je Geschoss)…]`. -#[wasm_bindgen] -pub fn kz_area_sums(n_levels: u32, rooms: &[f64], solids: &[f64], parcel_area: f64, parcel_ring: &[f64]) -> Vec { - let rooms = read_rooms(rooms).unwrap_or_default(); - let solids = read_solids(solids).unwrap_or_default(); - let s = kennzahlen::area_sums(n_levels.min(1 << 16) as usize, &rooms, &solids, parcel_area, &pairs(parcel_ring)); - let mut out = vec![s.gv, s.parcel.unwrap_or(f64::NAN)]; - for l in s.by_level { - out.extend(l); - } - out -} diff --git a/src-tauri/core/tests/fixtures/sample_project.json b/src-tauri/core/tests/fixtures/sample_project.json new file mode 100644 index 00000000..86feb523 --- /dev/null +++ b/src-tauri/core/tests/fixtures/sample_project.json @@ -0,0 +1,936 @@ +{ + "id": "demo", + "name": "Demo-Haus", + "lineStyles": [ + { + "id": "hatch-hair", + "name": "Volllinie 0.02", + "weight": 0.02, + "color": "#1a1a1a", + "dash": null + }, + { + "id": "thin", + "name": "Volllinie 0.13", + "weight": 0.13, + "color": "#1a1a1a", + "dash": null + }, + { + "id": "medium", + "name": "Volllinie 0.25", + "weight": 0.25, + "color": "#1a1a1a", + "dash": null + }, + { + "id": "thick", + "name": "Volllinie 0.5", + "weight": 0.5, + "color": "#0a0a0a", + "dash": null + }, + { + "id": "hatch-dash", + "name": "Dämmungsstrich", + "weight": 0.02, + "color": "#1a1a1a", + "dash": [ + 0.35, + 0.3 + ] + } + ], + "hatches": [ + { + "id": "none", + "name": "Ohne", + "pattern": "none", + "scale": 1, + "angle": 0, + "color": "#1a1a1a" + }, + { + "id": "insulation", + "name": "Wärmedämmung", + "pattern": "insulation", + "scale": 1, + "angle": 0, + "color": "#1a1a1a", + "lineStyleId": "thin" + }, + { + "id": "diagonal", + "name": "Diagonal", + "pattern": "diagonal", + "scale": 1, + "angle": 45, + "color": "#1a1a1a", + "lineStyleId": "thin" + }, + { + "id": "crosshatch", + "name": "Kreuzschraffur", + "pattern": "crosshatch", + "scale": 1, + "angle": 0, + "color": "#1a1a1a", + "lineStyleId": "thin" + }, + { + "id": "solid-concrete", + "name": "Beton (voll)", + "pattern": "solid", + "scale": 1, + "angle": 0, + "color": "#9aa0a6", + "lineStyleId": "thin" + }, + { + "id": "sia-concrete", + "name": "Beton (Kreuz)", + "pattern": "crosshatch", + "scale": 0.5, + "angle": 45, + "color": "#1a1a1a", + "lineStyleId": "hatch-hair" + }, + { + "id": "sia-brick", + "name": "Backstein (Diagonal)", + "pattern": "diagonal", + "scale": 0.5, + "angle": 45, + "relativeToWall": true, + "color": "#1a1a1a", + "lineStyleId": "hatch-hair" + }, + { + "id": "sia-insulation", + "name": "Dämmung (Strich)", + "pattern": "diagonal", + "scale": 0.45, + "angle": 0, + "relativeToWall": true, + "color": "#1a1a1a", + "lineStyleId": "hatch-hair" + } + ], + "components": [ + { + "id": "render-ext", + "name": "Aussenputz", + "color": "#d8d2c7", + "hatchId": "none", + "joinPriority": 10, + "material": { + "libraryId": "Plaster001", + "color": "/assets/materials/Plaster001/color.jpg", + "normal": "/assets/materials/Plaster001/normal.jpg", + "roughness": "/assets/materials/Plaster001/roughness.jpg", + "displacement": "/assets/materials/Plaster001/displacement.jpg", + "sizeM": 1 + } + }, + { + "id": "insulation", + "name": "Wärmedämmung", + "color": "#ffffff", + "hatchId": "sia-insulation", + "joinPriority": 20 + }, + { + "id": "brick", + "name": "Backstein", + "color": "#8c5544", + "hatchId": "sia-brick", + "joinPriority": 50, + "material": { + "libraryId": "Bricks104", + "color": "/assets/materials/Bricks104/color.jpg", + "normal": "/assets/materials/Bricks104/normal.jpg", + "roughness": "/assets/materials/Bricks104/roughness.jpg", + "displacement": "/assets/materials/Bricks104/displacement.jpg", + "ao": "/assets/materials/Bricks104/ao.jpg", + "sizeM": 1 + } + }, + { + "id": "render-int", + "name": "Innenputz", + "color": "#efece6", + "hatchId": "none", + "joinPriority": 10, + "material": { + "libraryId": "Plaster001", + "color": "/assets/materials/Plaster001/color.jpg", + "normal": "/assets/materials/Plaster001/normal.jpg", + "roughness": "/assets/materials/Plaster001/roughness.jpg", + "displacement": "/assets/materials/Plaster001/displacement.jpg", + "sizeM": 1 + } + }, + { + "id": "roof-tiles", + "name": "Dachziegel", + "color": "#b8735c", + "hatchId": "sia-brick", + "joinPriority": 15, + "material": { + "libraryId": "RoofingTiles013A", + "color": "/assets/materials/RoofingTiles013A/color.jpg", + "normal": "/assets/materials/RoofingTiles013A/normal.jpg", + "roughness": "/assets/materials/RoofingTiles013A/roughness.jpg", + "displacement": "/assets/materials/RoofingTiles013A/displacement.jpg", + "ao": "/assets/materials/RoofingTiles013A/ao.jpg", + "sizeM": 1 + } + }, + { + "id": "concrete", + "name": "Beton", + "color": "#9aa0a6", + "hatchId": "sia-concrete", + "joinPriority": 100, + "material": { + "libraryId": "Concrete048", + "color": "/assets/materials/Concrete048/color.jpg", + "normal": "/assets/materials/Concrete048/normal.jpg", + "roughness": "/assets/materials/Concrete048/roughness.jpg", + "displacement": "/assets/materials/Concrete048/displacement.jpg", + "ao": "/assets/materials/Concrete048/ao.jpg", + "sizeM": 1 + } + }, + { + "id": "screed", + "name": "Zementestrich", + "color": "#c9c2b3", + "hatchId": "diagonal", + "joinPriority": 30 + } + ], + "wallTypes": [ + { + "id": "aw", + "name": "Aussenwand 34.5 cm", + "layers": [ + { + "componentId": "render-ext", + "thickness": 0.02 + }, + { + "componentId": "insulation", + "thickness": 0.16, + "jointLineStyleId": "thin" + }, + { + "componentId": "brick", + "thickness": 0.15 + }, + { + "componentId": "render-int", + "thickness": 0.015 + } + ] + }, + { + "id": "iw", + "name": "Innenwand Mauerwerk verputzt 15 cm", + "layers": [ + { + "componentId": "render-int", + "thickness": 0.015 + }, + { + "componentId": "brick", + "thickness": 0.12 + }, + { + "componentId": "render-int", + "thickness": 0.015 + } + ] + } + ], + "ceilingTypes": [ + { + "id": "dg-massiv", + "name": "Geschossdecke mehrschichtig", + "layers": [ + { + "componentId": "screed", + "thickness": 0.06 + }, + { + "componentId": "insulation", + "thickness": 0.04, + "jointLineStyleId": "thin" + }, + { + "componentId": "concrete", + "thickness": 0.2 + } + ] + } + ], + "roofTypes": [ + { + "id": "roof-warm", + "name": "Steildach gedämmt", + "layers": [ + { + "componentId": "roof-tiles", + "thickness": 0.04 + }, + { + "componentId": "insulation", + "thickness": 0.22, + "jointLineStyleId": "thin" + }, + { + "componentId": "render-int", + "thickness": 0.0125 + } + ] + } + ], + "doorTypes": [ + { + "id": "door-standard", + "name": "Zimmertür 0.9 m", + "kind": "dreh", + "leafCount": 1, + "leafStyle": "glatt", + "frameThickness": 0.05, + "frameKind": "zarge", + "frameWidth": 0.06, + "defaultWidth": 0.9, + "defaultHeight": 2 + }, + { + "id": "door-entry", + "name": "Haustür Blockrahmen (Oberlicht)", + "kind": "dreh", + "leafCount": 1, + "leafStyle": "glas", + "glazingRatio": 0.35, + "frameThickness": 0.07, + "frameKind": "blockrahmen", + "frameWidth": 0.09, + "insetFromFace": 0.14, + "insetFace": "aussen", + "transomHeight": 0.45, + "threshold": true, + "defaultWidth": 1.1, + "defaultHeight": 2.1 + } + ], + "windowTypes": [ + { + "id": "window-standard", + "name": "Fenster 1.2 × 1.4 m", + "kind": "drehkipp", + "wingCount": 1, + "glazing": "zweifach", + "frameThickness": 0.06, + "frameWidth": 0.06, + "defaultSillHeight": 0.9, + "defaultWidth": 1.2, + "defaultHeight": 1.4 + }, + { + "id": "window-double", + "name": "Fenster 2-flügl. + Oberlicht", + "kind": "drehkipp", + "wingCount": 2, + "mullionRows": 1, + "glazing": "dreifach", + "frameThickness": 0.07, + "frameWidth": 0.07, + "insetFromFace": 0.12, + "insetFace": "aussen", + "transomHeight": 0.4, + "defaultSillHeight": 0.85, + "defaultWidth": 1.8, + "defaultHeight": 1.9 + } + ], + "stairTypes": [ + { + "id": "stair-standard", + "name": "Betontreppe 1.0 m", + "structure": "beton", + "closedRisers": true, + "treadThickness": 0.05, + "nosing": 0.03, + "railing": "keine", + "defaultWidth": 1 + }, + { + "id": "stair-massiv", + "name": "Massivtreppe (auf Sockel)", + "structure": "massiv", + "closedRisers": true, + "treadThickness": 0.04, + "nosing": 0.03, + "railing": "keine", + "defaultWidth": 1 + }, + { + "id": "stair-wange-holz", + "name": "Wangentreppe Holz (offen)", + "structure": "wange", + "closedRisers": false, + "treadThickness": 0.05, + "nosing": 0.03, + "railing": "keine", + "defaultWidth": 1 + }, + { + "id": "stair-aufgesattelt", + "name": "Aufgesattelt (Setzstufen)", + "structure": "aufgesattelt", + "closedRisers": true, + "treadThickness": 0.05, + "nosing": 0.025, + "railing": "keine", + "defaultWidth": 1 + } + ], + "drawingLevels": [ + { + "id": "eg", + "name": "Erdgeschoss", + "kind": "floor", + "visible": true, + "locked": false, + "floorHeight": 2.6, + "cutHeight": 1, + "baseElevation": 0 + }, + { + "id": "og", + "name": "Obergeschoss", + "kind": "floor", + "visible": true, + "locked": false, + "floorHeight": 2.6, + "cutHeight": 1, + "baseElevation": 2.6 + }, + { + "id": "schnitt-a", + "name": "Schnitt A", + "kind": "section", + "visible": true, + "locked": false, + "linePoints": [ + { + "x": -1, + "y": 2 + }, + { + "x": 6, + "y": 2 + } + ], + "directionSign": 1 + }, + { + "id": "ansicht-sued", + "name": "Ansicht Süd", + "kind": "elevation", + "visible": true, + "locked": false, + "linePoints": [ + { + "x": -1, + "y": -2 + }, + { + "x": 6, + "y": -2 + } + ], + "directionSign": 1, + "shadows": true + }, + { + "id": "detail-1", + "name": "Detail 1", + "kind": "drawing", + "visible": true, + "locked": false + } + ], + "layers": [ + { + "code": "00", + "name": "Raster", + "color": "#484850", + "lw": 0.13, + "visible": true, + "locked": false + }, + { + "code": "01", + "name": "Vermessung", + "color": "#707078", + "lw": 0.18, + "visible": true, + "locked": false + }, + { + "code": "05", + "name": "Kontext", + "color": "#707078", + "lw": 0.13, + "visible": true, + "locked": false, + "children": [ + { + "code": "10", + "name": "Situation", + "color": "#909090", + "lw": 0.18, + "visible": true, + "locked": false + }, + { + "code": "11", + "name": "Strasse", + "color": "#a89070", + "lw": 0.18, + "visible": true, + "locked": false + }, + { + "code": "12", + "name": "Gebäude", + "color": "#888888", + "lw": 0.25, + "visible": true, + "locked": false + }, + { + "code": "13", + "name": "Bäume", + "color": "#50a050", + "lw": 0.13, + "visible": true, + "locked": false + }, + { + "code": "14", + "name": "Höhenlinien", + "color": "#909050", + "lw": 0.18, + "visible": true, + "locked": false + } + ] + }, + { + "code": "20", + "name": "Wände", + "color": "#0a0a0a", + "lw": 0.35, + "visible": true, + "locked": false, + "children": [ + { + "code": "21", + "name": "Türen/Fenster", + "color": "#5080c8", + "lw": 0.25, + "visible": true, + "locked": false + }, + { + "code": "22", + "name": "Möbel", + "color": "#909090", + "lw": 0.13, + "visible": true, + "locked": false + }, + { + "code": "25", + "name": "Stützen", + "color": "#c87050", + "lw": 0.5, + "visible": true, + "locked": false + } + ] + }, + { + "code": "30", + "name": "Decken", + "color": "#605850", + "lw": 0.35, + "visible": true, + "locked": false + }, + { + "code": "31", + "name": "Dächer", + "color": "#7a4a3a", + "lw": 0.35, + "visible": true, + "locked": false + }, + { + "code": "40", + "name": "Treppen", + "color": "#4a6a58", + "lw": 0.35, + "visible": true, + "locked": false + }, + { + "code": "35", + "name": "Träger", + "color": "#a87858", + "lw": 0.5, + "visible": true, + "locked": false + }, + { + "code": "50", + "name": "Text", + "color": "#d0d0d0", + "lw": 0.13, + "visible": true, + "locked": false + }, + { + "code": "60", + "name": "Räume", + "color": "#5a7a9a", + "lw": 0.13, + "visible": true, + "locked": false + }, + { + "code": "90", + "name": "Referenzen", + "color": "#585860", + "lw": 0.13, + "visible": true, + "locked": false + }, + { + "code": "99", + "name": "Konstruktion", + "color": "#404048", + "lw": 0.13, + "visible": true, + "locked": false + } + ], + "walls": [ + { + "id": "W1", + "type": "wall", + "floorId": "eg", + "categoryCode": "20", + "start": { + "x": 0, + "y": 0 + }, + "end": { + "x": 5, + "y": 0 + }, + "wallTypeId": "aw", + "height": 2.6 + }, + { + "id": "W2", + "type": "wall", + "floorId": "eg", + "categoryCode": "20", + "start": { + "x": 5, + "y": 0 + }, + "end": { + "x": 5, + "y": 4 + }, + "wallTypeId": "aw", + "height": 2.6 + }, + { + "id": "W3", + "type": "wall", + "floorId": "eg", + "categoryCode": "20", + "start": { + "x": 5, + "y": 4 + }, + "end": { + "x": 0, + "y": 4 + }, + "wallTypeId": "aw", + "height": 2.6 + }, + { + "id": "W4", + "type": "wall", + "floorId": "eg", + "categoryCode": "20", + "start": { + "x": 0, + "y": 4 + }, + "end": { + "x": 0, + "y": 0 + }, + "wallTypeId": "aw", + "height": 2.6 + }, + { + "id": "W9", + "type": "wall", + "floorId": "eg", + "categoryCode": "20", + "start": { + "x": 2.4, + "y": 0 + }, + "end": { + "x": 2.4, + "y": 4 + }, + "wallTypeId": "iw", + "height": 2.6 + }, + { + "id": "W5", + "type": "wall", + "floorId": "og", + "categoryCode": "20", + "start": { + "x": 0, + "y": 0 + }, + "end": { + "x": 5, + "y": 0 + }, + "wallTypeId": "aw", + "height": 2.6 + }, + { + "id": "W6", + "type": "wall", + "floorId": "og", + "categoryCode": "20", + "start": { + "x": 5, + "y": 0 + }, + "end": { + "x": 5, + "y": 3 + }, + "wallTypeId": "aw", + "height": 2.6 + }, + { + "id": "W7", + "type": "wall", + "floorId": "og", + "categoryCode": "20", + "start": { + "x": 5, + "y": 3 + }, + "end": { + "x": 0, + "y": 3 + }, + "wallTypeId": "aw", + "height": 2.6 + }, + { + "id": "W8", + "type": "wall", + "floorId": "og", + "categoryCode": "20", + "start": { + "x": 0, + "y": 3 + }, + "end": { + "x": 0, + "y": 0 + }, + "wallTypeId": "aw", + "height": 2.6 + } + ], + "openings": [ + { + "id": "D1", + "type": "opening", + "hostWallId": "W1", + "categoryCode": "21", + "kind": "door", + "typeId": "door-standard", + "position": 0.8, + "width": 0.9, + "height": 2.1, + "sillHeight": 0, + "swing": "left", + "hinge": "start" + }, + { + "id": "O1", + "type": "opening", + "hostWallId": "W1", + "categoryCode": "21", + "kind": "window", + "typeId": "window-standard", + "position": 3, + "width": 1, + "height": 1.2, + "sillHeight": 0.9 + }, + { + "id": "O2", + "type": "opening", + "hostWallId": "W3", + "categoryCode": "21", + "kind": "window", + "typeId": "window-standard", + "position": 0.6, + "width": 1.4, + "height": 1.3, + "sillHeight": 0.9 + } + ], + "ceilings": [ + { + "id": "C1", + "type": "ceiling", + "floorId": "eg", + "categoryCode": "30", + "outline": [ + { + "x": 0, + "y": 0 + }, + { + "x": 5, + "y": 0 + }, + { + "x": 5, + "y": 4 + }, + { + "x": 0, + "y": 4 + } + ], + "wallTypeId": "aw", + "ceilingTypeId": "dg-massiv" + } + ], + "roofs": [ + { + "id": "RF1", + "type": "roof", + "floorId": "og", + "categoryCode": "31", + "outline": [ + { + "x": 0, + "y": 0 + }, + { + "x": 5, + "y": 0 + }, + { + "x": 5, + "y": 4 + }, + { + "x": 0, + "y": 4 + } + ], + "shape": "sattel", + "pitchDeg": 30, + "overhang": 0.4, + "ridgeAxis": "x", + "thickness": 0.2 + } + ], + "stairs": [ + { + "id": "ST1", + "type": "stair", + "floorId": "eg", + "categoryCode": "40", + "shape": "straight", + "typeId": "stair-standard", + "start": { + "x": 3.7, + "y": 0.4 + }, + "dir": { + "x": 0, + "y": 1 + }, + "runLength": 3.2, + "width": 1, + "totalRise": 2.6, + "stepCount": 15, + "up": true + } + ], + "rooms": [ + { + "id": "R1", + "type": "room", + "floorId": "eg", + "categoryCode": "60", + "siaCategory": "HNF", + "name": "Wohnen", + "boundary": [ + { + "x": 0.1725, + "y": 0.1725 + }, + { + "x": 4.8275, + "y": 0.1725 + }, + { + "x": 4.8275, + "y": 3.8275 + }, + { + "x": 0.1725, + "y": 3.8275 + } + ], + "color": "#6b7280", + "stampAnchor": { + "x": 2.5, + "y": 2 + } + } + ], + "drawings2d": [], + "context": [] +} \ No newline at end of file diff --git a/src/analysis/kennzahlen.ts b/src/analysis/kennzahlen.ts index 913878bc..d7c978ce 100644 --- a/src/analysis/kennzahlen.ts +++ b/src/analysis/kennzahlen.ts @@ -6,14 +6,14 @@ // • Ausnützungs-/Überbauungsziffer nur mit `project.parcelArea` oder der Parzellengrenze (`siteRules`). // • Raumprogramm (`project.roomProgram`, Soll) gegen die gezeichneten Räume. // Exakt für Prismen/Kegelstümpfe/Kreise, Näherung sonst (Fasen/Rundungen). Raumflächen je -// Geschoss und Kategorie, Volumen und Parzellenfläche rechnet der Rust-Kern -// (`src-tauri/core/src/kennzahlen.rs`); die Zusammenfassung nach SIA 416 (NF/NGF/GF) bleibt bei -// `geometry/roomArea.ts::balance`, die auch Raumstempel, Bilanz, Raumliste und IFC nutzen. +// Geschoss und Kategorie, Volumen, Parzellenfläche und die SIA-416-Zusammenfassung rechnet der +// Rust-Kern auf dem Projekt-Dokument (`src-tauri/core/src/kennzahlen.rs`). import type { ExtrudedSolid, Project } from "../model/types"; -import { SIA_CATEGORIES, balance, polygonArea } from "../geometry/roomArea"; +import { polygonArea } from "../geometry/roomArea"; import { core } from "../engine/coreWasm"; import { FlatWriter } from "../geometry/coreFlat"; +import { documentFor } from "../core/document"; export interface LevelKennzahlen { levelId: string; @@ -46,56 +46,12 @@ export function solidVolume(s: ExtrudedSolid): number { const finite = (n: number): number => (Number.isFinite(n) ? n : 0); -/** Körper flach (`web/kennzahlen.rs`). */ -function encodeSolids(solids: ExtrudedSolid[]): Float64Array { - const w = new FlatWriter().num(solids.length); - for (const s of solids) { - w.num(s.operation === "subtract" ? 1 : 0, s.circle ? s.circle.r : Number.NaN, s.height, s.taper ?? 0).ring(s.circle ? [] : s.points); - } - return w.done(); -} - +/** + * Flächen je Geschoss (SIA 416), Gebäudevolumen, Ausnützungs- und Überbauungsziffer. Rechnet der + * Kern auf dem Projekt-Dokument (`kennzahlen.rs`, [K4] S2). + */ export function computeKennzahlen(project: Project): Kennzahlen { - const floors = project.drawingLevels - .filter((l) => l.kind === "floor") - .slice() - .sort((a, b) => (a.baseElevation ?? 0) - (b.baseElevation ?? 0)); - const levelIndex = new Map(); - floors.forEach((l, i) => levelIndex.has(l.id) || levelIndex.set(l.id, i)); - const rooms = (project.rooms ?? []).filter((r) => levelIndex.has(r.floorId)); - const rw = new FlatWriter().num(rooms.length); - for (const r of rooms) { - const k = SIA_CATEGORIES.indexOf(r.siaCategory); - // Unbekannte Kategorie → Index ausserhalb, zählt im Kern nicht. - rw.num(levelIndex.get(r.floorId)!, k < 0 ? SIA_CATEGORIES.length : k).ring(r.boundary); - } - const parcelRing = project.siteRules?.parcel ?? []; - const sums = core().kz_area_sums( - floors.length, - rw.done(), - encodeSolids(project.extrudedSolids ?? []), - project.parcelArea ?? Number.NaN, - new FlatWriter().pts(Array.isArray(parcelRing) ? parcelRing : []).done(), - ); - const gv = sums[0]; - const parcel = Number.isNaN(sums[1]) ? null : sums[1]; - const levels: LevelKennzahlen[] = floors.map((l, i) => { - // Kategorie-Summen als Einträge der SIA-416-Bilanz → GF und NGF. - const b = balance(SIA_CATEGORIES.map((category, k) => ({ category, area: sums[2 + i * SIA_CATEGORIES.length + k] }))); - return { levelId: l.id, name: l.name, gf: b.byKey.GF, agf: b.byKey.NGF, rooms: rooms.filter((r) => r.floorId === l.id).length }; - }); - const gf = levels.reduce((s, l) => s + l.gf, 0); - const agf = levels.reduce((s, l) => s + l.agf, 0); - const footprint = levels.find((l) => l.gf > 0)?.gf ?? 0; - return { - levels, - gf, - agf, - gv, - footprint, - az: parcel ? agf / parcel : null, - uez: parcel ? footprint / parcel : null, - }; + return documentFor(project).kennzahlen(); } export type ProgramStatus = "ok" | "zu klein" | "zu gross" | "fehlt" | "zu wenige" | "zu viele"; diff --git a/src/core/document.ts b/src/core/document.ts index f1573072..07a5b10f 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -7,6 +7,7 @@ import type { Project } from "../model/types"; import { core } from "../engine/coreWasm"; import { diffToOps } from "./ops"; +import type { Kennzahlen } from "../analysis/kennzahlen"; export class ProjectDocument { private handle = 0; @@ -45,6 +46,13 @@ export class ProjectDocument { } } + /** Kennzahlen aus dem Kern (`kennzahlen.rs`). */ + kennzahlen(): Kennzahlen { + const text = this.handle ? core().doc_kennzahlen(this.handle) : ""; + if (!text) throw new Error("Kennzahlen: Projekt passt nicht zum Kern-Modell"); + return JSON.parse(text) as Kennzahlen; + } + /** Das Dokument als JSON-Text (Test, Export). */ json(): string { return this.handle ? core().doc_json(this.handle) : ""; @@ -55,3 +63,16 @@ export class ProjectDocument { this.handle = 0; } } + +let shared: ProjectDocument | null = null; + +/** + * Das gemeinsame Kern-Dokument, auf den Stand von `project` gebracht. Der Abgleich läuft über die + * Differenz zum zuletzt gesehenen Projekt (Referenzvergleich, unveränderte Teile kosten nichts); + * wechselt ein Aufrufer zwischen sehr verschiedenen Projekten, ist es nur langsamer, nie falsch. + */ +export function documentFor(project: Project): ProjectDocument { + if (!shared) shared = new ProjectDocument(project); + else shared.sync(project); + return shared; +} diff --git a/src/state/appStore.ts b/src/state/appStore.ts index 49aba7df..cc253945 100644 --- a/src/state/appStore.ts +++ b/src/state/appStore.ts @@ -7,7 +7,6 @@ // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import { createStore } from "./store"; -import { ProjectDocument } from "../core/document"; import type { StoreApi } from "./store"; import { createProjectSlice } from "./projectSlice"; import type { ProjectSlice } from "./projectSlice"; @@ -65,24 +64,3 @@ export const useStore = store.useStore; export const getState = store.getState; export const setState = store.setState; -// Kern-Dokument ([K4] S1): spiegelt jede Änderung von `project` (Setzen, Laden, Undo/Redo) als Ops -// in den Rust-Kern. Ohne geladenen Kern (Start, manche Tests) bleibt es aus und holt sich beim -// nächsten Zugriff den vollen Stand. -let coreDoc: ProjectDocument | null = null; - -/** Das Rust-Dokument zum aktuellen Projekt (synchron nachgezogen); `null`, solange der Kern fehlt. */ -export function projectDocument(): ProjectDocument | null { - try { - const p = store.getState().project; - if (!coreDoc) coreDoc = new ProjectDocument(p); - else coreDoc.sync(p); - return coreDoc; - } catch { - coreDoc = null; - return null; - } -} - -store.subscribe(() => { - void projectDocument(); -}); From b1ebfb9f3a8b154eda12ea68b0e904e691b751b3 Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:50:03 +0100 Subject: [PATCH 17/31] [K4] S2: Baurecht-Pruefung, Gebaeude-Grundflaeche und Modellhoehe rechnen auf dem Dokument (site_rules.rs, model/helpers.rs); TS-Sammler entfernt --- TODO.md | 5 +- src-tauri/core/src/model/helpers.rs | 183 ++++++++++++++++++++++++++++ src-tauri/core/src/model/mod.rs | 1 + src-tauri/core/src/site_rules.rs | 108 ++++++++++++++++ src-tauri/core/src/web/document.rs | 24 +++- src/analysis/kennzahlen.ts | 2 +- src/analysis/siteRules.ts | 67 ++-------- src/core/document.ts | 14 ++- 8 files changed, 331 insertions(+), 73 deletions(-) create mode 100644 src-tauri/core/src/model/helpers.rs diff --git a/TODO.md b/TODO.md index a9cd051e..ea42a975 100644 --- a/TODO.md +++ b/TODO.md @@ -128,8 +128,9 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern - ◐ **S2 Ableitungen lesen das Dokument** (28.10.): typisiertes Rust-Modell `model/` (`generated.rs` aus den TS-Typen per `scripts/gen-rust-model.py`, `manual.rs` für getaggte Unions; Hin-und-zurück-Test gegen das Beispielprojekt mit `deny_unknown_fields`), `Document::project()` als gecachte typisierte Sicht, `documentFor(project)` (TS) hält ein gemeinsames - Dokument per Differenz aktuell. Erster Verbraucher: Kennzahlen (`kennzahlen.rs::compute`, TS-Sammler gelöscht). - Nächste: Baurecht/Footprint, Sonnenstand, Raumprogramm, danach Plan/Schnitt/Ansicht, 3D, Export. + Dokument per Differenz aktuell. Verbraucher bisher: Kennzahlen (`kennzahlen.rs::compute`), Baurecht-Prüfung/Footprint/Modellhöhe (`site_rules.rs`); Abfragen laufen + über `doc_query`, Modell-Nachschlagen in `model/helpers.rs`. TS-Sammler gelöscht. + Nächste: Sonnenstand/Schatten, Raumprogramm, danach Plan/Schnitt/Ansicht, 3D, Export. 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). - ○ **S3 Änderungen kommen aus Rust**: Befehle (Zustandsautomaten, Werkzeuge) erzeugen Ops im Kern; Undo/Redo, Validierung diff --git a/src-tauri/core/src/model/helpers.rs b/src-tauri/core/src/model/helpers.rs new file mode 100644 index 00000000..d387ab52 --- /dev/null +++ b/src-tauri/core/src/model/helpers.rs @@ -0,0 +1,183 @@ +//! Abfragen auf dem typisierten Projekt ([K4] S2): Rust-Gegenstück zu den Nachschlage- und +//! Auflösungsfunktionen aus `src/model/types.ts` und `src/model/wall.ts` (`getWallType`, +//! `wallVerticalExtent`, `roofBaseElevation` …). Wo TS wirft und der Aufrufer einen Rückfall +//! einsetzt (try/catch), liefern die Funktionen hier `Option` und der Aufrufer setzt denselben +//! Rückfall ein. + +use super::*; +use crate::roof::{MansardType, RoofParams, Shape}; +use crate::roof_skeleton::Axis; + +impl Project { + pub fn floor(&self, id: &str) -> Option<&DrawingLevel> { + self.drawing_levels.iter().find(|l| l.id == id) + } + + pub fn wall_type(&self, w: &Wall) -> Option<&WallType> { + self.wall_types.iter().find(|t| t.id == w.wall_type_id) + } + + pub fn component(&self, id: &str) -> Option<&Component> { + self.components.iter().find(|c| c.id == id) + } + + pub fn hatch(&self, id: &str) -> Option<&HatchStyle> { + self.hatches.iter().find(|h| h.id == id) + } + + pub fn line_style(&self, id: &str) -> Option<&LineStyle> { + self.line_styles.iter().find(|l| l.id == id) + } + + pub fn door_type(&self, o: &Opening) -> Option<&DoorType> { + let id = o.type_id.as_deref()?; + self.door_types.as_deref()?.iter().find(|t| t.id == id) + } + + pub fn window_type(&self, o: &Opening) -> Option<&WindowType> { + let id = o.type_id.as_deref()?; + self.window_types.as_deref()?.iter().find(|t| t.id == id) + } + + pub fn stair_type(&self, s: &Stair) -> Option<&StairType> { + let id = s.type_id.as_deref()?; + self.stair_types.as_deref()?.iter().find(|t| t.id == id) + } + + pub fn openings_of_wall<'a>(&'a self, wall_id: &'a str) -> impl Iterator + 'a { + self.openings.as_deref().unwrap_or(&[]).iter().filter(move |o| o.host_wall_id == wall_id) + } + + /// Alle Kategorien flach (Reihenfolge wie `flattenCategories`). + pub fn flat_categories(&self) -> Vec<&LayerCategory> { + fn walk<'a>(list: &'a [LayerCategory], out: &mut Vec<&'a LayerCategory>) { + for c in list { + out.push(c); + if let Some(ch) = &c.children { + walk(ch, out); + } + } + } + let mut out = Vec::new(); + walk(&self.layers, &mut out); + out + } + + pub fn layer_category(&self, code: &str) -> Option<&LayerCategory> { + self.flat_categories().into_iter().find(|c| c.code == code) + } + + /// Dicke eines Wandtyps (Summe der Schichten). + pub fn type_thickness(layers: &[Layer]) -> f64 { + layers.iter().map(|l| l.thickness).sum() + } + + /// Wanddicke; nicht auflösbarer Typ → `fallback` (TS: try/catch mit 0.2). + pub fn wall_thickness(&self, w: &Wall, fallback: f64) -> f64 { + self.wall_type(w).map_or(fallback, |t| Self::type_thickness(&t.layers)) + } + + /// Deckendicke: `thickness` > 0, sonst Typ-Dicke, sonst 0.2. + pub fn ceiling_thickness(&self, c: &Ceiling) -> f64 { + if let Some(t) = c.thickness.filter(|t| *t > 0.0) { + return t; + } + let layers = c + .ceiling_type_id + .as_deref() + .and_then(|id| self.ceiling_types.as_deref()?.iter().find(|t| t.id == id).map(|t| &t.layers)) + .or_else(|| self.wall_types.iter().find(|t| t.id == c.wall_type_id).map(|t| &t.layers)); + layers.map_or(0.2, |l| Self::type_thickness(l)) + } + + /// Schichten eines Dachs; ohne Typ/Schichten eine Schicht mit der Dachdicke. + pub fn roof_layers(&self, r: &Roof) -> Vec { + if let Some(id) = r.roof_type_id.as_deref() { + if let Some(rt) = self.roof_types.as_deref().and_then(|v| v.iter().find(|t| t.id == id)) { + if !rt.layers.is_empty() { + return rt.layers.clone(); + } + } + } + vec![Layer { component_id: String::new(), thickness: r.thickness.max(0.0), joint_line_style_id: None }] + } + + fn resolve_anchor(&self, a: Option<&VerticalAnchor>) -> Option { + match a? { + VerticalAnchor::Custom { z } => Some(*z), + VerticalAnchor::Floor { floor_id, offset } => { + let f = self.floor(floor_id)?; + Some(f.base_elevation.unwrap_or(0.0) + offset.unwrap_or(0.0)) + } + } + } + + /// (UK, OK) einer Wand in Metern (`wallVerticalExtent`). + pub fn wall_vertical_extent(&self, w: &Wall) -> (f64, f64) { + let floor_base = self.floor(&w.floor_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0)); + let bottom = self.resolve_anchor(w.bottom.as_ref()).unwrap_or(floor_base); + let top = self.resolve_anchor(w.top.as_ref()).unwrap_or(bottom + w.height); + (bottom, top) + } + + pub fn ceiling_vertical_extent(&self, c: &Ceiling) -> (f64, f64) { + let floor_top = self.floor(&c.floor_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0) + f.floor_height.unwrap_or(0.0)); + let top = self.resolve_anchor(c.top.as_ref()).unwrap_or(floor_top); + let bottom = self.resolve_anchor(c.bottom.as_ref()).unwrap_or(top - self.ceiling_thickness(c)); + (bottom, top) + } + + pub fn stair_vertical_extent(&self, s: &Stair) -> (f64, f64) { + let (base, floor_height) = self.floor(&s.floor_id).map_or((0.0, 0.0), |f| (f.base_elevation.unwrap_or(0.0), f.floor_height.unwrap_or(0.0))); + let rise = match s.total_rise { + Some(r) if r > 0.0 => r, + _ if floor_height > 0.0 => floor_height, + _ => 2.6, + }; + (base, base + rise) + } + + pub fn column_vertical_extent(&self, c: &Column) -> (f64, f64) { + let floor_base = self.floor(&c.floor_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0)); + let bottom = self.resolve_anchor(c.bottom.as_ref()).unwrap_or(floor_base); + let top = self.resolve_anchor(c.top.as_ref()).unwrap_or(bottom + c.height); + (bottom, top) + } + + /// Traufhöhe (absolutes Z): `baseElevation`, sonst Oberkante des Geschosses (`roofBaseElevation`). + pub fn roof_base_elevation(&self, r: &Roof) -> f64 { + if let Some(b) = r.base_elevation { + return b; + } + self.floor(&r.floor_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0) + f.floor_height.unwrap_or(0.0)) + } +} + +impl Roof { + /// Parameter für die Dachgeometrie (`roof::roof_geometry`). + pub fn params(&self) -> RoofParams { + RoofParams { + outline: self.outline.iter().map(|v| [v.x, v.y]).collect(), + shape: match self.shape { + RoofShape::Flach => Shape::Flach, + RoofShape::Pult => Shape::Pult, + RoofShape::Sattel => Shape::Sattel, + RoofShape::Walm => Shape::Walm, + RoofShape::Mansarde => Shape::Mansarde, + RoofShape::Zelt => Shape::Zelt, + }, + pitch_deg: self.pitch_deg, + pitch_upper_deg: self.pitch_upper_deg, + mansard_type: match self.mansard_type { + Some(RoofMansardType::Walm) => MansardType::Walm, + Some(RoofMansardType::Zelt) => MansardType::Zelt, + _ => MansardType::Giebel, + }, + mansard_knee_ratio: self.mansard_knee_ratio, + half_hip_ratio: self.half_hip_ratio, + overhang: self.overhang, + overhang_gable: self.overhang_gable, + ridge_axis: if self.ridge_axis == RoofRidgeAxis::Y { Axis::Y } else { Axis::X }, + } + } +} diff --git a/src-tauri/core/src/model/mod.rs b/src-tauri/core/src/model/mod.rs index a0f73443..2d315e66 100644 --- a/src-tauri/core/src/model/mod.rs +++ b/src-tauri/core/src/model/mod.rs @@ -3,6 +3,7 @@ //! Typen mit Tag stehen in `manual.rs`. pub mod generated; +pub mod helpers; pub mod manual; pub use generated::*; diff --git a/src-tauri/core/src/site_rules.rs b/src-tauri/core/src/site_rules.rs index 7214aea1..df51244d 100644 --- a/src-tauri/core/src/site_rules.rs +++ b/src-tauri/core/src/site_rules.rs @@ -250,3 +250,111 @@ mod tests { assert!(close(c.violation_area, 0.0) && c.violations.is_empty() && c.height_exceeded); } } + +// ── Baurecht aus dem Projekt-Dokument ([K4] S2) ───────────────────────────── + +use crate::jsmath::hypot2; +use crate::model::{Project, Vec2}; +use serde::Serialize; + +/// Mehrfach-Fläche mit `Vec2`-Punkten (JSON-Form wie `Area` in TS). +pub type AreaOut = Vec>>; + +fn area_out(polys: &[Polygon]) -> AreaOut { + polys.iter().map(|p| p.iter().map(|r| r.iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect()).collect()).collect() +} + +fn wall_corners(start: Vec2, end: Vec2, thickness: f64) -> Vec<[f64; 2]> { + let h = thickness / 2.0; + let (dx, dy) = (end.x - start.x, end.y - start.y); + let l = hypot2(dx, dy); + let l = if l == 0.0 || l.is_nan() { 1.0 } else { l }; + let (ux, uy) = (dx / l, dy / l); + let (nx, ny) = (-uy, ux); + vec![ + [start.x + nx * h, start.y + ny * h], + [end.x + nx * h, end.y + ny * h], + [end.x + nx * -h, end.y + ny * -h], + [start.x + nx * -h, start.y + ny * -h], + ] +} + +/// Teile der Gebäude-Grundfläche (Wände aller Geschosse, freie Körper ohne Abzugskörper). +fn footprint_parts(p: &Project) -> Vec { + let mut parts: Vec = Vec::new(); + for w in &p.walls { + if hypot2(w.end.x - w.start.x, w.end.y - w.start.y) < 1e-9 { + continue; + } + parts.push(vec![wall_corners(w.start, w.end, p.wall_thickness(w, 0.2))]); + } + for s in p.extruded_solids.as_deref().unwrap_or(&[]) { + if s.operation.as_deref() == Some("subtract") || s.points.len() < 3 { + continue; + } + parts.push(vec![s.points.iter().map(|v| [v.x, v.y]).collect()]); + } + parts +} + +/// Grundfläche des Gebäudes (vereinigt). +pub fn building_footprint(p: &Project) -> AreaOut { + let parts = footprint_parts(p); + if parts.is_empty() { + return vec![]; + } + area_out(&polygon_bool::union(&parts)) +} + +/// Höchster Punkt des Modells über ±0.00 (Wände, freie Körper, Dächer); `None` ohne Bauteile. +pub fn model_top(p: &Project) -> Option { + let mut top = f64::NEG_INFINITY; + for w in &p.walls { + top = top.max(p.wall_vertical_extent(w).1); + } + for s in p.extruded_solids.as_deref().unwrap_or(&[]) { + if s.operation.as_deref() == Some("subtract") { + continue; + } + let base = p.floor(&s.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0)); + top = top.max(base + s.base_offset.unwrap_or(0.0) + s.height); + } + for r in p.roofs.as_deref().unwrap_or(&[]) { + let eaves = p.roof_base_elevation(r); + top = top.max(eaves + crate::roof::roof_geometry(&r.params(), eaves).ridge_height); + } + top.is_finite().then_some(top) +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SiteCheckOut { + pub parcel_area: f64, + pub allowed: AreaOut, + pub allowed_area: f64, + pub violations: AreaOut, + pub violation_area: f64, + pub max_top: Option, + pub height_exceeded: bool, +} + +/// Prüft das Modell gegen `siteRules`; `None` ohne (gültiges) Baurecht. +pub fn check_project(p: &Project) -> Option { + let r = p.site_rules.as_ref()?; + let max_top = model_top(p); + let rules = SiteRules { + parcel: r.parcel.iter().map(|v| [v.x, v.y]).collect(), + setbacks: (0..r.parcel.len()).map(|i| r.setbacks.as_ref().and_then(|s| s.get(i)).copied().unwrap_or(r.default_setback)).collect(), + lines: r.building_lines.as_deref().unwrap_or(&[]).iter().map(|l| BuildingLine { a: [l.a.x, l.a.y], b: [l.b.x, l.b.y] }).collect(), + }; + let c = check_site_rules(&rules, &footprint_parts(p), r.max_height.unwrap_or(f64::NAN), max_top.unwrap_or(f64::NAN))?; + Some(SiteCheckOut { + parcel_area: c.parcel_area, + allowed: area_out(&c.allowed), + allowed_area: c.allowed_area, + violations: area_out(&c.violations), + violation_area: c.violation_area, + max_top, + height_exceeded: c.height_exceeded, + }) +} diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index 15c08e25..a559a936 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -62,10 +62,24 @@ pub fn doc_json(h: u32) -> String { with_doc(h, |d| d.to_json()).unwrap_or_default() } -/// Kennzahlen des Projekts als JSON (leer bei Fehler: Dokument nicht offen oder Modell passt nicht). +/// Abfrage auf dem typisierten Projekt; Ergebnis als JSON, leer bei Fehler (Dokument nicht offen, +/// Modell passt nicht, unbekannte Abfrage). Abfragen: `kennzahlen`, `siteCheck` (`null` ohne +/// Baurecht), `buildingFootprint`, `modelTop` (`null` ohne Bauteile). #[wasm_bindgen] -pub fn doc_kennzahlen(h: u32) -> String { - with_doc(h, |d| d.project().ok().map(|p| serde_json::to_string(&crate::kennzahlen::compute(&p)).unwrap_or_default())) - .flatten() - .unwrap_or_default() +pub fn doc_query(h: u32, name: &str) -> String { + use crate::{kennzahlen, site_rules}; + let name = name.to_owned(); + with_doc(h, move |d| { + let p = d.project().ok()?; + let json = match name.as_str() { + "kennzahlen" => serde_json::to_string(&kennzahlen::compute(&p)), + "siteCheck" => serde_json::to_string(&site_rules::check_project(&p)), + "buildingFootprint" => serde_json::to_string(&site_rules::building_footprint(&p)), + "modelTop" => serde_json::to_string(&site_rules::model_top(&p)), + _ => return None, + }; + json.ok() + }) + .flatten() + .unwrap_or_default() } diff --git a/src/analysis/kennzahlen.ts b/src/analysis/kennzahlen.ts index d7c978ce..3d3540d6 100644 --- a/src/analysis/kennzahlen.ts +++ b/src/analysis/kennzahlen.ts @@ -51,7 +51,7 @@ const finite = (n: number): number => (Number.isFinite(n) ? n : 0); * Kern auf dem Projekt-Dokument (`kennzahlen.rs`, [K4] S2). */ export function computeKennzahlen(project: Project): Kennzahlen { - return documentFor(project).kennzahlen(); + return documentFor(project).query("kennzahlen"); } export type ProgramStatus = "ok" | "zu klein" | "zu gross" | "fehlt" | "zu wenige" | "zu viele"; diff --git a/src/analysis/siteRules.ts b/src/analysis/siteRules.ts index ea5c8c23..85f2c947 100644 --- a/src/analysis/siteRules.ts +++ b/src/analysis/siteRules.ts @@ -6,15 +6,12 @@ // • Baulinie: Halbebene auf der Seite des Parzellen-Schwerpunkts. // • Gebäude-Grundfläche: Wände aller Geschosse und freie Körper (ohne Abzugskörper). Vorsprünge // (Dachüberstand, Balkone) und ihre Sonderregeln zählen nicht. -// Gerechnet wird im Rust-Kern (`src-tauri/core/src/site_rules.rs`); hier wird aus dem Projekt -// gesammelt (Grundflächen-Teile, Modellhöhe) und die Datenform übersetzt. +// Gerechnet wird im Rust-Kern (`src-tauri/core/src/site_rules.rs`), die Prüfung des Modells auf dem +// Projekt-Dokument; die Flächen-Hilfen (`allowedArea`, `multiPolygonArea`) nehmen flache Daten. import type { Project, SiteRules, Vec2 } from "../model/types"; -import { getFloor, getWallType, wallTypeThickness } from "../model/types"; -import { wallVerticalExtent } from "../model/wall"; -import { wallCorners } from "../model/geometry"; -import { roofBaseElevation, roofGeometry } from "../geometry/roof"; import { core } from "../engine/coreWasm"; +import { documentFor } from "../core/document"; import { FlatReader, FlatWriter } from "../geometry/coreFlat"; /** Polygone mit Ringen: `[polygon][ring]`, Ring 0 aussen, weitere Löcher; Ringe offen. */ @@ -41,46 +38,14 @@ export function allowedArea(r: SiteRules): Area { return new FlatReader(core().site_allowed_area(encodeRules(r))).polygons(); } -/** Teile der Gebäude-Grundfläche (Wände aller Geschosse, freie Körper ohne Abzugskörper). */ -function footprintParts(project: Project): Area { - const parts: Area = []; - for (const w of project.walls) { - if (Math.hypot(w.end.x - w.start.x, w.end.y - w.start.y) < 1e-9) continue; - parts.push([wallCorners(w.start, w.end, wallTypeThickness(getWallType(project, w)))]); - } - for (const s of project.extrudedSolids ?? []) { - if (s.operation === "subtract" || s.points.length < 3) continue; - parts.push([s.points]); - } - return parts; -} - -/** Grundfläche des Gebäudes (Wände aller Geschosse, freie Körper ohne Abzugskörper). */ +/** Grundfläche des Gebäudes (Wände aller Geschosse, freie Körper ohne Abzugskörper). Rechnet der Kern. */ export function buildingFootprint(project: Project): Area { - const parts = footprintParts(project); - if (parts.length === 0) return []; - return new FlatReader(core().poly_union(new FlatWriter().polygons(parts).done())).polygons(); + return documentFor(project).query("buildingFootprint"); } /** Höchster Punkt des Modells über ±0.00 (Wände, freie Körper, Dächer); `null` ohne Bauteile. */ export function modelTop(project: Project): number | null { - let top = -Infinity; - for (const w of project.walls) top = Math.max(top, wallVerticalExtent(project, w).zTop); - for (const s of project.extrudedSolids ?? []) { - if (s.operation === "subtract") continue; - let base = 0; - try { - base = getFloor(project, s.levelId).baseElevation ?? 0; - } catch { - /* Geschoss fehlt → 0 */ - } - top = Math.max(top, base + (s.baseOffset ?? 0) + s.height); - } - for (const r of project.roofs ?? []) { - const eavesZ = roofBaseElevation(project, r); - top = Math.max(top, eavesZ + roofGeometry(r, eavesZ).ridgeHeight); - } - return Number.isFinite(top) ? top : null; + return documentFor(project).query("modelTop"); } export interface SiteCheck { @@ -96,22 +61,6 @@ export interface SiteCheck { /** Prüft das Modell gegen `project.siteRules`; `null` ohne (gültiges) Baurecht. Rechnung im Rust-Kern (`site_rules.rs`). */ export function checkSiteRules(project: Project): SiteCheck | null { - const r = project.siteRules; - if (!r) return null; - const maxTop = modelTop(project); - const out = core().site_check( - encodeRules(r), - new FlatWriter().polygons(footprintParts(project)).done(), - r.maxHeight ?? Number.NaN, - maxTop ?? Number.NaN, - ); - const rd = new FlatReader(out); - if (rd.num() !== 1) return null; - const parcelArea = rd.num(); - const allowedA = rd.num(); - const violationArea = rd.num(); - const heightExceeded = rd.num() === 1; - const allowed = rd.polygons(); - const violations = rd.polygons(); - return { parcelArea, allowed, allowedArea: allowedA, violations, violationArea, maxTop, heightExceeded }; + if (!project.siteRules) return null; + return documentFor(project).query("siteCheck"); } diff --git a/src/core/document.ts b/src/core/document.ts index 07a5b10f..d7e8825f 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -7,7 +7,6 @@ import type { Project } from "../model/types"; import { core } from "../engine/coreWasm"; import { diffToOps } from "./ops"; -import type { Kennzahlen } from "../analysis/kennzahlen"; export class ProjectDocument { private handle = 0; @@ -46,11 +45,14 @@ export class ProjectDocument { } } - /** Kennzahlen aus dem Kern (`kennzahlen.rs`). */ - kennzahlen(): Kennzahlen { - const text = this.handle ? core().doc_kennzahlen(this.handle) : ""; - if (!text) throw new Error("Kennzahlen: Projekt passt nicht zum Kern-Modell"); - return JSON.parse(text) as Kennzahlen; + /** + * Abfrage auf dem typisierten Projekt im Kern. Das Ergebnis ist JSON; ein Fehler (Projekt passt + * nicht zum Modell, unbekannte Abfrage) wirft. + */ + query(name: "kennzahlen" | "siteCheck" | "buildingFootprint" | "modelTop"): T { + const text = this.handle ? core().doc_query(this.handle, name) : ""; + if (!text) throw new Error(`Kern-Abfrage „${name}": Projekt passt nicht zum Kern-Modell`); + return JSON.parse(text) as T; } /** Das Dokument als JSON-Text (Test, Export). */ From f431053504b701a21939245fec08d83dc0086545 Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:51:33 +0100 Subject: [PATCH 18/31] [K4] S2: Schatten-Vereinigung rechnet auf dem Dokument (sun.rs, doc_query_args) --- src-tauri/core/src/site_rules.rs | 2 +- src-tauri/core/src/sun.rs | 62 ++++++++++++++++++++++++++++ src-tauri/core/src/web/document.rs | 13 +++++- src/analysis/sun.ts | 66 +++--------------------------- src/core/document.ts | 4 +- 5 files changed, 82 insertions(+), 65 deletions(-) diff --git a/src-tauri/core/src/site_rules.rs b/src-tauri/core/src/site_rules.rs index df51244d..7f722ed9 100644 --- a/src-tauri/core/src/site_rules.rs +++ b/src-tauri/core/src/site_rules.rs @@ -260,7 +260,7 @@ use serde::Serialize; /// Mehrfach-Fläche mit `Vec2`-Punkten (JSON-Form wie `Area` in TS). pub type AreaOut = Vec>>; -fn area_out(polys: &[Polygon]) -> AreaOut { +pub fn area_out(polys: &[Polygon]) -> AreaOut { polys.iter().map(|p| p.iter().map(|r| r.iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect()).collect()).collect() } diff --git a/src-tauri/core/src/sun.rs b/src-tauri/core/src/sun.rs index d4aa46f7..aee487e5 100644 --- a/src-tauri/core/src/sun.rs +++ b/src-tauri/core/src/sun.rs @@ -280,3 +280,65 @@ mod tests { assert_eq!(without_holes(&vec![square(0.0, 0.0, 3.0)]), vec![square(0.0, 0.0, 3.0)]); } } + +// ── Schatten aus dem Projekt-Dokument ([K4] S2) ───────────────────────────── + +use crate::jsmath::hypot2; +use crate::model::Project; + +/// Vereinigter Boden-Schatten aller Wände, freien Körper und Dächer des Projekts (leer bei Nacht). +/// Wände und Körper als Prismen, Dächer als Punktwolke (Traufe auf Traufhöhe, Traufe/First/Grate +/// auf Firsthöhe). +pub fn shadow_polygons_project(p: &Project, sun: SunPosition) -> Vec { + let mut prisms: Vec = Vec::new(); + for w in &p.walls { + let (z_bottom, z_top) = p.wall_vertical_extent(w); + let dx = w.end.x - w.start.x; + let dy = w.end.y - w.start.y; + let len = hypot2(dx, dy); + if len < 1e-9 { + continue; + } + let t = p.wall_thickness(w, 0.2) / 2.0; + let nx = (-dy / len) * t; + let ny = (dx / len) * t; + prisms.push(Prism { + footprint: vec![ + [w.start.x + nx, w.start.y + ny], + [w.end.x + nx, w.end.y + ny], + [w.end.x - nx, w.end.y - ny], + [w.start.x - nx, w.start.y - ny], + ], + z_bottom, + z_top, + }); + } + for s in p.extruded_solids.as_deref().unwrap_or(&[]) { + if s.operation.as_deref() == Some("subtract") { + continue; + } + let base = p.floor(&s.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0)); + let z0 = base + s.base_offset.unwrap_or(0.0); + prisms.push(Prism { footprint: s.points.iter().map(|v| [v.x, v.y]).collect(), z_bottom: z0, z_top: z0 + s.height }); + } + let mut clouds: Vec> = Vec::new(); + for r in p.roofs.as_deref().unwrap_or(&[]) { + let eaves_z = p.roof_base_elevation(r); + let geo = crate::roof::roof_geometry(&r.params(), eaves_z); + let top = eaves_z + geo.ridge_height; + let mut pts: Vec<[f64; 3]> = Vec::new(); + for e in &geo.eaves { + pts.push([e[0], e[1], eaves_z]); + pts.push([e[0], e[1], top]); + } + for l in &geo.ridges { + pts.push([l[0][0], l[0][1], top]); + pts.push([l[1][0], l[1][1], top]); + } + for l in &geo.hips { + pts.push([l[1][0], l[1][1], top]); + } + clouds.push(pts); + } + shadow_union(&prisms, &clouds, sun) +} diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index a559a936..4fc4a1cb 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -67,7 +67,14 @@ pub fn doc_json(h: u32) -> String { /// Baurecht), `buildingFootprint`, `modelTop` (`null` ohne Bauteile). #[wasm_bindgen] pub fn doc_query(h: u32, name: &str) -> String { - use crate::{kennzahlen, site_rules}; + doc_query_args(h, name, &[]) +} + +/// Wie [`doc_query`] mit Zahlenargumenten. `shadows`: `[azimut, höhe]` → vereinigter Boden-Schatten. +#[wasm_bindgen] +pub fn doc_query_args(h: u32, name: &str, args: &[f64]) -> String { + use crate::{kennzahlen, site_rules, sun}; + let args = args.to_vec(); let name = name.to_owned(); with_doc(h, move |d| { let p = d.project().ok()?; @@ -76,6 +83,10 @@ pub fn doc_query(h: u32, name: &str) -> String { "siteCheck" => serde_json::to_string(&site_rules::check_project(&p)), "buildingFootprint" => serde_json::to_string(&site_rules::building_footprint(&p)), "modelTop" => serde_json::to_string(&site_rules::model_top(&p)), + "shadows" if args.len() == 2 => { + let polys = sun::shadow_polygons_project(&p, sun::SunPosition { azimuth: args[0], elevation: args[1] }); + serde_json::to_string(&site_rules::area_out(&polys)) + } _ => return None, }; json.ok() diff --git a/src/analysis/sun.ts b/src/analysis/sun.ts index 68ec4a65..c62489bf 100644 --- a/src/analysis/sun.ts +++ b/src/analysis/sun.ts @@ -5,16 +5,13 @@ // • `shadowOfPrism`/`shadowPolygons`: Boden-Schatten (z = 0) von Wänden, freien Körpern und // Dächern als Vereinigung konvexer Hüllen (Prisma ∪ verschobenes Prisma). Modell: x = Ost, // y = Nord, Höhen über dem Geländenullpunkt (Meter). -// Gerechnet wird im Rust-Kern (`src-tauri/core/src/sun.rs`); hier wird nur aus dem Projekt -// gesammelt und die Datenform übersetzt. +// Gerechnet wird im Rust-Kern (`src-tauri/core/src/sun.rs`), die Schatten auf dem Projekt-Dokument. import { core } from "../engine/coreWasm"; import { FlatReader, FlatWriter, pointsOf } from "../geometry/coreFlat"; import type { Project, Vec2 } from "../model/types"; -import { wallVerticalExtent } from "../model/wall"; -import { roofBaseElevation, roofGeometry } from "../geometry/roof"; import { lv95ToWgs84 } from "../io/lv95"; -import { getFloor, getWallType, wallTypeThickness } from "../model/types"; +import { documentFor } from "../core/document"; export interface SunPosition { /** Grad von Nord im Uhrzeigersinn (Ost = 90, Süd = 180). */ @@ -47,64 +44,11 @@ export function shadowOfPrism(footprint: Vec2[], zBottom: number, zTop: number, export type ShadowPolygon = Vec2[][]; /** - * Vereinigter Schatten aller Wände, Körper und Dächer (leer bei Nacht). Hier werden nur die - * Körper gesammelt — Wände und freie Körper als Prismen, Dächer als Punktwolke (Traufe auf - * Traufhöhe, Traufe/First/Grate auf Firsthöhe); Schatten und Vereinigung rechnet der Rust-Kern. + * Vereinigter Schatten aller Wände, Körper und Dächer (leer bei Nacht). Rechnet der Kern auf dem + * Projekt-Dokument (`sun.rs`): Wände und freie Körper als Prismen, Dächer als Punktwolke. */ export function shadowPolygons(project: Project, sun: SunPosition): ShadowPolygon[] { - const prisms = new FlatWriter(); - const prismCount = prisms.slot(); - let nPrisms = 0; - for (const w of project.walls) { - const { zBottom, zTop } = wallVerticalExtent(project, w); - const dx = w.end.x - w.start.x; - const dy = w.end.y - w.start.y; - const len = Math.hypot(dx, dy); - if (len < 1e-9) continue; - const t = wallTypeThickness(getWallType(project, w)) / 2; - const nx = (-dy / len) * t; - const ny = (dx / len) * t; - prisms.num(zBottom, zTop).ring([ - { x: w.start.x + nx, y: w.start.y + ny }, - { x: w.end.x + nx, y: w.end.y + ny }, - { x: w.end.x - nx, y: w.end.y - ny }, - { x: w.start.x - nx, y: w.start.y - ny }, - ]); - nPrisms++; - } - for (const s of project.extrudedSolids ?? []) { - if (s.operation === "subtract") continue; - let base = 0; - try { - base = getFloor(project, s.levelId).baseElevation ?? 0; - } catch { - /* Geschoss fehlt → 0 */ - } - const z0 = base + (s.baseOffset ?? 0); - prisms.num(z0, z0 + s.height).ring(s.points); - nPrisms++; - } - const clouds = new FlatWriter(); - const cloudCount = clouds.slot(); - let nClouds = 0; - for (const r of project.roofs ?? []) { - const eavesZ = roofBaseElevation(project, r); - const geo = roofGeometry(r, eavesZ); - const top = eavesZ + geo.ridgeHeight; - const pts: number[] = []; - for (const p of geo.eaves) pts.push(p.x, p.y, eavesZ, p.x, p.y, top); - for (const [a, b] of geo.ridges) pts.push(a.x, a.y, top, b.x, b.y, top); - for (const [, b] of geo.hips) pts.push(b.x, b.y, top); - clouds.num(pts.length / 3, ...pts); - nClouds++; - } - const out = core().sun_shadow_union( - prisms.set(prismCount, nPrisms).done(), - clouds.set(cloudCount, nClouds).done(), - sun.azimuth, - sun.elevation, - ); - return new FlatReader(out).polygons(); + return documentFor(project).query("shadows", [sun.azimuth, sun.elevation]); } /** diff --git a/src/core/document.ts b/src/core/document.ts index d7e8825f..9df4ad03 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -49,8 +49,8 @@ export class ProjectDocument { * Abfrage auf dem typisierten Projekt im Kern. Das Ergebnis ist JSON; ein Fehler (Projekt passt * nicht zum Modell, unbekannte Abfrage) wirft. */ - query(name: "kennzahlen" | "siteCheck" | "buildingFootprint" | "modelTop"): T { - const text = this.handle ? core().doc_query(this.handle, name) : ""; + query(name: "kennzahlen" | "siteCheck" | "buildingFootprint" | "modelTop" | "shadows", args: number[] = []): T { + const text = this.handle ? core().doc_query_args(this.handle, name, Float64Array.from(args)) : ""; if (!text) throw new Error(`Kern-Abfrage „${name}": Projekt passt nicht zum Kern-Modell`); return JSON.parse(text) as T; } From 9db2122aae1192b1e34e8ef3277d3992894838d4 Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:55:54 +0100 Subject: [PATCH 19/31] [K4] S2 (Zwischenstand): model3d.rs mit Decken, Stuetzen, Waenden (Joins, Baender) aus dem Dokument; Parity-Test gegen TS --- scripts/gen-rust-model.py | 6 +- src-tauri/core/src/flat_write.rs | 64 +++ src-tauri/core/src/lib.rs | 3 + src-tauri/core/src/model/generated.rs | 4 +- src-tauri/core/src/model3d.rs | 549 ++++++++++++++++++++++++++ src-tauri/core/src/style.rs | 123 ++++++ src-tauri/core/src/web/document.rs | 3 + src/core/document.ts | 2 +- src/plan/model3d.parity.tmp.test.ts | 90 +++++ 9 files changed, 840 insertions(+), 4 deletions(-) create mode 100644 src-tauri/core/src/flat_write.rs create mode 100644 src-tauri/core/src/model3d.rs create mode 100644 src-tauri/core/src/style.rs create mode 100644 src/plan/model3d.parity.tmp.test.ts diff --git a/scripts/gen-rust-model.py b/scripts/gen-rust-model.py index 6c2f7649..13d283cd 100644 --- a/scripts/gen-rust-model.py +++ b/scripts/gen-rust-model.py @@ -14,6 +14,7 @@ MANUAL = {"Vec2", "Drawing2DGeom", "VerticalAnchor", "ColumnProfile", "LayoutAnn "LayoutAnnotationPatch", "ContextObject", "BuiltinPaletteBank", "SiaKey", "SiaAggregate", "BoolMark", "TextRange"} TAGGED = {"GridRule", "ModuleRule", "ConditionalThicknessRule", "ReferenceLineRule", "SequenceRule", "ImportedMesh", "ContourSet", "TerrainMesh", "ContextImage"} +RENAMES = {"OpeningKind2": "ElementKind"} ONLY = None # alle Interfaces aus SRC, die erreichbar sind def strip_comments(s): @@ -256,4 +257,7 @@ print("// GENERIERT von scripts/gen-rust-model.py aus den TS-Typen (Stand 28.10. "// Rust-Gegenstück zu src/model/types.ts ([K4] S2). Union-Typen mit Tag stehen in model/manual.rs.\n" "#![allow(clippy::large_enum_variant)]\n" "use super::manual::*;\nuse serde::{Deserialize, Serialize};\n") -print("\n".join(out_items)) +body = "\n".join(out_items) +for a, b in RENAMES.items(): + body = body.replace(a, b) +print(body) diff --git a/src-tauri/core/src/flat_write.rs b/src-tauri/core/src/flat_write.rs new file mode 100644 index 00000000..2719dfa0 --- /dev/null +++ b/src-tauri/core/src/flat_write.rs @@ -0,0 +1,64 @@ +//! Schreibhilfe für flache `f64`-Puffer (Gegenstück zu `FlatWriter` in `src/geometry/coreFlat.ts` +//! und zu `flat_read::Reader`): Rust-Sammler bauen damit dieselben Puffer, die die bestehenden +//! Kern-Funktionen (`ceilings3d`, `wall_bands` …) lesen. + +use crate::model::Vec2; + +#[derive(Default)] +pub struct FlatWriter { + buf: Vec, +} + +impl FlatWriter { + pub fn new() -> Self { + Self::default() + } + + pub fn num(&mut self, v: f64) -> &mut Self { + self.buf.push(v); + self + } + + pub fn nums(&mut self, v: &[f64]) -> &mut Self { + self.buf.extend_from_slice(v); + self + } + + /// Platz für eine erst später bekannte Zahl; mit [`set`](Self::set) nachtragen. + pub fn slot(&mut self) -> usize { + self.buf.push(0.0); + self.buf.len() - 1 + } + + pub fn set(&mut self, slot: usize, v: f64) -> &mut Self { + self.buf[slot] = v; + self + } + + /// Nur die Punkte `x0, y0, x1, y1, …`. + pub fn pts(&mut self, pts: &[Vec2]) -> &mut Self { + for p in pts { + self.buf.push(p.x); + self.buf.push(p.y); + } + self + } + + /// Anzahl, dann die Punkte. + pub fn ring(&mut self, pts: &[Vec2]) -> &mut Self { + self.buf.push(pts.len() as f64); + self.pts(pts) + } + + pub fn done(self) -> Vec { + self.buf + } + + pub fn len(&self) -> usize { + self.buf.len() + } + + pub fn is_empty(&self) -> bool { + self.buf.is_empty() + } +} diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 4d29f885..13bf1902 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -5,6 +5,7 @@ //! Datenübergabe: flache `f64`-Puffer (s. [`flat`]), kein JSON — schnell und ohne Serde-Kosten. pub mod flat; +pub mod flat_write; pub mod polygon_bool; pub mod roof; pub mod roof_skeleton; @@ -41,6 +42,8 @@ pub mod delaunay; pub mod document; pub mod mesh_section; pub mod model; +pub mod model3d; +pub mod style; pub mod plan_elevation; pub mod plan_misc; pub mod plan_section; diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs index 0495ba60..661166bd 100644 --- a/src-tauri/core/src/model/generated.rs +++ b/src-tauri/core/src/model/generated.rs @@ -940,7 +940,7 @@ pub struct Roof { } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub enum OpeningKind2 { +pub enum ElementKind { #[serde(rename = "window")] Window, #[serde(rename = "door")] @@ -1021,7 +1021,7 @@ pub struct Opening { pub category_code: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub locked: Option, - pub kind: OpeningKind2, + pub kind: ElementKind, pub position: f64, pub width: f64, pub height: f64, diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs new file mode 100644 index 00000000..b6193674 --- /dev/null +++ b/src-tauri/core/src/model3d.rs @@ -0,0 +1,549 @@ +//! 3D-Ableitung aus dem Projekt-Dokument ([K4] S2): Rust-Gegenstück zu `src/plan/toWalls3d.ts` und +//! `toWalls3d/*.ts`. Liefert das Modell-Bündel (`RModel3d`) für render3d, die Schnitt-Eingabe und +//! die Ansicht. Die Geometrie rechnen die bestehenden Kern-Module (`ceilings3d`, `columns3d`, +//! `wall_bands` …); hier werden sie aus dem typisierten `Project` gespeist und die Ergebnisse mit +//! Farbe, Schraffur und Ids versehen. + +use crate::flat_write::FlatWriter; +use crate::jsnum::{cos, sin}; +use crate::model::*; +use crate::style::{self, hex_to_rgb, resolve_component_hatch, resolve_cut_line_style, Rgb, SLAB_RGB}; +use serde::Serialize; + +pub type RVec2 = [f64; 2]; + +/// Schnitt-Verschneidungs-/Linienstil-Metadaten eines Bandes (`RCutMeta`). +#[derive(Debug, Clone, PartialEq, Serialize, Default)] +#[serde(rename_all = "camelCase")] +pub struct RCutMeta { + #[serde(skip_serializing_if = "Option::is_none")] + pub join_priority: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub component_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub line_color: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub line_weight: Option, +} + +/// Eine extrudierte Deckenplatte (`RSlab`). +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RSlab { + pub outline: Vec, + pub z_bottom: f64, + pub z_top: f64, + pub color: Rgb, + pub ceiling_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub hatch: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cut: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub monolith: Option, +} + +/// Ein rohes Dreiecks-Mesh (`RMesh`). +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RMesh { + pub positions: Vec, + pub indices: Vec, + pub kind: &'static str, + pub color: Rgb, + #[serde(skip_serializing_if = "Option::is_none")] + pub vertex_colors: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub material_index: Option, +} + +// ── Decken ────────────────────────────────────────────────────────────────── + +fn ceiling_layers<'a>(p: &'a Project, c: &Ceiling) -> Option<&'a [Layer]> { + if let Some(id) = c.ceiling_type_id.as_deref() { + if let Some(t) = p.ceiling_types.as_deref().and_then(|v| v.iter().find(|t| t.id == id)) { + return Some(&t.layers); + } + } + p.wall_types.iter().find(|t| t.id == c.wall_type_id).map(|t| t.layers.as_slice()) +} + +/// Deckenplatten (`emitSlabs`): eine Platte je Materiallage, oben→unten gestapelt. +pub fn emit_slabs(p: &Project) -> Vec { + let mut ceilings: Vec<&Ceiling> = Vec::new(); + let mut layers_of: Vec> = Vec::new(); + let mut w = FlatWriter::new(); + let count = w.slot(); + for c in p.ceilings.as_deref().unwrap_or(&[]) { + if c.outline.len() < 3 { + continue; + } + let (z_bottom, z_top) = p.ceiling_vertical_extent(c); + let layers = ceiling_layers(p, c); + w.ring(&c.outline); + let openings = c.openings.as_deref().unwrap_or(&[]); + w.num(openings.len() as f64); + for o in openings { + w.ring(o); + } + w.num(z_bottom).num(z_top).num(layers.map_or(0, |l| l.len()) as f64); + for l in layers.unwrap_or(&[]) { + w.num(l.thickness); + } + ceilings.push(c); + layers_of.push(layers); + } + if ceilings.is_empty() { + return vec![]; + } + w.set(count, ceilings.len() as f64); + let mut out = Vec::new(); + for d in crate::ceilings3d::ceilings(&w.done()) { + let c = ceilings[d.ceiling]; + let layers = layers_of[d.ceiling]; + let outline: Vec = d.ring.clone(); + for (layer_idx, z_bottom, z_top) in d.slabs { + let Some(layers) = layers.filter(|_| layer_idx >= 0) else { + out.push(RSlab { outline: outline.clone(), z_bottom, z_top, color: SLAB_RGB, ceiling_id: c.id.clone(), hatch: None, cut: None, monolith: None }); + continue; + }; + let l = &layers[layer_idx as usize]; + let (color, cut) = match p.component(&l.component_id) { + Some(comp) => { + let line = resolve_cut_line_style(p, l.joint_line_style_id.as_deref()); + ( + hex_to_rgb(&comp.color, style::WALL_RGB), + Some(RCutMeta { + join_priority: Some(comp.join_priority), + component_id: Some(comp.id.clone()), + line_color: line.map(|x| x.0), + line_weight: line.map(|x| x.1), + }), + ) + } + None => (SLAB_RGB, None), + }; + out.push(RSlab { + outline: outline.clone(), + z_bottom, + z_top, + color, + ceiling_id: c.id.clone(), + hatch: resolve_component_hatch(p, &l.component_id, None), + cut, + monolith: None, + }); + } + } + out +} + +// ── Stützen ───────────────────────────────────────────────────────────────── + +const COLUMN_ROUND_SEGMENTS: usize = 32; +const COLUMN_RGB: Rgb = [0.7, 0.7, 0.72]; + +/// Grundriss-Querschnitt einer Stütze (`columnFootprint`). +pub fn column_footprint(col: &Column) -> Vec { + let (cx, cy) = (col.position.x, col.position.y); + match &col.profile { + ColumnProfile::Round { radius } => (0..COLUMN_ROUND_SEGMENTS) + .map(|i| { + let t = (i as f64 / COLUMN_ROUND_SEGMENTS as f64) * std::f64::consts::PI * 2.0; + Vec2 { x: cx + radius * cos(t), y: cy + radius * sin(t) } + }) + .collect(), + ColumnProfile::Rect { width, depth } => { + let (hw, hd) = (width / 2.0, depth / 2.0); + let rot = col.rotation; + let (c, s) = (cos(rot), sin(rot)); + [(-hw, -hd), (hw, -hd), (hw, hd), (-hw, hd)] + .iter() + .map(|&(x, y)| Vec2 { x: cx + x * c - y * s, y: cy + x * s + y * c }) + .collect() + } + } +} + +/// Stützen als Prisma-Meshes (`emitColumns`). +pub fn emit_columns(p: &Project) -> Vec { + let mut cols: Vec<&Column> = Vec::new(); + let mut w = FlatWriter::new(); + let count = w.slot(); + for col in p.columns.as_deref().unwrap_or(&[]) { + if col.height <= 0.0 { + continue; + } + let (z_bottom, z_top) = p.column_vertical_extent(col); + let foot = column_footprint(col); + w.num(z_bottom).num(z_top).ring(&foot); + cols.push(col); + } + if cols.is_empty() { + return vec![]; + } + w.set(count, cols.len() as f64); + crate::columns3d::columns(&w.done()) + .into_iter() + .map(|m| { + let col = cols[m.src]; + let color = col + .component_id + .as_deref() + .and_then(|id| p.component(id)) + .map_or(COLUMN_RGB, |c| hex_to_rgb(&c.color, COLUMN_RGB)); + RMesh { positions: m.positions, indices: m.indices, kind: "extrusion", color, vertex_colors: None, material_index: None } + }) + .collect() +} + +// ── Wände ─────────────────────────────────────────────────────────────────── + +use crate::joins::{self, JoinLayer, JoinWall, Reference, WallCuts}; +use crate::jsmath::hypot2; +use crate::jsnum::atan2; +use crate::opening_geom::{self, WallRef}; +use crate::style::{dominant_layer, dominant_layer_color, dominant_layer_hatch, WALL_RGB}; +use crate::wall_bands::{self, BandIn, CeilingIn, FloorContext, OpeningIn, RoofIn, Termination}; +use kernel2d::Vec2 as KVec; +use std::collections::HashMap; + +/// Absenkung der Oberkante (`topDrop`), Löcher und Metadaten je Wandkörper (`RWall`). +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RHole { + pub from: f64, + pub to: f64, + pub z_bottom: f64, + pub z_top: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RWall { + pub start: RVec2, + pub end: RVec2, + pub thickness: f64, + pub height: f64, + pub base_elevation: f64, + #[serde(skip_serializing_if = "Option::is_none")] + pub top_drop: Option<[f64; 2]>, + pub color: Rgb, + pub layers: Vec<()>, + pub wall_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub holes: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub hatch: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub material_index: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cut: Option, +} + +/// Textur-Karten-URLs der Bauteile in der Reihenfolge des ersten Auftretens: Wandtypen, dann +/// Decken, dann Dächer (`wallMaterialColorMaps`). +pub fn wall_material_color_maps(p: &Project) -> Vec { + let mut seen = std::collections::HashSet::new(); + let mut list = Vec::new(); + let mut consider = |id: &str| { + if let Some(url) = p.component(id).and_then(|c| c.material.as_ref()).and_then(|m| m.color.as_deref()).filter(|u| !u.is_empty()) { + if seen.insert(url.to_owned()) { + list.push(url.to_owned()); + } + } + }; + for w in &p.walls { + if let Some(t) = p.wall_type(w) { + for l in &t.layers { + consider(&l.component_id); + } + } + } + for c in p.ceilings.as_deref().unwrap_or(&[]) { + if let Some(layers) = ceiling_layers(p, c) { + for l in layers { + consider(&l.component_id); + } + } + } + for r in p.roofs.as_deref().unwrap_or(&[]) { + for l in p.roof_layers(r) { + if !l.component_id.is_empty() { + consider(&l.component_id); + } + } + } + list +} + +/// Textur-Ebene (1-basiert) der Farbkarte eines Bauteils (`resolveComponentMaterialLayer`). +fn material_layer(p: &Project, maps: &[String], component_id: &str) -> Option { + let url = p.component(component_id)?.material.as_ref()?.color.as_deref().filter(|u| !u.is_empty())?; + maps.iter().position(|m| m == url).map(|i| (i + 1) as f64) +} + +struct WallBand { + thickness: f64, + color: Rgb, + hatch: Option, + material_index: Option, + priority: Option, + component_id: Option, + cut_line_color: Option, + cut_line_weight: Option, +} + +const SECTION_WALL_AXIS_ANGLE_DEG: f64 = 90.0; + +fn plain_band(thickness: f64) -> WallBand { + WallBand { thickness, color: WALL_RGB, hatch: None, material_index: None, priority: None, component_id: None, cut_line_color: None, cut_line_weight: None } +} + +/// Schichtstapel EINER Wand als Bänder (`resolveWallBands`); `stacked` = Lagen einzeln gestapelt. +fn resolve_wall_bands(p: &Project, maps: &[String], wall: &Wall, layered: bool) -> (Vec, bool) { + let fallback = || (vec![plain_band(0.2)], false); + let Some(wt) = p.wall_type(wall) else { return fallback() }; + if wt.layers.is_empty() { + return (vec![plain_band(Project::type_thickness(&wt.layers))], false); + } + if !layered { + let total = Project::type_thickness(&wt.layers); + let dominant = dominant_layer(&wt.layers).expect("nicht leer"); + return ( + vec![WallBand { + thickness: total, + color: dominant_layer_color(p, &wt.layers, WALL_RGB), + hatch: dominant_layer_hatch(p, &wt.layers, Some(SECTION_WALL_AXIS_ANGLE_DEG)), + material_index: material_layer(p, maps, &dominant.component_id), + ..plain_band(0.0) + }], + false, + ); + } + let mut bands = Vec::with_capacity(wt.layers.len()); + for l in &wt.layers { + let Some(comp) = p.component(&l.component_id) else { return fallback() }; + let line = resolve_cut_line_style(p, l.joint_line_style_id.as_deref()); + bands.push(WallBand { + thickness: l.thickness, + color: hex_to_rgb(&comp.color, WALL_RGB), + hatch: resolve_component_hatch(p, &l.component_id, Some(SECTION_WALL_AXIS_ANGLE_DEG)), + material_index: material_layer(p, maps, &l.component_id), + priority: Some(comp.join_priority), + component_id: Some(comp.id.clone()), + cut_line_color: line.map(|x| x.0), + cut_line_weight: line.map(|x| x.1), + }); + } + (bands, true) +} + +fn band_cut_meta(b: &WallBand) -> Option { + if b.priority.is_none() && b.component_id.is_none() && b.cut_line_color.is_none() && b.cut_line_weight.is_none() { + return None; + } + Some(RCutMeta { join_priority: b.priority, component_id: b.component_id.clone(), line_color: b.cut_line_color, line_weight: b.cut_line_weight }) +} + +fn with_top_angle(mut h: style::RHatch, dx: f64, dy: f64) -> style::RHatch { + let wall_angle = (atan2(dy, dx) * 180.0) / std::f64::consts::PI; + let svg_angle = if h.relative_to_wall { h.base_angle - wall_angle } else { h.base_angle }; + let quarter = if h.pattern == 2.0 || h.pattern == 3.0 { 90.0 } else { 0.0 }; + h.top_angle = Some(-svg_angle + quarter); + h +} + +fn kv(v: Vec2) -> KVec { + KVec::new(v.x, v.y) +} + +fn wall_reference(w: &Wall) -> Reference { + match (w.reference_offset, w.reference_line) { + (Some(v), _) => Reference::Offset(v), + (None, Some(WallReferenceLine::Left)) => Reference::Left, + (None, Some(WallReferenceLine::Right)) => Reference::Right, + _ => Reference::Center, + } +} + +fn wall_ref(p: &Project, w: &Wall) -> WallRef { + let total = p.wall_thickness(w, 0.2); + WallRef { start: opening_geom::v(w.start.x, w.start.y), end: opening_geom::v(w.end.x, w.end.y), total, ref_off: joins::reference_offset(wall_reference(w), total) } +} + +/// Öffnungs-Intervall und vertikale Lage aller Öffnungen einer Wand. +fn wall_openings(p: &Project, w: &Wall, with_recess: bool) -> Vec { + let wr = wall_ref(p, w); + let (zb, zt) = p.wall_vertical_extent(w); + let mut out = Vec::new(); + for o in p.openings_of_wall(&w.id) { + let Some((from, to)) = opening_geom::opening_interval(&wr, o.position, o.width) else { continue }; + let o_bottom = zb + o.sill_height.max(0.0); + let o_top = zt.min(o_bottom + o.height); + let recess = with_recess && o.kind == ElementKind::Window && p.window_type(o).and_then(|t| t.inner_layer_recess) == Some(true); + out.push(OpeningIn { from, to, z_bottom: o_bottom, z_top: o_top, recess_inner_layer: recess }); + } + out +} + +/// Verschneidung je Geschoss (`computeJoinsByFloor`); Fehler = unbekannter Wandtyp/Bauteil. +fn compute_joins_by_floor(p: &Project) -> Result, String> { + let mut groups: Vec<(String, Vec<&Wall>)> = Vec::new(); + for w in &p.walls { + match groups.iter_mut().find(|g| g.0 == w.floor_id) { + Some(g) => g.1.push(w), + None => groups.push((w.floor_id.clone(), vec![w])), + } + } + let mut merged = HashMap::new(); + for (_, walls) in &groups { + let mut comp_index: HashMap<&str, u32> = HashMap::new(); + let mut jw: Vec = Vec::with_capacity(walls.len()); + let mut finite = true; + for w in walls { + let layers = p.wall_type(w).map(|wt| { + wt.layers + .iter() + .map(|l| { + let comp = p.component(&l.component_id); + let idx = comp.map(|c| { + let n = comp_index.len() as u32; + *comp_index.entry(c.id.as_str()).or_insert(n) + }); + JoinLayer { thickness: l.thickness, component: idx, priority: comp.map_or(f64::NAN, |c| c.join_priority) } + }) + .collect::>() + }); + let reference = wall_reference(w); + finite &= [w.start.x, w.start.y, w.end.x, w.end.y].iter().all(|v| v.is_finite()) + && !matches!(reference, Reference::Offset(v) if !v.is_finite()) + && layers.as_ref().is_none_or(|l| l.iter().all(|x| x.thickness.is_finite())); + jw.push(JoinWall { start: kv(w.start), end: kv(w.end), reference, layers }); + } + if !finite { + for w in walls { + merged.insert(w.id.clone(), WallCuts::default()); + } + continue; + } + match joins::compute_joins(&jw) { + Ok(cuts) => { + for (w, c) in walls.iter().zip(cuts) { + merged.insert(w.id.clone(), c); + } + } + Err(joins::JoinError::UnknownWallType(i)) => return Err(format!("Unbekannter Wandtyp: {}", walls[i].wall_type_id)), + Err(joins::JoinError::UnknownComponent(i)) => { + let bad = walls[i]; + let missing = p.wall_type(bad).and_then(|t| t.layers.iter().find(|l| p.component(&l.component_id).is_none())).map(|l| l.component_id.clone()).unwrap_or_default(); + return Err(format!("Unbekanntes Bauteil-Material: {missing}")); + } + } + } + Ok(merged) +} + +fn floor_context(p: &Project, floor_id: &str) -> FloorContext { + let ceilings: Vec = p + .ceilings + .as_deref() + .unwrap_or(&[]) + .iter() + .filter(|c| c.floor_id == floor_id && c.outline.len() >= 3) + .map(|c| { + let (z_bottom, z_top) = p.ceiling_vertical_extent(c); + CeilingIn { + z_bottom, + z_top, + outline: c.outline.iter().map(|v| kv(*v)).collect(), + layers: ceiling_layers(p, c).map(|ls| ls.iter().map(|l| (l.thickness, p.component(&l.component_id).map(|k| k.join_priority))).collect()), + } + }) + .collect(); + let roofs: Vec = p + .roofs + .as_deref() + .unwrap_or(&[]) + .iter() + .filter(|r| r.floor_id == floor_id) + .map(|r| { + let eaves_z = p.roof_base_elevation(r); + let geo = crate::roof::roof_geometry(&r.params(), eaves_z); + let total: f64 = p.roof_layers(r).iter().fold(0.0, |s, l| s + l.thickness.max(0.0)); + RoofIn { eaves_z, total_thickness: total, eaves: geo.eaves, planes: geo.planes } + }) + .collect(); + FloorContext::new(ceilings, roofs) +} + +/// Wandkörper (`projectToWalls3d`): `layered` = ein Körper je Schicht mit Löchern (3D-Viewer), +/// sonst Pfeiler/Brüstung/Sturz-Segmente (Schnitt-Eingabe). +pub fn emit_walls(p: &Project, layered: bool) -> Result, String> { + let joins = if layered { Some(compute_joins_by_floor(p)?) } else { None }; + let maps = wall_material_color_maps(p); + let mut contexts: HashMap<&str, FloorContext> = HashMap::new(); + let empty = FloorContext::default(); + let mut out = Vec::new(); + for wall in &p.walls { + let (bands, stacked) = resolve_wall_bands(p, &maps, wall, layered); + let (z_bottom, z_top) = p.wall_vertical_extent(wall); + let ctx = if layered { + contexts.entry(wall.floor_id.as_str()).or_insert_with(|| floor_context(p, &wall.floor_id)) + } else { + &empty + }; + let win = wall_bands::WallIn { + start: kv(wall.start), + end: kv(wall.end), + z_bottom, + z_top, + layered, + stacked, + reference: wall_reference(wall), + thickness_safe: p.wall_thickness(wall, 0.2), + termination: match wall.slice_termination { + Some(SliceTermination::Below) => Termination::Below, + Some(SliceTermination::Above) => Termination::Above, + _ => Termination::Both, + }, + bands: bands.iter().map(|b| BandIn { thickness: b.thickness, priority: b.priority }).collect(), + openings: wall_openings(p, wall, true), + cuts: if layered { joins.as_ref().and_then(|j| j.get(&wall.id)).cloned().unwrap_or_default() } else { WallCuts::default() }, + }; + let (dx, dy) = (wall.end.x - wall.start.x, wall.end.y - wall.start.y); + for piece in wall_bands::wall_bands(&win, ctx) { + let Some(b) = bands.get(piece.band) else { continue }; + out.push(RWall { + start: [piece.start.x, piece.start.y], + end: [piece.end.x, piece.end.y], + thickness: b.thickness, + height: piece.z_top - piece.z_bottom, + base_elevation: piece.z_bottom, + top_drop: piece.top_drop, + color: b.color, + layers: vec![], + wall_id: wall.id.clone(), + holes: (!piece.holes.is_empty()).then(|| piece.holes.iter().map(|h| RHole { from: h[0], to: h[1], z_bottom: h[2], z_top: h[3] }).collect()), + hatch: b.hatch.clone().map(|h| with_top_angle(h, dx, dy)), + material_index: b.material_index, + cut: band_cut_meta(b), + }); + } + } + let _ = hypot2; + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn beispielprojekt_hat_decken_und_gueltige_farben() { + let p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap(); + let slabs = emit_slabs(&p); + assert!(!slabs.is_empty()); + assert!(slabs.iter().all(|s| s.z_top > s.z_bottom && s.outline.len() >= 3)); + } +} diff --git a/src-tauri/core/src/style.rs b/src-tauri/core/src/style.rs new file mode 100644 index 00000000..2a60c14c --- /dev/null +++ b/src-tauri/core/src/style.rs @@ -0,0 +1,123 @@ +//! Darstellungs-Auflösung aus dem Modell ([K4] S2): Farben, Schraffur und Schnitt-Linienstil, wie sie +//! `src/plan/generatePlan/shared.ts` und `src/plan/toWalls3d/shared.ts` aus dem `Project` ableiten. + +use crate::model::{HatchPattern, Project}; +use serde::Serialize; + +pub type Rgb = [f64; 3]; + +/// Warmer, neutraler Wand-Grundton (wie render3d). +pub const WALL_RGB: Rgb = [0.82, 0.8, 0.76]; +/// Etwas hellerer, kühlerer Ton für Deckenplatten. +pub const SLAB_RGB: Rgb = [0.86, 0.86, 0.88]; +/// Fallback-Farbe für Linien ohne Farbe ("#888888"). +pub const DRAWING_LINE_FALLBACK_RGB: Rgb = [0x88 as f64 / 255.0, 0x88 as f64 / 255.0, 0x88 as f64 / 255.0]; + +/// "#rrggbb" → RGB 0..1; ungültiges Format → `fallback`. +pub fn hex_to_rgb(hex: &str, fallback: Rgb) -> Rgb { + let h = hex.strip_prefix('#').unwrap_or(hex); + if h.len() != 6 || !h.bytes().all(|b| b.is_ascii_hexdigit()) { + return fallback; + } + let v = u32::from_str_radix(h, 16).unwrap_or(0); + [((v >> 16) & 0xff) as f64 / 255.0, ((v >> 8) & 0xff) as f64 / 255.0, (v & 0xff) as f64 / 255.0] +} + +/// Schnitt-Schraffur eines Bauteil-Bandes für den 3D-Live-Schnitt (`RHatch` in TS). +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RHatch { + pub pattern: f64, + pub angle: f64, + pub scale: f64, + pub line_weight: f64, + pub base_angle: f64, + pub relative_to_wall: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub top_angle: Option, +} + +fn pattern_id(p: HatchPattern) -> f64 { + match p { + HatchPattern::Solid => 1.0, + HatchPattern::Diagonal => 2.0, + HatchPattern::Crosshatch => 3.0, + HatchPattern::Insulation => 4.0, + _ => 0.0, + } +} + +/// Aufgelöste Schraffur (Kern von `resolveHatch`): Muster, Massstab, Endwinkel, Musterlinien-Stärke. +/// `None`, wenn Schraffur oder ihr Linienstil fehlen (TS wirft dort). +pub struct HatchCore { + pub pattern: HatchPattern, + pub scale: f64, + pub angle: f64, + pub line_weight: f64, +} + +pub fn resolve_hatch_core(p: &Project, hatch_id: &str, wall_angle_deg: Option) -> Option { + let h = p.hatch(hatch_id)?; + let ls = match h.line_style_id.as_deref().filter(|s| !s.is_empty()) { + Some(id) => Some(p.line_style(id)?), + None => None, + }; + let base = h.angle; + let angle = match wall_angle_deg { + Some(w) if h.relative_to_wall == Some(true) => base - w, + _ => base, + }; + Some(HatchCore { pattern: h.pattern, scale: h.scale * 1.0, angle, line_weight: ls.map_or(0.13, |l| l.weight) }) +} + +/// Schnitt-Schraffur eines Bauteils (`resolveComponentHatch`); `axis_angle_deg` 90 für Wand-Bänder, +/// `None` für Decken. +pub fn resolve_component_hatch(p: &Project, component_id: &str, axis_angle_deg: Option) -> Option { + let comp = p.component(component_id)?; + if comp.hatch_id.is_empty() { + return None; + } + let hr = resolve_hatch_core(p, &comp.hatch_id, axis_angle_deg)?; + let abs = resolve_hatch_core(p, &comp.hatch_id, None)?; + let relative = resolve_hatch_core(p, &comp.hatch_id, Some(90.0))?.angle != abs.angle; + Some(RHatch { + pattern: pattern_id(hr.pattern), + angle: hr.angle, + scale: hr.scale, + line_weight: hr.line_weight, + base_angle: abs.angle, + relative_to_wall: relative, + top_angle: None, + }) +} + +/// Schnitt-Schraffur der dicksten Schicht (`dominantLayerHatch`). +pub fn dominant_layer_hatch(p: &Project, layers: &[crate::model::Layer], axis_angle_deg: Option) -> Option { + let dominant = dominant_layer(layers)?; + resolve_component_hatch(p, &dominant.component_id, axis_angle_deg) +} + +/// Dickste Schicht (bei Gleichstand die erste). +pub fn dominant_layer(layers: &[crate::model::Layer]) -> Option<&crate::model::Layer> { + let mut best = layers.first()?; + for l in layers { + if l.thickness > best.thickness { + best = l; + } + } + Some(best) +} + +/// Repräsentative Farbe der dicksten Schicht (`dominantLayerColor`). +pub fn dominant_layer_color(p: &Project, layers: &[crate::model::Layer], fallback: Rgb) -> Rgb { + match dominant_layer(layers).and_then(|d| p.component(&d.component_id)) { + Some(c) => hex_to_rgb(&c.color, fallback), + None => fallback, + } +} + +/// Stil der Schnitt-Umrisslinie einer Schicht (`resolveCutLineStyle`). +pub fn resolve_cut_line_style(p: &Project, joint_line_style_id: Option<&str>) -> Option<(Rgb, f64)> { + let ls = p.line_styles.iter().find(|l| Some(l.id.as_str()) == joint_line_style_id.filter(|s| !s.is_empty()))?; + Some((hex_to_rgb(&ls.color, DRAWING_LINE_FALLBACK_RGB), ls.weight)) +} diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index 4fc4a1cb..6b6ac772 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -83,6 +83,9 @@ pub fn doc_query_args(h: u32, name: &str, args: &[f64]) -> String { "siteCheck" => serde_json::to_string(&site_rules::check_project(&p)), "buildingFootprint" => serde_json::to_string(&site_rules::building_footprint(&p)), "modelTop" => serde_json::to_string(&site_rules::model_top(&p)), + "walls" if args.len() == 1 => crate::model3d::emit_walls(&p, args[0] != 0.0).map_err(|_| ()).and_then(|w| serde_json::to_string(&w).map_err(|_| ())).map_err(|_| serde_json::Error::io(std::io::Error::other("walls"))), + "slabs" => serde_json::to_string(&crate::model3d::emit_slabs(&p)), + "columnMeshes" => serde_json::to_string(&crate::model3d::emit_columns(&p)), "shadows" if args.len() == 2 => { let polys = sun::shadow_polygons_project(&p, sun::SunPosition { azimuth: args[0], elevation: args[1] }); serde_json::to_string(&site_rules::area_out(&polys)) diff --git a/src/core/document.ts b/src/core/document.ts index 9df4ad03..a94ebb31 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -49,7 +49,7 @@ export class ProjectDocument { * Abfrage auf dem typisierten Projekt im Kern. Das Ergebnis ist JSON; ein Fehler (Projekt passt * nicht zum Modell, unbekannte Abfrage) wirft. */ - query(name: "kennzahlen" | "siteCheck" | "buildingFootprint" | "modelTop" | "shadows", args: number[] = []): T { + query(name: "kennzahlen" | "siteCheck" | "buildingFootprint" | "modelTop" | "shadows" | "slabs" | "columnMeshes" | "walls", args: number[] = []): T { const text = this.handle ? core().doc_query_args(this.handle, name, Float64Array.from(args)) : ""; if (!text) throw new Error(`Kern-Abfrage „${name}": Projekt passt nicht zum Kern-Modell`); return JSON.parse(text) as T; diff --git a/src/plan/model3d.parity.tmp.test.ts b/src/plan/model3d.parity.tmp.test.ts new file mode 100644 index 00000000..902dbedd --- /dev/null +++ b/src/plan/model3d.parity.tmp.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it } from "vitest"; +import { sampleProject } from "../model/sampleProject"; +import { documentFor } from "../core/document"; +import { emitSlabs } from "./toWalls3d/ceilings"; +import { emitColumns } from "./toWalls3d/columns"; +import { projectToWalls3d } from "./toWalls3d"; + +const plain = (v: T): T => JSON.parse(JSON.stringify(v)); +let seed = 21; +const rnd = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296); +const pick = (a: T[]) => a[Math.floor(rnd() * a.length)]; + +describe("model3d walls", () => { + it("sample project both paths", () => { + const doc = documentFor(sampleProject); + for (const layered of [true, false]) { + expect(doc.query("walls", [layered ? 1 : 0])).toEqual(plain(projectToWalls3d(sampleProject, layered))); + } + }); + it("random walls/openings/ceilings/roofs", () => { + let n = 0; + for (let t = 0; t < 150; t++) { + const lvl = sampleProject.drawingLevels.filter((l) => l.kind === "floor"); + const pts = [[0, 0], [6, 0], [6, 4], [0, 4], [3, 0], [3, 4], [8, 2], [-2, 2]]; + const walls = Array.from({ length: 2 + Math.floor(rnd() * 6) }, (_, k) => { + const a = pick(pts), b = pick(pts); + return { ...sampleProject.walls[0], id: "w" + k, floorId: pick(lvl).id, start: { x: a[0], y: a[1] }, end: { x: b[0], y: b[1] + (a[1] === b[1] && a[0] === b[0] ? 1 : 0) }, + wallTypeId: pick(sampleProject.wallTypes).id, + ...(rnd() < 0.3 ? { referenceLine: pick(["left", "right", "center"]) } : {}), + ...(rnd() < 0.15 ? { referenceOffset: rnd() * 0.3 - 0.15 } : {}), + ...(rnd() < 0.2 ? { sliceTermination: pick(["below", "above", "both"]) } : {}), + height: pick([2.5, 2.6, 3]) }; + }); + const openings = walls.flatMap((w, k) => rnd() < 0.6 ? [{ id: "o" + k, type: "opening", hostWallId: w.id, categoryCode: "21", kind: pick(["window", "door"]), + ...(rnd() < 0.5 ? { typeId: pick(["window-standard", "window-double", "door-standard", "door-entry"]) } : {}), + position: rnd() * 2, width: 0.6 + rnd(), height: 1.2 + rnd(), sillHeight: pick([0, 0.9]) }] : []); + const ceilings = Array.from({ length: Math.floor(rnd() * 3) }, (_, k) => ({ id: "c" + k, type: "ceiling", floorId: pick(lvl).id, categoryCode: "20", + outline: [{ x: -1, y: -1 }, { x: 7, y: -1 }, { x: 7, y: 5 }, { x: -1, y: 5 }], wallTypeId: sampleProject.wallTypes[0].id, + ...(sampleProject.ceilingTypes?.length && rnd() < 0.5 ? { ceilingTypeId: pick(sampleProject.ceilingTypes).id } : {}) })); + const roofs = rnd() < 0.5 ? [{ id: "R1", type: "roof", floorId: pick(lvl).id, categoryCode: "35", outline: [{ x: -1, y: -1 }, { x: 7, y: -1 }, { x: 7, y: 5 }, { x: -1, y: 5 }], + shape: pick(["sattel", "walm", "pult", "flach"]), pitchDeg: 30, overhang: 0.3, ridgeAxis: pick(["x", "y"]), thickness: 0.2 }] : []; + const project: any = { ...sampleProject, walls, openings, ceilings, roofs }; + const doc = documentFor(project); + for (const layered of [true, false]) { + let want: unknown; + try { want = plain(projectToWalls3d(project, layered)); } catch { want = undefined; } + if (want === undefined) { expect(() => doc.query("walls", [layered ? 1 : 0])).toThrow(); continue; } + expect(doc.query("walls", [layered ? 1 : 0])).toEqual(want); + n += (want as unknown[]).length; + } + } + expect(n).toBeGreaterThan(500); + }); +}); + +describe("model3d slabs/columns", () => { + it("random", () => { + let ns = 0, nc = 0; + for (let t = 0; t < 200; t++) { + const lvl = sampleProject.drawingLevels.filter((l) => l.kind === "floor"); + const ceilings = Array.from({ length: Math.floor(rnd() * 4) }, (_, k) => ({ + id: "c" + k, type: "ceiling", floorId: pick(lvl).id, categoryCode: "20", + outline: [{ x: 0, y: 0 }, { x: 5 + k, y: 0 }, { x: 5 + k, y: 4 }, { x: 0, y: 4 }], + ...(rnd() < 0.5 ? { openings: [[{ x: 1, y: 1 }, { x: 2, y: 1 }, { x: 2, y: 2 }, { x: 1, y: 2 }]] } : {}), + wallTypeId: sampleProject.wallTypes[0].id, + ...(rnd() < 0.5 && sampleProject.ceilingTypes?.length ? { ceilingTypeId: pick(sampleProject.ceilingTypes).id } : {}), + ...(rnd() < 0.3 ? { thickness: 0.25 } : {}), + ...(rnd() < 0.2 ? { top: { mode: "custom", z: 3.1 } } : {}), + })); + const columns = Array.from({ length: Math.floor(rnd() * 4) }, (_, k) => ({ + id: "k" + k, type: "column", floorId: pick(lvl).id, categoryCode: "20", + position: { x: k, y: 1 }, rotation: rnd() * 3, height: pick([0, 2.5, 3]), + profile: pick([{ kind: "rect", width: 0.3, depth: 0.4 }, { kind: "round", radius: 0.2 }]), + ...(rnd() < 0.5 ? { componentId: pick(sampleProject.components).id } : {}), + ...(rnd() < 0.3 ? { componentId: "nope" } : {}), + })); + const project: any = { ...sampleProject, ceilings, columns }; + const doc = documentFor(project); + const a = doc.query("slabs"); + const b = plain(emitSlabs(project)); + expect(a).toEqual(b); + const c = doc.query("columnMeshes"); + const d = plain(emitColumns(project)); + expect(c).toEqual(d); + ns += b.length; nc += d.length; + } + expect(ns).toBeGreaterThan(100); + expect(nc).toBeGreaterThan(100); + }); +}); From 6ebe85fdf6ef6deed32e3f42a118adf40202f9e3 Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:57:14 +0100 Subject: [PATCH 20/31] [K4] S2 (Zwischenstand): Oeffnungs-Einbauteile (3D) aus dem Dokument --- src-tauri/core/src/model3d.rs | 166 ++++++++++++++++++++++++++++ src-tauri/core/src/web/document.rs | 1 + src/core/document.ts | 2 +- src/plan/model3d.parity.tmp.test.ts | 17 ++- 4 files changed, 184 insertions(+), 2 deletions(-) diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index b6193674..6a427725 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -535,6 +535,172 @@ pub fn emit_walls(p: &Project, layered: bool) -> Result, String> { Ok(out) } +// ── Öffnungs-Einbauteile (Glas, Rahmen, Sprossen, Bank, Kasten) ───────────── + +/// Farbe je Bauteil-Klasse (Index = `Part` in `openings3d.rs`). +const PART_RGB: [Rgb; 6] = [ + [0.62, 0.76, 0.85], + [0.85, 0.85, 0.83], + [0.88, 0.88, 0.9], + [0.8, 0.8, 0.78], + [0.25, 0.27, 0.3], + [0.93, 0.9, 0.85], +]; + +/// Dreiecke eines Öffnungs-Quaders (Ecken-Bits: bit0 = Achse, bit1 = Höhe, bit2 = quer). +const OPENING_BOX_TRIS: [u32; 36] = [0, 1, 3, 0, 3, 2, 4, 5, 7, 4, 7, 6, 0, 1, 5, 0, 5, 4, 2, 3, 7, 2, 7, 6, 0, 2, 6, 0, 6, 4, 1, 3, 7, 1, 7, 5]; + +fn opt(v: Option) -> f64 { + v.unwrap_or(f64::NAN) +} + +fn flag(b: bool) -> f64 { + if b { + 1.0 + } else { + 0.0 + } +} + +fn join_code(j: Option) -> f64 { + match j { + Some(FrameCornerJoin::Horizontal) => 1.0, + Some(FrameCornerJoin::Gehrung) => 2.0, + _ => 0.0, + } +} + +fn opening_kind_code(k: Option) -> f64 { + match k { + None => 0.0, + Some(OpeningKind::Dreh) => 1.0, + Some(OpeningKind::Kipp) => 2.0, + Some(OpeningKind::Drehkipp) => 3.0, + Some(OpeningKind::Fest) => 4.0, + Some(OpeningKind::Schiebe) => 5.0, + } +} + +fn write_common(w: &mut FlatWriter, frame_depth: Option, inset: Option, inner: bool, join: Option, frame_width: Option, transom: Option) { + w.nums(&[opt(frame_depth), opt(inset), flag(inner), join_code(join), opt(frame_width), opt(transom)]); +} + +fn glazing_panes_of(wt: &WindowType) -> f64 { + match wt.glazing_panes { + Some(p) if p != 0.0 => p, + _ => match wt.glazing { + WindowTypeGlazing::Dreifach => 3.0, + WindowTypeGlazing::Zweifach => 2.0, + _ => 1.0, + }, + } +} + +fn write_opening(w: &mut FlatWriter, p: &Project, op: &Opening) { + if op.kind == ElementKind::Window { + let Some(wt) = p.window_type(op) else { + w.num(0.0); + return; + }; + w.num(1.0); + write_common(w, wt.frame_depth, wt.inset_from_face, wt.inset_face == Some(WindowTypeInsetFace::Innen), wt.frame_corner_join, wt.frame_width, wt.transom_height); + let shading = wt.shading.as_ref().filter(|s| s.create).map(|s| &s.r#box); + w.nums(&[ + glazing_panes_of(wt), + opt(wt.mullion_rows), + opt(wt.mullion_cols), + match wt.sill_board { + Some(WindowTypeSillBoard::Keine) => 1.0, + Some(WindowTypeSillBoard::Innen) => 2.0, + Some(WindowTypeSillBoard::Beide) => 3.0, + _ => 0.0, + }, + flag(shading.is_some()), + shading.map_or(0.0, |b| b.width), + shading.map_or(0.0, |b| b.height), + shading.map_or(0.0, |b| b.depth), + op.wing_count.unwrap_or(wt.wing_count), + opening_kind_code(Some(wt.kind)), + ]); + let sashes = wt.sashes.as_deref().unwrap_or(&[]); + w.num(sashes.len() as f64); + for s in sashes { + w.nums(&[ + if s.kind == SashDefKind::Fluegel { 0.0 } else { 1.0 }, + flag(s.auto_width == Some(false)), + opt(s.width), + opt(s.post_width), + opening_kind_code(s.opening), + flag(s.hinge_side != Some(SashDefHingeSide::Right)), + ]); + } + return; + } + let Some(dt) = p.door_type(op) else { + w.num(0.0); + return; + }; + w.num(1.0); + write_common(w, dt.frame_depth, dt.inset_from_face, dt.inset_face == Some(DoorTypeInsetFace::Innen), dt.frame_corner_join, dt.frame_width, dt.transom_height); + w.nums(&[ + flag(dt.threshold == Some(true)), + dt.leaf_count, + match dt.leaf_style { + DoorTypeLeafStyle::Glas => 1.0, + DoorTypeLeafStyle::Kassette => 2.0, + _ => 0.0, + }, + opt(dt.glazing_ratio), + flag(dt.frame_kind != Some(DoorTypeFrameKind::Blockrahmen)), + opt(dt.panel_cols), + opt(dt.panel_rows), + ]); +} + +/// Öffnungs-Einbauteile als Quader-Meshes (`emitOpeningMeshes`); `detail`: 0 grob, 1 mittel, 2 fein. +pub fn emit_opening_meshes(p: &Project, detail: f64) -> Vec { + let mut w = FlatWriter::new(); + w.num(detail).num(p.walls.len() as f64); + for wall in &p.walls { + w.nums(&[wall.start.x, wall.start.y, wall.end.x, wall.end.y]); + let slot = w.slot(); + let mut count = 0.0; + let wr = wall_ref(p, wall); + let (zb, zt) = p.wall_vertical_extent(wall); + let mut thickness: Option = None; + for op in p.openings_of_wall(&wall.id) { + let Some((from, to)) = opening_geom::opening_interval(&wr, op.position, op.width) else { continue }; + let o_bottom = zb + op.sill_height.max(0.0); + let o_top = zt.min(o_bottom + op.height); + let t = *thickness.get_or_insert_with(|| p.wall_thickness(wall, 0.2)); + w.nums(&[from, to, o_bottom, o_top, flag(op.kind != ElementKind::Window), t]); + write_opening(&mut w, p, op); + count += 1.0; + } + w.set(slot, count); + } + let buf = crate::openings3d::opening_meshes_flat(&w.done()); + let n = buf.first().copied().unwrap_or(0.0).max(0.0) as usize; + let mut out = Vec::new(); + let mut i = 1; + for _ in 0..n { + if i + 25 > buf.len() { + break; + } + let part = buf[i] as usize; + out.push(RMesh { + positions: buf[i + 1..i + 25].to_vec(), + indices: OPENING_BOX_TRIS.to_vec(), + kind: "extrusion", + color: PART_RGB.get(part).copied().unwrap_or(PART_RGB[1]), + vertex_colors: None, + material_index: None, + }); + i += 25; + } + out +} + #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index 6b6ac772..a17af4f5 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -84,6 +84,7 @@ pub fn doc_query_args(h: u32, name: &str, args: &[f64]) -> String { "buildingFootprint" => serde_json::to_string(&site_rules::building_footprint(&p)), "modelTop" => serde_json::to_string(&site_rules::model_top(&p)), "walls" if args.len() == 1 => crate::model3d::emit_walls(&p, args[0] != 0.0).map_err(|_| ()).and_then(|w| serde_json::to_string(&w).map_err(|_| ())).map_err(|_| serde_json::Error::io(std::io::Error::other("walls"))), + "openingMeshes" if args.len() == 1 => serde_json::to_string(&crate::model3d::emit_opening_meshes(&p, args[0])), "slabs" => serde_json::to_string(&crate::model3d::emit_slabs(&p)), "columnMeshes" => serde_json::to_string(&crate::model3d::emit_columns(&p)), "shadows" if args.len() == 2 => { diff --git a/src/core/document.ts b/src/core/document.ts index a94ebb31..fadefe1d 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -49,7 +49,7 @@ export class ProjectDocument { * Abfrage auf dem typisierten Projekt im Kern. Das Ergebnis ist JSON; ein Fehler (Projekt passt * nicht zum Modell, unbekannte Abfrage) wirft. */ - query(name: "kennzahlen" | "siteCheck" | "buildingFootprint" | "modelTop" | "shadows" | "slabs" | "columnMeshes" | "walls", args: number[] = []): T { + query(name: "kennzahlen" | "siteCheck" | "buildingFootprint" | "modelTop" | "shadows" | "slabs" | "columnMeshes" | "walls" | "openingMeshes", args: number[] = []): T { const text = this.handle ? core().doc_query_args(this.handle, name, Float64Array.from(args)) : ""; if (!text) throw new Error(`Kern-Abfrage „${name}": Projekt passt nicht zum Kern-Modell`); return JSON.parse(text) as T; diff --git a/src/plan/model3d.parity.tmp.test.ts b/src/plan/model3d.parity.tmp.test.ts index 902dbedd..70b37e56 100644 --- a/src/plan/model3d.parity.tmp.test.ts +++ b/src/plan/model3d.parity.tmp.test.ts @@ -4,6 +4,7 @@ import { documentFor } from "../core/document"; import { emitSlabs } from "./toWalls3d/ceilings"; import { emitColumns } from "./toWalls3d/columns"; import { projectToWalls3d } from "./toWalls3d"; +import { emitOpeningMeshes } from "./toWalls3d/openings"; const plain = (v: T): T => JSON.parse(JSON.stringify(v)); let seed = 21; @@ -39,8 +40,22 @@ describe("model3d walls", () => { ...(sampleProject.ceilingTypes?.length && rnd() < 0.5 ? { ceilingTypeId: pick(sampleProject.ceilingTypes).id } : {}) })); const roofs = rnd() < 0.5 ? [{ id: "R1", type: "roof", floorId: pick(lvl).id, categoryCode: "35", outline: [{ x: -1, y: -1 }, { x: 7, y: -1 }, { x: 7, y: 5 }, { x: -1, y: 5 }], shape: pick(["sattel", "walm", "pult", "flach"]), pitchDeg: 30, overhang: 0.3, ridgeAxis: pick(["x", "y"]), thickness: 0.2 }] : []; - const project: any = { ...sampleProject, walls, openings, ceilings, roofs }; + const kinds = ["fest", "dreh", "kipp", "drehkipp", "schiebe"]; + const wts = Array.from({ length: 2 }, (_, k) => ({ ...sampleProject.windowTypes![0], id: "wt" + k, kind: pick(kinds), wingCount: 1 + Math.floor(rnd() * 3), + frameWidth: rnd() < 0.5 ? pick([0.04, 0.06, 0.09]) : undefined, transomHeight: rnd() < 0.5 ? pick([0.2, 0.4]) : undefined, + mullionRows: rnd() < 0.5 ? pick([1, 2, 3]) : undefined, mullionCols: rnd() < 0.5 ? pick([1, 2]) : undefined, + sillBoard: pick(["keine", "innen", "aussen", "beide", undefined]), glazingPanes: pick([1, 2, 3, undefined]), glazing: pick(["einfach", "zweifach", "dreifach"]), + frameCornerJoin: pick(["vertikal", "horizontal", "gehrung", undefined]), insetFromFace: rnd() < 0.5 ? 0.1 : undefined, insetFace: pick(["aussen", "innen", undefined]), + innerLayerRecess: rnd() < 0.3 ? true : undefined, shading: rnd() < 0.4 ? { create: true, kind: "rollladen", box: { width: 1, height: 0.2, depth: 0.2 } } : undefined, + sashes: rnd() < 0.6 ? Array.from({ length: 1 + Math.floor(rnd() * 3) }, () => ({ kind: pick(["fluegel", "fluegel", "pfosten"]), autoWidth: pick([true, false, undefined]), width: rnd() < 0.5 ? 0.4 : undefined, postWidth: rnd() < 0.5 ? 0.08 : undefined, opening: pick([...kinds, undefined]), hingeSide: pick(["left", "right", undefined]) })) : undefined })); + const dts = Array.from({ length: 2 }, (_, k) => ({ ...sampleProject.doorTypes![0], id: "dt" + k, leafStyle: pick(["glatt", "glas", "kassette"]), glazingRatio: rnd() < 0.5 ? pick([0.3, 1]) : undefined, + frameKind: pick(["zarge", "blockrahmen", undefined]), threshold: pick([true, false, undefined]), leafCount: pick([1, 2]) , panelCols: rnd() < 0.5 ? 2 : undefined, panelRows: rnd() < 0.5 ? 3 : undefined })); + const openings2 = openings.map((o: any) => ({ ...o, ...(rnd() < 0.8 ? { typeId: o.kind === "door" ? pick(dts).id : pick(wts).id } : {}), ...(rnd() < 0.3 ? { wingCount: 2 } : {}) })); + const project: any = { ...sampleProject, walls, openings: openings2, ceilings, roofs, windowTypes: wts, doorTypes: dts }; const doc = documentFor(project); + for (const [dc, dn] of [[0, "grob"], [1, "mittel"], [2, "fein"]] as const) { + expect(doc.query("openingMeshes", [dc])).toEqual(plain(emitOpeningMeshes(project, dn))); + } for (const layered of [true, false]) { let want: unknown; try { want = plain(projectToWalls3d(project, layered)); } catch { want = undefined; } From 478135e204840d08d65aa6f4e48dbc37c3e7654a Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:58:06 +0100 Subject: [PATCH 21/31] [K4] S2 (Zwischenstand): Treppen (3D) aus dem Dokument --- src-tauri/core/src/model/helpers.rs | 33 +++++++++++ src-tauri/core/src/model3d.rs | 90 +++++++++++++++++++++++++++++ src-tauri/core/src/web/document.rs | 3 + src/core/document.ts | 2 +- src/plan/model3d.parity.tmp.test.ts | 30 ++++++++++ 5 files changed, 157 insertions(+), 1 deletion(-) diff --git a/src-tauri/core/src/model/helpers.rs b/src-tauri/core/src/model/helpers.rs index d387ab52..9c7d0f97 100644 --- a/src-tauri/core/src/model/helpers.rs +++ b/src-tauri/core/src/model/helpers.rs @@ -181,3 +181,36 @@ impl Roof { } } } + +impl Stair { + /// Treppen-Parameter als 16 Zahlen (Aufbau: `stair.rs`, `encodeStair` in TS); fehlend = NaN. + pub fn encode(&self) -> [f64; 16] { + let n = |v: Option| v.unwrap_or(f64::NAN); + [ + match self.shape { + StairShape::Straight => 0.0, + StairShape::L => 1.0, + StairShape::Spiral => 2.0, + }, + self.start.x, + self.start.y, + self.dir.x, + self.dir.y, + self.run_length, + n(self.run2_length), + n(self.turn), + n(self.center.map(|c| c.x)), + n(self.center.map(|c| c.y)), + n(self.radius), + n(self.sweep), + self.width, + self.step_count, + self.up.map_or(f64::NAN, |u| if u { 1.0 } else { 0.0 }), + match self.referenz { + Some(StairReferenz::Links) => 1.0, + Some(StairReferenz::Rechts) => 2.0, + _ => 0.0, + }, + ] + } +} diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index 6a427725..b6fb68b0 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -701,6 +701,96 @@ pub fn emit_opening_meshes(p: &Project, detail: f64) -> Vec { out } +// ── Treppen ───────────────────────────────────────────────────────────────── + +fn stair_rgb() -> Rgb { + hex_to_rgb("#9aa0a6", SLAB_RGB) +} + +fn rail_rgb() -> Rgb { + hex_to_rgb("#74797f", SLAB_RGB) +} + +/// Flache Eingabe der Treppen für `stairs3d` (23 Zahlen je Treppe); `wanted` wählt vor. +fn stair_input<'a>(p: &'a Project, wanted: impl Fn(&Stair, Option<&StairType>) -> bool) -> Option<(Vec<&'a Stair>, Vec)> { + let mut stairs: Vec<&Stair> = Vec::new(); + let mut types: Vec> = Vec::new(); + for s in p.stairs.as_deref().unwrap_or(&[]) { + let st = p.stair_type(s); + if !wanted(s, st) { + continue; + } + stairs.push(s); + types.push(st); + } + if stairs.is_empty() { + return None; + } + let mut buf = vec![stairs.len() as f64]; + for (s, st) in stairs.iter().zip(&types) { + let (z_bottom, z_top) = p.stair_vertical_extent(s); + buf.extend(s.encode()); + buf.push(z_bottom); + buf.push(z_top); + buf.push(match st.map(|t| t.structure) { + None | Some(StairTypeStructure::Massiv) => 0.0, + Some(StairTypeStructure::Beton) => 1.0, + _ => 2.0, + }); + buf.push(st.map_or(0.04, |t| t.tread_thickness)); + buf.push(st.and_then(|t| t.nosing).unwrap_or(0.0)); + buf.push(if st.is_some_and(|t| t.closed_risers) { 1.0 } else { 0.0 }); + buf.push(match st.and_then(|t| t.railing) { + Some(StairTypeRailing::Links) => 1.0, + Some(StairTypeRailing::Rechts) => 2.0, + Some(StairTypeRailing::Beide) => 3.0, + _ => 0.0, + }); + } + Some((stairs, buf)) +} + +/// Treppen als extrudierte Platten (`emitStairs`); `for_section`: auch gerade Betontreppen als Tritte. +pub fn emit_stairs(p: &Project, for_section: bool) -> Vec { + let Some((stairs, buf)) = stair_input(p, |_, _| true) else { return vec![] }; + crate::stairs3d::slabs(&buf, for_section) + .into_iter() + .map(|s| { + let stair = stairs[s.src]; + RSlab { + outline: s.pts, + z_bottom: s.z_bottom, + z_top: s.z_top, + color: stair_rgb(), + ceiling_id: stair.id.clone(), + hatch: None, + cut: None, + monolith: s.monolith.then(|| stair.id.clone()), + } + }) + .collect() +} + +fn meshes_of(meshes: Vec, color: Rgb) -> Vec { + meshes.into_iter().map(|m| RMesh { positions: m.positions, indices: m.indices, kind: "extrusion", color, vertex_colors: None, material_index: None }).collect() +} + +/// Glatte Ortbeton-Laufplatten gerader Treppen (`emitStairMeshes`). +pub fn emit_stair_meshes(p: &Project) -> Vec { + match stair_input(p, |s, st| st.is_some_and(|t| t.structure == StairTypeStructure::Beton) && s.shape == StairShape::Straight) { + Some((_, buf)) => meshes_of(crate::stairs3d::slab_meshes(&buf), stair_rgb()), + None => vec![], + } +} + +/// Handlauf und Pfosten gerader Treppen (`emitStairRailings`). +pub fn emit_stair_railings(p: &Project) -> Vec { + match stair_input(p, |s, st| s.shape == StairShape::Straight && st.and_then(|t| t.railing).is_some_and(|r| r != StairTypeRailing::Keine)) { + Some((_, buf)) => meshes_of(crate::stairs3d::railings(&buf), rail_rgb()), + None => vec![], + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index a17af4f5..646a8d1f 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -85,6 +85,9 @@ pub fn doc_query_args(h: u32, name: &str, args: &[f64]) -> String { "modelTop" => serde_json::to_string(&site_rules::model_top(&p)), "walls" if args.len() == 1 => crate::model3d::emit_walls(&p, args[0] != 0.0).map_err(|_| ()).and_then(|w| serde_json::to_string(&w).map_err(|_| ())).map_err(|_| serde_json::Error::io(std::io::Error::other("walls"))), "openingMeshes" if args.len() == 1 => serde_json::to_string(&crate::model3d::emit_opening_meshes(&p, args[0])), + "stairSlabs" if args.len() == 1 => serde_json::to_string(&crate::model3d::emit_stairs(&p, args[0] != 0.0)), + "stairMeshes" => serde_json::to_string(&crate::model3d::emit_stair_meshes(&p)), + "stairRailings" => serde_json::to_string(&crate::model3d::emit_stair_railings(&p)), "slabs" => serde_json::to_string(&crate::model3d::emit_slabs(&p)), "columnMeshes" => serde_json::to_string(&crate::model3d::emit_columns(&p)), "shadows" if args.len() == 2 => { diff --git a/src/core/document.ts b/src/core/document.ts index fadefe1d..bb0d099e 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -49,7 +49,7 @@ export class ProjectDocument { * Abfrage auf dem typisierten Projekt im Kern. Das Ergebnis ist JSON; ein Fehler (Projekt passt * nicht zum Modell, unbekannte Abfrage) wirft. */ - query(name: "kennzahlen" | "siteCheck" | "buildingFootprint" | "modelTop" | "shadows" | "slabs" | "columnMeshes" | "walls" | "openingMeshes", args: number[] = []): T { + query(name: "kennzahlen" | "siteCheck" | "buildingFootprint" | "modelTop" | "shadows" | "slabs" | "columnMeshes" | "walls" | "openingMeshes" | "stairSlabs" | "stairMeshes" | "stairRailings", args: number[] = []): T { const text = this.handle ? core().doc_query_args(this.handle, name, Float64Array.from(args)) : ""; if (!text) throw new Error(`Kern-Abfrage „${name}": Projekt passt nicht zum Kern-Modell`); return JSON.parse(text) as T; diff --git a/src/plan/model3d.parity.tmp.test.ts b/src/plan/model3d.parity.tmp.test.ts index 70b37e56..b34a3c2d 100644 --- a/src/plan/model3d.parity.tmp.test.ts +++ b/src/plan/model3d.parity.tmp.test.ts @@ -5,6 +5,7 @@ import { emitSlabs } from "./toWalls3d/ceilings"; import { emitColumns } from "./toWalls3d/columns"; import { projectToWalls3d } from "./toWalls3d"; import { emitOpeningMeshes } from "./toWalls3d/openings"; +import { emitStairs, emitStairMeshes, emitStairRailings } from "./toWalls3d/stairs"; const plain = (v: T): T => JSON.parse(JSON.stringify(v)); let seed = 21; @@ -68,6 +69,35 @@ describe("model3d walls", () => { }); }); +describe("model3d stairs", () => { + it("random", () => { + let n = 0; + for (let t = 0; t < 200; t++) { + const lvl = sampleProject.drawingLevels.filter((l) => l.kind === "floor"); + const types = Array.from({ length: 3 }, (_, k) => ({ id: "st" + k, name: "t", structure: pick(["massiv", "beton", "wange", "aufgesattelt", "spindel"]), closedRisers: rnd() < 0.5, + treadThickness: pick([0.04, 0.06]), nosing: rnd() < 0.5 ? 0.03 : undefined, railing: pick(["keine", "links", "rechts", "beide", undefined]), defaultWidth: 1 })); + const stairs = Array.from({ length: 1 + Math.floor(rnd() * 3) }, (_, k) => { + const shape = pick(["straight", "L", "spiral"]); + return { id: "s" + k, type: "stair", floorId: pick(lvl).id, categoryCode: "25", shape, start: { x: rnd() * 5, y: rnd() * 5 }, dir: pick([{ x: 1, y: 0 }, { x: 0, y: 1 }, { x: -1, y: 0 }]), + runLength: 2 + rnd() * 3, ...(shape === "L" ? { run2Length: 1.5, turn: pick([1, -1]) } : {}), ...(shape === "spiral" ? { center: { x: 2, y: 2 }, radius: 1.2, sweep: 4 } : {}), + width: 1, stepCount: 8 + Math.floor(rnd() * 8), ...(rnd() < 0.5 ? { totalRise: 2.6 } : {}), ...(rnd() < 0.5 ? { up: pick([true, false]) } : {}), + ...(rnd() < 0.7 ? { typeId: pick(types).id } : {}), ...(rnd() < 0.3 ? { referenz: pick(["links", "rechts", "mitte"]) } : {}) }; + }); + const project: any = { ...sampleProject, stairs, stairTypes: types }; + const doc = documentFor(project); + for (const fs of [false, true]) { + const a = doc.query("stairSlabs", [fs ? 1 : 0]); + const b = plain(emitStairs(project, { forSection: fs })); + expect(a).toEqual(b); + n += b.length; + } + expect(doc.query("stairMeshes")).toEqual(plain(emitStairMeshes(project))); + expect(doc.query("stairRailings")).toEqual(plain(emitStairRailings(project))); + } + expect(n).toBeGreaterThan(300); + }); +}); + describe("model3d slabs/columns", () => { it("random", () => { let ns = 0, nc = 0; From 0817697e195b16fe0095b24166acf6578177e2b2 Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 01:59:27 +0100 Subject: [PATCH 22/31] [K4] S2 (Zwischenstand): Daecher (3D, Schnitt-Schichten) aus dem Dokument --- src-tauri/core/src/model3d.rs | 260 ++++++++++++++++++++++++++++ src-tauri/core/src/web/document.rs | 2 + src/core/document.ts | 2 +- src/plan/model3d.parity.tmp.test.ts | 24 +++ 4 files changed, 287 insertions(+), 1 deletion(-) diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index b6fb68b0..b27d9daf 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -791,6 +791,266 @@ pub fn emit_stair_railings(p: &Project) -> Vec { } } +// ── Dächer ────────────────────────────────────────────────────────────────── + +use crate::jsmath::hypot; +use crate::jsnum::round; + +type V3 = [f64; 3]; +const ROOF_RGB: Rgb = [0.72, 0.45, 0.36]; +const EPS: f64 = 1e-4; + +/// Eine Dachschicht für den Live-Schnitt (`RRoofLayer`). +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RRoofLayer { + pub polygon: Vec, + pub normal: V3, + pub thickness: f64, + pub color: Rgb, + #[serde(skip_serializing_if = "Option::is_none")] + pub cut: Option, +} + +fn push_fan_triangles(positions: &mut Vec, indices: &mut Vec, pts: &[V3], flip: bool) { + if pts.len() < 3 { + return; + } + let base = (positions.len() / 3) as u32; + for p in pts { + positions.extend(*p); + } + for i in 1..pts.len() as u32 - 1 { + if flip { + indices.extend([base, base + i + 1, base + i]); + } else { + indices.extend([base, base + i, base + i + 1]); + } + } +} + +/// Newell-Normale einer Dachfläche, nach oben orientiert (`planeNormalUp`). +fn plane_normal_up(pts: &[V3]) -> V3 { + let (mut nx, mut ny, mut nz) = (0.0, 0.0, 0.0); + for i in 0..pts.len() { + let c = pts[i]; + let d = pts[(i + 1) % pts.len()]; + nx += (c[1] - d[1]) * (c[2] + d[2]); + ny += (c[2] - d[2]) * (c[0] + d[0]); + nz += (c[0] - d[0]) * (c[1] + d[1]); + } + let len = hypot(&[nx, ny, nz]); + let len = if len == 0.0 || len.is_nan() { 1.0 } else { len }; + let u = [nx / len, ny / len, nz / len]; + if u[2] < 0.0 { + [-u[0], -u[1], -u[2]] + } else { + u + } +} + +fn dot3(a: V3, b: V3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +fn cross3(a: V3, b: V3) -> V3 { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +/// Gehrte Versatz-Ecken aller Dachflächen (`mitredRoofOffsets`). +struct Mitre<'a> { + planes: &'a [Vec], + normals: Vec, + neighbor: Vec>, + shared: Vec>, +} + +impl<'a> Mitre<'a> { + fn new(planes: &'a [Vec]) -> Self { + let key = |p: &V3| (round(p[0] * 1e5) as i64, round(p[1] * 1e5) as i64, round(p[2] * 1e5) as i64); + let ek = |a: &V3, b: &V3| { + let (ka, kb) = (key(a), key(b)); + if ka <= kb { (ka, kb) } else { (kb, ka) } + }; + let mut owners: HashMap<_, Vec> = HashMap::new(); + for (i, pts) in planes.iter().enumerate() { + for k in 0..pts.len() { + owners.entry(ek(&pts[k], &pts[(k + 1) % pts.len()])).or_default().push(i); + } + } + let normals: Vec = planes.iter().map(|p| plane_normal_up(p)).collect(); + let neighbor: Vec> = planes + .iter() + .enumerate() + .map(|(i, pts)| { + (0..pts.len()) + .map(|k| { + owners + .get(&ek(&pts[k], &pts[(k + 1) % pts.len()])) + .and_then(|o| o.iter().find(|&&x| x != i)) + .map_or(-1, |&j| j as isize) + }) + .collect() + }) + .collect(); + let shared = neighbor.iter().map(|row| row.iter().map(|&j| j >= 0).collect()).collect(); + Mitre { planes, normals, neighbor, shared } + } + + fn edge_plane(&self, i: usize, k: usize, d: f64) -> (V3, f64) { + let pts = &self.planes[i]; + let a = pts[k]; + let b = pts[(k + 1) % pts.len()]; + let j = self.neighbor[i][k]; + if j >= 0 { + let j = j as usize; + return (self.normals[j], dot3(self.normals[j], self.planes[j][0]) - d); + } + let dir = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + let m = cross3(dir, self.normals[i]); + (m, dot3(m, a)) + } + + fn solve(rows: [(V3, f64); 3]) -> Option { + let [(a, ca), (b, cb), (c, cc)] = rows; + let bc = cross3(b, c); + let det = dot3(a, bc); + if det.abs() < 1e-9 { + return None; + } + let cxa = cross3(c, a); + let axb = cross3(a, b); + Some([ + (ca * bc[0] + cb * cxa[0] + cc * axb[0]) / det, + (ca * bc[1] + cb * cxa[1] + cc * axb[1]) / det, + (ca * bc[2] + cb * cxa[2] + cc * axb[2]) / det, + ]) + } + + fn at(&self, i: usize, d: f64) -> Vec { + let pts = &self.planes[i]; + let n = self.normals[i]; + if d <= EPS { + return pts.clone(); + } + let own = (n, dot3(n, pts[0]) - d); + (0..pts.len()) + .map(|k| { + let p = pts[k]; + let prev = (k + pts.len() - 1) % pts.len(); + let fallback = [p[0] - n[0] * d, p[1] - n[1] * d, p[2] - n[2] * d]; + if !self.shared[i][prev] && !self.shared[i][k] { + return fallback; + } + match Self::solve([own, self.edge_plane(i, prev, d), self.edge_plane(i, k, d)]) { + Some(q) if hypot(&[q[0] - fallback[0], q[1] - fallback[1], q[2] - fallback[2]]) <= 4.0 * d + 0.5 => q, + _ => fallback, + } + }) + .collect() + } +} + +fn push_roof_slab_between(positions: &mut Vec, indices: &mut Vec, top: &[V3], bottom: &[V3], shared: &[bool]) { + let mut nz = 0.0; + for i in 0..top.len() { + let a = top[i]; + let b = top[(i + 1) % top.len()]; + nz += (a[0] - b[0]) * (a[1] + b[1]); + } + let ccw = nz > 0.0; + push_fan_triangles(positions, indices, top, !ccw); + push_fan_triangles(positions, indices, bottom, ccw); + for i in 0..top.len() { + if shared[i] { + continue; + } + let j = (i + 1) % top.len(); + let base = (positions.len() / 3) as u32; + positions.extend(top[i]); + positions.extend(bottom[i]); + positions.extend(bottom[j]); + positions.extend(top[j]); + if ccw { + indices.extend([base, base + 1, base + 2, base, base + 2, base + 3]); + } else { + indices.extend([base, base + 2, base + 1, base, base + 3, base + 2]); + } + } +} + +fn roof_color(p: &Project, override_color: Option, component_id: &str) -> Result { + if let Some(c) = override_color { + return Ok(c); + } + if component_id.is_empty() { + return Ok(ROOF_RGB); + } + p.component(component_id).map(|c| hex_to_rgb(&c.color, ROOF_RGB)).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {component_id}")) +} + +/// Dächer als geschlossene, geschichtete Dreiecks-Meshes (`emitRoofs`). +pub fn emit_roofs(p: &Project) -> Result, String> { + let maps = wall_material_color_maps(p); + let mut out = Vec::new(); + for roof in p.roofs.as_deref().unwrap_or(&[]) { + let eaves_z = p.roof_base_elevation(roof); + let g = crate::roof::roof_geometry(&roof.params(), eaves_z); + let override_color = roof.color.as_deref().filter(|c| !c.is_empty()).map(|c| hex_to_rgb(c, ROOF_RGB)); + let mitre = Mitre::new(&g.planes); + let mut offset_above = 0.0; + for layer in p.roof_layers(roof) { + let t = layer.thickness.max(0.0); + if t <= EPS { + continue; + } + let color = roof_color(p, override_color, &layer.component_id)?; + let material_index = if override_color.is_none() && !layer.component_id.is_empty() { material_layer(p, &maps, &layer.component_id) } else { None }; + let (mut positions, mut indices) = (Vec::new(), Vec::new()); + for (i, plane) in g.planes.iter().enumerate() { + if plane.len() < 3 { + continue; + } + let top = mitre.at(i, offset_above); + let bottom = mitre.at(i, offset_above + t); + push_roof_slab_between(&mut positions, &mut indices, &top, &bottom, &mitre.shared[i]); + } + if !indices.is_empty() { + out.push(RMesh { positions, indices, kind: "extrusion", color, vertex_colors: None, material_index }); + } + offset_above += t; + } + } + Ok(out) +} + +/// Dachschicht-Eingabe für den 3D-Live-Schnitt (`emitRoofCutLayers`). +pub fn emit_roof_cut_layers(p: &Project) -> Result, String> { + let mut out = Vec::new(); + for roof in p.roofs.as_deref().unwrap_or(&[]) { + let eaves_z = p.roof_base_elevation(roof); + let g = crate::roof::roof_geometry(&roof.params(), eaves_z); + let override_color = roof.color.as_deref().filter(|c| !c.is_empty()).map(|c| hex_to_rgb(c, ROOF_RGB)); + let mut offset_above = 0.0; + for layer in p.roof_layers(roof) { + let t = layer.thickness.max(0.0); + if t <= EPS { + continue; + } + let color = roof_color(p, override_color, &layer.component_id)?; + let line = resolve_cut_line_style(p, layer.joint_line_style_id.as_deref()); + let cut = line.map(|(c, w)| RCutMeta { line_color: Some(c), line_weight: Some(w), ..Default::default() }); + for plane in &g.planes { + let nrm = plane_normal_up(plane); + let polygon = plane.iter().map(|q| [q[0] - nrm[0] * offset_above, q[1] - nrm[1] * offset_above, q[2] - nrm[2] * offset_above]).collect(); + out.push(RRoofLayer { polygon, normal: nrm, thickness: t, color, cut: cut.clone() }); + } + offset_above += t; + } + } + Ok(out) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index 646a8d1f..514f9a41 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -88,6 +88,8 @@ pub fn doc_query_args(h: u32, name: &str, args: &[f64]) -> String { "stairSlabs" if args.len() == 1 => serde_json::to_string(&crate::model3d::emit_stairs(&p, args[0] != 0.0)), "stairMeshes" => serde_json::to_string(&crate::model3d::emit_stair_meshes(&p)), "stairRailings" => serde_json::to_string(&crate::model3d::emit_stair_railings(&p)), + "roofMeshes" => crate::model3d::emit_roofs(&p).map_err(|e| serde_json::Error::io(std::io::Error::other(e))).and_then(|v| serde_json::to_string(&v)), + "roofCutLayers" => crate::model3d::emit_roof_cut_layers(&p).map_err(|e| serde_json::Error::io(std::io::Error::other(e))).and_then(|v| serde_json::to_string(&v)), "slabs" => serde_json::to_string(&crate::model3d::emit_slabs(&p)), "columnMeshes" => serde_json::to_string(&crate::model3d::emit_columns(&p)), "shadows" if args.len() == 2 => { diff --git a/src/core/document.ts b/src/core/document.ts index bb0d099e..2ddaa62e 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -49,7 +49,7 @@ export class ProjectDocument { * Abfrage auf dem typisierten Projekt im Kern. Das Ergebnis ist JSON; ein Fehler (Projekt passt * nicht zum Modell, unbekannte Abfrage) wirft. */ - query(name: "kennzahlen" | "siteCheck" | "buildingFootprint" | "modelTop" | "shadows" | "slabs" | "columnMeshes" | "walls" | "openingMeshes" | "stairSlabs" | "stairMeshes" | "stairRailings", args: number[] = []): T { + query(name: "kennzahlen" | "siteCheck" | "buildingFootprint" | "modelTop" | "shadows" | "slabs" | "columnMeshes" | "walls" | "openingMeshes" | "stairSlabs" | "stairMeshes" | "stairRailings" | "roofMeshes" | "roofCutLayers", args: number[] = []): T { const text = this.handle ? core().doc_query_args(this.handle, name, Float64Array.from(args)) : ""; if (!text) throw new Error(`Kern-Abfrage „${name}": Projekt passt nicht zum Kern-Modell`); return JSON.parse(text) as T; diff --git a/src/plan/model3d.parity.tmp.test.ts b/src/plan/model3d.parity.tmp.test.ts index b34a3c2d..be7ebb47 100644 --- a/src/plan/model3d.parity.tmp.test.ts +++ b/src/plan/model3d.parity.tmp.test.ts @@ -5,6 +5,7 @@ import { emitSlabs } from "./toWalls3d/ceilings"; import { emitColumns } from "./toWalls3d/columns"; import { projectToWalls3d } from "./toWalls3d"; import { emitOpeningMeshes } from "./toWalls3d/openings"; +import { emitRoofs, emitRoofCutLayers } from "./toWalls3d/roofs"; import { emitStairs, emitStairMeshes, emitStairRailings } from "./toWalls3d/stairs"; const plain = (v: T): T => JSON.parse(JSON.stringify(v)); @@ -98,6 +99,29 @@ describe("model3d stairs", () => { }); }); +describe("model3d roofs", () => { + it("random", () => { + let n = 0; + const L = [{ x: 0, y: 0 }, { x: 11, y: 0 }, { x: 11, y: 4 }, { x: 8, y: 4 }, { x: 8, y: 6 }, { x: 0, y: 6 }]; + const R = [{ x: 0, y: 0 }, { x: 8, y: 0 }, { x: 8, y: 5 }, { x: 0, y: 5 }]; + for (let t = 0; t < 200; t++) { + const lvl = sampleProject.drawingLevels.filter((l) => l.kind === "floor"); + const roofTypes = sampleProject.roofTypes ?? []; + const roofs = Array.from({ length: 1 + Math.floor(rnd() * 2) }, (_, k) => ({ id: "R" + k, type: "roof", floorId: pick(lvl).id, categoryCode: "35", outline: pick([L, R]), + shape: pick(["sattel", "walm", "pult", "flach", "mansarde", "zelt"]), pitchDeg: 10 + Math.floor(rnd() * 40), overhang: rnd() * 0.5, ridgeAxis: pick(["x", "y"]), thickness: pick([0.1, 0.2]), + ...(roofTypes.length && rnd() < 0.7 ? { roofTypeId: pick(roofTypes).id } : {}), ...(rnd() < 0.3 ? { color: "#aa3322" } : {}), ...(rnd() < 0.3 ? { baseElevation: 3 } : {}) })); + const project: any = { ...sampleProject, roofs }; + const doc = documentFor(project); + const a = doc.query("roofMeshes"); + const b = plain(emitRoofs(project)); + expect(a).toEqual(b); + expect(plain(doc.query("roofCutLayers"))).toEqual(plain(emitRoofCutLayers(project))); + n += b.length; + } + expect(n).toBeGreaterThan(100); + }); +}); + describe("model3d slabs/columns", () => { it("random", () => { let ns = 0, nc = 0; From 8995ea161dccd6e71353a58c844c7834c6c420cf Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 02:06:10 +0100 Subject: [PATCH 23/31] [K4] S2: 3D-Modell (Waende, Decken, Treppen, Stuetzen, Daecher, Oeffnungen, Kontext) rechnet komplett auf dem Dokument (model3d.rs, queries.rs); TS-Sammler und unbenutzte Bindungen geloescht --- TODO.md | 7 +- scripts/gen-rust-model.py | 6 +- src-tauri/core/src/ceilings3d.rs | 15 - src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/mesh3d.rs | 28 +- src-tauri/core/src/model/generated.rs | 390 ++++++++++++++++--------- src-tauri/core/src/model/manual.rs | 12 + src-tauri/core/src/model3d.rs | 115 +++++++- src-tauri/core/src/openings3d.rs | 25 +- src-tauri/core/src/queries.rs | 32 ++ src-tauri/core/src/stairs3d.rs | 10 - src-tauri/core/src/wall_bands.rs | 175 ----------- src-tauri/core/src/web/ceilings3d.rs | 10 - src-tauri/core/src/web/columns3d.rs | 11 - src-tauri/core/src/web/document.rs | 48 +-- src-tauri/core/src/web/mod.rs | 5 - src-tauri/core/src/web/openings3d.rs | 15 - src-tauri/core/src/web/site_rules.rs | 12 - src-tauri/core/src/web/stairs3d.rs | 23 -- src-tauri/core/src/web/sun.rs | 33 +-- src-tauri/core/src/web/wall_bands.rs | 9 - src/core/document.ts | 38 ++- src/export/exportIfc.ts | 6 +- src/plan/model3d.parity.tmp.test.ts | 159 ---------- src/plan/toWalls3d.ts | 168 ++++------- src/plan/toWalls3d/bands.ts | 346 ---------------------- src/plan/toWalls3d/ceilings.ts | 106 ------- src/plan/toWalls3d/columns.ts | 90 ------ src/plan/toWalls3d/frameRing.test.ts | 37 --- src/plan/toWalls3d/openings.ts | 201 ------------- src/plan/toWalls3d/roofMitre.test.ts | 36 --- src/plan/toWalls3d/roofWinding.test.ts | 6 +- src/plan/toWalls3d/roofs.ts | 298 ------------------- src/plan/toWalls3d/shared.ts | 181 +----------- src/plan/toWalls3d/stairs.ts | 160 ---------- 35 files changed, 545 insertions(+), 2269 deletions(-) create mode 100644 src-tauri/core/src/queries.rs delete mode 100644 src-tauri/core/src/web/ceilings3d.rs delete mode 100644 src-tauri/core/src/web/columns3d.rs delete mode 100644 src-tauri/core/src/web/openings3d.rs delete mode 100644 src-tauri/core/src/web/stairs3d.rs delete mode 100644 src-tauri/core/src/web/wall_bands.rs delete mode 100644 src/plan/model3d.parity.tmp.test.ts delete mode 100644 src/plan/toWalls3d/bands.ts delete mode 100644 src/plan/toWalls3d/ceilings.ts delete mode 100644 src/plan/toWalls3d/columns.ts delete mode 100644 src/plan/toWalls3d/frameRing.test.ts delete mode 100644 src/plan/toWalls3d/openings.ts delete mode 100644 src/plan/toWalls3d/roofMitre.test.ts delete mode 100644 src/plan/toWalls3d/roofs.ts delete mode 100644 src/plan/toWalls3d/stairs.ts diff --git a/TODO.md b/TODO.md index ea42a975..a436d307 100644 --- a/TODO.md +++ b/TODO.md @@ -130,7 +130,12 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern `deny_unknown_fields`), `Document::project()` als gecachte typisierte Sicht, `documentFor(project)` (TS) hält ein gemeinsames Dokument per Differenz aktuell. Verbraucher bisher: Kennzahlen (`kennzahlen.rs::compute`), Baurecht-Prüfung/Footprint/Modellhöhe (`site_rules.rs`); Abfragen laufen über `doc_query`, Modell-Nachschlagen in `model/helpers.rs`. TS-Sammler gelöscht. - Nächste: Sonnenstand/Schatten, Raumprogramm, danach Plan/Schnitt/Ansicht, 3D, Export. + Sonnenstand/Schatten ebenso. **3D-Modell komplett** (28.10.): `model3d.rs` (Wände mit Verschneidung/Bändern/Öffnungen, Decken, Treppen, + Stützen, Dächer inkl. Schnitt-Schichten, Öffnungs-Einbauteile, Kontext) → `projectToModel3d` holt die Teile per `doc_query` + (`queries.rs`), nur die truck-Körper (async) fügt TS ein; TS-Sammler `toWalls3d/{bands,ceilings,columns,openings,stairs,roofs}.ts` + gelöscht, unbenutzte Bindungen/Kodierer entfernt. Hin-und-her-Vergleich mit der TS-Fassung lief über Zufallsprojekte, danach + prüft die bestehende Suite (2123 Tests) den neuen Weg. Das Modell ist tolerant (fehlende Felder = Standardwert). + Nächste: Plan/Schnitt/Ansicht-Sammler (generatePlan, toSection, toElevation), Export (IFC/DXF/SVG), Raumprogramm. 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). - ○ **S3 Änderungen kommen aus Rust**: Befehle (Zustandsautomaten, Werkzeuge) erzeugen Ops im Kern; Undo/Redo, Validierung diff --git a/scripts/gen-rust-model.py b/scripts/gen-rust-model.py index 13d283cd..3cd725d1 100644 --- a/scripts/gen-rust-model.py +++ b/scripts/gen-rust-model.py @@ -155,7 +155,8 @@ def rust_enum(name, lits): while v in seen: v = f"{base}{n}"; n += 1 seen.add(v) lines.append(f' #[serde(rename = {json.dumps(l, ensure_ascii=False)})]\n {v},') - return ("#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]\n" + lines[0] = " #[default]\n" + lines[0] + return ("#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]\n" f"pub enum {name} {{\n" + "\n".join(lines) + "\n}\n") def rtype(t, ctx): @@ -228,7 +229,8 @@ def emit_struct(name, fields): r = f"Option<{r}>" a = f" #[serde({', '.join(attrs)})]\n" if attrs else "" lines.append(f"{a} pub {rn}: {r},") - out_items.append("#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n" + out_items.append("#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]\n" + + '#[serde(default)]\n' + '#[cfg_attr(test, serde(deny_unknown_fields))]\n' + f"pub struct {name} {{\n" + "\n".join(lines) + "\n}\n") diff --git a/src-tauri/core/src/ceilings3d.rs b/src-tauri/core/src/ceilings3d.rs index 63e9d59c..b6949836 100644 --- a/src-tauri/core/src/ceilings3d.rs +++ b/src-tauri/core/src/ceilings3d.rs @@ -76,21 +76,6 @@ pub fn ceilings(buf: &[f64]) -> Vec { out } -pub fn encode(c: &[CeilingSlabs]) -> Vec { - let mut out = vec![c.len() as f64]; - for d in c { - out.push(d.ceiling as f64); - out.push(d.ring.len() as f64); - for p in &d.ring { - out.extend(*p); - } - out.push(d.slabs.len() as f64); - for (l, zb, zt) in &d.slabs { - out.extend([*l as f64, *zb, *zt]); - } - } - out -} #[cfg(test)] mod tests { diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 13bf1902..1de38036 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -33,6 +33,7 @@ pub mod jsnum; pub mod hatch; pub mod hatch_flat; pub mod plan_buf; +pub mod queries; pub mod gpu_compile; pub mod plan_stairs; pub mod plan_walls; diff --git a/src-tauri/core/src/mesh3d.rs b/src-tauri/core/src/mesh3d.rs index acf481c1..183bae5d 100644 --- a/src-tauri/core/src/mesh3d.rs +++ b/src-tauri/core/src/mesh3d.rs @@ -1,33 +1,9 @@ //! Gemeinsame Mesh-Ausgabe der 3D-Ableitungen (`stairs3d`, `columns3d`): ein Dreiecksnetz je -//! Eingabeelement, flach kodiert als `[n, (quelle, nPos, nIdx, positionen…, indizes…)…]`. -//! `quelle` ist der Index des Elements in der Eingabe, damit TS Farbe und Id zuordnen kann. +//! Eingabeelement. `src` ist der Index des Elements in der Eingabe, damit `model3d` Farbe und Id +//! zuordnen kann. pub struct Mesh { pub src: usize, pub positions: Vec, pub indices: Vec, } - -pub fn encode_meshes(meshes: &[Mesh]) -> Vec { - let total: usize = meshes.iter().map(|m| 3 + m.positions.len() + m.indices.len()).sum(); - let mut out = Vec::with_capacity(1 + total); - out.push(meshes.len() as f64); - for m in meshes { - out.extend([m.src as f64, m.positions.len() as f64, m.indices.len() as f64]); - out.extend(&m.positions); - out.extend(m.indices.iter().map(|&i| i as f64)); - } - out -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn kodierung() { - let m = Mesh { src: 2, positions: vec![0.0, 1.0, 2.0], indices: vec![0, 0, 0] }; - assert_eq!(encode_meshes(&[m]), vec![1.0, 2.0, 3.0, 3.0, 0.0, 1.0, 2.0, 0.0, 0.0, 0.0]); - assert_eq!(encode_meshes(&[]), vec![0.0]); - } -} diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs index 661166bd..258894ab 100644 --- a/src-tauri/core/src/model/generated.rs +++ b/src-tauri/core/src/model/generated.rs @@ -4,8 +4,9 @@ use super::manual::*; use serde::{Deserialize, Serialize}; -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum LineStyleKind { + #[default] #[serde(rename = "dash")] Dash, #[serde(rename = "zigzag")] @@ -14,21 +15,24 @@ pub enum LineStyleKind { Custom, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct LineStyleZigzag { pub amplitude: f64, pub wavelength: f64, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct LineStyleMotif { pub points: Vec, pub length: f64, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct LineStyle { pub id: String, @@ -45,7 +49,8 @@ pub struct LineStyle { pub motif: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Marks { #[serde(default, skip_serializing_if = "Option::is_none")] @@ -68,7 +73,8 @@ pub struct Marks { pub color: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct TextStylePreset { pub id: String, @@ -76,8 +82,9 @@ pub struct TextStylePreset { pub marks: Marks, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum HatchStyleKind { + #[default] #[serde(rename = "vector")] Vector, #[serde(rename = "image")] @@ -86,15 +93,17 @@ pub enum HatchStyleKind { Gradient, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum HatchStyleLines { + #[default] #[serde(rename = "parallel")] Parallel, #[serde(rename = "random")] Random, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct HatchStyleImage { pub src: String, @@ -105,15 +114,17 @@ pub struct HatchStyleImage { pub rotation: f64, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum HatchStyleGradientType { + #[default] #[serde(rename = "linear")] Linear, #[serde(rename = "radial")] Radial, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct HatchStyleGradient { pub color1: String, @@ -122,8 +133,9 @@ pub struct HatchStyleGradient { pub r#type: HatchStyleGradientType, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum HatchPattern { + #[default] #[serde(rename = "none")] None, #[serde(rename = "solid")] @@ -138,14 +150,16 @@ pub enum HatchPattern { Custom, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct HatchStyleMotif { pub points: Vec, pub length: f64, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct HatchStyle { pub id: String, @@ -178,7 +192,8 @@ pub struct HatchStyle { pub motif: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ComponentMaterial { #[serde(rename = "libraryId", default, skip_serializing_if = "Option::is_none")] @@ -199,7 +214,8 @@ pub struct ComponentMaterial { pub size_m: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Component { pub id: String, @@ -229,7 +245,8 @@ pub struct Component { pub join_priority: f64, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Layer { #[serde(rename = "componentId")] @@ -239,7 +256,8 @@ pub struct Layer { pub joint_line_style_id: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct WallType { pub id: String, @@ -247,7 +265,8 @@ pub struct WallType { pub layers: Vec, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct CeilingType { pub id: String, @@ -255,7 +274,8 @@ pub struct CeilingType { pub layers: Vec, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct RoofType { pub id: String, @@ -263,7 +283,8 @@ pub struct RoofType { pub layers: Vec, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct BlockDef { pub id: String, @@ -271,8 +292,9 @@ pub struct BlockDef { pub geom2d: Vec, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum DoorTypeKind { + #[default] #[serde(rename = "dreh")] Dreh, #[serde(rename = "schiebe")] @@ -281,8 +303,9 @@ pub enum DoorTypeKind { Wandoeffnung, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum DoorTypeLeafStyle { + #[default] #[serde(rename = "glatt")] Glatt, #[serde(rename = "kassette")] @@ -291,16 +314,18 @@ pub enum DoorTypeLeafStyle { Glas, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum DoorTypeFrameKind { + #[default] #[serde(rename = "zarge")] Zarge, #[serde(rename = "blockrahmen")] Blockrahmen, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum FrameCornerJoin { + #[default] #[serde(rename = "vertikal")] Vertikal, #[serde(rename = "horizontal")] @@ -309,15 +334,17 @@ pub enum FrameCornerJoin { Gehrung, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum DoorTypeInsetFace { + #[default] #[serde(rename = "aussen")] Aussen, #[serde(rename = "innen")] Innen, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct DoorType { pub id: String, @@ -357,8 +384,9 @@ pub struct DoorType { pub threshold: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum OpeningKind { + #[default] #[serde(rename = "dreh")] Dreh, #[serde(rename = "kipp")] @@ -371,23 +399,26 @@ pub enum OpeningKind { Schiebe, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum SashDefKind { + #[default] #[serde(rename = "fluegel")] Fluegel, #[serde(rename = "pfosten")] Pfosten, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum SashDefHingeSide { + #[default] #[serde(rename = "left")] Left, #[serde(rename = "right")] Right, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct SashDef { pub kind: SashDefKind, @@ -403,8 +434,9 @@ pub struct SashDef { pub hinge_side: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum WindowShadingKind { + #[default] #[serde(rename = "rollladen")] Rollladen, #[serde(rename = "raffstore")] @@ -413,7 +445,8 @@ pub enum WindowShadingKind { Markise, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct WindowShadingBox { pub width: f64, @@ -421,7 +454,8 @@ pub struct WindowShadingBox { pub depth: f64, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct WindowShading { pub create: bool, @@ -429,8 +463,9 @@ pub struct WindowShading { pub r#box: WindowShadingBox, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum WindowTypeGlazing { + #[default] #[serde(rename = "einfach")] Einfach, #[serde(rename = "zweifach")] @@ -439,16 +474,18 @@ pub enum WindowTypeGlazing { Dreifach, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum WindowTypeInsetFace { + #[default] #[serde(rename = "aussen")] Aussen, #[serde(rename = "innen")] Innen, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum WindowTypeSillLineFaces { + #[default] #[serde(rename = "aussen")] Aussen, #[serde(rename = "innen")] @@ -457,23 +494,26 @@ pub enum WindowTypeSillLineFaces { Beide, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum WindowTypeSillLineView { + #[default] #[serde(rename = "auf")] Auf, #[serde(rename = "unter")] Unter, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct WindowTypeSillLine { pub faces: WindowTypeSillLineFaces, pub view: WindowTypeSillLineView, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum WindowTypeSillBoard { + #[default] #[serde(rename = "keine")] Keine, #[serde(rename = "innen")] @@ -484,7 +524,8 @@ pub enum WindowTypeSillBoard { Beide, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct WindowType { pub id: String, @@ -531,8 +572,9 @@ pub struct WindowType { pub sill_board: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum StairTypeStructure { + #[default] #[serde(rename = "massiv")] Massiv, #[serde(rename = "beton")] @@ -545,8 +587,9 @@ pub enum StairTypeStructure { Spindel, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum StairTypeRailing { + #[default] #[serde(rename = "keine")] Keine, #[serde(rename = "links")] @@ -557,7 +600,8 @@ pub enum StairTypeRailing { Beide, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct StairType { pub id: String, @@ -575,21 +619,24 @@ pub struct StairType { pub default_width: f64, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ColorPen { pub id: String, pub name: String, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct PenStyle { pub color: String, pub weight: f64, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct PenSet { pub id: String, @@ -597,7 +644,8 @@ pub struct PenSet { pub pens: std::collections::BTreeMap, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct CustomPalette { pub id: String, @@ -607,7 +655,8 @@ pub struct CustomPalette { pub visible: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct BuiltinPaletteBanks { #[serde(default, skip_serializing_if = "Option::is_none")] @@ -620,8 +669,9 @@ pub struct BuiltinPaletteBanks { pub ral: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum DrawingLevelKind { + #[default] #[serde(rename = "floor")] Floor, #[serde(rename = "section")] @@ -632,7 +682,8 @@ pub enum DrawingLevelKind { Drawing, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct DrawingLevel { pub id: String, @@ -662,8 +713,9 @@ pub struct DrawingLevel { pub level_marks: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum SiaCategory { + #[default] #[serde(rename = "HNF")] HNF, #[serde(rename = "NNF")] @@ -678,7 +730,8 @@ pub enum SiaCategory { AGF, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct RoomProgramRow { pub name: String, @@ -689,21 +742,24 @@ pub struct RoomProgramRow { pub count: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct SunStudy { pub when: String, pub show: bool, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct SiteRulesBuildingLines { pub a: Vec2, pub b: Vec2, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct SiteRules { pub parcel: Vec, @@ -719,7 +775,8 @@ pub struct SiteRules { pub show: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct LayerCategory { pub code: String, @@ -736,16 +793,18 @@ pub struct LayerCategory { pub children: Option>, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum AttributeSource { + #[default] #[serde(rename = "layer")] Layer, #[serde(rename = "object")] Object, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum WallReferenceLine { + #[default] #[serde(rename = "left")] Left, #[serde(rename = "center")] @@ -754,8 +813,9 @@ pub enum WallReferenceLine { Right, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum SliceTermination { + #[default] #[serde(rename = "both")] Both, #[serde(rename = "below")] @@ -764,7 +824,8 @@ pub enum SliceTermination { Above, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Wall { pub id: String, @@ -816,7 +877,8 @@ pub struct Wall { pub slice_termination: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Ceiling { pub id: String, @@ -866,8 +928,9 @@ pub struct Ceiling { pub bottom: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum RoofShape { + #[default] #[serde(rename = "flach")] Flach, #[serde(rename = "pult")] @@ -882,8 +945,9 @@ pub enum RoofShape { Zelt, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum RoofMansardType { + #[default] #[serde(rename = "giebel")] Giebel, #[serde(rename = "walm")] @@ -892,15 +956,17 @@ pub enum RoofMansardType { Zelt, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum RoofRidgeAxis { + #[default] #[serde(rename = "x")] X, #[serde(rename = "y")] Y, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Roof { pub id: String, @@ -939,48 +1005,54 @@ pub struct Roof { pub color_pen_id: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum ElementKind { + #[default] #[serde(rename = "window")] Window, #[serde(rename = "door")] Door, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum OpeningDoorType { + #[default] #[serde(rename = "normal")] Normal, #[serde(rename = "wandoeffnung")] Wandoeffnung, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum OpeningHinge { + #[default] #[serde(rename = "start")] Start, #[serde(rename = "end")] End, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum SwingSide { + #[default] #[serde(rename = "left")] Left, #[serde(rename = "right")] Right, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum OpeningOpeningDir { + #[default] #[serde(rename = "in")] In, #[serde(rename = "out")] Out, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum OpeningLintelLines { + #[default] #[serde(rename = "keine")] Keine, #[serde(rename = "innen")] @@ -991,8 +1063,9 @@ pub enum OpeningLintelLines { Beide, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum DetailLevel { + #[default] #[serde(rename = "grob")] Grob, #[serde(rename = "mittel")] @@ -1001,7 +1074,8 @@ pub enum DetailLevel { Fein, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct LineStyleOverride { #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1010,7 +1084,8 @@ pub struct LineStyleOverride { pub weight: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Opening { pub id: String, @@ -1061,8 +1136,9 @@ pub struct Opening { pub sill_line_style: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum StairShape { + #[default] #[serde(rename = "straight")] Straight, #[serde(rename = "L")] @@ -1071,8 +1147,9 @@ pub enum StairShape { Spiral, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum StairReferenz { + #[default] #[serde(rename = "links")] Links, #[serde(rename = "mitte")] @@ -1081,15 +1158,17 @@ pub enum StairReferenz { Rechts, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum StairArrowStyle { + #[default] #[serde(rename = "line")] Line, #[serde(rename = "filled")] Filled, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Stair { pub id: String, @@ -1136,15 +1215,17 @@ pub struct Stair { pub arrow_style: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct TextRun { pub text: String, pub marks: Marks, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum Align { + #[default] #[serde(rename = "left")] Left, #[serde(rename = "center")] @@ -1153,7 +1234,8 @@ pub enum Align { Right, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Paragraph { pub runs: Vec, @@ -1163,14 +1245,16 @@ pub struct Paragraph { pub line_height: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct RichTextDoc { pub version: f64, pub paragraphs: Vec, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct RoomStamp { #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1198,7 +1282,8 @@ pub struct RoomStamp { pub rounding_step: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Room { pub id: String, @@ -1224,8 +1309,9 @@ pub struct Room { pub stamp: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum EndMark { + #[default] #[serde(rename = "none")] None, #[serde(rename = "arrow")] @@ -1240,7 +1326,8 @@ pub enum EndMark { Square, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Drawing2DEndMarks { #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1251,7 +1338,8 @@ pub struct Drawing2DEndMarks { pub size_mm: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Drawing2D { pub id: String, @@ -1309,14 +1397,16 @@ pub struct Drawing2D { pub hatch_source: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ExtrudedSolidCircle { pub center: Vec2, pub r: f64, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ExtrudedSolidBrep { pub spec: std::collections::BTreeMap, @@ -1325,7 +1415,8 @@ pub struct ExtrudedSolidBrep { pub label: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ExtrudedSolid { pub id: String, @@ -1350,7 +1441,8 @@ pub struct ExtrudedSolid { pub brep: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Column { pub id: String, @@ -1397,7 +1489,8 @@ pub struct Column { pub hatch_source: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Group { pub id: String, @@ -1423,7 +1516,8 @@ pub struct Group { pub group_ids: Vec, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ParametricWall { pub id: String, @@ -1435,16 +1529,18 @@ pub struct ParametricWall { pub default_wall_type_id: String, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum OverrideConditionType { + #[default] #[serde(rename = "layer_name")] LayerName, #[serde(rename = "object_name")] ObjectName, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum OverrideOperator { + #[default] #[serde(rename = "equals")] Equals, #[serde(rename = "contains")] @@ -1455,7 +1551,8 @@ pub enum OverrideOperator { NotEquals, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct OverrideCondition { pub r#type: OverrideConditionType, @@ -1463,7 +1560,8 @@ pub struct OverrideCondition { pub value: String, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct OverrideActions { #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1474,7 +1572,8 @@ pub struct OverrideActions { pub linetype_id: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct OverrideRule { pub id: String, @@ -1484,16 +1583,18 @@ pub struct OverrideRule { pub actions: OverrideActions, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum ViewType { + #[default] #[serde(rename = "grundriss")] Grundriss, #[serde(rename = "perspektive")] Perspektive, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum View3d { + #[default] #[serde(rename = "front")] Front, #[serde(rename = "back")] @@ -1516,7 +1617,8 @@ pub enum View3d { Perspective, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ViewSnapshot { pub id: String, @@ -1547,7 +1649,8 @@ pub struct ViewSnapshot { pub camera_px_per_meter: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ViewSnapshotFolder { pub id: String, @@ -1556,8 +1659,9 @@ pub struct ViewSnapshotFolder { pub parent_id: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum LayoutPaperFormat { + #[default] #[serde(rename = "a0")] A0, #[serde(rename = "a1")] @@ -1588,15 +1692,17 @@ pub enum LayoutPaperFormat { B6, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum LayoutOrientation { + #[default] #[serde(rename = "portrait")] Portrait, #[serde(rename = "landscape")] Landscape, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct LayoutViewport { pub id: String, @@ -1614,7 +1720,8 @@ pub struct LayoutViewport { pub scale_denominator: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Layout { pub id: String, @@ -1636,7 +1743,8 @@ pub struct Layout { pub annotations: Option>, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct LayoutTitleBlock { #[serde(rename = "projectName", default, skip_serializing_if = "Option::is_none")] @@ -1651,7 +1759,8 @@ pub struct LayoutTitleBlock { pub author: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct MasterLayout { pub id: String, @@ -1670,15 +1779,17 @@ pub struct MasterLayout { pub custom_height_mm: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum LayoutFolderKind { + #[default] #[serde(rename = "layout")] Layout, #[serde(rename = "master")] Master, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct LayoutFolder { pub id: String, @@ -1689,14 +1800,16 @@ pub struct LayoutFolder { pub kind: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ProjectGeoAnchorLv95 { pub e: f64, pub n: f64, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ProjectGeoAnchor { pub lv95: ProjectGeoAnchorLv95, @@ -1707,7 +1820,8 @@ pub struct ProjectGeoAnchor { pub label: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Project { #[serde(rename = "formatVersion", default, skip_serializing_if = "Option::is_none")] @@ -1797,8 +1911,9 @@ pub struct Project { pub geo_anchor: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum GridRuleDirections { + #[default] #[serde(rename = "x")] X, #[serde(rename = "y")] @@ -1807,7 +1922,8 @@ pub enum GridRuleDirections { Both, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct GridRule { #[serde(rename = "gridId", default, skip_serializing_if = "Option::is_none")] @@ -1825,15 +1941,17 @@ pub struct GridRule { pub height: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum ModuleRuleDirection { + #[default] #[serde(rename = "x")] X, #[serde(rename = "y")] Y, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ModuleRule { #[serde(rename = "moduleSize")] @@ -1849,15 +1967,17 @@ pub struct ModuleRule { pub height: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum ConditionalThicknessRuleLogic { + #[default] #[serde(rename = "and")] And, #[serde(rename = "or")] Or, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ConditionalThicknessRule { pub condition: serde_json::Value, @@ -1867,7 +1987,8 @@ pub struct ConditionalThicknessRule { pub logic: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ReferenceLineRule { #[serde(rename = "referenceLine")] @@ -1875,7 +1996,8 @@ pub struct ReferenceLineRule { pub target: serde_json::Value, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct SequenceRule { pub rules: Vec, @@ -1883,7 +2005,8 @@ pub struct SequenceRule { pub stop_on_match: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ImportedMesh { pub id: String, @@ -1896,15 +2019,17 @@ pub struct ImportedMesh { pub indices: Vec, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub enum ContourCurveKind { + #[default] #[serde(rename = "circle")] Circle, #[serde(rename = "arc")] Arc, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ContourCurve { pub kind: ContourCurveKind, @@ -1915,7 +2040,8 @@ pub struct ContourCurve { pub a1: f64, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Contour { pub z: f64, @@ -1929,7 +2055,8 @@ pub struct Contour { pub curve: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ContourSet { pub id: String, @@ -1941,7 +2068,8 @@ pub struct ContourSet { pub contours: Vec, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct TerrainMesh { pub id: String, @@ -1956,7 +2084,8 @@ pub struct TerrainMesh { pub vertex_colors: Option>, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ContextImageFilters { #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1969,7 +2098,8 @@ pub struct ContextImageFilters { pub grayscale: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(default)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct ContextImage { pub id: String, diff --git a/src-tauri/core/src/model/manual.rs b/src-tauri/core/src/model/manual.rs index 0ca1631e..1d94d384 100644 --- a/src-tauri/core/src/model/manual.rs +++ b/src-tauri/core/src/model/manual.rs @@ -271,3 +271,15 @@ pub enum ContextObject { #[serde(rename = "image")] Image(ContextImage), } + +impl Default for Drawing2DGeom { + fn default() -> Self { + Drawing2DGeom::Pointmarker { at: Vec2::default() } + } +} + +impl Default for ColumnProfile { + fn default() -> Self { + ColumnProfile::Rect { width: 0.0, depth: 0.0 } + } +} diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index b27d9daf..051a7a04 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -244,6 +244,11 @@ pub struct RWall { /// Textur-Karten-URLs der Bauteile in der Reihenfolge des ersten Auftretens: Wandtypen, dann /// Decken, dann Dächer (`wallMaterialColorMaps`). pub fn wall_material_color_maps(p: &Project) -> Vec { + material_color_maps(p, None) +} + +/// Wie [`wall_material_color_maps`]; `only_roof` beschränkt die Dächer auf eines (IFC-Export). +pub fn material_color_maps(p: &Project, only_roof: Option<&str>) -> Vec { let mut seen = std::collections::HashSet::new(); let mut list = Vec::new(); let mut consider = |id: &str| { @@ -267,7 +272,7 @@ pub fn wall_material_color_maps(p: &Project) -> Vec { } } } - for r in p.roofs.as_deref().unwrap_or(&[]) { + for r in p.roofs.as_deref().unwrap_or(&[]).iter().filter(|r| only_roof.is_none_or(|id| r.id == id)) { for l in p.roof_layers(r) { if !l.component_id.is_empty() { consider(&l.component_id); @@ -990,10 +995,10 @@ fn roof_color(p: &Project, override_color: Option, component_id: &str) -> R } /// Dächer als geschlossene, geschichtete Dreiecks-Meshes (`emitRoofs`). -pub fn emit_roofs(p: &Project) -> Result, String> { - let maps = wall_material_color_maps(p); +pub fn emit_roofs(p: &Project, only_roof: Option<&str>) -> Result, String> { + let maps = material_color_maps(p, only_roof); let mut out = Vec::new(); - for roof in p.roofs.as_deref().unwrap_or(&[]) { + for roof in p.roofs.as_deref().unwrap_or(&[]).iter().filter(|r| only_roof.is_none_or(|id| r.id == id)) { let eaves_z = p.roof_base_elevation(roof); let g = crate::roof::roof_geometry(&roof.params(), eaves_z); let override_color = roof.color.as_deref().filter(|c| !c.is_empty()).map(|c| hex_to_rgb(c, ROOF_RGB)); @@ -1051,10 +1056,112 @@ pub fn emit_roof_cut_layers(p: &Project) -> Result, String> { Ok(out) } +// ── Kontext und Bündel ────────────────────────────────────────────────────── + +const TERRAIN_RGB: Rgb = [169.0 / 255.0, 176.0 / 255.0, 162.0 / 255.0]; +const IMPORTED_RGB: Rgb = [159.0 / 255.0, 166.0 / 255.0, 174.0 / 255.0]; + +fn indices_u32(v: &[f64]) -> Vec { + v.iter().map(|&i| i as u32).collect() +} + +/// Rohe Kontext-Meshes: Gelände-TIN und importierte Volumen (`emitMeshes`). +pub fn emit_context_meshes(p: &Project) -> Vec { + let mut out = Vec::new(); + for obj in p.context.as_deref().unwrap_or(&[]) { + match obj { + ContextObject::TerrainMesh(m) if m.positions.len() >= 9 && m.indices.len() >= 3 => out.push(RMesh { + positions: m.positions.clone(), + indices: indices_u32(&m.indices), + kind: "terrain", + color: TERRAIN_RGB, + vertex_colors: m.vertex_colors.clone().filter(|v| !v.is_empty()), + material_index: None, + }), + ContextObject::ImportedMesh(m) if m.positions.len() >= 9 && m.indices.len() >= 3 => out.push(RMesh { + positions: m.positions.clone(), + indices: indices_u32(&m.indices), + kind: "imported", + color: IMPORTED_RGB, + vertex_colors: None, + material_index: None, + }), + _ => {} + } + } + out +} + +/// Das 3D-Modell in Teilen: TS fügt die truck-Körper (asynchron) zwischen Kontext und Stützen ein. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Parts { + pub walls: Vec, + pub slabs: Vec, + pub context_meshes: Vec, + pub column_meshes: Vec, + pub opening_meshes: Vec, + pub stair_meshes: Vec, + pub stair_railings: Vec, + pub roof_meshes: Vec, + pub roof_layers: Vec, +} + +/// `detail`: 0 grob, 1 mittel, 2 fein. +pub fn parts(p: &Project, layered: bool, detail: f64, for_section: bool) -> Result { + let mut slabs = emit_slabs(p); + slabs.extend(emit_stairs(p, for_section)); + Ok(Parts { + walls: emit_walls(p, layered)?, + slabs, + context_meshes: emit_context_meshes(p), + column_meshes: emit_columns(p), + opening_meshes: emit_opening_meshes(p, detail), + stair_meshes: emit_stair_meshes(p), + stair_railings: emit_stair_railings(p), + roof_meshes: emit_roofs(p, None)?, + roof_layers: emit_roof_cut_layers(p)?, + }) +} + #[cfg(test)] mod tests { use super::*; + /// Walmdach 12×7 m: zwei Trapeze + zwei Walm-Dreiecke, First (3,3)-(8,3). + fn walm_planes() -> Vec> { + vec![ + vec![[-0.5, -0.5, 5.2], [11.5, -0.5, 5.2], [8.0, 3.0, 7.061], [3.0, 3.0, 7.061]], + vec![[-0.5, 6.5, 5.2], [11.5, 6.5, 5.2], [8.0, 3.0, 7.061], [3.0, 3.0, 7.061]], + vec![[-0.5, -0.5, 5.2], [-0.5, 6.5, 5.2], [3.0, 3.0, 7.061]], + vec![[11.5, -0.5, 5.2], [11.5, 6.5, 5.2], [8.0, 3.0, 7.061]], + ] + } + + fn near(a: V3, b: V3) -> bool { + hypot(&[a[0] - b[0], a[1] - b[1], a[2] - b[2]]) < 1e-6 + } + + #[test] + fn gehrung_erkennt_first_und_grate_als_geteilt() { + let planes = walm_planes(); + let m = Mitre::new(&planes); + assert_eq!(m.shared[0], vec![false, true, true, true]); // Traufe, Grat, First, Grat + assert_eq!(m.shared[2], vec![false, true, true]); + } + + #[test] + fn unterseiten_treffen_sich_am_first_apex() { + let planes = walm_planes(); + let m = Mitre::new(&planes); + let d = 0.27; + let (a, b, c) = (m.at(0, d)[3], m.at(1, d)[3], m.at(2, d)[2]); + assert!(near(a, b) && near(a, c)); + assert!(a[2] < 7.061); + assert_eq!(m.at(0, 0.0), planes[0]); + assert!(m.at(0, 0.2)[0][2] < 5.2); + } + #[test] fn beispielprojekt_hat_decken_und_gueltige_farben() { let p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap(); diff --git a/src-tauri/core/src/openings3d.rs b/src-tauri/core/src/openings3d.rs index 3acba463..31eef1fa 100644 --- a/src-tauri/core/src/openings3d.rs +++ b/src-tauri/core/src/openings3d.rs @@ -1005,23 +1005,6 @@ pub fn opening_meshes_flat(buf: &[f64]) -> Vec { out } -/// Flache Bindung von [`frame_ring_quads`]: `[n, (u, h) × 4 …]`; Eckstoss wie oben. -pub fn frame_ring_quads_flat(from: f64, to: f64, z_b: f64, z_t: f64, w: f64, join: f64, bottom: bool) -> Vec { - let join = match join as i64 { - 1 => CornerJoin::Horizontal, - 2 => CornerJoin::Mitre, - _ => CornerJoin::Vertical, - }; - let qs = frame_ring_quads(from, to, z_b, z_t, w, join, bottom); - let mut out = vec![qs.len() as f64]; - for q in qs { - for [u, h] in q { - out.push(u); - out.push(h); - } - } - out -} #[cfg(test)] mod tests { @@ -1220,9 +1203,9 @@ mod tests { assert_eq!(out.len(), 1 + 25); assert_eq!(out[0], 1.0); assert_eq!(out[1], Part::Glass as i32 as f64); - let ring = frame_ring_quads_flat(0.0, 1.0, 0.0, 1.0, 0.1, 0.0, true); - assert_eq!(ring[0], 4.0); - assert_eq!(&ring[1..9], &[0.0, 0.0, 0.1, 0.0, 0.0, 1.0, 0.1, 1.0]); + let ring = frame_ring_quads(0.0, 1.0, 0.0, 1.0, 0.1, CornerJoin::Vertical, true); + assert_eq!(ring.len(), 4); + assert_eq!(ring[0], [[0.0, 0.0], [0.1, 0.0], [0.0, 1.0], [0.1, 1.0]]); } #[test] @@ -1241,6 +1224,6 @@ mod tests { let mut big = vec![2.0, 1.0, 0.0, 0.0, 5.0, 0.0, 1.0, 1.0, 4.0, 0.0, 2.0, 1.0, 0.3, 1.0]; big.extend([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1e12, 2.0, f64::NAN, 1.0, 1e12, 1e12]); assert!(opening_meshes_flat(&big)[0] >= 0.0); - let _ = frame_ring_quads_flat(f64::NAN, f64::INFINITY, -1.0, 1.0, -3.0, 9.0, false); + let _ = frame_ring_quads(f64::NAN, f64::INFINITY, -1.0, 1.0, -3.0, CornerJoin::Mitre, false); } } diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs new file mode 100644 index 00000000..0f26f366 --- /dev/null +++ b/src-tauri/core/src/queries.rs @@ -0,0 +1,32 @@ +//! Abfragen auf dem Projekt-Dokument ([K4] S2): eine Tabelle von Name → Rechnung, die als JSON +//! antwortet. TS ruft sie über `ProjectDocument.query(name, args, text)`. + +use crate::model::Project; +use crate::{kennzahlen, model3d, site_rules, sun}; + +fn json(v: &T) -> Result { + serde_json::to_string(v).map_err(|e| e.to_string()) +} + +/// Führt die Abfrage `name` aus. `args`: Zahlen, `text`: ein Text (z. B. eine id). +pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result { + match (name, args.len()) { + ("kennzahlen", _) => json(&kennzahlen::compute(p)), + ("siteCheck", _) => json(&site_rules::check_project(p)), + ("buildingFootprint", _) => json(&site_rules::building_footprint(p)), + ("modelTop", _) => json(&site_rules::model_top(p)), + ("shadows", 2) => json(&site_rules::area_out(&sun::shadow_polygons_project(p, sun::SunPosition { azimuth: args[0], elevation: args[1] }))), + ("materialMaps", _) => json(&model3d::wall_material_color_maps(p)), + ("slabs", _) => json(&model3d::emit_slabs(p)), + ("columnMeshes", _) => json(&model3d::emit_columns(p)), + ("walls", 1) => json(&model3d::emit_walls(p, args[0] != 0.0)?), + ("openingMeshes", 1) => json(&model3d::emit_opening_meshes(p, args[0])), + ("stairSlabs", 1) => json(&model3d::emit_stairs(p, args[0] != 0.0)), + ("stairMeshes", _) => json(&model3d::emit_stair_meshes(p)), + ("stairRailings", _) => json(&model3d::emit_stair_railings(p)), + ("roofMeshes", _) => json(&model3d::emit_roofs(p, if text.is_empty() { None } else { Some(text) })?), + ("roofCutLayers", _) => json(&model3d::emit_roof_cut_layers(p)?), + ("model3dParts", 3) => json(&model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?), + _ => Err(format!("Unbekannte Abfrage: {name}")), + } +} diff --git a/src-tauri/core/src/stairs3d.rs b/src-tauri/core/src/stairs3d.rs index dafa48e3..b933d3db 100644 --- a/src-tauri/core/src/stairs3d.rs +++ b/src-tauri/core/src/stairs3d.rs @@ -491,16 +491,6 @@ pub fn railings(buf: &[f64]) -> Vec { out } -pub fn encode_slabs(slabs: &[Slab]) -> Vec { - let mut out = vec![slabs.len() as f64]; - for s in slabs { - out.extend([s.src as f64, if s.monolith { 1.0 } else { 0.0 }, s.z_bottom, s.z_top, s.pts.len() as f64]); - for p in &s.pts { - out.extend(*p); - } - } - out -} #[cfg(test)] mod tests { diff --git a/src-tauri/core/src/wall_bands.rs b/src-tauri/core/src/wall_bands.rs index f3add672..70fa644f 100644 --- a/src-tauri/core/src/wall_bands.rs +++ b/src-tauri/core/src/wall_bands.rs @@ -640,160 +640,6 @@ fn emit_band_piece(em: &mut Emitter, li: usize, off: f64, cutouts: &[OpeningIn], em.push(li, a, bb, zb, zt, off, holes, [zt - zt_start, zt - zt_end]); } -// ── Flache Kodierung ───────────────────────────────────────────────────────── -// -// Geschosse: [nGeschosse, (nDecken, (zBottom, zTop, nPkt, (x, y)…, typOk, nSchichten, -// (dicke, prio|NaN)…)…, nDächer, (traufZ, schichtdicke, nPkt, (x, y)…, nFlächen, -// (m, (x, y, z)…)…)…)…] -// Wände: [nWände, (geschoss, sx, sy, ex, ey, zBottom, zTop, layered, stacked, refKind, refValue, -// dickeHülle, terminierung (0 beide, 1 unten, 2 oben), nBänder, (dicke, prio|NaN)…, -// nÖffnungen, (from, to, zBottom, zTop, rücksprung)…, )…] -// geschoss: Index in die Geschosse (ausserhalb = ohne Decken/Dächer). -// Ausgabe: [nWände, (nKörper, (band, x1, y1, x2, y2, zBottom, zTop, schräg 0/1, drop0, drop1, -// nLöcher, (from, to, zBottom, zTop)…)…)…] — nWände < Eingabe, wenn der Puffer mittendrin -// kaputt ist; eine Wand mit ungültigen Werten (NaN …) hat keine Körper. - -use crate::flat_read::Reader; - -fn fin(v: &[f64]) -> bool { - v.iter().all(|x| x.is_finite()) -} - -/// Liest die Decken und Dächer eines Geschosses; einzelne ungültige fallen weg. -fn decode_context(r: &mut Reader) -> Option { - let nc = r.count()?; - let mut ceilings = Vec::with_capacity(nc.min(1 << 12)); - for _ in 0..nc { - let (czb, czt) = (r.num()?, r.num()?); - let outline = r.ring()?; - let type_ok = r.num()? != 0.0; - let nl = r.count()?; - let mut layers = Vec::with_capacity(nl.min(1 << 10)); - let mut ok = fin(&[czb, czt]) && outline.iter().all(|p| fin(p)); - for _ in 0..nl { - let (t, p) = (r.num()?, r.num()?); - ok &= t.is_finite() && !p.is_infinite(); - layers.push((t, (!p.is_nan()).then_some(p))); - } - if ok { - let outline = outline.into_iter().map(|p| Vec2::new(p[0], p[1])).collect(); - ceilings.push(CeilingIn { z_bottom: czb, z_top: czt, outline, layers: type_ok.then_some(layers) }); - } - } - let nr = r.count()?; - let mut roofs = Vec::with_capacity(nr.min(1 << 12)); - for _ in 0..nr { - let (ez, total) = (r.num()?, r.num()?); - let eaves = r.ring()?; - let np = r.count()?; - let mut planes = Vec::with_capacity(np.min(1 << 12)); - for _ in 0..np { - let m = r.count()?; - planes.push(r.points3(m)?); - } - if fin(&[ez, total]) && eaves.iter().all(|p| fin(p)) && planes.iter().flatten().all(|p| fin(p)) { - roofs.push(RoofIn { eaves_z: ez, total_thickness: total, eaves, planes }); - } - } - Some(FloorContext::new(ceilings, roofs)) -} - -/// Liest eine Wand: `None` = Puffer kaputt (Abbruch), `Some((geschoss, None))` = Werte ungültig. -fn decode_wall(r: &mut Reader) -> Option<(f64, Option)> { - let floor = r.num()?; - let (sx, sy, ex, ey, zb, zt) = (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?); - let (layered, stacked, kind, value, thick, term) = (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?); - let mut ok = fin(&[sx, sy, ex, ey, zb, zt, thick]); - let reference = match kind as i64 { - 1 => Reference::Left, - 2 => Reference::Right, - 3 => { - ok &= value.is_finite(); - Reference::Offset(value) - } - _ => Reference::Center, - }; - let termination = match term as i64 { - 1 => Termination::Below, - 2 => Termination::Above, - _ => Termination::Both, - }; - let nb = r.count()?; - let mut bands = Vec::with_capacity(nb.min(1 << 10)); - for _ in 0..nb { - let (t, p) = (r.num()?, r.num()?); - ok &= t.is_finite() && !p.is_infinite(); - bands.push(BandIn { thickness: t, priority: (!p.is_nan()).then_some(p) }); - } - let no = r.count()?; - let mut openings = Vec::with_capacity(no.min(1 << 12)); - for _ in 0..no { - let o = [r.num()?, r.num()?, r.num()?, r.num()?]; - let recess = r.num()? != 0.0; - ok &= fin(&o); - openings.push(OpeningIn { from: o[0], to: o[1], z_bottom: o[2], z_top: o[3], recess_inner_layer: recess }); - } - let cuts = crate::joins::decode_cuts(r)?; - let wall = WallIn { - start: Vec2::new(sx, sy), - end: Vec2::new(ex, ey), - z_bottom: zb, - z_top: zt, - layered: layered != 0.0, - stacked: stacked != 0.0, - reference, - thickness_safe: thick, - termination, - bands, - openings, - cuts, - }; - Some((floor, ok.then_some(wall))) -} - -fn encode_pieces(out: &mut Vec, pieces: &[Piece]) { - out.push(pieces.len() as f64); - for p in pieces { - out.extend([p.band as f64, p.start.x, p.start.y, p.end.x, p.end.y, p.z_bottom, p.z_top]); - match p.top_drop { - Some([d0, d1]) => out.extend([1.0, d0, d1]), - None => out.extend([0.0, 0.0, 0.0]), - } - out.push(p.holes.len() as f64); - for h in &p.holes { - out.extend(h); - } - } -} - -/// Wände + Geschosse flach → Körper je Wand flach (s. Kodierung oben); nie ein Panic. -pub fn wall_bands_flat(walls: &[f64], floors: &[f64]) -> Vec { - let mut fr = Reader::new(floors); - let mut contexts = Vec::new(); - if let Some(n) = fr.count() { - for _ in 0..n { - match decode_context(&mut fr) { - Some(c) => contexts.push(c), - None => break, - } - } - } - let empty = FloorContext::default(); - let mut out = vec![0.0]; - let mut r = Reader::new(walls); - let Some(n) = r.count() else { return out }; - let mut done = 0usize; - for _ in 0..n { - let Some((floor, wall)) = decode_wall(&mut r) else { break }; - let ctx = if floor >= 0.0 && floor.fract() == 0.0 { contexts.get(floor as usize).unwrap_or(&empty) } else { &empty }; - let pieces = wall.map(|w| wall_bands(&w, ctx)).unwrap_or_default(); - encode_pieces(&mut out, &pieces); - done += 1; - } - out[0] = done as f64; - out -} - #[cfg(test)] mod tests { use super::*; @@ -929,9 +775,6 @@ mod tests { #[test] fn unsinn_ohne_panic() { - assert_eq!(wall_bands_flat(&[], &[]), vec![0.0]); - assert_eq!(wall_bands_flat(&[f64::NAN; 40], &[f64::NAN]), vec![0.0]); - assert_eq!(wall_bands_flat(&[0.0; 3], &[1.0, 5.0]), vec![0.0]); // Nulllänge, umgekehrte Höhen, Öffnung ausserhalb, Bänder ohne Dicke, entartete Decke/Dach. let mut w = base((1.0, 1.0), (1.0, 1.0), vec![band(0.2, 50.0)]); assert!(bands_of(&w).is_empty()); @@ -947,23 +790,5 @@ mod tests { ); let _ = wall_bands(&w, &ctx); - // Flach: zwei Wände (die zweite mit NaN-Koordinate → keine Körper), ein Geschoss. - let wall = |x: f64| { - let mut b = vec![0.0, x, 1.0, 2.0, 1.0, 0.0, 2.0, 1.0, 1.0, 0.0, 0.0, 0.2, 0.0, 1.0, 0.2, 50.0, 0.0]; - crate::joins::encode_cuts(&mut b, &WallCuts::default()); - b - }; - let mut buf = vec![2.0]; - buf.extend(wall(1.0)); - buf.extend(wall(f64::NAN)); - let floors = [1.0, 0.0, 0.0]; - let out = wall_bands_flat(&buf, &floors); - assert_eq!(out[0], 2.0); - assert_eq!(out[1], 1.0); // ein Körper - assert_eq!(*out.last().unwrap(), 0.0); // zweite Wand: keine Körper - // Abgeschnittener Puffer: nur die vollständige erste Wand. - assert_eq!(wall_bands_flat(&buf[..buf.len() - 1], &floors)[0], 1.0); - // Kaputte Geschosse: Wände ohne Decken/Dächer. - assert_eq!(wall_bands_flat(&buf, &[3.0, 1.0])[0], 2.0); } } diff --git a/src-tauri/core/src/web/ceilings3d.rs b/src-tauri/core/src/web/ceilings3d.rs deleted file mode 100644 index 44c4dd7a..00000000 --- a/src-tauri/core/src/web/ceilings3d.rs +++ /dev/null @@ -1,10 +0,0 @@ -//! Bindung der Decken im 3D (`crate::ceilings3d`). Kodierung s. dort. - -use crate::ceilings3d as c; -use wasm_bindgen::prelude::wasm_bindgen; - -/// Deckenumrisse (mit eingefügten Aussparungen) und Schicht-z-Spannen; Unsinn → leer. -#[wasm_bindgen] -pub fn ceilings3d_flat(ceilings: &[f64]) -> Vec { - c::encode(&c::ceilings(ceilings)) -} diff --git a/src-tauri/core/src/web/columns3d.rs b/src-tauri/core/src/web/columns3d.rs deleted file mode 100644 index 23393fd2..00000000 --- a/src-tauri/core/src/web/columns3d.rs +++ /dev/null @@ -1,11 +0,0 @@ -//! Bindung der Stützen im 3D (`crate::columns3d`). Kodierung s. dort. - -use crate::columns3d as c; -use crate::mesh3d::encode_meshes; -use wasm_bindgen::prelude::wasm_bindgen; - -/// Prisma-Meshes aller Stützen aus Querschnitt und Höhen; Unsinn → leer. -#[wasm_bindgen] -pub fn columns3d_flat(columns: &[f64]) -> Vec { - encode_meshes(&c::columns(columns)) -} diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index 514f9a41..6dcd4355 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -62,44 +62,24 @@ pub fn doc_json(h: u32) -> String { with_doc(h, |d| d.to_json()).unwrap_or_default() } -/// Abfrage auf dem typisierten Projekt; Ergebnis als JSON, leer bei Fehler (Dokument nicht offen, -/// Modell passt nicht, unbekannte Abfrage). Abfragen: `kennzahlen`, `siteCheck` (`null` ohne -/// Baurecht), `buildingFootprint`, `modelTop` (`null` ohne Bauteile). +/// Abfrage auf dem typisierten Projekt; Ergebnis als JSON. Fehler (Dokument nicht offen, Modell +/// passt nicht, unbekannte Abfrage, Rechenfehler) kommen als Text mit vorangestelltem `\u{1}`. +/// Abfragen s. `crate::queries`. #[wasm_bindgen] pub fn doc_query(h: u32, name: &str) -> String { - doc_query_args(h, name, &[]) + doc_query_args(h, name, &[], "") } -/// Wie [`doc_query`] mit Zahlenargumenten. `shadows`: `[azimut, höhe]` → vereinigter Boden-Schatten. +/// Wie [`doc_query`] mit Zahlen- und Textargument. #[wasm_bindgen] -pub fn doc_query_args(h: u32, name: &str, args: &[f64]) -> String { - use crate::{kennzahlen, site_rules, sun}; - let args = args.to_vec(); - let name = name.to_owned(); - with_doc(h, move |d| { - let p = d.project().ok()?; - let json = match name.as_str() { - "kennzahlen" => serde_json::to_string(&kennzahlen::compute(&p)), - "siteCheck" => serde_json::to_string(&site_rules::check_project(&p)), - "buildingFootprint" => serde_json::to_string(&site_rules::building_footprint(&p)), - "modelTop" => serde_json::to_string(&site_rules::model_top(&p)), - "walls" if args.len() == 1 => crate::model3d::emit_walls(&p, args[0] != 0.0).map_err(|_| ()).and_then(|w| serde_json::to_string(&w).map_err(|_| ())).map_err(|_| serde_json::Error::io(std::io::Error::other("walls"))), - "openingMeshes" if args.len() == 1 => serde_json::to_string(&crate::model3d::emit_opening_meshes(&p, args[0])), - "stairSlabs" if args.len() == 1 => serde_json::to_string(&crate::model3d::emit_stairs(&p, args[0] != 0.0)), - "stairMeshes" => serde_json::to_string(&crate::model3d::emit_stair_meshes(&p)), - "stairRailings" => serde_json::to_string(&crate::model3d::emit_stair_railings(&p)), - "roofMeshes" => crate::model3d::emit_roofs(&p).map_err(|e| serde_json::Error::io(std::io::Error::other(e))).and_then(|v| serde_json::to_string(&v)), - "roofCutLayers" => crate::model3d::emit_roof_cut_layers(&p).map_err(|e| serde_json::Error::io(std::io::Error::other(e))).and_then(|v| serde_json::to_string(&v)), - "slabs" => serde_json::to_string(&crate::model3d::emit_slabs(&p)), - "columnMeshes" => serde_json::to_string(&crate::model3d::emit_columns(&p)), - "shadows" if args.len() == 2 => { - let polys = sun::shadow_polygons_project(&p, sun::SunPosition { azimuth: args[0], elevation: args[1] }); - serde_json::to_string(&site_rules::area_out(&polys)) - } - _ => return None, - }; - json.ok() +pub fn doc_query_args(h: u32, name: &str, args: &[f64], text: &str) -> String { + let result = with_doc(h, |d| { + let p = d.project().map_err(|e| format!("Projekt passt nicht zum Kern-Modell: {e}"))?; + crate::queries::run(&p, name, args, text) }) - .flatten() - .unwrap_or_default() + .unwrap_or_else(|| Err("Dokument nicht offen".to_string())); + match result { + Ok(json) => json, + Err(e) => format!("\u{1}{e}"), + } } diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index d05dd9e1..bf98c8a3 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -13,15 +13,10 @@ mod kennzahlen; mod bulge; mod stair; mod joins; -mod wall_bands; mod room_area; mod room_boundary; mod polygon_holes; -mod stairs3d; -mod ceilings3d; -mod columns3d; mod drawing2d_3d; -mod openings3d; mod wall_mesh_cut; mod plan_buf; mod gpu_compile; diff --git a/src-tauri/core/src/web/openings3d.rs b/src-tauri/core/src/web/openings3d.rs deleted file mode 100644 index 45ccc8fc..00000000 --- a/src-tauri/core/src/web/openings3d.rs +++ /dev/null @@ -1,15 +0,0 @@ -//! Bindungen der Öffnungs-Einbauteile in 3D (`crate::openings3d`). Kodierung s. dort. - -use wasm_bindgen::prelude::wasm_bindgen; - -/// Wände mit Öffnungen (+ Detailgrad) flach → Quader (Bauteil-Klasse, 8 Ecken) flach; nie ein Panic. -#[wasm_bindgen] -pub fn opening_meshes_flat(buf: &[f64]) -> Vec { - crate::openings3d::opening_meshes_flat(buf) -} - -/// Rahmen-Ring als Vierecke (u, h) flach: `[n, (u, h) × 4 …]`. -#[wasm_bindgen] -pub fn frame_ring_quads_flat(from: f64, to: f64, z_b: f64, z_t: f64, w: f64, join: f64, bottom: bool) -> Vec { - crate::openings3d::frame_ring_quads_flat(from, to, z_b, z_t, w, join, bottom) -} diff --git a/src-tauri/core/src/web/site_rules.rs b/src-tauri/core/src/web/site_rules.rs index 36d38963..825e4f67 100644 --- a/src-tauri/core/src/web/site_rules.rs +++ b/src-tauri/core/src/web/site_rules.rs @@ -31,15 +31,3 @@ pub fn site_multi_polygon_area(polys: &[f64]) -> f64 { pub fn site_allowed_area(rules: &[f64]) -> Vec { encode(&read_rules(rules).map(|r| site_rules::allowed_area(&r)).unwrap_or_default()) } - -/// `[gültig, Parzelle, zulässig, Verstoss, HöheÜberschritten, …flat(zulässig), …flat(Verstösse)]`; -/// ungültig → `[0]`. `footprint` = Teile der Gebäude-Grundfläche (`flat`), `max_top` NaN = keine. -#[wasm_bindgen] -pub fn site_check(rules: &[f64], footprint: &[f64], max_height: f64, max_top: f64) -> Vec { - let (Some(r), Some(fp)) = (read_rules(rules), decode(footprint)) else { return vec![0.0] }; - let Some(c) = site_rules::check_site_rules(&r, &fp, max_height, max_top) else { return vec![0.0] }; - let mut out = vec![1.0, c.parcel_area, c.allowed_area, c.violation_area, if c.height_exceeded { 1.0 } else { 0.0 }]; - out.extend(encode(&c.allowed)); - out.extend(encode(&c.violations)); - out -} diff --git a/src-tauri/core/src/web/stairs3d.rs b/src-tauri/core/src/web/stairs3d.rs deleted file mode 100644 index 8655be1a..00000000 --- a/src-tauri/core/src/web/stairs3d.rs +++ /dev/null @@ -1,23 +0,0 @@ -//! Bindungen der Treppen im 3D (`crate::stairs3d`). Kodierung s. dort. - -use crate::mesh3d::encode_meshes; -use crate::stairs3d as s; -use wasm_bindgen::prelude::wasm_bindgen; - -/// Tritt-Prismen und Podeste aller Treppen als Slabs; `for_section`: auch gerade Betontreppen. -#[wasm_bindgen] -pub fn stairs3d_slabs_flat(stairs: &[f64], for_section: bool) -> Vec { - s::encode_slabs(&s::slabs(stairs, for_section)) -} - -/// Glatte Laufplatte gerader Betontreppen als Meshes. -#[wasm_bindgen] -pub fn stairs3d_meshes_flat(stairs: &[f64]) -> Vec { - encode_meshes(&s::slab_meshes(stairs)) -} - -/// Handlauf und Pfosten gerader Treppen als Quader-Meshes. -#[wasm_bindgen] -pub fn stairs3d_railings_flat(stairs: &[f64]) -> Vec { - encode_meshes(&s::railings(stairs)) -} diff --git a/src-tauri/core/src/web/sun.rs b/src-tauri/core/src/web/sun.rs index f5ac2e05..de922fb1 100644 --- a/src-tauri/core/src/web/sun.rs +++ b/src-tauri/core/src/web/sun.rs @@ -2,8 +2,7 @@ use crate::flat_read::pairs; use crate::flat::{decode, encode}; -use crate::flat_read::Reader; -use crate::sun::{self, Prism, SunPosition}; +use crate::sun::{self, SunPosition}; use wasm_bindgen::prelude::wasm_bindgen; /// `[azimut, höhe]` in Grad. @@ -20,36 +19,6 @@ pub fn sun_shadow_of_prism(footprint: &[f64], z_bottom: f64, z_top: f64, azimuth r.into_iter().flatten().collect() } -fn read_prisms(buf: &[f64]) -> Option> { - let mut r = Reader::new(buf); - let n = r.count()?; - let mut out = Vec::with_capacity(n.min(1 << 16)); - for _ in 0..n { - let (z_bottom, z_top) = (r.num()?, r.num()?); - out.push(Prism { footprint: r.ring()?, z_bottom, z_top }); - } - Some(out) -} - -fn read_clouds(buf: &[f64]) -> Option>> { - let mut r = Reader::new(buf); - let n = r.count()?; - let mut out = Vec::with_capacity(n.min(1 << 16)); - for _ in 0..n { - let k = r.count()?; - out.push(r.points3(k)?); - } - Some(out) -} - -/// Prismen `[n, (zUnten, zOben, nPkt, x, y, …)…]` und Punktwolken `[n, (nPkt, x, y, z, …)…]` -/// → vereinigter Schatten (Polygone, `flat`-Kodierung). -#[wasm_bindgen] -pub fn sun_shadow_union(prisms: &[f64], clouds: &[f64], azimuth: f64, elevation: f64) -> Vec { - let (Some(p), Some(c)) = (read_prisms(prisms), read_clouds(clouds)) else { return encode(&[]) }; - encode(&sun::shadow_union(&p, &c, SunPosition { azimuth, elevation })) -} - /// Ein Polygon (`flat`, erstes Polygon zählt) → lochfreie Teile (`flat`, je ein Ring). #[wasm_bindgen] pub fn sun_without_holes(poly: &[f64]) -> Vec { diff --git a/src-tauri/core/src/web/wall_bands.rs b/src-tauri/core/src/web/wall_bands.rs deleted file mode 100644 index 8f201d85..00000000 --- a/src-tauri/core/src/web/wall_bands.rs +++ /dev/null @@ -1,9 +0,0 @@ -//! Bindungen der Wand-Schichtbänder (`crate::wall_bands`). Kodierung s. dort. - -use wasm_bindgen::prelude::wasm_bindgen; - -/// Wände + Geschosse (Decken, Dächer) flach → Körper je Wand flach; nie ein Panic. -#[wasm_bindgen] -pub fn wall_bands_flat(walls: &[f64], floors: &[f64]) -> Vec { - crate::wall_bands::wall_bands_flat(walls, floors) -} diff --git a/src/core/document.ts b/src/core/document.ts index 2ddaa62e..5c7ad2b0 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -8,6 +8,25 @@ import type { Project } from "../model/types"; import { core } from "../engine/coreWasm"; import { diffToOps } from "./ops"; +/** Abfragen des Kerns (`queries.rs`). */ +export type QueryName = + | "kennzahlen" + | "siteCheck" + | "buildingFootprint" + | "modelTop" + | "shadows" + | "materialMaps" + | "slabs" + | "columnMeshes" + | "walls" + | "openingMeshes" + | "stairSlabs" + | "stairMeshes" + | "stairRailings" + | "roofMeshes" + | "roofCutLayers" + | "model3dParts"; + export class ProjectDocument { private handle = 0; private mirror: Project; @@ -46,13 +65,20 @@ export class ProjectDocument { } /** - * Abfrage auf dem typisierten Projekt im Kern. Das Ergebnis ist JSON; ein Fehler (Projekt passt - * nicht zum Modell, unbekannte Abfrage) wirft. + * Abfrage auf dem typisierten Projekt im Kern (`queries.rs`); `args` Zahlen, `text` ein Text + * (z. B. eine id). Das Ergebnis ist JSON; Fehler im Kern (Projekt passt nicht zum Modell, + * Rechenfehler) werfen mit der Meldung des Kerns. */ - query(name: "kennzahlen" | "siteCheck" | "buildingFootprint" | "modelTop" | "shadows" | "slabs" | "columnMeshes" | "walls" | "openingMeshes" | "stairSlabs" | "stairMeshes" | "stairRailings" | "roofMeshes" | "roofCutLayers", args: number[] = []): T { - const text = this.handle ? core().doc_query_args(this.handle, name, Float64Array.from(args)) : ""; - if (!text) throw new Error(`Kern-Abfrage „${name}": Projekt passt nicht zum Kern-Modell`); - return JSON.parse(text) as T; + query(name: QueryName, args: number[] = [], text = ""): T { + return JSON.parse(this.queryJson(name, args, text)) as T; + } + + /** Wie {@link query}, aber das JSON als Text (spart das Parsen, wenn es nur weitergereicht wird). */ + queryJson(name: QueryName, args: number[] = [], text = ""): string { + if (!this.handle) throw new Error(`Kern-Abfrage „${name}": Dokument nicht offen`); + const out = core().doc_query_args(this.handle, name, Float64Array.from(args), text); + if (out.startsWith("\u0001")) throw new Error(out.slice(1)); + return out; } /** Das Dokument als JSON-Text (Test, Export). */ diff --git a/src/export/exportIfc.ts b/src/export/exportIfc.ts index 8a671042..e4504d91 100644 --- a/src/export/exportIfc.ts +++ b/src/export/exportIfc.ts @@ -76,7 +76,7 @@ import type { RWall } from "../plan/toWalls3d"; import { isWatertight, wallCutMeshes, type CutMesh } from "../plan/wallMeshCut"; import { evaluateRoom } from "../geometry/roomArea"; import { columnFootprint } from "../geometry/column"; -import { emitRoofs } from "../plan/toWalls3d/roofs"; +import { roofMeshes } from "../plan/toWalls3d"; // ── IFC-GUID (Base64-Kompression, 22 Zeichen) ─────────────────────────────── // Standard-Kompressionsalgorithmus (IfcOpenShell guid.compress): das erste @@ -830,7 +830,7 @@ export function exportIfcSpf(projectIn: Project): string { } // ── Dächer → IfcRoof ─────────────────────────────────────────────────── - // Dieselben geschlossenen Schicht-Meshes wie das 3D (`emitRoofs`: Dachflächen je Schicht, + // Dieselben geschlossenen Schicht-Meshes wie das 3D (`roofMeshes`: Dachflächen je Schicht, // an First/Grat gehrt), zu EINEM Face-Set je Dach vereint. Modell-Koordinaten sind bereits // Z-oben (kein Achsentausch wie bei den Wänden); die Wicklung wird so gewählt, dass das Volumen // positiv ist — nur dann ist das Face-Set als geschlossen markiert. @@ -846,7 +846,7 @@ export function exportIfcSpf(projectIn: Project): string { const structure = resolveStructure(roof.floorId); const positions: number[] = []; const indices: number[] = []; - for (const mesh of emitRoofs({ ...project, roofs: [roof] })) { + for (const mesh of roofMeshes(project, roof.id)) { const base = positions.length / 3; for (let i = 0; i < mesh.positions.length; i += 3) { positions.push(mesh.positions[i], mesh.positions[i + 1], mesh.positions[i + 2] - structure.baseElevation); diff --git a/src/plan/model3d.parity.tmp.test.ts b/src/plan/model3d.parity.tmp.test.ts deleted file mode 100644 index be7ebb47..00000000 --- a/src/plan/model3d.parity.tmp.test.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { sampleProject } from "../model/sampleProject"; -import { documentFor } from "../core/document"; -import { emitSlabs } from "./toWalls3d/ceilings"; -import { emitColumns } from "./toWalls3d/columns"; -import { projectToWalls3d } from "./toWalls3d"; -import { emitOpeningMeshes } from "./toWalls3d/openings"; -import { emitRoofs, emitRoofCutLayers } from "./toWalls3d/roofs"; -import { emitStairs, emitStairMeshes, emitStairRailings } from "./toWalls3d/stairs"; - -const plain = (v: T): T => JSON.parse(JSON.stringify(v)); -let seed = 21; -const rnd = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296); -const pick = (a: T[]) => a[Math.floor(rnd() * a.length)]; - -describe("model3d walls", () => { - it("sample project both paths", () => { - const doc = documentFor(sampleProject); - for (const layered of [true, false]) { - expect(doc.query("walls", [layered ? 1 : 0])).toEqual(plain(projectToWalls3d(sampleProject, layered))); - } - }); - it("random walls/openings/ceilings/roofs", () => { - let n = 0; - for (let t = 0; t < 150; t++) { - const lvl = sampleProject.drawingLevels.filter((l) => l.kind === "floor"); - const pts = [[0, 0], [6, 0], [6, 4], [0, 4], [3, 0], [3, 4], [8, 2], [-2, 2]]; - const walls = Array.from({ length: 2 + Math.floor(rnd() * 6) }, (_, k) => { - const a = pick(pts), b = pick(pts); - return { ...sampleProject.walls[0], id: "w" + k, floorId: pick(lvl).id, start: { x: a[0], y: a[1] }, end: { x: b[0], y: b[1] + (a[1] === b[1] && a[0] === b[0] ? 1 : 0) }, - wallTypeId: pick(sampleProject.wallTypes).id, - ...(rnd() < 0.3 ? { referenceLine: pick(["left", "right", "center"]) } : {}), - ...(rnd() < 0.15 ? { referenceOffset: rnd() * 0.3 - 0.15 } : {}), - ...(rnd() < 0.2 ? { sliceTermination: pick(["below", "above", "both"]) } : {}), - height: pick([2.5, 2.6, 3]) }; - }); - const openings = walls.flatMap((w, k) => rnd() < 0.6 ? [{ id: "o" + k, type: "opening", hostWallId: w.id, categoryCode: "21", kind: pick(["window", "door"]), - ...(rnd() < 0.5 ? { typeId: pick(["window-standard", "window-double", "door-standard", "door-entry"]) } : {}), - position: rnd() * 2, width: 0.6 + rnd(), height: 1.2 + rnd(), sillHeight: pick([0, 0.9]) }] : []); - const ceilings = Array.from({ length: Math.floor(rnd() * 3) }, (_, k) => ({ id: "c" + k, type: "ceiling", floorId: pick(lvl).id, categoryCode: "20", - outline: [{ x: -1, y: -1 }, { x: 7, y: -1 }, { x: 7, y: 5 }, { x: -1, y: 5 }], wallTypeId: sampleProject.wallTypes[0].id, - ...(sampleProject.ceilingTypes?.length && rnd() < 0.5 ? { ceilingTypeId: pick(sampleProject.ceilingTypes).id } : {}) })); - const roofs = rnd() < 0.5 ? [{ id: "R1", type: "roof", floorId: pick(lvl).id, categoryCode: "35", outline: [{ x: -1, y: -1 }, { x: 7, y: -1 }, { x: 7, y: 5 }, { x: -1, y: 5 }], - shape: pick(["sattel", "walm", "pult", "flach"]), pitchDeg: 30, overhang: 0.3, ridgeAxis: pick(["x", "y"]), thickness: 0.2 }] : []; - const kinds = ["fest", "dreh", "kipp", "drehkipp", "schiebe"]; - const wts = Array.from({ length: 2 }, (_, k) => ({ ...sampleProject.windowTypes![0], id: "wt" + k, kind: pick(kinds), wingCount: 1 + Math.floor(rnd() * 3), - frameWidth: rnd() < 0.5 ? pick([0.04, 0.06, 0.09]) : undefined, transomHeight: rnd() < 0.5 ? pick([0.2, 0.4]) : undefined, - mullionRows: rnd() < 0.5 ? pick([1, 2, 3]) : undefined, mullionCols: rnd() < 0.5 ? pick([1, 2]) : undefined, - sillBoard: pick(["keine", "innen", "aussen", "beide", undefined]), glazingPanes: pick([1, 2, 3, undefined]), glazing: pick(["einfach", "zweifach", "dreifach"]), - frameCornerJoin: pick(["vertikal", "horizontal", "gehrung", undefined]), insetFromFace: rnd() < 0.5 ? 0.1 : undefined, insetFace: pick(["aussen", "innen", undefined]), - innerLayerRecess: rnd() < 0.3 ? true : undefined, shading: rnd() < 0.4 ? { create: true, kind: "rollladen", box: { width: 1, height: 0.2, depth: 0.2 } } : undefined, - sashes: rnd() < 0.6 ? Array.from({ length: 1 + Math.floor(rnd() * 3) }, () => ({ kind: pick(["fluegel", "fluegel", "pfosten"]), autoWidth: pick([true, false, undefined]), width: rnd() < 0.5 ? 0.4 : undefined, postWidth: rnd() < 0.5 ? 0.08 : undefined, opening: pick([...kinds, undefined]), hingeSide: pick(["left", "right", undefined]) })) : undefined })); - const dts = Array.from({ length: 2 }, (_, k) => ({ ...sampleProject.doorTypes![0], id: "dt" + k, leafStyle: pick(["glatt", "glas", "kassette"]), glazingRatio: rnd() < 0.5 ? pick([0.3, 1]) : undefined, - frameKind: pick(["zarge", "blockrahmen", undefined]), threshold: pick([true, false, undefined]), leafCount: pick([1, 2]) , panelCols: rnd() < 0.5 ? 2 : undefined, panelRows: rnd() < 0.5 ? 3 : undefined })); - const openings2 = openings.map((o: any) => ({ ...o, ...(rnd() < 0.8 ? { typeId: o.kind === "door" ? pick(dts).id : pick(wts).id } : {}), ...(rnd() < 0.3 ? { wingCount: 2 } : {}) })); - const project: any = { ...sampleProject, walls, openings: openings2, ceilings, roofs, windowTypes: wts, doorTypes: dts }; - const doc = documentFor(project); - for (const [dc, dn] of [[0, "grob"], [1, "mittel"], [2, "fein"]] as const) { - expect(doc.query("openingMeshes", [dc])).toEqual(plain(emitOpeningMeshes(project, dn))); - } - for (const layered of [true, false]) { - let want: unknown; - try { want = plain(projectToWalls3d(project, layered)); } catch { want = undefined; } - if (want === undefined) { expect(() => doc.query("walls", [layered ? 1 : 0])).toThrow(); continue; } - expect(doc.query("walls", [layered ? 1 : 0])).toEqual(want); - n += (want as unknown[]).length; - } - } - expect(n).toBeGreaterThan(500); - }); -}); - -describe("model3d stairs", () => { - it("random", () => { - let n = 0; - for (let t = 0; t < 200; t++) { - const lvl = sampleProject.drawingLevels.filter((l) => l.kind === "floor"); - const types = Array.from({ length: 3 }, (_, k) => ({ id: "st" + k, name: "t", structure: pick(["massiv", "beton", "wange", "aufgesattelt", "spindel"]), closedRisers: rnd() < 0.5, - treadThickness: pick([0.04, 0.06]), nosing: rnd() < 0.5 ? 0.03 : undefined, railing: pick(["keine", "links", "rechts", "beide", undefined]), defaultWidth: 1 })); - const stairs = Array.from({ length: 1 + Math.floor(rnd() * 3) }, (_, k) => { - const shape = pick(["straight", "L", "spiral"]); - return { id: "s" + k, type: "stair", floorId: pick(lvl).id, categoryCode: "25", shape, start: { x: rnd() * 5, y: rnd() * 5 }, dir: pick([{ x: 1, y: 0 }, { x: 0, y: 1 }, { x: -1, y: 0 }]), - runLength: 2 + rnd() * 3, ...(shape === "L" ? { run2Length: 1.5, turn: pick([1, -1]) } : {}), ...(shape === "spiral" ? { center: { x: 2, y: 2 }, radius: 1.2, sweep: 4 } : {}), - width: 1, stepCount: 8 + Math.floor(rnd() * 8), ...(rnd() < 0.5 ? { totalRise: 2.6 } : {}), ...(rnd() < 0.5 ? { up: pick([true, false]) } : {}), - ...(rnd() < 0.7 ? { typeId: pick(types).id } : {}), ...(rnd() < 0.3 ? { referenz: pick(["links", "rechts", "mitte"]) } : {}) }; - }); - const project: any = { ...sampleProject, stairs, stairTypes: types }; - const doc = documentFor(project); - for (const fs of [false, true]) { - const a = doc.query("stairSlabs", [fs ? 1 : 0]); - const b = plain(emitStairs(project, { forSection: fs })); - expect(a).toEqual(b); - n += b.length; - } - expect(doc.query("stairMeshes")).toEqual(plain(emitStairMeshes(project))); - expect(doc.query("stairRailings")).toEqual(plain(emitStairRailings(project))); - } - expect(n).toBeGreaterThan(300); - }); -}); - -describe("model3d roofs", () => { - it("random", () => { - let n = 0; - const L = [{ x: 0, y: 0 }, { x: 11, y: 0 }, { x: 11, y: 4 }, { x: 8, y: 4 }, { x: 8, y: 6 }, { x: 0, y: 6 }]; - const R = [{ x: 0, y: 0 }, { x: 8, y: 0 }, { x: 8, y: 5 }, { x: 0, y: 5 }]; - for (let t = 0; t < 200; t++) { - const lvl = sampleProject.drawingLevels.filter((l) => l.kind === "floor"); - const roofTypes = sampleProject.roofTypes ?? []; - const roofs = Array.from({ length: 1 + Math.floor(rnd() * 2) }, (_, k) => ({ id: "R" + k, type: "roof", floorId: pick(lvl).id, categoryCode: "35", outline: pick([L, R]), - shape: pick(["sattel", "walm", "pult", "flach", "mansarde", "zelt"]), pitchDeg: 10 + Math.floor(rnd() * 40), overhang: rnd() * 0.5, ridgeAxis: pick(["x", "y"]), thickness: pick([0.1, 0.2]), - ...(roofTypes.length && rnd() < 0.7 ? { roofTypeId: pick(roofTypes).id } : {}), ...(rnd() < 0.3 ? { color: "#aa3322" } : {}), ...(rnd() < 0.3 ? { baseElevation: 3 } : {}) })); - const project: any = { ...sampleProject, roofs }; - const doc = documentFor(project); - const a = doc.query("roofMeshes"); - const b = plain(emitRoofs(project)); - expect(a).toEqual(b); - expect(plain(doc.query("roofCutLayers"))).toEqual(plain(emitRoofCutLayers(project))); - n += b.length; - } - expect(n).toBeGreaterThan(100); - }); -}); - -describe("model3d slabs/columns", () => { - it("random", () => { - let ns = 0, nc = 0; - for (let t = 0; t < 200; t++) { - const lvl = sampleProject.drawingLevels.filter((l) => l.kind === "floor"); - const ceilings = Array.from({ length: Math.floor(rnd() * 4) }, (_, k) => ({ - id: "c" + k, type: "ceiling", floorId: pick(lvl).id, categoryCode: "20", - outline: [{ x: 0, y: 0 }, { x: 5 + k, y: 0 }, { x: 5 + k, y: 4 }, { x: 0, y: 4 }], - ...(rnd() < 0.5 ? { openings: [[{ x: 1, y: 1 }, { x: 2, y: 1 }, { x: 2, y: 2 }, { x: 1, y: 2 }]] } : {}), - wallTypeId: sampleProject.wallTypes[0].id, - ...(rnd() < 0.5 && sampleProject.ceilingTypes?.length ? { ceilingTypeId: pick(sampleProject.ceilingTypes).id } : {}), - ...(rnd() < 0.3 ? { thickness: 0.25 } : {}), - ...(rnd() < 0.2 ? { top: { mode: "custom", z: 3.1 } } : {}), - })); - const columns = Array.from({ length: Math.floor(rnd() * 4) }, (_, k) => ({ - id: "k" + k, type: "column", floorId: pick(lvl).id, categoryCode: "20", - position: { x: k, y: 1 }, rotation: rnd() * 3, height: pick([0, 2.5, 3]), - profile: pick([{ kind: "rect", width: 0.3, depth: 0.4 }, { kind: "round", radius: 0.2 }]), - ...(rnd() < 0.5 ? { componentId: pick(sampleProject.components).id } : {}), - ...(rnd() < 0.3 ? { componentId: "nope" } : {}), - })); - const project: any = { ...sampleProject, ceilings, columns }; - const doc = documentFor(project); - const a = doc.query("slabs"); - const b = plain(emitSlabs(project)); - expect(a).toEqual(b); - const c = doc.query("columnMeshes"); - const d = plain(emitColumns(project)); - expect(c).toEqual(d); - ns += b.length; nc += d.length; - } - expect(ns).toBeGreaterThan(100); - expect(nc).toBeGreaterThan(100); - }); -}); diff --git a/src/plan/toWalls3d.ts b/src/plan/toWalls3d.ts index 05267559..a99dad7d 100644 --- a/src/plan/toWalls3d.ts +++ b/src/plan/toWalls3d.ts @@ -40,7 +40,7 @@ // truck-Extrusionen, freie 2D-Geometrie) hat ihre eigene Datei unter // `toWalls3d/` — siehe dort für die konkrete Emissions-Logik je Bauteil. -import type { Project, Vec2, Wall } from "../model/types"; +import type { Project, Vec2 } from "../model/types"; import { getWallType, wallTypeThickness } from "../model/types"; import { stairVerticalExtent } from "../model/wall"; import { openingJambs, openingVerticalExtent } from "../geometry/opening"; @@ -48,14 +48,10 @@ import type { DetailLevel } from "../model/viewTypes"; import { stairBBox, stairGeometry } from "../geometry/stair"; import { roofBaseElevation, roofGeometry } from "../geometry/roof"; import type { Vec3 as RoofVec3 } from "../geometry/roof"; -import { computeJoins } from "../model/joins"; -import type { WallCuts } from "../model/joins"; +import { documentFor } from "../core/document"; import type { PickOpening, PickRoof, PickStair, PickContextMesh, PickDrawingSeg } from "./pickTypes"; import { EPS, - IMPORTED_RGB, - TERRAIN_RGB, - wallMaterialColorMaps, type RMesh, type RModel3d, type RRgb, @@ -63,20 +59,14 @@ import { type RVec2, type RWall, } from "./toWalls3d/shared"; -import { emitWalls } from "./toWalls3d/bands"; -import { emitSlabs } from "./toWalls3d/ceilings"; -import { emitStairMeshes, emitStairRailings, emitStairs } from "./toWalls3d/stairs"; import { emitExtrudedSolids, TRUCK_MESH_READY_EVENT } from "./toWalls3d/extrusions"; import { applyVoids3d } from "./toWalls3d/voids3d"; import { emitDrawingLineVerts, pickDrawingSegs } from "./toWalls3d/drawing2d"; -import { emitColumns } from "./toWalls3d/columns"; -import { emitRoofCutLayers, emitRoofs } from "./toWalls3d/roofs"; -import { emitOpeningMeshes } from "./toWalls3d/openings"; // Re-Export des gemeinsamen Vokabulars — externe Konsumenten (viewport/, // export/, toSection.ts, nativeSync.ts, …) importieren weiterhin // ausschliesslich von hier, unverändert zur Zeit vor dem Domänen-Split. -export { wallMaterialColorMaps, TRUCK_MESH_READY_EVENT }; +export { TRUCK_MESH_READY_EVENT }; // 2D-Boden-Spuren gehen NICHT über `RModel3d`, sondern als LineList über den // binären `set_drawing_lines`-Kanal (s. dortige Funktionsdoc) — der Viewport // holt sie direkt hier ab. @@ -90,87 +80,34 @@ type RoofPickVec3 = [number, number, number]; type RVec3 = [number, number, number]; /** - * Emittiert die rohen Kontext-Meshes eines Projekts: Gelände-TINs (`terrainMesh`) - * und importierte Volumen (`importedMesh`) aus `project.context`, plus alle - * übrigen Kontext-Mesh-Domänen (truck-Extrusionen, Stützen, 2D-Boden-Spuren). - * `contourSet` bleibt außen vor — das sind nur 2D-Linien (Höhenlinien/ - * Footprints), keine Dreiecksmeshes. Die `positions`/`indices` der Geo-Meshes - * werden 1:1 durchgereicht (Modell-Koordinaten, x,y,z=Höhe); render3d bildet - * sie selbst nach world ab. - */ -function emitMeshes(project: Project): RMesh[] { - const out: RMesh[] = []; - for (const obj of project.context ?? []) { - if (obj.type === "terrainMesh" || obj.type === "importedMesh") { - // Leere/entartete Meshes überspringen (render3d würde sie ohnehin verwerfen). - if (obj.positions.length < 9 || obj.indices.length < 3) continue; - out.push({ - positions: obj.positions, - indices: obj.indices, - kind: obj.type === "terrainMesh" ? "terrain" : "imported", - color: obj.type === "terrainMesh" ? TERRAIN_RGB : IMPORTED_RGB, - // Luftbild-Drape: das Gelände-TIN kann Pro-Vertex-Farben tragen (beim - // Import aus dem Luftbild gesampelt) — dann zeigt render3d das Ortho - // statt der Flächen-Grundfarbe. - vertexColors: - obj.type === "terrainMesh" && obj.vertexColors?.length - ? obj.vertexColors - : undefined, - }); - } - } - // 2D-Zeichnungen sind hier bewusst NICHT dabei: sie gehen als LineList über - // den binären `set_drawing_lines`-Kanal (s. `emitDrawingLineVerts`), weil ein - // Kataster-Import als Meshes im JSON-Modell weder serialisierbar noch - // speicherbar wäre (s. dortige Funktionsdoc). - // - // KEIN `out.push(...emitX(project))`: der Spread-Operator sprengt bei grossen - // Arrays die Argumentzahl-Grenze von `push` (RangeError "Maximum call stack - // size exceeded") — dieselbe, bereits dokumentierte Falle wie in - // `swissBuildings3d.ts::concatMeshes`/`dwgParser.ts`. - for (const m of emitExtrudedSolids(project)) out.push(m); - for (const m of emitColumns(project)) out.push(m); - return out; -} - -/** - * Nur die Wände (Rückwärts-Kompatibilität / bestehende Aufrufer). Zerlegt Wände - * mit Öffnungen in Teilquader. + * Nur die Wände (Rückwärts-Kompatibilität / bestehende Aufrufer). Zerlegt Wände mit Öffnungen in + * Teilquader bzw. (layered) in Schicht-Bänder. Rechnet der Kern auf dem Projekt-Dokument + * (`model3d.rs`: Verschneidung je Geschoss, Bänder, Öffnungen, Decken-/Dach-Dominanz). */ export function projectToWalls3d(project: Project, layered = true): RWall[] { - const out: RWall[] = []; - // Verschneidungs-Schnittlinien PRO GESCHOSS berechnen (wie generatePlan.ts sie - // je Grundriss auf der gefilterten Wandmenge bildet) — nur für den layered-3D- - // Pfad. Nach Geschoss gruppieren, damit deckungsgleiche Wände verschiedener - // Geschosse (z. B. EG/OG an identischen XY-Knoten) NICHT fälschlich verschneiden. - // Der Schnitt-Pfad (layered=false) bekommt KEINE Cuts (unverändert, seine - // Dominanz macht toSection.ts). Anders als im 2D wird hier NICHT nach - // Sichtbarkeit gefiltert — 3D zeigt alle Wände, alle nehmen an den Joins teil. - const joins = layered ? computeJoinsByFloor(project) : undefined; - emitWalls(out, project, project.walls, layered, joins); - return out; + return documentFor(project).query("walls", [layered ? 1 : 0]); } /** - * Berechnet `computeJoins` getrennt je Geschoss (`wall.floorId`) und führt - * die Ergebnis-Maps zu einer flachen `wallId → WallCuts` zusammen. So bilden nur - * Wände desselben Geschosses gemeinsame Ecken/T-Stösse (identisch zur 2D-Semantik, - * wo `generatePlan` je Grundriss aufruft). + * Textur-Karten-URLs der Bauteile in der Reihenfolge des ersten Auftretens (Wandtypen, Decken, + * Dächer): die Position + 1 ist die Textur-Ebene (`materialIndex`). Memoisiert je Projekt-Referenz. */ -function computeJoinsByFloor(project: Project): Map { - const byFloor = new Map(); - for (const w of project.walls) { - const key = w.floorId ?? ""; - const list = byFloor.get(key); - if (list) list.push(w); - else byFloor.set(key, [w]); +const materialMapCache = new WeakMap(); +export function wallMaterialColorMaps(project: Project): string[] { + let maps = materialMapCache.get(project); + if (!maps) { + maps = documentFor(project).query("materialMaps"); + materialMapCache.set(project, maps); } - const merged = new Map(); - for (const walls of byFloor.values()) { - const cuts = computeJoins(project, walls); - for (const [id, wc] of cuts) merged.set(id, wc); - } - return merged; + return maps; +} + +/** + * Dach-Meshes (geschlossene, geschichtete Körper je Dachschicht); `onlyRoofId` beschränkt auf ein + * Dach (IFC-Export). Rechnet der Kern. + */ +export function roofMeshes(project: Project, onlyRoofId?: string): RMesh[] { + return documentFor(project).query("roofMeshes", [], onlyRoofId ?? ""); } /** @@ -210,33 +147,46 @@ export interface Model3dOptions { export function projectToModel3d(project: Project, opts: Model3dOptions = {}): RModel3d { const layered = opts.layeredWalls ?? true; const detail = opts.detail ?? "fein"; + const parts = documentFor(project).query( + "model3dParts", + [layered ? 1 : 0, DETAIL_CODE[detail] ?? 3, opts.forSection ? 1 : 0], + ); + // Die truck-Körper (asynchron, mit Cache) kommen zwischen Kontext-Meshes und Stützen. + const meshes: RMesh[] = [...parts.contextMeshes]; + for (const m of emitExtrudedSolids(project)) meshes.push(m); + for (const m of parts.columnMeshes) meshes.push(m); + for (const m of parts.openingMeshes) meshes.push(m); + for (const m of parts.stairMeshes) meshes.push(m); + for (const m of parts.stairRailings) meshes.push(m); + for (const m of parts.roofMeshes) meshes.push(m); const model: RModel3d = { - walls: projectToWalls3d(project, layered), - // Decken + Treppen (Treppentritte als extrudierte Slabs) — so wird die Treppe - // auch im WASM/wgpu-Renderer sichtbar (der three.js-Pfad rendert sie separat). - slabs: [...emitSlabs(project), ...emitStairs(project, { forSection: opts.forSection })], - // Kontext-Meshes (Terrain/Import) + Fenster-/Tür-Glasscheiben (eigenes Mesh - // je Scheibe) + Rahmen-/Sprossen-Riegel typisierter Öffnungen (Zarge/ - // Blendrahmen/Kämpfer/Mittelpfosten, s. emitOpeningMeshes) + glatte Beton- - // Laufplatten (gerade Betontreppen als Mesh) + Dachflächen/-giebel - // (s. emitRoofs) — pickGeometry/Highlight nutzen `meshes` bewusst NICHT (man - // wählt Wand/Öffnung/Treppe; Treppen-Pick läuft über die pickGeometry-Boxen). - meshes: [ - ...emitMeshes(project), - ...emitOpeningMeshes(project, detail), - ...emitStairMeshes(project), - ...emitStairRailings(project), - ...emitRoofs(project), - ], - // Dach-Schicht-Eingabe für den 3D-Live-Schnitt (render3d::roof_cut) — s. - // Kopfkommentar bei `RRoofLayer`/`emitRoofCutLayers`: getrennt von `meshes`, - // weil `section.rs` beliebige Dreiecksnetze nicht schneiden kann. - roofLayers: emitRoofCutLayers(project), + walls: parts.walls, + // Decken + Treppen (Treppentritte als extrudierte Slabs), Kontext-Meshes, Öffnungs-Einbauteile, + // Betonlaufplatten, Handläufe und Dachflächen: alles aus dem Kern; Dach-Schichten für den + // 3D-Live-Schnitt getrennt (`roofLayers`). + slabs: parts.slabs, + meshes, + roofLayers: parts.roofLayers, }; if (opts.voids) applyVoids3d(model, project); return model; } +/** Teile des 3D-Modells aus dem Kern (`model3d::Parts`). */ +interface Model3dParts { + walls: RWall[]; + slabs: RSlab[]; + contextMeshes: RMesh[]; + columnMeshes: RMesh[]; + openingMeshes: RMesh[]; + stairMeshes: RMesh[]; + stairRailings: RMesh[]; + roofMeshes: RMesh[]; + roofLayers: RModel3d["roofLayers"]; +} + +const DETAIL_CODE: Record = { grob: 0, mittel: 1, fein: 2 }; + /** * Pick-Geometrie für den TS-seitigen 3D-Raycast (siehe viewport/raycast3d): die * Wand-Teilquader (mit `wallId`) und Decken-Prismen (mit `ceilingId`) desselben @@ -340,7 +290,7 @@ export function pickGeometry( const drawings = pickDrawingSegs(project); return { walls: projectToWalls3d(project), - slabs: emitSlabs(project), + slabs: documentFor(project).query("slabs"), openings, stairs, roofs, diff --git a/src/plan/toWalls3d/bands.ts b/src/plan/toWalls3d/bands.ts deleted file mode 100644 index 5edeecf3..00000000 --- a/src/plan/toWalls3d/bands.ts +++ /dev/null @@ -1,346 +0,0 @@ -// Wand-Domäne der 3D-Ableitung (SCHICHTEN → Bänder → Boxen, siehe Moduldoc in -// `../../toWalls3d.ts`): löst den Schichtaufbau EINER Wand in quer zur Dicke -// gestapelte Materialbänder auf und emittiert daraus Wandkörper — inklusive -// aller materialbewussten Verschneidungen (Gehrungs-/Anschluss-Cuts an L-/ -// T-Stössen, Durchgangswand-Span-Cutouts, Decken-Dominanz pro Schicht, Dach- -// Unterkanten-Kappung mit schräger Oberkante). Das 3D-Pendant zu -// `generatePlan/walls.ts::addWallPoche`. -// -// Gerechnet wird im Rust-Kern (`src-tauri/core/src/wall_bands.rs`); hier bleiben -// das Sammeln aus dem `Project` (Wandtyp, Öffnungen, Decken- und Dachaufbau, -// Höhen), die flache Übergabe und die Darstellungs-Metadaten je Band (Farbe, -// Schraffur, Material, Schnitt-Stil). - -import type { Project, Wall } from "../../model/types"; -import { - getCeilingType, - getComponent, - getWallType, - getWindowType, - openingsOfWall, - roofLayers, - wallTypeThickness, -} from "../../model/types"; -import { ceilingVerticalExtent, wallVerticalExtent } from "../../model/wall"; -import { openingInterval, openingVerticalExtent } from "../../geometry/opening"; -import { roofBaseElevation, roofGeometry, roofPlanesFlat } from "../../geometry/roof"; -import { writeWallCuts, type WallCuts } from "../../model/joins"; -import { FlatReader, FlatWriter } from "../../geometry/coreFlat"; -import { core } from "../../engine/coreWasm"; -import { - WALL_RGB, - dominantLayerColor, - dominantLayerHatch, - hexToRgb, - resolveComponentHatch, - resolveComponentMaterialLayer, - resolveCutLineStyle, - type RCutMeta, - type RHatch, - type RHole, - type RRgb, - type RWall, -} from "./shared"; - -/** - * Achswinkel einer GESCHNITTENEN Wand im Schnitt-Koordinatensystem (Modell- - * Konvention, identisch zu `SECTION_WALL_AXIS_ANGLE_DEG` in toSection.ts): das - * Wand-Band steht vertikal (Achse entlang v, atan2(1,0) = 90°). Damit drehen - * `relativeToWall`-Muster (Dämmung, Backstein) im 3D-Schnitt genauso mit der Wand - * wie im 2D-Schnitt (`splitWallLayers` → `resolveHatch(…, 90, …)`). Für DECKEN gibt - * es keinen Wandachsen-Bezug — dort bleibt der Winkel absolut (`emitSlabs` ruft - * `resolveComponentHatch` ohne Achswinkel, wie `splitSlabLayers` → `resolveHatch(…, - * undefined, …)`), sodass die liegende Boden-Dämmung vertikal statt horizontal läuft. - */ -const SECTION_WALL_AXIS_ANGLE_DEG = 90; - -/** - * Eine quer zur Wanddicke gestapelte Materiallage als 3D-Band: eigene Dicke und - * Materialfarbe. Den Mitten-Versatz (Stapel um die Achse, Referenzlinie) rechnet - * der Kern (`wall_bands.rs`); jede Lage wird dort pro Achsen-Teilstück zu einer - * eigenen Voll-Box. - */ -interface WallBand { - thickness: number; - color: RRgb; - /** Schnitt-Schraffur des Band-Bauteils (siehe {@link RHatch}). */ - hatch?: RHatch; - /** Material-Textur-Ebene des Band-Bauteils (1-basiert, siehe `wallMaterialColorMaps`). */ - materialIndex?: number; - /** - * Verschneidungs-Rang dieser Materiallage (`Component.joinPriority`) — treibt - * die per-Schicht-Dominanz gegen Decken im layered-3D-Pfad (s. `wall_bands.rs`): - * eine Decke mit STRIKT höherer - * `joinPriority` schneidet nur die Bänder mit niedrigerem Rang aus ihrem - * z-Intervall (der Kern höherer Priorität läuft durch). `undefined` (kein - * auflösbarer WallType / synthetisches Fallback-Band) ⇒ keine Decken- - * Subtraktion (konservativ, wie das frühere Trim-Verhalten bei unbekanntem Typ). - */ - priority?: number; - /** - * Bauteil-Identität dieser Materiallage (`Component.id`) — treibt die MERGE-Regel - * der Schnitt-Boolean-Dominanz (gleiche Komponente + Priorität verschmelzen, keine - * innere Trennlinie). Reist als `RCutMeta.componentId` mit. - */ - componentId?: string; - /** Farbe der Schnitt-Umrisslinie dieser Schicht (aus `jointLineStyleId`, sonst Default). */ - cutLineColor?: RRgb; - /** Strichstärke der Schnitt-Umrisslinie in mm-Papier (aus `jointLineStyleId`, sonst Default). */ - cutLineWeight?: number; -} - -/** - * Baut die {@link RCutMeta}-Nutzlast eines Wand-Bandes (Priorität/Identität/ - * Schnittkanten-Stil), oder `undefined`, wenn das Band keinerlei Schnitt-Metadaten - * trägt (z. B. das Fallback-Vollkörper-Band ohne auflösbaren WallType). Nur gesetzte - * Felder werden übernommen, damit `#[serde(default)]` auf der Rust-Seite greift. - */ -function bandCutMeta(b: WallBand): RCutMeta | undefined { - const meta: RCutMeta = {}; - if (b.priority !== undefined) meta.joinPriority = b.priority; - if (b.componentId !== undefined) meta.componentId = b.componentId; - if (b.cutLineColor !== undefined) meta.lineColor = b.cutLineColor; - if (b.cutLineWeight !== undefined) meta.lineWeight = b.cutLineWeight; - return Object.keys(meta).length > 0 ? meta : undefined; -} - -/** - * Löst den Schichtstapel EINER Wand auf: je Materiallage ein {@link WallBand} - * mit ihrer Dicke und Component-Farbe (`stacked: true`). Der Kern stapelt die - * Lagen um die Wandachse und verschiebt den Stapel um den Referenzversatz - * (`Wall.referenceLine`/`referenceOffset`), wie der 2D-Plan und die Gehrungs- - * Cuts. Gesamtdicke = SUMME der Lagen-Dicken (lückenlos). Kein auflösbarer - * WallType / keine Lagen ⇒ EIN Vollkörper-Band über die volle Dicke im neutralen - * Grundton (`stacked: false`, ebenfalls Referenz-versetzt). - */ -function resolveWallBands(project: Project, wall: Wall, layered = true): { bands: WallBand[]; stacked: boolean } { - try { - const wt = getWallType(project, wall); - if (wt.layers.length > 0) { - // Gesamtdicke = Summe der Lagen (konsistent mit den Offsets); wenn diese - // von wallTypeThickness abwiche, gewinnt die Lagen-Summe (keine Lücken). - const total = wt.layers.reduce((s, l) => s + l.thickness, 0); - // Schnitt-Eingabe (layered=false): EINE Voll-Box über die ganze Dicke statt - // je Lage eine Box. So bleibt die Emission 1:1 Wand→Rechteck — passend zu - // `wallSegmentOwners`/`splitWallLayers` in toSection.ts, die die Schicht- - // Zerlegung TS-seitig aus diesem einen Rechteck machen. (Der 3D-Viewer ruft - // mit Default layered=true auf und bekommt unverändert die Schicht-Bänder.) - if (!layered) { - const dominant = wt.layers.reduce((best, l) => (l.thickness > best.thickness ? l : best)); - const band: WallBand = { - thickness: total, - color: dominantLayerColor(wt.layers, project, WALL_RGB), - hatch: dominantLayerHatch(wt.layers, project, SECTION_WALL_AXIS_ANGLE_DEG), - materialIndex: resolveComponentMaterialLayer(project, dominant.componentId), - }; - return { bands: [band], stacked: false }; - } - const bands: WallBand[] = []; - for (const l of wt.layers) { - const comp = getComponent(project, l.componentId); - const color = hexToRgb(comp.color); - const lineStyle = resolveCutLineStyle(project, l.jointLineStyleId); - bands.push({ - thickness: l.thickness, - color, - priority: comp.joinPriority, - componentId: comp.id, - cutLineColor: lineStyle?.color, - cutLineWeight: lineStyle?.weight, - hatch: resolveComponentHatch(project, l.componentId, SECTION_WALL_AXIS_ANGLE_DEG), - materialIndex: resolveComponentMaterialLayer(project, l.componentId), - }); - } - return { bands, stacked: true }; - } - // WallType ohne Schichten: EIN Vollkörper über die Typ-Gesamtdicke. - return { bands: [{ thickness: wallTypeThickness(wt), color: WALL_RGB }], stacked: false }; - } catch { - // Kein auflösbarer WallType: EIN Vollkörper mit Default-Dicke/Grundton. - return { bands: [{ thickness: 0.2, color: WALL_RGB }], stacked: false }; - } -} - -/** - * Setzt `topAngle` (Draufsicht): wie der 2D-Grundriss — das Muster folgt der Wandachse - * (`relativeToWall`), `resolveHatch` zieht den Wandwinkel ab (SVG-Konvention, y nach unten); - * render3d rechnet in Modell-Winkeln (gegen den Uhrzeigersinn), daher das Vorzeichen. - */ -function withTopAngle(h: RHatch, dx: number, dy: number): RHatch { - if (h.baseAngle === undefined) return h; - const wallAngle = (Math.atan2(dy, dx) * 180) / Math.PI; - const svgAngle = h.relativeToWall ? h.baseAngle - wallAngle : h.baseAngle; - // Parallel-/Kreuzschar (diagonal=2, crosshatch=3): die 2D-Kachel trägt bei Winkel 0 eine - // SENKRECHTE Musterlinie (glPlanHatch: Basisrichtung (0,−1)), der 3D-Shader bei Winkel 0 - // eine HORIZONTALE → um 90° versetzen. Die Dämmungs-Welle (4) läuft in beiden entlang u. - const quarter = h.pattern === 2 || h.pattern === 3 ? 90 : 0; - return { ...h, topAngle: -svgAngle + quarter }; -} - -/** - * Dicke einer Wand für die grobe Grundriss-Hülle (Decken-Vorfilter im Kern): - * Summe der WallType-Schichtdicken, sonst der Fallback-Grundton-Dicke aus - * {@link resolveWallBands} (0.2 m), falls kein WallType auflösbar ist. Auch von - * `openings.ts::emitOpeningMeshes` genutzt (Rahmen-Tiefe auf die Wanddicke - * klemmen). - */ -export function wallThicknessSafe(project: Project, wall: Wall): number { - try { - return wallTypeThickness(getWallType(project, wall)); - } catch { - return 0.2; - } -} - -/** `Wall.sliceTermination` → Kodierung im Kern (0 = beide/Standard). */ -const TERMINATION = { below: 1, above: 2 } as const; - -/** - * Schreibt Decken und Dächer EINES Geschosses (Kodierung `wall_bands.rs`): Decken - * mit z-Ausdehnung, Umriss und Schichten samt Rang (NaN = Bauteil unbekannt, - * Typ-Flag 0 = Deckentyp unbekannt); Dächer mit Traufhöhe, Schichtdicke, Traufe - * und Flächen. Ob und wo eine Decke ein Band schneidet bzw. ein Dach die Oberkante - * kappt, entscheidet der Kern. - */ -function writeFloor(w: FlatWriter, project: Project, floorId: string | undefined): void { - const ceilings = (project.ceilings ?? []).filter((c) => c.floorId === floorId && c.outline && c.outline.length >= 3); - w.num(ceilings.length); - for (const c of ceilings) { - const ext = ceilingVerticalExtent(project, c); - w.num(ext.zBottom, ext.zTop).ring(c.outline); - let layers; - try { - layers = getCeilingType(project, c).layers; - } catch { - w.num(0, 0); - continue; - } - w.num(1, layers.length); - for (const l of layers) { - let prio = Number.NaN; - try { - prio = getComponent(project, l.componentId).joinPriority; - } catch { - // Unbekanntes Bauteil: diese Deckenschicht schneidet nicht. - } - w.num(l.thickness, prio); - } - } - const roofs = (project.roofs ?? []).filter((r) => r.floorId === floorId); - w.num(roofs.length); - for (const r of roofs) { - const eavesZ = roofBaseElevation(project, r); - const geo = roofGeometry(r, eavesZ); - const total = roofLayers(project, r).reduce((s, l) => s + Math.max(0, l.thickness), 0); - w.num(eavesZ, total).ring(geo.eaves); - const planes = roofPlanesFlat(geo); - for (let i = 0; i < planes.length; i++) w.num(planes[i]); - } -} - -/** - * Emittiert die Wandkörper der Wände `walls` in EINEM Kern-Aufruf (Decken/Dächer je - * Geschoss nur einmal übergeben). Reihenfolge der Körper wie Wand für Wand. - * - * ZWEI PFADE je `layered`: - * • layered=true (3D-Viewer, Default): EIN Körper pro Schicht-Band über die - * VOLLE Achse mit allen Öffnungen als echte `holes` (render3d stanzt sie in - * die Langseiten), dazu die materialbewussten Verschneidungen (End-Cuts/Merge - * an L-/T-Stössen aus `joins`, Durchgangswand-Span-Cutouts, Decken-Dominanz - * pro Schicht, schräge Oberkante unter Dächern als `topDrop`). - * • layered=false (Schnitt-Pfad, `computeSection`): Pfeiler/Brüstung/Sturz- - * Segmentierung (EIN Voll-Band je Segment), passend zu - * `toSection.ts::wallSegmentOwners`. Keine Löcher, keine Cuts. - */ -export function emitWalls( - out: RWall[], - project: Project, - walls: readonly Wall[], - layered = true, - joins?: Map, -): void { - const w = new FlatWriter().num(walls.length); - const floors = new FlatWriter(); - const floorIndex = new Map(); - const bandsOf: WallBand[][] = []; - - for (const wall of walls) { - const { bands, stacked } = resolveWallBands(project, wall, layered); - bandsOf.push(bands); - const { zBottom, zTop } = wallVerticalExtent(project, wall); - let floor = -1; - if (layered) { - floor = floorIndex.get(wall.floorId) ?? -1; - if (floor < 0) { - floor = floorIndex.size; - floorIndex.set(wall.floorId, floor); - writeFloor(floors, project, wall.floorId); - } - } - w.num(floor, wall.start.x, wall.start.y, wall.end.x, wall.end.y, zBottom, zTop, layered ? 1 : 0, stacked ? 1 : 0); - if (wall.referenceOffset != null) w.num(3, wall.referenceOffset); - else w.num(wall.referenceLine === "left" ? 1 : wall.referenceLine === "right" ? 2 : 0, 0); - const term = wall.sliceTermination === "below" || wall.sliceTermination === "above" ? TERMINATION[wall.sliceTermination] : 0; - w.num(wallThicknessSafe(project, wall), term, bands.length); - for (const b of bands) w.num(b.thickness, b.priority ?? Number.NaN); - - // Öffnungen (Fenster und Türen): Achsen-Intervall + vertikale Ausdehnung. - const slot = w.slot(); - let nOpenings = 0; - for (const op of openingsOfWall(project, wall.id)) { - const iv = openingInterval(wall, op); - if (!iv) continue; - const v = openingVerticalExtent(project, wall, op); - const recess = op.kind === "window" && getWindowType(project, op)?.innerLayerRecess === true; - w.num(iv.from, iv.to, v.zBottom, v.zTop, recess ? 1 : 0); - nOpenings++; - } - w.set(slot, nOpenings); - writeWallCuts(w, layered ? joins?.get(wall.id) : undefined); - } - - const floorBuf = new FlatWriter().num(floorIndex.size).done(); - const r = new FlatReader(core().wall_bands_flat(w.done(), concat(floorBuf, floors.done()))); - const nWalls = Math.min(r.count(), walls.length); - for (let i = 0; i < nWalls; i++) { - const wall = walls[i]; - const bands = bandsOf[i]; - const dx = wall.end.x - wall.start.x; - const dy = wall.end.y - wall.start.y; - for (let n = r.count(); n > 0; n--) { - const b = bands[r.num()]; - const start: [number, number] = [r.num(), r.num()]; - const end: [number, number] = [r.num(), r.num()]; - const zb = r.num(); - const zt = r.num(); - const sloped = r.num() === 1; - const topDrop: [number, number] = [r.num(), r.num()]; - const holes: RHole[] = []; - for (let k = r.count(); k > 0; k--) holes.push({ from: r.num(), to: r.num(), zBottom: r.num(), zTop: r.num() }); - if (!b) continue; - const cut = bandCutMeta(b); - out.push({ - start, - end, - thickness: b.thickness, - height: zt - zb, - baseElevation: zb, - ...(sloped ? { topDrop } : {}), - color: b.color, - layers: [], - wallId: wall.id, - ...(b.hatch ? { hatch: withTopAngle(b.hatch, dx, dy) } : {}), - ...(b.materialIndex != null ? { materialIndex: b.materialIndex } : {}), - ...(holes.length > 0 ? { holes } : {}), - ...(cut ? { cut } : {}), - }); - } - } -} - -function concat(a: Float64Array, b: Float64Array): Float64Array { - const out = new Float64Array(a.length + b.length); - out.set(a); - out.set(b, a.length); - return out; -} diff --git a/src/plan/toWalls3d/ceilings.ts b/src/plan/toWalls3d/ceilings.ts deleted file mode 100644 index c9162faa..00000000 --- a/src/plan/toWalls3d/ceilings.ts +++ /dev/null @@ -1,106 +0,0 @@ -// Decken-Domäne der 3D-Ableitung: extrudiert `project.ceilings` zu geschichteten -// Deckenplatten (eine RSlab je Materiallage, oben→unten gestapelt) — das 3D- -// Pendant zu `generatePlan/ceilings.ts::addCeilingPoche`. -// -// Die Rechnung (Aussparungen über den Brücken-Trick in EINEN einfachen Umriss, derselbe Ring für -// ALLE Schichten; z-Spanne proportional auf die Schichten verteilt) steht in Rust -// (`src-tauri/core/src/ceilings3d.rs`). Hier nur: aus dem `Project` sammeln und je Schicht -// Farbe, Schraffur und Schnitt-Metadaten zuordnen. - -import type { Ceiling, Layer, Project } from "../../model/types"; -import { getCeilingType, getComponent } from "../../model/types"; -import { ceilingVerticalExtent } from "../../model/wall"; -import { core } from "../../engine/coreWasm"; -import { FlatWriter } from "../../geometry/coreFlat"; -import { - SLAB_RGB, - hexToRgb, - resolveComponentHatch, - resolveCutLineStyle, - type RCutMeta, - type RRgb, - type RSlab, - type RVec2, -} from "./shared"; - -/** Emittiert die Deckenplatten eines Projekts (falls vorhanden). */ -export function emitSlabs(project: Project): RSlab[] { - const ceilings: Ceiling[] = []; - const layersOf: (Layer[] | undefined)[] = []; - const w = new FlatWriter(); - const count = w.slot(); - for (const c of project.ceilings ?? []) { - if (!c.outline || c.outline.length < 3) continue; - // zBottom/zTop (und damit die Deckendicke) berechnet ceilingVerticalExtent - // bereits über ceilingThickness (respektiert Typ-Dicke + Übersteuerung). - const { zBottom, zTop } = ceilingVerticalExtent(project, c); - // Kein auflösbarer Deckentyp ⇒ keine Lagen ⇒ EIN Vollkörper-Slab in SLAB_RGB. - let layers: Layer[] | undefined; - try { - layers = getCeilingType(project, c).layers; - } catch { - layers = undefined; - } - w.ring(c.outline); - const openings = c.openings ?? []; - w.num(openings.length); - for (const o of openings) w.ring(o); - w.num(zBottom, zTop, layers?.length ?? 0); - for (const l of layers ?? []) w.num(l.thickness); - ceilings.push(c); - layersOf.push(layers); - } - if (ceilings.length === 0) return []; - w.set(count, ceilings.length); - const f = core().ceilings3d_flat(w.done()); - - const out: RSlab[] = []; - let i = 1; - for (let n = f.length ? f[0] : 0; n > 0; n--) { - const ci = f[i++]; - const c = ceilings[ci]; - const layers = layersOf[ci]; - const nPts = f[i++]; - const outline: RVec2[] = new Array(nPts); - for (let k = 0; k < nPts; k++, i += 2) outline[k] = [f[i], f[i + 1]]; - for (let s = f[i++]; s > 0; s--, i += 3) { - const layerIdx = f[i]; - const zBottom = f[i + 1]; - const zTop = f[i + 2]; - if (layerIdx < 0 || !layers) { - out.push({ outline, zBottom, zTop, color: SLAB_RGB, ceilingId: c.id }); - continue; - } - const l = layers[layerIdx]; - let color: RRgb = SLAB_RGB; - let cut: RCutMeta | undefined; - try { - const comp = getComponent(project, l.componentId); - color = hexToRgb(comp.color); - // Schnitt-Metadaten der Schicht: joinPriority + Identität (für die - // Boolean-Dominanz/MERGE) + Schnittkanten-Stil aus jointLineStyleId. - const lineStyle = resolveCutLineStyle(project, l.jointLineStyleId); - cut = { - joinPriority: comp.joinPriority, - componentId: comp.id, - ...(lineStyle?.color ? { lineColor: lineStyle.color } : {}), - ...(lineStyle?.weight != null ? { lineWeight: lineStyle.weight } : {}), - }; - } catch { - color = SLAB_RGB; - cut = undefined; - } - const hatch = resolveComponentHatch(project, l.componentId); - out.push({ - outline, - zBottom, - zTop, - color, - ceilingId: c.id, - ...(hatch ? { hatch } : {}), - ...(cut ? { cut } : {}), - }); - } - } - return out; -} diff --git a/src/plan/toWalls3d/columns.ts b/src/plan/toWalls3d/columns.ts deleted file mode 100644 index 75a41e1c..00000000 --- a/src/plan/toWalls3d/columns.ts +++ /dev/null @@ -1,90 +0,0 @@ -// Stützen-Domäne der 3D-Ableitung (Tragwerk): extrudiert `project.columns` zu -// parametrischen Prisma-Meshes (Rechteck-Box bzw. tesselliertes Kreis-Prisma). -// -// Das Prisma (Mantel-Quads, Deckel als Dreiecksfächer) rechnet Rust -// (`src-tauri/core/src/columns3d.rs`); hier nur Querschnitt und Höhen sammeln und einfärben. - -import type { Column, Project, Vec2 } from "../../model/types"; -import { getComponent } from "../../model/types"; -import { columnFootprint } from "../../geometry/column"; -import { columnVerticalExtent } from "../../model/wall"; -import { core } from "../../engine/coreWasm"; -import { hexToRgb, type RMesh, type RRgb } from "./shared"; - -/** Neutraler Beton-/Tragwerks-Grauton für Stützen (Fallback ohne Bauteil-Farbe). */ -const COLUMN_RGB: RRgb = [0.7, 0.7, 0.72]; - -/** - * 3D-Farbe einer Stütze: die Bauteil-Albedo (`Component.color`), falls ein - * `componentId` auflösbar ist, sonst der neutrale Tragwerks-Grauton {@link - * COLUMN_RGB}. Eine explizite `column.color` (Grundriss-Umrissfarbe) wirkt - * bewusst NICHT auf die 3D-Fläche (nur der 2D-Umriss), damit die 3D-Darstellung - * material-/neutral bleibt — analog Wand (Umrissfarbe ≠ 3D-Albedo). - */ -function columnColor3d(project: Project, col: Column): RRgb { - if (col.componentId) { - try { - return hexToRgb(getComponent(project, col.componentId).color, COLUMN_RGB); - } catch { - return COLUMN_RGB; - } - } - return COLUMN_RGB; -} - -/** - * Extrudiert `project.columns` (Tragwerk) zu parametrischen Prisma-Meshes — - * Rechteck-Box bzw. tesselliertes Kreis-Prisma, je Profil. SYNCHRON (anders als - * die truck-Extrusion der `ExtrudedSolid`s, s. `../extrusions.ts`): die - * Kontur kommt aus `columnFootprint`, die vertikale Lage aus - * `columnVerticalExtent` (UK/OK-Anker bzw. Geschoss-UK + Höhe). `positions` in MODELL-Metern - * (x, y, z=Höhe); render3d rendert Kontext-Meshes doppelseitig, die Winding-Reihenfolge ist - * unerheblich. Rust/render3d bleibt unverändert (Kontext-Mesh-Pfad). - */ -export function emitColumns(project: Project): RMesh[] { - const cols: Column[] = []; - const feet: Vec2[][] = []; - const zs: number[] = []; - let doubles = 1; - for (const col of project.columns ?? []) { - if (col.height <= 0) continue; - const { zBottom, zTop } = columnVerticalExtent(project, col); - const foot = columnFootprint(col); - cols.push(col); - feet.push(foot); - zs.push(zBottom, zTop); - doubles += 3 + 2 * foot.length; - } - if (cols.length === 0) return []; - const buf = new Float64Array(doubles); - buf[0] = cols.length; - let w = 1; - for (let k = 0; k < cols.length; k++) { - const foot = feet[k]; - buf[w++] = zs[2 * k]; - buf[w++] = zs[2 * k + 1]; - buf[w++] = foot.length; - for (const p of foot) { - buf[w++] = p.x; - buf[w++] = p.y; - } - } - const f = core().columns3d_flat(buf); - - const out: RMesh[] = []; - let i = 1; - for (let n = f.length ? f[0] : 0; n > 0; n--) { - const col = cols[f[i]]; - const nPos = f[i + 1]; - const nIdx = f[i + 2]; - i += 3; - const positions: number[] = []; - for (let k = 0; k < nPos; k++) positions.push(f[i + k]); - i += nPos; - const indices: number[] = []; - for (let k = 0; k < nIdx; k++) indices.push(f[i + k]); - i += nIdx; - out.push({ positions, indices, kind: "extrusion", color: columnColor3d(project, col) }); - } - return out; -} diff --git a/src/plan/toWalls3d/frameRing.test.ts b/src/plan/toWalls3d/frameRing.test.ts deleted file mode 100644 index faa973be..00000000 --- a/src/plan/toWalls3d/frameRing.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { describe, expect, it } from "vitest"; -import type { FrameCornerJoin } from "../../model/types"; -import { frameRingQuads } from "./openings"; - -type Q = ReturnType[number]; -// Eckenfolge (from,UK),(to,UK),(from,OK),(to,OK) → als Ring 0,1,3,2. -const ring = (q: Q) => [q[0], q[1], q[3], q[2]]; -const area = (q: Q) => { - const r = ring(q); - let a = 0; - for (let i = 0; i < 4; i++) a += r[i][0] * r[(i + 1) % 4][1] - r[(i + 1) % 4][0] * r[i][1]; - return Math.abs(a) / 2; -}; - -describe("frameRingQuads", () => { - const modes: FrameCornerJoin[] = ["vertikal", "horizontal", "gehrung"]; - for (const mode of modes) { - it(`${mode}: Profile decken genau den Ring ab (keine Überlappung)`, () => { - const qs = frameRingQuads(0, 1.2, 0.9, 2.1, 0.06, mode, true); - expect(qs.length).toBe(4); - const total = qs.reduce((a, q) => a + area(q), 0); - const ringArea = 1.2 * 1.2 - (1.2 - 0.12) * (1.2 - 0.12); - expect(total).toBeCloseTo(ringArea, 9); - }); - it(`${mode}: ohne Schwelle (Tür) drei Profile`, () => { - const qs = frameRingQuads(0, 1.0, 0, 2.1, 0.06, mode, false); - expect(qs.length).toBe(3); - const total = qs.reduce((a, q) => a + area(q), 0); - expect(total).toBeCloseTo(1.0 * 2.1 - (1.0 - 0.12) * (2.1 - 0.06), 9); - }); - } - it("vertikal: Pfosten laufen durch, Riegel dazwischen", () => { - const [left] = frameRingQuads(0, 1, 0, 1, 0.1, "vertikal", true); - expect(left[0]).toEqual([0, 0]); - expect(left[3]).toEqual([0.1, 1]); - }); -}); diff --git a/src/plan/toWalls3d/openings.ts b/src/plan/toWalls3d/openings.ts deleted file mode 100644 index 9cdf3591..00000000 --- a/src/plan/toWalls3d/openings.ts +++ /dev/null @@ -1,201 +0,0 @@ -// Öffnungs-Domäne der 3D-Ableitung: Glasscheibe(n)/Türblatt, Rahmen-/Sprossen- -// Riegel (Zarge/Blendrahmen/Kämpfer/Mittelpfosten/Flügelrahmen + SIA-Symbole), -// Fensterbänke, Zargen-Umgriff, Schwellenprofil und der Rollladen-/Sonnenschutz- -// kasten typisierter Tür-/Fensteröffnungen — das 3D-Pendant zu -// `generatePlan/openings.ts`. -// -// Gerechnet wird im Rust-Kern (`src-tauri/core/src/openings3d.rs`, Kodierung -// dort); hier bleiben das Sammeln aus dem `Project` (Tür-/Fenstertyp, Flügel- -// tabelle, Öffnungs-Intervall und -Höhe, Wanddicke), die flache Übergabe aller -// Wände in EINEM Kern-Aufruf und die Farbe je Bauteil-Klasse. -// -// Die Quader liegen in MODELL-Metern (x, y, z = Höhe); render3d bildet sie nach -// world ab und rendert sie doppelseitig (Winding egal). `kind: "extrusion"` -// (NICHT "imported"): die Nord-Achsen-Negation in `append_context_mesh` gilt nur -// für echte Import-Rohdaten, Öffnungs-Quader entstehen orientierungserhaltend aus -// der Wandachse (Fund 2026-09-27). - -import type { DoorType, FrameCornerJoin, Opening, Project, WindowType } from "../../model/types"; -import { getDoorType, getWindowType, glazingPanesOf } from "../../model/types"; -import { openingInterval, openingVerticalExtent } from "../../geometry/opening"; -import type { DetailLevel } from "../../model/viewTypes"; -import { FlatReader, FlatWriter } from "../../geometry/coreFlat"; -import { core } from "../../engine/coreWasm"; -import type { RMesh, RRgb } from "./shared"; -import { wallThicknessSafe } from "./bands"; - -/** - * Farbe je Bauteil-Klasse (Index = `Part` in `openings3d.rs`): Glas (hell, - * bläulich), Rahmen (helles, warmes Grau), Rollladenkasten, Fensterbank/ - * Schwelle (Stein-Grau), SIA-Symbole (dunkle Linien auf dem Glas), Türblatt - * (warm, hell). - */ -const PART_RGB: readonly RRgb[] = [ - [0.62, 0.76, 0.85], - [0.85, 0.85, 0.83], - [0.88, 0.88, 0.9], - [0.8, 0.8, 0.78], - [0.25, 0.27, 0.3], - [0.93, 0.9, 0.85], -]; - -/** Dreiecke eines Öffnungs-Quaders (Ecken-Bits: bit0 = Achse, bit1 = Höhe, bit2 = quer). */ -const OPENING_BOX_TRIS: readonly number[] = [ - 0, 1, 3, 0, 3, 2, // quer nMin - 4, 5, 7, 4, 7, 6, // quer nMax - 0, 1, 5, 0, 5, 4, // UK - 2, 3, 7, 2, 7, 6, // OK - 0, 2, 6, 0, 6, 4, // from - 1, 3, 7, 1, 7, 5, // to -]; - -const DETAIL_CODE: Record = { grob: 0, mittel: 1, fein: 2 }; -const JOIN_CODE: Record = { horizontal: 1, gehrung: 2 }; -const OPENING_KIND_CODE: Record = { dreh: 1, kipp: 2, drehkipp: 3, fest: 4, schiebe: 5 }; -const SILL_BOARD_CODE: Record = { keine: 1, innen: 2, beide: 3 }; - -/** Fehlender Wert → NaN (der Kern setzt dort den Default). */ -const opt = (v: number | null | undefined): number => v ?? Number.NaN; -const flag = (b: boolean): number => (b ? 1 : 0); -const openingKindCode = (k: string | undefined): number => (k ? OPENING_KIND_CODE[k] ?? 6 : 0); - -/** Gemeinsame Typwerte (Kodierung `openings3d.rs`). */ -function writeCommon(w: FlatWriter, t: DoorType | WindowType): void { - w.num( - opt(t.frameDepth), - opt(t.insetFromFace), - flag((t.insetFace ?? "aussen") === "innen"), - JOIN_CODE[t.frameCornerJoin ?? ""] ?? 0, - opt(t.frameWidth), - opt(t.transomHeight), - ); -} - -function writeOpening(w: FlatWriter, project: Project, op: Opening): void { - if (op.kind === "window") { - const wt = getWindowType(project, op); - if (!wt) { - w.num(0); - return; - } - w.num(1); - writeCommon(w, wt); - const shading = wt.shading?.create ? wt.shading.box : undefined; - w.num( - glazingPanesOf(wt), - opt(wt.mullionRows), - opt(wt.mullionCols), - SILL_BOARD_CODE[wt.sillBoard ?? ""] ?? 0, - flag(!!shading), - shading?.width ?? 0, - shading?.height ?? 0, - shading?.depth ?? 0, - op.wingCount ?? wt.wingCount ?? 1, - openingKindCode(wt.kind), - ); - const sashes = wt.sashes ?? []; - w.num(sashes.length); - for (const s of sashes) { - w.num( - s.kind === "fluegel" ? 0 : s.kind === "pfosten" ? 1 : 2, - flag(s.autoWidth === false), - opt(s.width), - opt(s.postWidth), - openingKindCode(s.opening), - flag((s.hingeSide ?? "left") === "left"), - ); - } - return; - } - const dt = getDoorType(project, op); - if (!dt) { - w.num(0); - return; - } - w.num(1); - writeCommon(w, dt); - w.num( - flag(dt.threshold === true), - opt(dt.leafCount), - dt.leafStyle === "glas" ? 1 : dt.leafStyle === "kassette" ? 2 : 0, - opt(dt.glazingRatio), - flag((dt.frameKind ?? "zarge") === "zarge"), - opt(dt.panelCols), - opt(dt.panelRows), - ); -} - -/** - * Alle Öffnungs-Einbauteile eines Projekts als rohe Quader-Meshes, in EINEM - * Kern-Aufruf. Reihenfolge wie früher: erst Glas/Türblätter aller Wände, dann - * Rahmen/Sprossen/Bänke/Zargen (nicht bei „grob"), dann Rollladenkästen (nicht - * bei „grob"). - * - * • Ohne auflösbaren Typ: Fenster = EINE Vollscheibe mittig in der Wand, Tür = - * offenes Loch, kein Rahmen (Rückwärtskompatibilität). - * • „mittel": Blendrahmen + Oberlicht-Kämpfer + Flügelrahmen + Fensterbank/ - * Zargen-Umgriff/Schwellenprofil, keine Sprossen, keine SIA-Symbole. - * • „fein": zusätzlich Flügel-Mittelpfosten, Kämpfer-Zeilen und SIA-Symbole. - */ -export function emitOpeningMeshes(project: Project, detail: DetailLevel = "fein"): RMesh[] { - const byWall = new Map(); - for (const op of project.openings ?? []) { - const list = byWall.get(op.hostWallId); - if (list) list.push(op); - else byWall.set(op.hostWallId, [op]); - } - const w = new FlatWriter().num(DETAIL_CODE[detail] ?? 3, project.walls.length); - for (const wall of project.walls) { - w.num(wall.start.x, wall.start.y, wall.end.x, wall.end.y); - const slot = w.slot(); - let count = 0; - let thickness: number | undefined; - for (const op of byWall.get(wall.id) ?? []) { - const iv = openingInterval(wall, op); - if (!iv) continue; - const vert = openingVerticalExtent(project, wall, op); - thickness ??= wallThicknessSafe(project, wall); - w.num(iv.from, iv.to, vert.zBottom, vert.zTop, flag(op.kind !== "window"), thickness); - writeOpening(w, project, op); - count++; - } - w.set(slot, count); - } - const buf = core().opening_meshes_flat(w.done()); - const out: RMesh[] = []; - const n = new FlatReader(buf).count(); - for (let k = 0, i = 1; k < n && i + 25 <= buf.length; k++, i += 25) { - const positions = new Array(24); - for (let j = 0; j < 24; j++) positions[j] = buf[i + 1 + j]; - out.push({ positions, indices: [...OPENING_BOX_TRIS], kind: "extrusion", color: PART_RGB[buf[i]] ?? PART_RGB[1] }); - } - return out; -} - -/** - * Rahmen-Ring (Pfosten links/rechts, Riegel oben, Riegel unten nur bei - * `bottom`) über das Feld `[from,to]×[zB,zT]` mit Profilbreite `w`, ohne - * überlappende Profile; `join` bestimmt die durchlaufenden Glieder. Glieder als - * (u,h)-Vierecke: (from,UK), (to,UK), (from,OK), (to,OK). Rechnet im Kern. - */ -export function frameRingQuads( - from: number, - to: number, - zB: number, - zT: number, - w: number, - join: FrameCornerJoin, - bottom: boolean, -): Array<[[number, number], [number, number], [number, number], [number, number]]> { - const r = new FlatReader(core().frame_ring_quads_flat(from, to, zB, zT, w, JOIN_CODE[join] ?? 0, bottom)); - const out: Array<[[number, number], [number, number], [number, number], [number, number]]> = []; - for (let n = r.count(); n > 0; n--) { - out.push([ - [r.num(), r.num()], - [r.num(), r.num()], - [r.num(), r.num()], - [r.num(), r.num()], - ]); - } - return out; -} diff --git a/src/plan/toWalls3d/roofMitre.test.ts b/src/plan/toWalls3d/roofMitre.test.ts deleted file mode 100644 index 2bb65878..00000000 --- a/src/plan/toWalls3d/roofMitre.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { describe, expect, it } from "vitest"; -import type { Vec3 } from "../../geometry/roof"; -import { mitredRoofOffsets } from "./roofs"; - -// Walmdach 12×7 m: zwei Trapeze + zwei Walm-Dreiecke, First (3,3)-(8,3). -const planes: Vec3[][] = [ - [[-0.5, -0.5, 5.2], [11.5, -0.5, 5.2], [8, 3, 7.061], [3, 3, 7.061]], - [[-0.5, 6.5, 5.2], [11.5, 6.5, 5.2], [8, 3, 7.061], [3, 3, 7.061]], - [[-0.5, -0.5, 5.2], [-0.5, 6.5, 5.2], [3, 3, 7.061]], - [[11.5, -0.5, 5.2], [11.5, 6.5, 5.2], [8, 3, 7.061]], -]; - -const near = (a: Vec3, b: Vec3) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]) < 1e-6; - -describe("mitredRoofOffsets", () => { - const m = mitredRoofOffsets(planes); - it("erkennt First und Grate als geteilte Kanten, Traufen als frei", () => { - expect(m.shared[0]).toEqual([false, true, true, true]); // Traufe, Grat, First, Grat - expect(m.shared[2]).toEqual([false, true, true]); - }); - it("Unterseiten treffen sich am First-Apex in EINEM Punkt (Gehrung statt Durchdringung)", () => { - const d = 0.27; - const apexA = m.at(0, d)[3]; // (3,3) der Trapezfläche - const apexB = m.at(1, d)[3]; - const apexC = m.at(2, d)[2]; // Walm-Spitze - expect(near(apexA, apexB)).toBe(true); - expect(near(apexA, apexC)).toBe(true); - expect(apexA[2]).toBeLessThan(7.061); - }); - it("Versatz 0 = Originalfläche, freie Traufecke bleibt senkrecht versetzt", () => { - expect(m.at(0, 0)).toEqual(planes[0]); - const eaves = m.at(0, 0.2)[0]; - // Traufecke (−0.5,−0.5) teilt den Grat mit dem Walm → gehrt, aber Höhe unter der Traufe. - expect(eaves[2]).toBeLessThan(5.2); - }); -}); diff --git a/src/plan/toWalls3d/roofWinding.test.ts b/src/plan/toWalls3d/roofWinding.test.ts index dc80981e..5177dc4c 100644 --- a/src/plan/toWalls3d/roofWinding.test.ts +++ b/src/plan/toWalls3d/roofWinding.test.ts @@ -1,8 +1,8 @@ -// Dach-Meshes (`emitRoofs`) sind je Schicht geschlossene, nach aussen gewundene Körper — Voraussetzung +// Dach-Meshes (`roofMeshes`) sind je Schicht geschlossene, nach aussen gewundene Körper — Voraussetzung // für Closed-Face-Sets im IFC und korrektes Rückseiten-Culling. import { describe, expect, it } from "vitest"; -import { emitRoofs } from "./roofs"; +import { roofMeshes } from "../toWalls3d"; import { isWatertight } from "../wallMeshCut"; import { sampleProject } from "../../model/sampleProject"; import type { Project, Roof, RoofShape } from "../../model/types"; @@ -37,7 +37,7 @@ describe("Dach-Meshes geschlossen und nach aussen gewunden", () => { for (const axis of ["x", "y"] as const) { it(`${shape} (First ${axis})`, () => { const p: Project = { ...sampleProject, roofs: [roof(shape, axis)] }; - const meshes = emitRoofs(p); + const meshes = roofMeshes(p); expect(meshes.length).toBeGreaterThan(0); for (const m of meshes) { const c = closure(m); diff --git a/src/plan/toWalls3d/roofs.ts b/src/plan/toWalls3d/roofs.ts deleted file mode 100644 index acfac3d6..00000000 --- a/src/plan/toWalls3d/roofs.ts +++ /dev/null @@ -1,298 +0,0 @@ -// Dach-Domäne der 3D-Ableitung: emittiert Dächer (`project.roofs`) als -// geschlossene, geschichtete Dreiecks-Meshes (Eindeckung → innen) aus den -// geneigten Dachflächen (`RoofGeometry.planes`) — jede Schicht ein eigener -// solider Slab mit ihrer Bauteilfarbe/-textur. - -import type { Project } from "../../model/types"; -import { getComponent, roofLayers } from "../../model/types"; -import { roofBaseElevation, roofGeometry } from "../../geometry/roof"; -import type { Vec3 as RoofVec3 } from "../../geometry/roof"; -import { - EPS, - hexToRgb, - resolveComponentMaterialLayer, - resolveCutLineStyle, - type RCutMeta, - type RMesh, - type RRgb, - type RRoofLayer, -} from "./shared"; - -/** Warmer Terrakotta-Grauton für Dachflächen/-giebel — hebt das Dach klar von Wand/Decke/Kontext ab. */ -const ROOF_RGB: RRgb = [0.72, 0.45, 0.36]; - -/** - * Trianguliert ein KONVEXES 3D-Polygon per Dreiecks-Fächer ab Vertex 0 und hängt - * die Dreiecke an `positions`/`indices` an. `roofGeometry` (Vertrag in - * `geometry/roof.ts`) liefert für `planes`/`gables` ausschliesslich konvexe - * Polygone (Dreieck/Quader bei den meisten Formen, ein Fünfeck-Giebel bei - * Mansarde) — ein Fächer trianguliert diese korrekt, ohne Ear-Clipping. - */ -function pushFanTriangles(positions: number[], indices: number[], pts: RoofVec3[], flip = false): void { - if (pts.length < 3) return; - const base = positions.length / 3; - for (const p of pts) positions.push(p[0], p[1], p[2]); - for (let i = 1; i < pts.length - 1; i++) { - if (flip) indices.push(base, base + i + 1, base + i); - else indices.push(base, base + i, base + i + 1); - } -} - -/** - * Robuste Flächennormale (Newell) einer Polygon-Ebene in MODELL-Koordinaten - * ([x, y, z=Höhe]), nach OBEN orientiert (positive Höhen-Komponente) — für die - * Dach-Dickenversetzung (Unterseite = Oberseite − Normale·Dicke). - */ -function planeNormalUp(pts: RoofVec3[]): [number, number, number] { - let nx = 0; - let ny = 0; - let nz = 0; - for (let i = 0; i < pts.length; i++) { - const c = pts[i]; - const d = pts[(i + 1) % pts.length]; - nx += (c[1] - d[1]) * (c[2] + d[2]); - ny += (c[2] - d[2]) * (c[0] + d[0]); - nz += (c[0] - d[0]) * (c[1] + d[1]); - } - const len = Math.hypot(nx, ny, nz) || 1; - const u: [number, number, number] = [nx / len, ny / len, nz / len]; - return u[2] < 0 ? [-u[0], -u[1], -u[2]] : u; -} - -/** - * Gehrte Versatz-Ecken für ALLE Dachflächen eines Daches: liefert je Fläche die - * um `d` (Meter, entlang der Flächennormalen nach innen) versetzten Ecken — - * aber an Kanten, die sich zwei Flächen teilen (First/Grat/Knick), NICHT - * stur entlang der EIGENEN Normalen, sondern auf der Gehrung: die Ecke liegt im - * Schnitt der versetzten Ebenen beider Flächen. Vorher durchdrangen sich die - * Slabs benachbarter Flächen am First, ihre Stirnflächen lagen deckungsgleich - * auf der Nachbar-Oberseite (Störtriangle am First-Apex im „Schattiert mit - * Kanten"-Modus). Freie Kanten (Traufe/Ortgang) behalten die senkrechte - * Stirnfläche. `shared[i][k]` = Kante k→k+1 von Fläche i ist geteilt. - */ -export function mitredRoofOffsets(planes: RoofVec3[][]): { - at: (i: number, d: number) => RoofVec3[]; - shared: boolean[][]; -} { - const r = (v: number) => Math.round(v * 1e5); - const pk = (p: RoofVec3) => `${r(p[0])},${r(p[1])},${r(p[2])}`; - const ek = (a: RoofVec3, b: RoofVec3) => { - const ka = pk(a); - const kb = pk(b); - return ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`; - }; - const edgeOwners = new Map(); - planes.forEach((pts, i) => { - for (let k = 0; k < pts.length; k++) { - const key = ek(pts[k], pts[(k + 1) % pts.length]); - const list = edgeOwners.get(key); - if (list) list.push(i); - else edgeOwners.set(key, [i]); - } - }); - const normals = planes.map((pts) => planeNormalUp(pts)); - const neighbor = planes.map((pts, i) => - pts.map((p, k) => { - const owners = edgeOwners.get(ek(p, pts[(k + 1) % pts.length])) ?? []; - const j = owners.find((o) => o !== i); - return j === undefined ? -1 : j; - }), - ); - const shared = neighbor.map((row) => row.map((j) => j >= 0)); - const dot = (a: RoofVec3, b: RoofVec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; - const cross = (a: RoofVec3, b: RoofVec3): RoofVec3 => [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], - ]; - // Ebene (Normale m, Abstand c: m·x = c) der Kante k→k+1 von Fläche i beim Versatz d: - // geteilt → versetzte Nachbarebene (Gehrung), frei → senkrechte Stirnebene. - const edgePlane = (i: number, k: number, d: number): [RoofVec3, number] => { - const pts = planes[i]; - const a = pts[k]; - const b = pts[(k + 1) % pts.length]; - const j = neighbor[i][k]; - if (j >= 0) return [normals[j], dot(normals[j], planes[j][0]) - d]; - const dir: RoofVec3 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; - const m = cross(dir, normals[i]); - return [m, dot(m, a)]; - }; - // Schnittpunkt dreier Ebenen (Cramer über Kreuzprodukte), null wenn entartet. - const solve = (rows: Array<[RoofVec3, number]>): RoofVec3 | null => { - const [[a, ca], [b, cb], [c, cc]] = rows; - const bc = cross(b, c); - const det = dot(a, bc); - if (Math.abs(det) < 1e-9) return null; - const cxa = cross(c, a); - const axb = cross(a, b); - return [ - (ca * bc[0] + cb * cxa[0] + cc * axb[0]) / det, - (ca * bc[1] + cb * cxa[1] + cc * axb[1]) / det, - (ca * bc[2] + cb * cxa[2] + cc * axb[2]) / det, - ]; - }; - const at = (i: number, d: number): RoofVec3[] => { - const pts = planes[i]; - const n = normals[i]; - if (d <= EPS) return pts.map((p) => [p[0], p[1], p[2]]); - const own: [RoofVec3, number] = [n, dot(n, pts[0]) - d]; - return pts.map((p, k) => { - const prev = (k + pts.length - 1) % pts.length; - const fallback: RoofVec3 = [p[0] - n[0] * d, p[1] - n[1] * d, p[2] - n[2] * d]; - if (!shared[i][prev] && !shared[i][k]) return fallback; - const q = solve([own, edgePlane(i, prev, d), edgePlane(i, k, d)]); - // Ausreisser (fast parallele Ebenen) abfangen: nicht weiter als ein paar - // Dicken von der senkrechten Lösung entfernt. - if (!q || Math.hypot(q[0] - fallback[0], q[1] - fallback[1], q[2] - fallback[2]) > 4 * d + 0.5) { - return fallback; - } - return q; - }); - }; - return { at, shared }; -} - -/** - * Slab einer Dachfläche zwischen fertigen Ober-/Unterseiten-Ecken (gleiche - * Reihenfolge). Stirnflächen nur an FREIEN Kanten (`shared[k]` = false) — an - * geteilten Kanten stossen die Nachbarflächen auf Gehrung, eine Stirnfläche - * läge dort im Inneren des Dachs. - */ -function pushRoofSlabBetween( - positions: number[], - indices: number[], - top: RoofVec3[], - bottom: RoofVec3[], - shared: boolean[], -): void { - // Wicklung nach aussen (geschlossener Körper, s. roofWinding.test.ts): Umlaufsinn der - // Oberseite von oben gesehen (Newell, Höhen-Komponente). Gegen den Uhrzeigersinn ⇒ Oberseite - // wie gegeben, Unterseite umgekehrt, Stirnfläche je Kante i→j als top[i], bottom[i], bottom[j], - // top[j] (Normale zeigt rechts der Kante = aussen); im Uhrzeigersinn alles gespiegelt. - let nz = 0; - for (let i = 0; i < top.length; i++) { - const a = top[i]; - const b = top[(i + 1) % top.length]; - nz += (a[0] - b[0]) * (a[1] + b[1]); - } - const ccw = nz > 0; - pushFanTriangles(positions, indices, top, !ccw); - pushFanTriangles(positions, indices, bottom, ccw); - for (let i = 0; i < top.length; i++) { - if (shared[i]) continue; - const j = (i + 1) % top.length; - const base = positions.length / 3; - positions.push(top[i][0], top[i][1], top[i][2]); - positions.push(bottom[i][0], bottom[i][1], bottom[i][2]); - positions.push(bottom[j][0], bottom[j][1], bottom[j][2]); - positions.push(top[j][0], top[j][1], top[j][2]); - if (ccw) indices.push(base, base + 1, base + 2, base, base + 2, base + 3); - else indices.push(base, base + 2, base + 1, base, base + 3, base + 2); - } -} - -/** - * Emittiert Dächer (`project.roofs`) als geschlossene Dreiecks-Meshes: sowohl die - * geneigten Dachflächen (`RoofGeometry.planes`) als auch die Giebelflächen - * (`RoofGeometry.gables`) — erst zusammen bilden sie einen von aussen - * geschlossenen Körper (die Giebel schliessen die offenen Enden bei Sattel/ - * Mansarde, die First-/Grat-/Knicklinien sind reine Grundriss-Hilfslinien und - * werden hier nicht gebraucht). Traufhöhe über `roofBaseElevation` - * (Override oder Geschoss-Oberkante), Flächen über `roofGeometry`. Farbe: - * `roof.color` (falls gültiges Hex), sonst {@link ROOF_RGB}. `positions` in - * MODELL-Metern (x, y, z=Höhe); render3d rendert Kontext-Meshes doppelseitig, - * die Winding-Reihenfolge ist also unerheblich. - */ -export function emitRoofs(project: Project): RMesh[] { - const out: RMesh[] = []; - for (const roof of project.roofs ?? []) { - const eavesZ = roofBaseElevation(project, roof); - const g = roofGeometry(roof, eavesZ); - const overrideColor = roof.color ? hexToRgb(roof.color, ROOF_RGB) : null; - // Schichtaufbau (aussen/Eindeckung → innen). Jede Schicht wird zu einem - // eigenen RMesh mit ihrer Bauteilfarbe, entlang der Flächennormalen unter die - // vorige gestapelt. Leere componentId (einschichtige thickness-Fallback) ⇒ - // Default-Dachfarbe. Eine Roof.color-Übersteuerung gilt für alle Schichten. - const layers = roofLayers(project, roof); - const mitre = mitredRoofOffsets(g.planes.map((pl) => pl.pts)); - layers.reduce((offsetAbove, layer) => { - const t = Math.max(0, layer.thickness); - if (t <= EPS) return offsetAbove; - const color = - overrideColor ?? - (layer.componentId ? hexToRgb(getComponent(project, layer.componentId).color, ROOF_RGB) : ROOF_RGB); - // Material-Textur-Ebene fürs Textured-Rendering (z. B. echte Dachziegel- - // Textur der Eindeckung) — nur wenn KEIN Farb-Override greift (Override - // = bewusst eine einheitliche Farbe für alle Schichten, kein Bauteil-Bezug). - const materialIndex = - !overrideColor && layer.componentId - ? resolveComponentMaterialLayer(project, layer.componentId) - : undefined; - const positions: number[] = []; - const indices: number[] = []; - g.planes.forEach((plane, i) => { - // Oberseite dieser Schicht = Dachfläche um `offsetAbove` nach innen - // versetzt, Unterseite um `offsetAbove + t` — an First/Grat gehrt. - if (plane.pts.length < 3) return; - const top = mitre.at(i, offsetAbove); - const bottom = mitre.at(i, offsetAbove + t); - pushRoofSlabBetween(positions, indices, top, bottom, mitre.shared[i]); - }); - if (indices.length > 0) out.push({ positions, indices, kind: "extrusion", color, materialIndex }); - return offsetAbove + t; - }, 0); - // Giebel-ENDFÜLLUNG bewusst NICHT mehr emittieren: die dreieckige Giebelfläche - // wurde früher als papierdünne Einzelfläche gebaut ("komischer Abschluss" an - // den Sattel-/Mansard-Enden) und lag zudem deckungsgleich vor der Giebelwand, - // die ohnehin bis an die Dach-Unterkante hochgeklemmt wird (s. - // `../bands.ts::clipPieceToRoofs`) — also doppelt und optisch als dünne - // 2D-Schicht sichtbar. Es wird nur noch das Dach SELBST (die geneigten - // Slab-Flächen) konstruiert; der Giebel entsteht aus der Wand darunter. - } - return out; -} - -/** - * Baut die Dach-Schicht-Eingabe für den 3D-Live-Schnitt (`RRoofLayer[]`, - * `render3d::roof_cut::cut_roof_layer`) — GETRENNT von {@link emitRoofs} (dem - * Render-Mesh), weil `section.rs` beliebige Dreiecksnetze nicht schneiden - * kann (nur Wand-Boxen/Decken-Polygone; eine Dachfläche ist kein vertikales - * Prisma, s. `RRoofLayer`-Doc in `shared.ts`). EIN Eintrag je (Dach, Schicht, - * geneigte Fläche) — ein mehrflächiges Dach (Sattel/Walm/Mansarde) hat - * mehrere `g.planes`, jede mit ihrer eigenen Normalen, anders als beim - * gemeinsam tessellierten Render-Mesh also KEIN zusammengefasster Eintrag. - * Punkte/Normalen bleiben in MODELL-Metern (wie `emitRoofs`) — render3d macht - * den Modell->Welt-Wechsel selbst (dieselbe Konvention wie `RMesh`). - */ -export function emitRoofCutLayers(project: Project): RRoofLayer[] { - const out: RRoofLayer[] = []; - for (const roof of project.roofs ?? []) { - const eavesZ = roofBaseElevation(project, roof); - const g = roofGeometry(roof, eavesZ); - const overrideColor = roof.color ? hexToRgb(roof.color, ROOF_RGB) : null; - const layers = roofLayers(project, roof); - layers.reduce((offsetAbove, layer) => { - const t = Math.max(0, layer.thickness); - if (t <= EPS) return offsetAbove; - const color = - overrideColor ?? - (layer.componentId ? hexToRgb(getComponent(project, layer.componentId).color, ROOF_RGB) : ROOF_RGB); - const lineStyle = resolveCutLineStyle(project, layer.jointLineStyleId); - const cut: RCutMeta | undefined = - lineStyle && (lineStyle.color !== undefined || lineStyle.weight !== undefined) - ? { lineColor: lineStyle.color, lineWeight: lineStyle.weight } - : undefined; - for (const plane of g.planes) { - const nrm = planeNormalUp(plane.pts); - const top: RoofVec3[] = plane.pts.map((p) => [ - p[0] - nrm[0] * offsetAbove, - p[1] - nrm[1] * offsetAbove, - p[2] - nrm[2] * offsetAbove, - ]); - out.push({ polygon: top, normal: nrm, thickness: t, color, cut }); - } - return offsetAbove + t; - }, 0); - } - return out; -} diff --git a/src/plan/toWalls3d/shared.ts b/src/plan/toWalls3d/shared.ts index b553892b..a83931ab 100644 --- a/src/plan/toWalls3d/shared.ts +++ b/src/plan/toWalls3d/shared.ts @@ -1,15 +1,12 @@ // Gemeinsame Grundlage der 3D-Ableitung: das Serde-Vokabular (`RWall`/`RSlab`/ // `RMesh`/…, matcht 1:1 render3d::types) sowie die Farb-/Schraffur-/Material- // Auflösung, die über mehrere Bauteil-Domänen hinweg identisch gelten muss -// (Hex→RGB, dominante Schicht, Schnitt-Schraffur, Material-Textur-Ebene). +// (Hex→RGB). Die Ableitung selbst rechnet der Rust-Kern (`src-tauri/core/src/model3d.rs`). // // Jede Datei unter `toWalls3d/` importiert von hier, NIE von `../toWalls3d` // selbst — das hielte die Orchestrator-Datei (`toWalls3d.ts`) andernfalls in // einem Zirkelimport mit jeder einzelnen Domäne. -import type { HatchPattern, Layer, Project } from "../../model/types"; -import { getCeilingType, getComponent, getWallType, roofLayers } from "../../model/types"; -import { resolveHatch } from "../generatePlan"; import type { Vec3 as RoofVec3 } from "../../geometry/roof"; export type RVec2 = [number, number]; @@ -60,144 +57,6 @@ export interface RHatch { topAngle?: number; } -/** Bildet ein 2D-{@link HatchPattern} auf die Muster-Id von {@link RHatch}/CAP_WGSL ab. */ -function hatchPatternId(p: HatchPattern): number { - switch (p) { - case "solid": - return 1; - case "diagonal": - return 2; - case "crosshatch": - return 3; - case "insulation": - return 4; - case "none": - default: - return 0; - } -} - -/** - * Löst die Schnitt-Schraffur eines Bauteils (per `Component.hatchId`) zu einem - * {@link RHatch} auf — dasselbe Muster/Winkel/Skalierung wie der 2D-Schnitt - * (`generatePlan.ts::resolveHatch`, hier bewusst NICHT aufgerufen: nur die drei - * render3d-relevanten Felder werden direkt aus dem `HatchStyle` gezogen, die - * Farbe bleibt monochrom im Shader). `undefined`, wenn das Bauteil/die Schraffur - * nicht auflösbar ist (der Cap-Shader fällt dann auf sein Diagonalmuster zurück). - */ -export function resolveComponentHatch( - project: Project, - componentId: string, - axisAngleDeg?: number, -): RHatch | undefined { - try { - const comp = getComponent(project, componentId); - if (!comp.hatchId) return undefined; - // GENAU der 2D-Schnitt-Pfad (`splitWallLayers`/`splitSlabLayers` → - // `resolveHatch`): `axisAngleDeg` = 90 für WAND-Bänder (die geschnittene Wand - // steht vertikal, `relativeToWall`-Muster drehen mit), `undefined` für DECKEN - // (kein Wandachsen-Bezug → absoluter Winkel). Wir übernehmen den ENDWINKEL - // (`HatchRender.angle`, bereits relativeToWall-korrigiert) UND die Musterlinien- - // Stärke (`lineWeight`, aus dem LineStyle) — nicht mehr den rohen Hatch-Winkel. - const hr = resolveHatch(project, comp.hatchId, axisAngleDeg); - // Wandbezug für die Draufsicht: Grundwinkel + ob das Muster der Wandachse folgt. - const abs = resolveHatch(project, comp.hatchId, undefined); - const relativeToWall = resolveHatch(project, comp.hatchId, 90).angle !== abs.angle; - return { - pattern: hatchPatternId(hr.pattern), - angle: hr.angle, - scale: hr.scale, - lineWeight: hr.lineWeight, - baseAngle: abs.angle, - relativeToWall, - }; - } catch { - return undefined; - } -} - -/** - * Schnitt-Schraffur der dicksten (dominanten) Schicht eines Schichtstapels. - * `axisAngleDeg` wie {@link resolveComponentHatch} (90 für Wand, undefined für Decke). - */ -export function dominantLayerHatch( - layers: Layer[], - project: Project, - axisAngleDeg?: number, -): RHatch | undefined { - if (layers.length === 0) return undefined; - const dominant = layers.reduce((best, l) => (l.thickness > best.thickness ? l : best)); - return resolveComponentHatch(project, dominant.componentId, axisAngleDeg); -} - -/** - * Geordnete Liste der EINDEUTIGEN Material-Farbkarten-URLs (`Component.material. - * color`), die von Wand-/Decken-Bauteilen des Projekts benutzt werden — in - * deterministischer First-Seen-Reihenfolge über `project.walls` (Wandtyp-Schichten) - * dann `project.ceilings`. Die POSITION in dieser Liste (+1) ist der Textur-Array- - * Index (`WallInput.materialIndex`, 1-basiert; Ebene 0 = Fallback-Schachbrett), den - * sowohl {@link resolveComponentMaterialLayer} (Zuweisung je Band) als auch der - * JS-Decoder (`viewport/materialTextures`) verwenden — so stimmen Band-Index und - * hochgeladene Textur-Ebene ohne separaten Map-Transport überein. Memoisiert je - * Projekt-REFERENZ (der Store ist immutabel — jede Änderung liefert ein neues - * Objekt, also kein Stale-Risiko), damit die per-Band-Auflösung nicht quadratisch wird. - */ -const materialMapCache = new WeakMap(); -export function wallMaterialColorMaps(project: Project): string[] { - const cached = materialMapCache.get(project); - if (cached) return cached; - const seen = new Set(); - const list: string[] = []; - const consider = (componentId: string): void => { - try { - const url = getComponent(project, componentId).material?.color; - if (url && !seen.has(url)) { - seen.add(url); - list.push(url); - } - } catch { - // Unauflösbares Bauteil überspringen. - } - }; - for (const w of project.walls) { - try { - for (const l of getWallType(project, w).layers) consider(l.componentId); - } catch { - // Kein auflösbarer Wandtyp. - } - } - for (const c of project.ceilings ?? []) { - try { - for (const l of getCeilingType(project, c).layers) consider(l.componentId); - } catch { - // Kein auflösbarer Deckentyp. - } - } - for (const r of project.roofs ?? []) { - for (const l of roofLayers(project, r)) { - if (l.componentId) consider(l.componentId); - } - } - materialMapCache.set(project, list); - return list; -} - -/** - * Textur-Array-Ebene (1-basiert) der Material-Farbkarte eines Bauteils, oder - * `undefined`, wenn das Bauteil kein Material mit Farbkarte trägt. Ebene 0 ist das - * Fallback-Schachbrett — deshalb `indexOf + 1`. Siehe {@link wallMaterialColorMaps}. - */ -export function resolveComponentMaterialLayer(project: Project, componentId: string): number | undefined { - try { - const url = getComponent(project, componentId).material?.color; - if (!url) return undefined; - const idx = wallMaterialColorMaps(project).indexOf(url); - return idx >= 0 ? idx + 1 : undefined; - } catch { - return undefined; - } -} - /** * Ein rechteckiges LOCH (Fenster/Tür) in EINEM Wandkörper — matcht 1:1 * render3d::types::Hole. KONVENTION: `from`/`to` sind Achsen-Meter ab @@ -407,41 +266,3 @@ export function hexToRgb(hex: string, fallback: RRgb = WALL_RGB): RRgb { const v = parseInt(m[1], 16); return [((v >> 16) & 0xff) / 255, ((v >> 8) & 0xff) / 255, (v & 0xff) / 255]; } - -/** - * Repräsentative Bauteilfarbe eines Schichtaufbaus: die Farbe der DICKSTEN - * Schicht (i. d. R. die tragende/dominante Schicht, z. B. Mauerwerk/Beton) — - * einfache Näherung, solange Wände/Decken als EIN Vollkörper emittiert werden - * (kein Schicht-Rendering in 3D). Fällt auf `fallback` zurück, wenn keine - * Schicht vorhanden ist oder deren Component nicht auflösbar ist. - */ -export function dominantLayerColor(layers: Layer[], project: Project, fallback: RRgb): RRgb { - if (layers.length === 0) return fallback; - const dominant = layers.reduce((best, l) => (l.thickness > best.thickness ? l : best)); - try { - return hexToRgb(getComponent(project, dominant.componentId).color, fallback); - } catch { - return fallback; - } -} - -/** - * Löst den Schnitt-UMRISSLINIEN-Stil einer Schicht aus ihrem - * `Layer.jointLineStyleId` (LineStyle) auf: Farbe (hex→RGB 0..1) + Strichstärke - * (mm-Papier) — dieselbe Quelle wie die 2D-Schichtfuge (`generatePlan/walls.ts`). - * Fehlt der Verweis/LineStyle, `undefined` (der 3D-Cut fällt dann auf seinen - * Default-Schnittkanten-Stil zurück, siehe `section_fill::build_cut_cap_lines`). - * Bewusst tolerant (`find` statt `getLineStyle`), wie im 2D — ein verwaister - * Verweis darf den 3D-Push nicht werfen. Von {@link ../bands.resolveWallBands} - * UND `../ceilings.emitSlabs` genutzt (Wand- wie Deckenschicht teilen dieselbe - * Fugen-Auflösung). - */ -export function resolveCutLineStyle( - project: Project, - jointLineStyleId: string | undefined, -): { color?: RRgb; weight?: number } | undefined { - if (!jointLineStyleId) return undefined; - const ls = project.lineStyles.find((l) => l.id === jointLineStyleId); - if (!ls) return undefined; - return { color: hexToRgb(ls.color, DRAWING_LINE_FALLBACK_RGB), weight: ls.weight }; -} diff --git a/src/plan/toWalls3d/stairs.ts b/src/plan/toWalls3d/stairs.ts deleted file mode 100644 index 80287079..00000000 --- a/src/plan/toWalls3d/stairs.ts +++ /dev/null @@ -1,160 +0,0 @@ -// Treppen-Domäne der 3D-Ableitung: emittiert Treppen als extrudierte RSlabs -// (Tritte + Podest, tragart-abhängige Untersicht) — der WASM/wgpu-Renderer -// kennt sonst KEINE Treppen (nur Wände/Decken/Meshes). Für Ortbeton-Läufe -// zusätzlich ein glattes Dreiecks-Mesh der schrägen Laufplatten-Untersicht, und für gerade -// Läufe Handlauf + Pfosten (`StairType.railing`). -// -// Die ganze Rechnung (Tritt-Prismen je Tragart, Nasen-Verlängerung `StairType.nosing`, dünne -// Setzstufen-Platten `closedRisers`, Podest, Soffit-Scheiben im Schnitt, Laufplatten-Mesh, -// Handlauf/Pfosten-Quader) steht in Rust (`src-tauri/core/src/stairs3d.rs`, Treppengeometrie aus -// `kernel2d`). Hier nur: aus dem `Project` sammeln und die Ergebnisse einfärben. -// `ceilingId` trägt bei den Slabs die Treppen-Id (nur TS-seitiges Tagging; render3d ignoriert -// das Feld, und der Pick läuft separat über `pickGeometry`). - -import type { Project, Stair, StairType } from "../../model/types"; -import { getStairType } from "../../model/types"; -import { stairVerticalExtent } from "../../model/wall"; -import { encodeStair } from "../../geometry/stair"; -import { core } from "../../engine/coreWasm"; -import { SLAB_RGB, hexToRgb, type RMesh, type RRgb, type RSlab, type RVec2 } from "./shared"; - -/** Neutraler Beton-Grauton für Treppen (wie der Three.js-Pfad `addStairMeshes`). */ -const STAIR_RGB: RRgb = hexToRgb("#9aa0a6", SLAB_RGB); -/** Neutrales Metallgrau für Handlauf + Pfosten. */ -const RAIL_RGB: RRgb = hexToRgb("#74797f", SLAB_RGB); - -const STRUCTURE = { massiv: 0, beton: 1, wange: 2, aufgesattelt: 2, spindel: 2 } as const; -const RAILING = { keine: 0, links: 1, rechts: 2, beide: 3 } as const; - -/** - * Flache Rust-Eingabe der Treppen (Aufbau: `stairs3d.rs`); `null` ohne Treppen. `wanted` wählt - * nur vor, welche Treppen sich lohnen (spart den WASM-Aufruf); die Regeln selbst prüft Rust. - */ -function stairInput( - project: Project, - wanted: (stair: Stair, st: StairType | undefined) => boolean = () => true, -): { stairs: Stair[]; buf: Float64Array } | null { - const stairs: Stair[] = []; - const types: (StairType | undefined)[] = []; - for (const stair of project.stairs ?? []) { - const st = getStairType(project, stair); - if (!wanted(stair, st)) continue; - stairs.push(stair); - types.push(st); - } - if (stairs.length === 0) return null; - const buf = new Float64Array(1 + 23 * stairs.length); - buf[0] = stairs.length; - stairs.forEach((stair, k) => { - const { zBottom, zTop } = stairVerticalExtent(project, stair); - const st = types[k]; - const o = 1 + 23 * k; - buf.set(encodeStair(stair), o); - buf[o + 16] = zBottom; - buf[o + 17] = zTop; - buf[o + 18] = STRUCTURE[st?.structure ?? "massiv"] ?? 2; - buf[o + 19] = st?.treadThickness ?? 0.04; - buf[o + 20] = st?.nosing ?? 0; - buf[o + 21] = st?.closedRisers ? 1 : 0; - buf[o + 22] = RAILING[st?.railing ?? "keine"] ?? 0; - }); - return { stairs, buf }; -} - -/** Rust-Meshes `[n, (treppe, nPos, nIdx, positionen…, indizes…)…]` → `RMesh[]`. */ -function meshesOf(f: Float64Array, color: RRgb): RMesh[] { - const out: RMesh[] = []; - let i = 1; - for (let n = f.length ? f[0] : 0; n > 0; n--) { - const nPos = f[i + 1]; - const nIdx = f[i + 2]; - i += 3; - const positions: number[] = []; - for (let k = 0; k < nPos; k++) positions.push(f[i + k]); - i += nPos; - const indices: number[] = []; - for (let k = 0; k < nIdx; k++) indices.push(f[i + k]); - i += nIdx; - out.push({ positions, indices, kind: "extrusion", color }); - } - return out; -} - -/** - * Emittiert Treppen als RSlabs (extrudierte Grundriss-Polygone) — der WASM/wgpu- - * Renderer kennt sonst KEINE Treppen (nur Wände/Decken/Meshes), sodass Treppen im - * Standard-3D unsichtbar blieben. Jeder Tritt ist ein extrudiertes Polygon; das - * ist exakt eine RSlab. Tragart über `getStairType`: - * • "massiv" / kein Typ — Vollblock je Tritt von der Treppen-UK bis zur Tritt-OK - * (gestuftes Massiv, Treppe auf Erdreich/Sockel). - * • "beton" — Ortbeton-Laufplatte: je Tritt ein Block von der SCHRÄGEN Untersicht - * (eine Stufe + Laufplattendicke unter der Tritt-OK, an der Treppen-UK gekappt) - * bis zur Tritt-OK. Die stufig gestapelten Blöcke bilden die schräge, UNTEN - * OFFENE Untersicht der klassischen Betontreppe. - * • "wange"/"aufgesattelt"/"spindel" — nur eine dünne Tritt-Platte der Dicke - * `treadThickness` an der Tritt-OK, darunter offen. - * Podest (L/Wendel) als Vollblock bis zur halben Steighöhe. Bei OFFENEN - * Tragarten wird die Vorderkante jedes Tritts zusätzlich um `StairType.nosing` - * (Trittkanten-Überstand) verlängert und — bei `StairType.closedRisers` — eine dünne - * Setzstufen-Platte an der Rückkante ergänzt. Massiv/Beton bilden EIN Körper - * (`monolith`, s. render3d `SlabInput::monolith`). - */ -export function emitStairs( - project: Project, - /** - * `forSection`: auch gerade Betontreppen als Tritt-Prismen liefern (deren - * glatte Laufplatte ist im 3D ein Mesh, das der Schnitt-Extraktor nicht - * schneiden kann — ohne diese Näherung fehlte die Treppe im Schnitt ganz). - */ - opts: { forSection?: boolean } = {}, -): RSlab[] { - const input = stairInput(project); - if (!input) return []; - const f = core().stairs3d_slabs_flat(input.buf, !!opts.forSection); - const out: RSlab[] = []; - let i = 1; - for (let n = f.length ? f[0] : 0; n > 0; n--) { - const stair = input.stairs[f[i]]; - const monolith = f[i + 1] !== 0; - const zBottom = f[i + 2]; - const zTop = f[i + 3]; - const nPts = f[i + 4]; - i += 5; - const outline: RVec2[] = new Array(nPts); - for (let k = 0; k < nPts; k++, i += 2) outline[k] = [f[i], f[i + 1]]; - out.push({ - outline, - zBottom, - zTop, - color: STAIR_RGB, - ceilingId: stair.id, - ...(monolith ? { monolith: stair.id } : {}), - }); - } - return out; -} - -/** - * Glatte Ortbeton-Laufplatte (Tragart "beton") als echtes Dreiecks-Mesh — nur für - * GERADE Läufe. Anders als die stufige Slab-Näherung ({@link emitStairs}) entsteht - * eine SPIEGELGLATTE schräge Untersicht: je Tritt ein konvexes Prisma mit - * HORIZONTALER Oberkante (= Trittfläche) und SCHRÄGER Unterkante auf EINER - * gemeinsamen Soffit-Geraden. Positions in MODELL-Metern (x, y, z=Höhe); render3d bildet - * nach world (x, z, y) ab. - */ -export function emitStairMeshes(project: Project): RMesh[] { - // Nur gerade Betontreppen haben eine glatte Laufplatte. - const input = stairInput(project, (s, st) => st?.structure === "beton" && s.shape === "straight"); - return input ? meshesOf(core().stairs3d_meshes_flat(input.buf), STAIR_RGB) : []; -} - -/** - * Handlauf + Pfosten (`StairType.railing`: "keine"|"links"|"rechts"|"beide"). Nur für GERADE - * Läufe: dort liegt die Vorderkante jedes Tritts exakt auf der linearen Rampen-Geraden, ein - * gerades, schräges Segment je Seite + ein Pfosten je Trittvorderkante genügen. L-Läufe und - * Wendeltreppen bleiben bewusst aussen vor (eigener Folgeschritt). - */ -export function emitStairRailings(project: Project): RMesh[] { - const input = stairInput(project, (s, st) => s.shape === "straight" && (st?.railing ?? "keine") !== "keine"); - return input ? meshesOf(core().stairs3d_railings_flat(input.buf), RAIL_RGB) : []; -} From 8d61363724978a92059e27bd1c5c7c1896c58cbb Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 02:09:29 +0100 Subject: [PATCH 24/31] [K4] S2: Pick-Geometrie und 2D-Boden-Spuren im 3D rechnen auf dem Dokument; drawing2d.ts (3D) geloescht --- src-tauri/core/src/model3d.rs | 227 +++++++++++++++++++++++++++ src-tauri/core/src/queries.rs | 1 + src-tauri/core/src/web/document.rs | 7 + src/core/document.ts | 6 + src/plan/toWalls3d.ts | 110 ++----------- src/plan/toWalls3d/drawing2d.test.ts | 4 +- src/plan/toWalls3d/drawing2d.ts | 202 ------------------------ 7 files changed, 254 insertions(+), 303 deletions(-) delete mode 100644 src/plan/toWalls3d/drawing2d.ts diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index 051a7a04..7207b9b3 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -1124,6 +1124,233 @@ pub fn parts(p: &Project, layered: bool, detail: f64, for_section: bool) -> Resu }) } +// ── 2D-Zeichnungen im 3D (Boden-Spuren) ───────────────────────────────────── + +/// Doppelte je Charge an `drawing2d_3d` — begrenzt den Speicher bei Kataster-Importen. +const CHUNK_DOUBLES: usize = 1 << 18; +const DRAWING_LINE_ELEVATION_EPS: f64 = 0.01; +const DRAWING_PICK_TOLERANCE: f64 = 0.12; + +/// Linienfarbe einer Zeichnung: color → Linienstil → Kategorie (`drawingColor3d`). +fn drawing_color( + d: &Drawing2D, + by_category: &HashMap<&str, &str>, + by_line_style: &HashMap<&str, &str>, +) -> Rgb { + let fb = style::DRAWING_LINE_FALLBACK_RGB; + if let Some(c) = d.color.as_deref().filter(|c| !c.is_empty()) { + return hex_to_rgb(c, fb); + } + if let Some(c) = d.line_style_id.as_deref().and_then(|id| by_line_style.get(id)) { + return hex_to_rgb(c, fb); + } + by_category.get(d.category_code.as_str()).map_or(fb, |c| hex_to_rgb(c, fb)) +} + +/// Packt die darstellbaren Zeichnungen (Linie, Polylinie, Rechteck) in Chargen für `drawing2d_3d`. +fn for_each_drawing_chunk(p: &Project, with_color: bool, mut f: impl FnMut(&[f64], &[&Drawing2D])) { + if p.drawings2d.is_empty() { + return; + } + let cats = p.flat_categories(); + let by_category: HashMap<&str, &str> = cats.iter().filter(|c| !c.color.is_empty()).map(|c| (c.code.as_str(), c.color.as_str())).collect(); + let by_line_style: HashMap<&str, &str> = p.line_styles.iter().filter(|l| !l.color.is_empty()).map(|l| (l.id.as_str(), l.color.as_str())).collect(); + let mut elevations: HashMap<&str, f64> = HashMap::new(); + let mut buf: Vec = vec![0.0]; + let mut ids: Vec<&Drawing2D> = Vec::new(); + let flush = |buf: &mut Vec, ids: &mut Vec<&Drawing2D>, f: &mut dyn FnMut(&[f64], &[&Drawing2D])| { + if ids.is_empty() { + return; + } + buf[0] = ids.len() as f64; + f(buf, ids); + ids.clear(); + buf.truncate(1); + }; + for d in &p.drawings2d { + let (kind, pts): (f64, Vec) = match &d.geom { + Drawing2DGeom::Line { a, b } => (1.0, vec![*a, *b]), + Drawing2DGeom::Rect { min, max } => (3.0, vec![*min, *max]), + Drawing2DGeom::Polyline { pts, .. } => (2.0, pts.clone()), + _ => continue, + }; + let need = 7 + 2 * pts.len(); + if buf.len() + need > CHUNK_DOUBLES { + flush(&mut buf, &mut ids, &mut f); + } + let elev = *elevations.entry(d.level_id.as_str()).or_insert_with(|| p.floor(&d.level_id).map_or(0.0, |l| l.base_elevation.unwrap_or(0.0)) + DRAWING_LINE_ELEVATION_EPS); + let rgb = if with_color { drawing_color(d, &by_category, &by_line_style) } else { [0.0; 3] }; + let closed = matches!(&d.geom, Drawing2DGeom::Polyline { closed: true, .. }); + buf.extend([kind, elev, rgb[0], rgb[1], rgb[2], if closed { 1.0 } else { 0.0 }, pts.len() as f64]); + for q in &pts { + buf.extend([q.x, q.y]); + } + ids.push(d); + } + flush(&mut buf, &mut ids, &mut f); +} + +/// Boden-Spuren aller Zeichnungen als LineList-Vertices `[px, py, pz, r, g, b]` (`emitDrawingLineVerts`). +pub fn drawing_line_verts(p: &Project) -> Vec { + let mut out = Vec::new(); + for_each_drawing_chunk(p, true, |buf, _| out.extend(crate::drawing2d_3d::line_verts(buf))); + out +} + +/// Pick-Strecke einer Zeichnung (`PickDrawingSeg`). +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PickDrawingSeg { + pub start: [f64; 2], + pub end: [f64; 2], + pub base_elevation: f64, + pub drawing_id: String, +} + +fn pick_drawing_segs(p: &Project) -> Vec { + let mut out = Vec::new(); + for_each_drawing_chunk(p, false, |buf, drawings| { + let f = crate::drawing2d_3d::pick_segs(buf, DRAWING_PICK_TOLERANCE); + for c in f.chunks_exact(6) { + out.push(PickDrawingSeg { start: [c[0], c[1]], end: [c[2], c[3]], base_elevation: c[4], drawing_id: drawings[c[5] as usize].id.clone() }); + } + }); + out +} + +// ── Pick-Geometrie ────────────────────────────────────────────────────────── + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PickBox { + pub start: [f64; 2], + pub end: [f64; 2], + pub thickness: f64, + pub height: f64, + pub base_elevation: f64, + pub opening_id: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PickStair { + pub outline: [[f64; 2]; 4], + pub z_bottom: f64, + pub z_top: f64, + pub stair_id: String, +} + +type Tri = [V3; 3]; + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PickRoof { + pub tris: Vec, + pub roof_id: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PickContextMesh { + pub tris: Vec, + pub context_object_id: String, +} + +#[derive(Debug, Serialize)] +pub struct PickGeometry { + pub walls: Vec, + pub slabs: Vec, + pub openings: Vec, + pub stairs: Vec, + pub roofs: Vec, + #[serde(rename = "contextMeshes")] + pub context_meshes: Vec, + pub drawings: Vec, +} + +/// Geometrie für den 3D-Raycast (`pickGeometry`). +pub fn pick_geometry(p: &Project) -> Result { + // Dächer: Flächen + Giebel als Welt-Dreiecke (Fächer ab Punkt 0), Modell [x, y, h] → Welt [x, h, y]. + let mut roofs = Vec::new(); + for roof in p.roofs.as_deref().unwrap_or(&[]) { + let g = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof)); + let to_world = |q: &V3| -> V3 { [q[0], q[2], q[1]] }; + let mut tris: Vec = Vec::new(); + for poly in g.planes.iter().chain(g.gables.iter()) { + for i in 1..poly.len().saturating_sub(1) { + tris.push([to_world(&poly[0]), to_world(&poly[i]), to_world(&poly[i + 1])]); + } + } + if !tris.is_empty() { + roofs.push(PickRoof { tris, roof_id: roof.id.clone() }); + } + } + let mut openings = Vec::new(); + for o in p.openings.as_deref().unwrap_or(&[]) { + let Some(wall) = p.walls.iter().find(|w| w.id == o.host_wall_id) else { continue }; + let wr = wall_ref(p, wall); + let Some((jamb_start, jamb_end)) = opening_geom::opening_jambs(&wr, o.position, o.width) else { continue }; + let thickness = p.wall_type(wall).map(|t| Project::type_thickness(&t.layers)).ok_or_else(|| format!("Unbekannter Wandtyp: {}", wall.wall_type_id))?; + let (zb, zt) = p.wall_vertical_extent(wall); + let o_bottom = zb + o.sill_height.max(0.0); + let o_top = zt.min(o_bottom + o.height); + if o_top - o_bottom <= 0.0 { + continue; + } + openings.push(PickBox { + start: [jamb_start.x, jamb_start.y], + end: [jamb_end.x, jamb_end.y], + thickness, + height: o_top - o_bottom, + base_elevation: o_bottom, + opening_id: o.id.clone(), + }); + } + let mut stairs = Vec::new(); + for st in p.stairs.as_deref().unwrap_or(&[]) { + let (z_bottom, z_top) = p.stair_vertical_extent(st); + let total_rise = z_top - z_bottom; + if total_rise <= 0.0 { + continue; + } + let geo = crate::stair::geometry(&st.encode(), total_rise); + let b = crate::stair::bbox(&geo); + let (min_x, min_y, max_x, max_y) = if b.len() >= 4 { (b[0], b[1], b[2], b[3]) } else { (0.0, 0.0, 0.0, 0.0) }; + stairs.push(PickStair { outline: [[min_x, min_y], [max_x, min_y], [max_x, max_y], [min_x, max_y]], z_bottom, z_top, stair_id: st.id.clone() }); + } + // Kontext-Meshes: rohe Welt-Dreiecke, Modell (x, y, z) → Welt (x, z, −y). + let mut context_meshes = Vec::new(); + for obj in p.context.as_deref().unwrap_or(&[]) { + let (pos, idx, id) = match obj { + ContextObject::TerrainMesh(m) => (&m.positions, &m.indices, &m.id), + ContextObject::ImportedMesh(m) => (&m.positions, &m.indices, &m.id), + _ => continue, + }; + let vcount = pos.len() / 3; + let at = |i: usize| -> V3 { [pos[i * 3], pos[i * 3 + 2], -pos[i * 3 + 1]] }; + let mut tris: Vec = Vec::new(); + for t in idx.chunks_exact(3) { + let ok = |v: f64| v >= 0.0 && v.fract() == 0.0 && (v as usize) < vcount; + if !(ok(t[0]) && ok(t[1]) && ok(t[2])) { + continue; + } + tris.push([at(t[0] as usize), at(t[1] as usize), at(t[2] as usize)]); + } + if !tris.is_empty() { + context_meshes.push(PickContextMesh { tris, context_object_id: id.clone() }); + } + } + Ok(PickGeometry { + walls: emit_walls(p, true)?, + slabs: emit_slabs(p), + openings, + stairs, + roofs, + context_meshes, + drawings: pick_drawing_segs(p), + }) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs index 0f26f366..4c2890f8 100644 --- a/src-tauri/core/src/queries.rs +++ b/src-tauri/core/src/queries.rs @@ -26,6 +26,7 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result json(&model3d::emit_stair_railings(p)), ("roofMeshes", _) => json(&model3d::emit_roofs(p, if text.is_empty() { None } else { Some(text) })?), ("roofCutLayers", _) => json(&model3d::emit_roof_cut_layers(p)?), + ("pickGeometry", _) => json(&model3d::pick_geometry(p)?), ("model3dParts", 3) => json(&model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?), _ => Err(format!("Unbekannte Abfrage: {name}")), } diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index 6dcd4355..ad13f78a 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -83,3 +83,10 @@ pub fn doc_query_args(h: u32, name: &str, args: &[f64], text: &str) -> String { Err(e) => format!("\u{1}{e}"), } } + +/// Boden-Spuren aller 2D-Zeichnungen als LineList-Vertices `[px, py, pz, r, g, b]` (Float32); +/// leer bei Fehler oder ohne Zeichnungen. +#[wasm_bindgen] +pub fn doc_drawing_line_verts(h: u32) -> Vec { + with_doc(h, |d| d.project().ok().map(|p| crate::model3d::drawing_line_verts(&p))).flatten().unwrap_or_default() +} diff --git a/src/core/document.ts b/src/core/document.ts index 5c7ad2b0..21828f48 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -25,6 +25,7 @@ export type QueryName = | "stairRailings" | "roofMeshes" | "roofCutLayers" + | "pickGeometry" | "model3dParts"; export class ProjectDocument { @@ -81,6 +82,11 @@ export class ProjectDocument { return out; } + /** Boden-Spuren der 2D-Zeichnungen als LineList-Vertices `[px, py, pz, r, g, b]`. */ + drawingLineVerts(): Float32Array { + return this.handle ? core().doc_drawing_line_verts(this.handle) : new Float32Array(0); + } + /** Das Dokument als JSON-Text (Test, Export). */ json(): string { return this.handle ? core().doc_json(this.handle) : ""; diff --git a/src/plan/toWalls3d.ts b/src/plan/toWalls3d.ts index a99dad7d..b90b7636 100644 --- a/src/plan/toWalls3d.ts +++ b/src/plan/toWalls3d.ts @@ -41,13 +41,8 @@ // `toWalls3d/` — siehe dort für die konkrete Emissions-Logik je Bauteil. import type { Project, Vec2 } from "../model/types"; -import { getWallType, wallTypeThickness } from "../model/types"; -import { stairVerticalExtent } from "../model/wall"; -import { openingJambs, openingVerticalExtent } from "../geometry/opening"; import type { DetailLevel } from "../model/viewTypes"; -import { stairBBox, stairGeometry } from "../geometry/stair"; import { roofBaseElevation, roofGeometry } from "../geometry/roof"; -import type { Vec3 as RoofVec3 } from "../geometry/roof"; import { documentFor } from "../core/document"; import type { PickOpening, PickRoof, PickStair, PickContextMesh, PickDrawingSeg } from "./pickTypes"; import { @@ -61,20 +56,22 @@ import { } from "./toWalls3d/shared"; import { emitExtrudedSolids, TRUCK_MESH_READY_EVENT } from "./toWalls3d/extrusions"; import { applyVoids3d } from "./toWalls3d/voids3d"; -import { emitDrawingLineVerts, pickDrawingSegs } from "./toWalls3d/drawing2d"; // Re-Export des gemeinsamen Vokabulars — externe Konsumenten (viewport/, // export/, toSection.ts, nativeSync.ts, …) importieren weiterhin // ausschliesslich von hier, unverändert zur Zeit vor dem Domänen-Split. export { TRUCK_MESH_READY_EVENT }; -// 2D-Boden-Spuren gehen NICHT über `RModel3d`, sondern als LineList über den -// binären `set_drawing_lines`-Kanal (s. dortige Funktionsdoc) — der Viewport -// holt sie direkt hier ab. -export { emitDrawingLineVerts }; export type { RVec2, RRgb, RWall, RSlab, RModel3d }; -/** World-Punkt [x, Höhe, y] für den Dach-Pick (Vec3-Konvention von raycast3d). */ -type RoofPickVec3 = [number, number, number]; +/** + * Boden-Spuren aller 2D-Zeichnungen (Linie, Polylinie, Rechteck) als LineList-Vertices + * `[px, py, pz, r, g, b]` in Welt-Metern für render3d (`set_drawing_lines`, Binärkanal — ein + * Kataster-DXF kann Millionen Segmente liefern, als JSON-Mesh sprengte das Speicher und + * String-Länge). Rechnet der Kern (`model3d.rs`, Chargen). + */ +export function emitDrawingLineVerts(project: Project): Float32Array { + return documentFor(project).drawingLineVerts(); +} /** Weltpunkt (x, elevation, y) — nur intern für Highlight-Kantengeometrie. */ type RVec3 = [number, number, number]; @@ -209,94 +206,7 @@ export function pickGeometry( contextMeshes: PickContextMesh[]; drawings: PickDrawingSeg[]; } { - // Dächer: Dachflächen + Giebel als WORLD-Dreiecke (fan-trianguliert wie - // emitRoofs; model [x,y,z=Höhe] → world [x, z, y]) — präzise geneigte - // Flächen für den Ray-Dreieck-Pick (raycast3d.rayRoofTris). - const roofs: PickRoof[] = []; - for (const roof of project.roofs ?? []) { - const eavesZ = roofBaseElevation(project, roof); - const g = roofGeometry(roof, eavesZ); - const tris: [RoofPickVec3, RoofPickVec3, RoofPickVec3][] = []; - const toWorld = (p: RoofVec3): RoofPickVec3 => [p[0], p[2], p[1]]; - for (const poly of [...g.planes.map((pl) => pl.pts), ...g.gables]) { - for (let i = 1; i + 1 < poly.length; i++) { - tris.push([toWorld(poly[0]), toWorld(poly[i]), toWorld(poly[i + 1])]); - } - } - if (tris.length > 0) roofs.push({ tris, roofId: roof.id }); - } - const openings: PickOpening[] = []; - for (const o of project.openings ?? []) { - const wall = project.walls.find((w) => w.id === o.hostWallId); - if (!wall) continue; - const jambs = openingJambs(wall, o); - if (!jambs) continue; - const thickness = wallTypeThickness(getWallType(project, wall)); - const { zBottom, zTop } = openingVerticalExtent(project, wall, o); - if (zTop - zBottom <= 0) continue; - openings.push({ - start: [jambs.jambStart.x, jambs.jambStart.y], - end: [jambs.jambEnd.x, jambs.jambEnd.y], - thickness, - height: zTop - zBottom, - baseElevation: zBottom, - openingId: o.id, - }); - } - const stairs: PickStair[] = []; - for (const st of project.stairs ?? []) { - const { zBottom, zTop } = stairVerticalExtent(project, st); - const totalRise = zTop - zBottom; - if (totalRise <= 0) continue; - const bbox = stairBBox(stairGeometry(st, totalRise)); - stairs.push({ - outline: [ - [bbox.minX, bbox.minY], - [bbox.maxX, bbox.minY], - [bbox.maxX, bbox.maxY], - [bbox.minX, bbox.maxY], - ], - zBottom, - zTop, - stairId: st.id, - }); - } - // Kontext-Meshes (importierte Gebäude/Terrain, s. ContextObject): rohe - // WORLD-Dreiecke, direkt aus dem Indexpuffer (kein Fan nötig — ImportedMesh/ - // TerrainMesh liefern bereits ein echtes Dreiecksnetz). Kaputte Indizes - // robust überspringen statt abzustürzen (importierte Daten). - // Modell (x,y,z) → world (x, z, −y) — Nord-Achse NEGIERT, damit der Pick - // dieselbe (gespiegelte→korrigierte) Lage trifft wie die sichtbare Geometrie - // in `viewport3d/meshBuilders.ts::buildContextMesh` (dort ausführlich - // begründet: reines Achsen-Vertauschen ohne Vorzeichenwechsel ist für einen - // allgemeinen xyz-Punktsatz eine Spiegelung, anders als bei Wand/Dach, die - // über eine orientierungserhaltende Rotation/Fächer-Triangulation entstehen). - const contextMeshes: PickContextMesh[] = []; - for (const obj of project.context ?? []) { - if (obj.type === "contourSet" || obj.type === "image") continue; - const pos = obj.positions; - const vcount = pos.length / 3; - const tris: [RoofPickVec3, RoofPickVec3, RoofPickVec3][] = []; - for (let i = 0; i + 2 < obj.indices.length; i += 3) { - const ia = obj.indices[i]; - const ib = obj.indices[i + 1]; - const ic = obj.indices[i + 2]; - if (ia >= vcount || ib >= vcount || ic >= vcount) continue; - const at = (idx: number): RoofPickVec3 => [pos[idx * 3], pos[idx * 3 + 2], -pos[idx * 3 + 1]]; - tris.push([at(ia), at(ib), at(ic)]); - } - if (tris.length > 0) contextMeshes.push({ tris, contextObjectId: obj.id }); - } - const drawings = pickDrawingSegs(project); - return { - walls: projectToWalls3d(project), - slabs: documentFor(project).query("slabs"), - openings, - stairs, - roofs, - contextMeshes, - drawings, - }; + return documentFor(project).query("pickGeometry"); } /** diff --git a/src/plan/toWalls3d/drawing2d.test.ts b/src/plan/toWalls3d/drawing2d.test.ts index 11179a40..4dbe2456 100644 --- a/src/plan/toWalls3d/drawing2d.test.ts +++ b/src/plan/toWalls3d/drawing2d.test.ts @@ -1,7 +1,9 @@ import { describe, expect, it } from "vitest"; import type { Project } from "../../model/types"; import { sampleProject } from "../../model/sampleProject"; -import { emitDrawingLineVerts, pickDrawingSegs } from "./drawing2d"; +import { emitDrawingLineVerts, pickGeometry } from "../toWalls3d"; + +const pickDrawingSegs = (p: Project) => pickGeometry(p).drawings; // `emitDrawingLineVerts` liefert die 2D-Boden-Spuren als LineList-Vertices für // render3ds `set_drawing_lines` (binärer Float32Array-Kanal) — interleaved diff --git a/src/plan/toWalls3d/drawing2d.ts b/src/plan/toWalls3d/drawing2d.ts deleted file mode 100644 index 95c4c610..00000000 --- a/src/plan/toWalls3d/drawing2d.ts +++ /dev/null @@ -1,202 +0,0 @@ -// Freie-2D-Geometrie-Domäne der 3D-Ableitung: zeigt jede 2D-Zeichnung -// (line/polyline/rect) als Boden-Spur knapp über ihrer Geschossebene — die -// "2D-Referenz im 3D", die der drei.js-Fallback (`addDrawing2DLines` in -// Viewport3D.tsx) zeigt. -// -// Die Spuren gehen als LineList-Vertices (`emitDrawingLineVerts`) über einen -// eigenen BINÄREN Kanal an render3d (`set_drawing_lines`), NICHT als Meshes -// über `RModel3d.meshes`/`set_model`. Grund: ein Kataster-DXF kann Millionen -// Segmente liefern — als Ribbon-Meshes im JSON-Modell sprengt das sowohl die -// JS-String-Längengrenze als auch den Vertexspeicher (s. Funktionsdoc unten). - -import type { Drawing2D, Project } from "../../model/types"; -import { flattenCategories, getFloor } from "../../model/types"; -import { core } from "../../engine/coreWasm"; -import { DRAWING_LINE_FALLBACK_RGB, hexToRgb, type RRgb } from "./shared"; -import { DRAWING_PICK_TOLERANCE, type PickDrawingSeg } from "../pickTypes"; - -/** Höhen-Offset über der Geschossebene gegen Z-Fighting (wie addDrawing2DLines in Viewport3D.tsx). */ -const DRAWING_LINE_ELEVATION_EPS = 0.01; - -/** - * Farb-Nachschlagetabellen für {@link drawingColor3d} — EINMAL je Emitter-Lauf - * gebaut statt je Element. Vorher rief `drawingColor3d` pro Zeichnung - * `flattenCategories(project.layers).find(...)` auf und baute damit den - * GESAMTEN Kategorie-Baum je Element neu als Array auf (O(n·L) plus - * entsprechender GC-Druck). Bei einem Kataster-Import mit >100'000 Elementen - * war das zweistellige Millionen Allokationen pro Renderdurchlauf. Muster wie - * `generatePlan.ts::categoryColorMap`. - */ -interface DrawingColorMaps { - byCategory: Map; - byLineStyle: Map; -} - -function buildDrawingColorMaps(project: Project): DrawingColorMaps { - const byCategory = new Map(); - for (const c of flattenCategories(project.layers)) { - if (c.color) byCategory.set(c.code, c.color); - } - const byLineStyle = new Map(); - for (const l of project.lineStyles) { - if (l.color) byLineStyle.set(l.id, l.color); - } - return { byCategory, byLineStyle }; -} - -/** Modellfarbe einer 2D-Zeichnung (color → LineStyle → Kategorie), analog `drawing2DColor`. */ -function drawingColor3d(maps: DrawingColorMaps, d: Drawing2D): RRgb { - if (d.color) return hexToRgb(d.color, DRAWING_LINE_FALLBACK_RGB); - const ls = d.lineStyleId ? maps.byLineStyle.get(d.lineStyleId) : undefined; - if (ls) return hexToRgb(ls, DRAWING_LINE_FALLBACK_RGB); - const cat = maps.byCategory.get(d.categoryCode); - return cat ? hexToRgb(cat, DRAWING_LINE_FALLBACK_RGB) : DRAWING_LINE_FALLBACK_RGB; -} - -/** Boden-Spur-Höhe (world-Y) einer 2D-Zeichnung: Geschoss-UK + Epsilon gegen - * Z-Fighting, oder 0 als Fallback (Geschoss nicht mehr auflösbar). Gemeinsam - * für `emitDrawingLineVerts` (Sichtbarkeit) UND `pickDrawingSegs` (Klickbarkeit) — - * beide MÜSSEN dieselbe Höhe verwenden, sonst klickt man daneben. */ -function drawingElevation(project: Project, d: Drawing2D): number { - let baseZ = 0; - try { - baseZ = getFloor(project, d.levelId).baseElevation ?? 0; - } catch { - // Geschoss nicht (mehr) auflösbar: bei UK 0 zeichnen (Fallback). - } - return baseZ + DRAWING_LINE_ELEVATION_EPS; -} - -/** Doppelte je Charge an den Rust-Kern (Eingabe: `drawing2d_3d.rs`) — begrenzt den Speicher. */ -const CHUNK_DOUBLES = 1 << 18; -let scratch: Float64Array | null = null; -/** Art-Kennzahl der Zeichnung im Rust-Puffer; Kreis/Bogen/Text zeigt das 3D nicht. */ -const SHAPE_KIND = { line: 1, polyline: 2, rect: 3 } as const; - -/** - * Packt die darstellbaren Zeichnungen (line/polyline/rect — Parität mit `drawing2DSegments` - * im drei.js-Fallback `Viewport3D.tsx`) in Chargen und ruft `fn(puffer, zeichnungen)` je Charge - * auf. `color` liefert die Linienfarbe (`null`: ohne, für den Pick). - */ -function forEachChunk( - project: Project, - color: ((d: Drawing2D) => RRgb) | null, - fn: (buf: Float64Array, drawings: Drawing2D[]) => void, -): void { - if (project.drawings2d.length === 0) return; - // Der Zwischenpuffer lebt zwischen den Aufrufen weiter (Neuanlage von 2 MB kostet mehr als die - // Rechnung bei kleinen Projekten); der Kern kopiert den Inhalt je Aufruf. - scratch ??= new Float64Array(CHUNK_DOUBLES); - let buf = scratch; - let ids: Drawing2D[] = []; - let w = 1; // [0] = Anzahl - const flush = () => { - if (ids.length === 0) return; - buf[0] = ids.length; - fn(buf.subarray(0, w), ids); - ids = []; - w = 1; - }; - // Geschoss-UK je Ebene nur einmal auflösen (bei Kataster-Importen hängen Tausende Zeichnungen an einer). - const elevations = new Map(); - for (const d of project.drawings2d) { - const g = d.geom; - if (g.shape !== "line" && g.shape !== "rect" && g.shape !== "polyline") continue; - const kind = SHAPE_KIND[g.shape]; - const nPts = g.shape === "polyline" ? g.pts.length : 2; - const need = 7 + 2 * nPts; - if (w + need > buf.length) { - flush(); - if (1 + need > buf.length) buf = new Float64Array(1 + need); - } - let elev = elevations.get(d.levelId); - if (elev === undefined) { - elev = drawingElevation(project, d); - elevations.set(d.levelId, elev); - } - const [r, gr, b] = color ? color(d) : [0, 0, 0]; - buf[w++] = kind; - buf[w++] = elev; - buf[w++] = r; - buf[w++] = gr; - buf[w++] = b; - buf[w++] = g.shape === "polyline" && g.closed ? 1 : 0; - buf[w++] = nPts; - if (g.shape === "line") { - buf[w++] = g.a.x; buf[w++] = g.a.y; buf[w++] = g.b.x; buf[w++] = g.b.y; - } else if (g.shape === "rect") { - buf[w++] = g.min.x; buf[w++] = g.min.y; buf[w++] = g.max.x; buf[w++] = g.max.y; - } else { - for (const p of g.pts) { - buf[w++] = p.x; - buf[w++] = p.y; - } - } - ids.push(d); - } - flush(); -} - -/** - * Boden-Spuren aller 2D-Zeichnungen als LineList-Vertices für render3d — - * die "2D-Referenz im 3D" (z. B. ein Kataster-Plan oder Boden-Raster), die - * auch der drei.js-Fallback (`addDrawing2DLines`) zeigt. - * - * Liefert interleaved `[px, py, pz, r, g, b, ...]` in WORLD-Metern, je zwei - * Vertices ein Segment — direkt für `WebModelRenderer::set_drawing_lines` - * (Binärtransfer als `Float32Array`, kein JSON). Entartete Segmente entfallen. - * - * WARUM LINIEN STATT MESHES (Nutzer-Report 2026-10-08, Kataster-DXF „Amtliche - * Vermessung Luzern", 439 MB → 3,6 Mio. Segmente): als Ribbon-MESH im JSON-Modell sprengte das - * die JS-String-Längengrenze, und `append_context_mesh` hätte ~1,55 GB Vertexdaten erzeugt. - * Als LineList sind es 2 Vertices je Segment (~173 MB) ohne jede Textkodierung. - * - * WORLD-TRANSFORM: Modell `(x, y, z=Höhe)` → world `(x, Höhe, y)` — exakt die - * `MeshKind::Extrusion`-Konvention (KEINE Nord-Negation; die gilt nur für `Terrain`/`Imported`, - * s. `mesh.rs`). Die Segmente erzeugt der Rust-Kern (`drawing2d_3d.rs`) in Chargen; die - * Teilergebnisse werden am Ende in EINEN Puffer kopiert. - */ -export function emitDrawingLineVerts(project: Project): Float32Array { - if (project.drawings2d.length === 0) return new Float32Array(0); - const maps = buildDrawingColorMaps(project); - const parts: Float32Array[] = []; - let total = 0; - forEachChunk(project, (d) => drawingColor3d(maps, d), (buf) => { - const v = core().drawing3d_line_verts(buf); - if (v.length) { - parts.push(v); - total += v.length; - } - }); - if (parts.length === 0) return new Float32Array(0); - if (parts.length === 1) return parts[0]; - const out = new Float32Array(total); - let w = 0; - for (const p of parts) { - out.set(p, w); - w += p.length; - } - return out; -} - -/** - * Pick-Kandidaten (Raycast-Boxen, s. `viewport/raycast3d.ts::PickDrawingSeg`) - * für alle 2D-Zeichnungen — dieselben Segmente/Höhen wie `emitDrawingLineVerts` - * (Klick trifft, was sichtbar ist), nur mit grosszügiger Toleranz statt der - * sichtbaren 0.008m Linienbreite. - */ -export function pickDrawingSegs(project: Project): PickDrawingSeg[] { - const out: PickDrawingSeg[] = []; - forEachChunk(project, null, (buf, drawings) => { - const f = core().drawing3d_pick_segs(buf, DRAWING_PICK_TOLERANCE); - for (let i = 0; i + 5 < f.length; i += 6) { - out.push({ - start: [f[i], f[i + 1]], - end: [f[i + 2], f[i + 3]], - baseElevation: f[i + 4], - drawingId: drawings[f[i + 5]].id, - }); - } - }); - return out; -} From e53fb21eb631b8f2b67c4e1a3ad74f23e03eee12 Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 02:11:57 +0100 Subject: [PATCH 25/31] [K4] S2: Modell verlustfrei (Extra-Felder), typisierte Sicht wird nach Ops feldweise nachgefuehrt --- scripts/gen-rust-model.py | 10 +- src-tauri/core/src/document.rs | 60 ++- src-tauri/core/src/model/generated.rs | 528 ++++++++++++++++++++++---- src-tauri/core/src/model/helpers.rs | 2 +- src-tauri/core/src/model/manual.rs | 23 ++ 5 files changed, 524 insertions(+), 99 deletions(-) diff --git a/scripts/gen-rust-model.py b/scripts/gen-rust-model.py index 3cd725d1..db536a76 100644 --- a/scripts/gen-rust-model.py +++ b/scripts/gen-rust-model.py @@ -205,6 +205,8 @@ def rtype(t, ctx): return "serde_json::Value", opt raise ValueError(t) +project_fields = [] + def emit_struct(name, fields): if name in emitted: return emitted.add(name) @@ -229,9 +231,11 @@ def emit_struct(name, fields): r = f"Option<{r}>" a = f" #[serde({', '.join(attrs)})]\n" if attrs else "" lines.append(f"{a} pub {rn}: {r},") + if name == "Project": + project_fields.append((fname, rn, r)) + lines.append(" #[serde(flatten)]\n pub extra: Extra,") out_items.append("#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]\n" + '#[serde(default)]\n' - + '#[cfg_attr(test, serde(deny_unknown_fields))]\n' + f"pub struct {name} {{\n" + "\n".join(lines) + "\n}\n") def ensure(n): @@ -259,6 +263,10 @@ print("// GENERIERT von scripts/gen-rust-model.py aus den TS-Typen (Stand 28.10. "// Rust-Gegenstück zu src/model/types.ts ([K4] S2). Union-Typen mit Tag stehen in model/manual.rs.\n" "#![allow(clippy::large_enum_variant)]\n" "use super::manual::*;\nuse serde::{Deserialize, Serialize};\n") +impl_lines = [] +for jn, rn, rt in project_fields: + impl_lines.append(f" {json.dumps(jn)} => {{\n self.{rn} = match v {{\n Some(v) => <{rt}>::deserialize(v).map_err(|e| e.to_string())?,\n None => Default::default(),\n }};\n }}") +out_items.append("impl Project {\n /// Setzt EIN Feld aus dem JSON-Baum (`None` = Feld entfernt → Standardwert); so bleibt die\n /// typisierte Sicht nach einer Op ohne Neu-Parsen des ganzen Projekts aktuell.\n pub fn set_field(&mut self, key: &str, v: Option<&serde_json::Value>) -> Result<(), String> {\n match key {\n" + "\n".join(impl_lines) + "\n other => match v {\n Some(v) => {\n self.extra.0.insert(other.to_owned(), v.clone());\n }\n None => {\n self.extra.0.remove(other);\n }\n },\n }\n Ok(())\n }\n}\n") body = "\n".join(out_items) for a, b in RENAMES.items(): body = body.replace(a, b) diff --git a/src-tauri/core/src/document.rs b/src-tauri/core/src/document.rs index 4c649296..b9693ce2 100644 --- a/src-tauri/core/src/document.rs +++ b/src-tauri/core/src/document.rs @@ -11,7 +11,6 @@ use crate::model::Project; use serde::Deserialize; use serde_json::{Map, Value}; use std::collections::HashSet; -use std::rc::Rc; /// Eine Änderung am Projekt (Spiegel von `CoreOp` in `core/ops.ts`). #[derive(Clone, Debug, PartialEq)] @@ -93,14 +92,16 @@ fn has_dup(v: Option<&Value>) -> bool { #[derive(Clone, Debug, Default)] pub struct Document { root: Map, - /// Typisierte Sicht (Cache); jede Änderung verwirft sie. - typed: Option>, + /// Typisierte Sicht (Cache). Eine Op markiert nur ihr Feld als geändert; `project()` liest dann + /// genau diese Felder neu ein. + typed: Option, + dirty: HashSet, } impl Document { pub fn from_json(text: &str) -> Result { match serde_json::from_str::(text) { - Ok(Value::Object(root)) => Ok(Document { root, typed: None }), + Ok(Value::Object(root)) => Ok(Document { root, typed: None, dirty: HashSet::new() }), Ok(_) => Err("Projekt ist kein JSON-Objekt".into()), Err(e) => Err(e.to_string()), } @@ -110,21 +111,35 @@ impl Document { serde_json::to_string(&self.root).unwrap_or_default() } - /// Typisierte Sicht des Projekts (gecacht bis zur nächsten Änderung). Fehler = Feld, das dem - /// Modell widerspricht (Meldung von serde). - pub fn project(&mut self) -> Result, String> { - if let Some(p) = &self.typed { - return Ok(p.clone()); + /// Typisierte Sicht des Projekts (gecacht; nach Ops werden nur die berührten Felder neu gelesen). + /// Fehler = Feld, das dem Modell widerspricht (Meldung von serde). + pub fn project(&mut self) -> Result<&Project, String> { + if self.typed.is_none() { + // Die Map wird nur ausgeliehen: `Value::Object` braucht Besitz, daher temporär herausnehmen. + let value = Value::Object(std::mem::take(&mut self.root)); + let parsed = Project::deserialize(&value).map_err(|e| e.to_string()); + if let Value::Object(m) = value { + self.root = m; + } + self.typed = Some(parsed?); + self.dirty.clear(); + } else if !self.dirty.is_empty() { + let dirty: Vec = self.dirty.drain().collect(); + let mut failed = None; + if let Some(t) = self.typed.as_mut() { + for key in &dirty { + if let Err(e) = t.set_field(key, self.root.get(key)) { + failed = Some(e); + break; + } + } + } + if let Some(e) = failed { + self.typed = None; + return Err(e); + } } - // Die Map wird nur ausgeliehen: `Value::Object` braucht Besitz, daher temporär herausnehmen. - let value = Value::Object(std::mem::take(&mut self.root)); - let parsed = Project::deserialize(&value).map_err(|e| e.to_string()); - if let Value::Object(m) = value { - self.root = m; - } - let p = Rc::new(parsed?); - self.typed = Some(p.clone()); - Ok(p) + Ok(self.typed.as_ref().expect("gerade gesetzt")) } pub fn field(&self, key: &str) -> Option<&Value> { @@ -189,7 +204,9 @@ impl Document { /// Wendet `ops` atomar an. Verstösse (neue doppelte ids) → `Err(Meldungen)`, Dokument unverändert. pub fn apply(&mut self, ops: &[Op]) -> Result<(), Vec> { - self.typed = None; + for op in ops { + self.dirty.insert(op.key().to_owned()); + } // Zustand der berührten Felder sichern (Rücknahme) und Alt-Doppelungen merken. let mut saved: Vec<(String, Option)> = Vec::new(); let mut had_dup: HashSet = HashSet::new(); @@ -291,6 +308,11 @@ mod tests { let id = d.project().unwrap().walls[0].id.clone(); d.apply(&ops(json!([{"kind":"remove","collection":"walls","ids":[id]}]))).unwrap(); assert_eq!(d.project().unwrap().walls.len(), n - 1); + // Feld entfernen und wieder setzen + d.apply(&ops(json!([{"kind":"setField","key":"name"}]))).unwrap(); + assert_eq!(d.project().unwrap().name, ""); + d.apply(&ops(json!([{"kind":"setField","key":"name","value":"X"}]))).unwrap(); + assert_eq!(d.project().unwrap().name, "X"); } #[test] diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs index 258894ab..757552be 100644 --- a/src-tauri/core/src/model/generated.rs +++ b/src-tauri/core/src/model/generated.rs @@ -17,23 +17,24 @@ pub enum LineStyleKind { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct LineStyleZigzag { pub amplitude: f64, pub wavelength: f64, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct LineStyleMotif { pub points: Vec, pub length: f64, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct LineStyle { pub id: String, pub name: String, @@ -47,11 +48,12 @@ pub struct LineStyle { pub zigzag: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub motif: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Marks { #[serde(default, skip_serializing_if = "Option::is_none")] pub bold: Option, @@ -71,15 +73,18 @@ pub struct Marks { pub size_pt: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub color: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct TextStylePreset { pub id: String, pub label: String, pub marks: Marks, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -104,7 +109,6 @@ pub enum HatchStyleLines { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct HatchStyleImage { pub src: String, #[serde(rename = "scaleX")] @@ -112,6 +116,8 @@ pub struct HatchStyleImage { #[serde(rename = "scaleY")] pub scale_y: f64, pub rotation: f64, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -125,12 +131,13 @@ pub enum HatchStyleGradientType { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct HatchStyleGradient { pub color1: String, pub color2: String, pub angle: f64, pub r#type: HatchStyleGradientType, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -152,15 +159,15 @@ pub enum HatchPattern { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct HatchStyleMotif { pub points: Vec, pub length: f64, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct HatchStyle { pub id: String, pub name: String, @@ -190,11 +197,12 @@ pub struct HatchStyle { pub length_max: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub motif: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ComponentMaterial { #[serde(rename = "libraryId", default, skip_serializing_if = "Option::is_none")] pub library_id: Option, @@ -212,11 +220,12 @@ pub struct ComponentMaterial { pub ao: Option, #[serde(rename = "sizeM", default, skip_serializing_if = "Option::is_none")] pub size_m: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Component { pub id: String, pub name: String, @@ -243,53 +252,60 @@ pub struct Component { pub abbrev: Option, #[serde(rename = "joinPriority")] pub join_priority: f64, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Layer { #[serde(rename = "componentId")] pub component_id: String, pub thickness: f64, #[serde(rename = "jointLineStyleId", default, skip_serializing_if = "Option::is_none")] pub joint_line_style_id: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct WallType { pub id: String, pub name: String, pub layers: Vec, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct CeilingType { pub id: String, pub name: String, pub layers: Vec, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct RoofType { pub id: String, pub name: String, pub layers: Vec, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct BlockDef { pub id: String, pub name: String, pub geom2d: Vec, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -345,7 +361,6 @@ pub enum DoorTypeInsetFace { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct DoorType { pub id: String, pub name: String, @@ -382,6 +397,8 @@ pub struct DoorType { pub default_height: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub threshold: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -419,7 +436,6 @@ pub enum SashDefHingeSide { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct SashDef { pub kind: SashDefKind, #[serde(rename = "autoWidth", default, skip_serializing_if = "Option::is_none")] @@ -432,6 +448,8 @@ pub struct SashDef { pub opening: Option, #[serde(rename = "hingeSide", default, skip_serializing_if = "Option::is_none")] pub hinge_side: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -447,20 +465,22 @@ pub enum WindowShadingKind { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct WindowShadingBox { pub width: f64, pub height: f64, pub depth: f64, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct WindowShading { pub create: bool, pub kind: WindowShadingKind, pub r#box: WindowShadingBox, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -505,10 +525,11 @@ pub enum WindowTypeSillLineView { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct WindowTypeSillLine { pub faces: WindowTypeSillLineFaces, pub view: WindowTypeSillLineView, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -526,7 +547,6 @@ pub enum WindowTypeSillBoard { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct WindowType { pub id: String, pub name: String, @@ -570,6 +590,8 @@ pub struct WindowType { pub default_height: f64, #[serde(rename = "sillBoard", default, skip_serializing_if = "Option::is_none")] pub sill_board: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -602,7 +624,6 @@ pub enum StairTypeRailing { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct StairType { pub id: String, pub name: String, @@ -617,47 +638,52 @@ pub struct StairType { pub railing: Option, #[serde(rename = "defaultWidth")] pub default_width: f64, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ColorPen { pub id: String, pub name: String, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct PenStyle { pub color: String, pub weight: f64, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct PenSet { pub id: String, pub name: String, pub pens: std::collections::BTreeMap, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct CustomPalette { pub id: String, pub name: String, pub colors: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub visible: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct BuiltinPaletteBanks { #[serde(default, skip_serializing_if = "Option::is_none")] pub simple: Option, @@ -667,6 +693,8 @@ pub struct BuiltinPaletteBanks { pub material: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub ral: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -684,7 +712,6 @@ pub enum DrawingLevelKind { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct DrawingLevel { pub id: String, pub name: String, @@ -711,6 +738,8 @@ pub struct DrawingLevel { pub plan_underlay_id: Option, #[serde(rename = "levelMarks", default, skip_serializing_if = "Option::is_none")] pub level_marks: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -732,7 +761,6 @@ pub enum SiaCategory { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct RoomProgramRow { pub name: String, #[serde(rename = "siaCategory", default, skip_serializing_if = "Option::is_none")] @@ -740,27 +768,30 @@ pub struct RoomProgramRow { pub area: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub count: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct SunStudy { pub when: String, pub show: bool, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct SiteRulesBuildingLines { pub a: Vec2, pub b: Vec2, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct SiteRules { pub parcel: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -773,11 +804,12 @@ pub struct SiteRules { pub max_height: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub show: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct LayerCategory { pub code: String, pub name: String, @@ -791,6 +823,8 @@ pub struct LayerCategory { pub hatch: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub children: Option>, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -826,7 +860,6 @@ pub enum SliceTermination { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Wall { pub id: String, pub r#type: String, @@ -875,11 +908,12 @@ pub struct Wall { pub top: Option, #[serde(rename = "sliceTermination", default, skip_serializing_if = "Option::is_none")] pub slice_termination: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Ceiling { pub id: String, pub r#type: String, @@ -926,6 +960,8 @@ pub struct Ceiling { pub top: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub bottom: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -967,7 +1003,6 @@ pub enum RoofRidgeAxis { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Roof { pub id: String, pub r#type: String, @@ -1003,6 +1038,8 @@ pub struct Roof { pub color: Option, #[serde(rename = "colorPenId", default, skip_serializing_if = "Option::is_none")] pub color_pen_id: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1076,17 +1113,17 @@ pub enum DetailLevel { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct LineStyleOverride { #[serde(default, skip_serializing_if = "Option::is_none")] pub color: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub weight: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Opening { pub id: String, pub r#type: String, @@ -1134,6 +1171,8 @@ pub struct Opening { pub sash_line: Option, #[serde(rename = "sillLineStyle", default, skip_serializing_if = "Option::is_none")] pub sill_line_style: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1169,7 +1208,6 @@ pub enum StairArrowStyle { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Stair { pub id: String, pub r#type: String, @@ -1213,14 +1251,17 @@ pub struct Stair { pub color_pen_id: Option, #[serde(rename = "arrowStyle", default, skip_serializing_if = "Option::is_none")] pub arrow_style: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct TextRun { pub text: String, pub marks: Marks, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1236,26 +1277,27 @@ pub enum Align { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Paragraph { pub runs: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub align: Option, #[serde(rename = "lineHeight", default, skip_serializing_if = "Option::is_none")] pub line_height: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct RichTextDoc { pub version: f64, pub paragraphs: Vec, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct RoomStamp { #[serde(default, skip_serializing_if = "Option::is_none")] pub number: Option, @@ -1280,11 +1322,12 @@ pub struct RoomStamp { pub occupancy: Option, #[serde(rename = "roundingStep", default, skip_serializing_if = "Option::is_none")] pub rounding_step: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Room { pub id: String, pub r#type: String, @@ -1307,6 +1350,8 @@ pub struct Room { pub stamp_doc: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub stamp: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1328,7 +1373,6 @@ pub enum EndMark { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Drawing2DEndMarks { #[serde(default, skip_serializing_if = "Option::is_none")] pub start: Option, @@ -1336,11 +1380,12 @@ pub struct Drawing2DEndMarks { pub end: Option, #[serde(rename = "sizeMm", default, skip_serializing_if = "Option::is_none")] pub size_mm: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Drawing2D { pub id: String, pub r#type: String, @@ -1395,29 +1440,32 @@ pub struct Drawing2D { pub stroke_weight_source: Option, #[serde(rename = "hatchSource", default, skip_serializing_if = "Option::is_none")] pub hatch_source: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ExtrudedSolidCircle { pub center: Vec2, pub r: f64, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ExtrudedSolidBrep { pub spec: std::collections::BTreeMap, pub origin: Vec2, #[serde(default, skip_serializing_if = "Option::is_none")] pub label: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ExtrudedSolid { pub id: String, pub r#type: String, @@ -1439,11 +1487,12 @@ pub struct ExtrudedSolid { pub chamfer: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub brep: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Column { pub id: String, pub r#type: String, @@ -1487,11 +1536,12 @@ pub struct Column { pub stroke_weight_source: Option, #[serde(rename = "hatchSource", default, skip_serializing_if = "Option::is_none")] pub hatch_source: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Group { pub id: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1514,11 +1564,12 @@ pub struct Group { pub opening_ids: Vec, #[serde(rename = "groupIds")] pub group_ids: Vec, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ParametricWall { pub id: String, pub name: String, @@ -1527,6 +1578,8 @@ pub struct ParametricWall { pub rules: Vec, #[serde(rename = "defaultWallTypeId")] pub default_wall_type_id: String, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1553,16 +1606,16 @@ pub enum OverrideOperator { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct OverrideCondition { pub r#type: OverrideConditionType, pub operator: OverrideOperator, pub value: String, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct OverrideActions { #[serde(default, skip_serializing_if = "Option::is_none")] pub color: Option, @@ -1570,17 +1623,20 @@ pub struct OverrideActions { pub lineweight: Option, #[serde(rename = "linetypeId", default, skip_serializing_if = "Option::is_none")] pub linetype_id: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct OverrideRule { pub id: String, pub name: String, pub enabled: bool, pub condition: OverrideCondition, pub actions: OverrideActions, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1619,7 +1675,6 @@ pub enum View3d { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ViewSnapshot { pub id: String, pub name: String, @@ -1647,16 +1702,19 @@ pub struct ViewSnapshot { pub camera_center: Option, #[serde(rename = "cameraPxPerMeter", default, skip_serializing_if = "Option::is_none")] pub camera_px_per_meter: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ViewSnapshotFolder { pub id: String, pub name: String, #[serde(rename = "parentId", default, skip_serializing_if = "Option::is_none")] pub parent_id: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1703,7 +1761,6 @@ pub enum LayoutOrientation { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct LayoutViewport { pub id: String, #[serde(rename = "snapshotId")] @@ -1718,11 +1775,12 @@ pub struct LayoutViewport { pub height_mm: f64, #[serde(rename = "scaleDenominator", default, skip_serializing_if = "Option::is_none")] pub scale_denominator: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Layout { pub id: String, pub name: String, @@ -1741,11 +1799,12 @@ pub struct Layout { pub viewports: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub annotations: Option>, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct LayoutTitleBlock { #[serde(rename = "projectName", default, skip_serializing_if = "Option::is_none")] pub project_name: Option, @@ -1757,11 +1816,12 @@ pub struct LayoutTitleBlock { pub date: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub author: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct MasterLayout { pub id: String, pub name: String, @@ -1777,6 +1837,8 @@ pub struct MasterLayout { pub custom_width_mm: Option, #[serde(rename = "customHeightMm", default, skip_serializing_if = "Option::is_none")] pub custom_height_mm: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1790,7 +1852,6 @@ pub enum LayoutFolderKind { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct LayoutFolder { pub id: String, pub name: String, @@ -1798,19 +1859,21 @@ pub struct LayoutFolder { pub parent_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub kind: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ProjectGeoAnchorLv95 { pub e: f64, pub n: f64, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ProjectGeoAnchor { pub lv95: ProjectGeoAnchorLv95, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1818,11 +1881,12 @@ pub struct ProjectGeoAnchor { pub model: Vec2, #[serde(default, skip_serializing_if = "Option::is_none")] pub label: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Project { #[serde(rename = "formatVersion", default, skip_serializing_if = "Option::is_none")] pub format_version: Option, @@ -1909,6 +1973,8 @@ pub struct Project { pub reference_elevation_masl: Option, #[serde(rename = "geoAnchor", default, skip_serializing_if = "Option::is_none")] pub geo_anchor: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1924,7 +1990,6 @@ pub enum GridRuleDirections { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct GridRule { #[serde(rename = "gridId", default, skip_serializing_if = "Option::is_none")] pub grid_id: Option, @@ -1939,6 +2004,8 @@ pub struct GridRule { pub reference_line: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub height: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1952,7 +2019,6 @@ pub enum ModuleRuleDirection { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ModuleRule { #[serde(rename = "moduleSize")] pub module_size: f64, @@ -1965,6 +2031,8 @@ pub struct ModuleRule { pub reference_line: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub height: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1978,36 +2046,38 @@ pub enum ConditionalThicknessRuleLogic { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ConditionalThicknessRule { pub condition: serde_json::Value, #[serde(rename = "wallTypeId")] pub wall_type_id: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub logic: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ReferenceLineRule { #[serde(rename = "referenceLine")] pub reference_line: WallReferenceLine, pub target: serde_json::Value, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct SequenceRule { pub rules: Vec, #[serde(rename = "stopOnMatch", default, skip_serializing_if = "Option::is_none")] pub stop_on_match: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ImportedMesh { pub id: String, pub name: String, @@ -2017,6 +2087,8 @@ pub struct ImportedMesh { pub category_code: Option, pub positions: Vec, pub indices: Vec, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -2030,7 +2102,6 @@ pub enum ContourCurveKind { #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ContourCurve { pub kind: ContourCurveKind, pub cx: f64, @@ -2038,11 +2109,12 @@ pub struct ContourCurve { pub r: f64, pub a0: f64, pub a1: f64, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct Contour { pub z: f64, pub pts: Vec, @@ -2053,11 +2125,12 @@ pub struct Contour { pub filled: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub curve: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ContourSet { pub id: String, pub name: String, @@ -2066,11 +2139,12 @@ pub struct ContourSet { #[serde(rename = "categoryCode", default, skip_serializing_if = "Option::is_none")] pub category_code: Option, pub contours: Vec, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct TerrainMesh { pub id: String, pub name: String, @@ -2082,11 +2156,12 @@ pub struct TerrainMesh { pub indices: Vec, #[serde(rename = "vertexColors", default, skip_serializing_if = "Option::is_none")] pub vertex_colors: Option>, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ContextImageFilters { #[serde(default, skip_serializing_if = "Option::is_none")] pub saturation: Option, @@ -2096,11 +2171,12 @@ pub struct ContextImageFilters { pub contrast: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub grayscale: Option, + #[serde(flatten)] + pub extra: Extra, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] -#[cfg_attr(test, serde(deny_unknown_fields))] pub struct ContextImage { pub id: String, pub name: String, @@ -2117,5 +2193,301 @@ pub struct ContextImage { pub drape: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub filters: Option, + #[serde(flatten)] + pub extra: Extra, +} + +impl Project { + /// Setzt EIN Feld aus dem JSON-Baum (`None` = Feld entfernt → Standardwert); so bleibt die + /// typisierte Sicht nach einer Op ohne Neu-Parsen des ganzen Projekts aktuell. + pub fn set_field(&mut self, key: &str, v: Option<&serde_json::Value>) -> Result<(), String> { + match key { + "formatVersion" => { + self.format_version = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "id" => { + self.id = match v { + Some(v) => ::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "name" => { + self.name = match v { + Some(v) => ::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "lineStyles" => { + self.line_styles = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "textStyles" => { + self.text_styles = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "hatches" => { + self.hatches = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "components" => { + self.components = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "wallTypes" => { + self.wall_types = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "ceilingTypes" => { + self.ceiling_types = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "roofTypes" => { + self.roof_types = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "blockDefs" => { + self.block_defs = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "doorTypes" => { + self.door_types = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "windowTypes" => { + self.window_types = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "stairTypes" => { + self.stair_types = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "pens" => { + self.pens = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "penSets" => { + self.pen_sets = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "activePenSetId" => { + self.active_pen_set_id = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "customPalettes" => { + self.custom_palettes = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "builtinPaletteBanks" => { + self.builtin_palette_banks = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "drawingLevels" => { + self.drawing_levels = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "roomProgram" => { + self.room_program = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "parcelArea" => { + self.parcel_area = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "sunStudy" => { + self.sun_study = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "siteRules" => { + self.site_rules = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "scaleLineWeights" => { + self.scale_line_weights = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "layers" => { + self.layers = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "walls" => { + self.walls = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "ceilings" => { + self.ceilings = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "roofs" => { + self.roofs = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "openings" => { + self.openings = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "stairs" => { + self.stairs = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "rooms" => { + self.rooms = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "drawings2d" => { + self.drawings2d = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "context" => { + self.context = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "extrudedSolids" => { + self.extruded_solids = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "columns" => { + self.columns = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "groups" => { + self.groups = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "parametricWalls" => { + self.parametric_walls = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "overrideRules" => { + self.override_rules = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "viewSnapshots" => { + self.view_snapshots = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "viewSnapshotFolders" => { + self.view_snapshot_folders = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "layouts" => { + self.layouts = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "masterLayouts" => { + self.master_layouts = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "layoutFolders" => { + self.layout_folders = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "referenceElevationMasl" => { + self.reference_elevation_masl = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "geoAnchor" => { + self.geo_anchor = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + other => match v { + Some(v) => { + self.extra.0.insert(other.to_owned(), v.clone()); + } + None => { + self.extra.0.remove(other); + } + }, + } + Ok(()) + } } diff --git a/src-tauri/core/src/model/helpers.rs b/src-tauri/core/src/model/helpers.rs index 9c7d0f97..3a44c458 100644 --- a/src-tauri/core/src/model/helpers.rs +++ b/src-tauri/core/src/model/helpers.rs @@ -99,7 +99,7 @@ impl Project { } } } - vec![Layer { component_id: String::new(), thickness: r.thickness.max(0.0), joint_line_style_id: None }] + vec![Layer { component_id: String::new(), thickness: r.thickness.max(0.0), ..Default::default() }] } fn resolve_anchor(&self, a: Option<&VerticalAnchor>) -> Option { diff --git a/src-tauri/core/src/model/manual.rs b/src-tauri/core/src/model/manual.rs index 1d94d384..6aa14d7e 100644 --- a/src-tauri/core/src/model/manual.rs +++ b/src-tauri/core/src/model/manual.rs @@ -4,6 +4,29 @@ use super::generated::*; use serde::{Deserialize, Serialize}; +/// Felder, die das Modell (noch) nicht kennt: bleiben beim Hin-und-zurück erhalten, damit Rust +/// nichts verliert, was neuere Programmstände oder Erweiterungen in die Datei geschrieben haben. +/// In Tests meldet ein unbekanntes Feld sich als Panic — so fällt eine Lücke im Modell auf. +#[derive(Debug, Clone, PartialEq, Default, Serialize)] +pub struct Extra(pub serde_json::Map); + +impl<'de> Deserialize<'de> for Extra { + fn deserialize>(d: D) -> Result { + let m = serde_json::Map::::deserialize(d)?; + #[cfg(test)] + if !m.is_empty() { + panic!("Modell kennt Felder nicht: {:?}", m.keys().collect::>()); + } + Ok(Extra(m)) + } +} + +impl Extra { + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + #[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)] #[cfg_attr(test, serde(deny_unknown_fields))] pub struct Vec2 { From aaa7fae8126524aec49d08881092e68dfe4c601e Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 02:19:53 +0100 Subject: [PATCH 26/31] [K4] S2: IFC-Export in Rust (export_ifc.rs, js_fmt.rs, geo_rebase.rs), byte-genau zur TS-Fassung; exportIfc.ts nur noch Fassade --- TODO.md | 5 +- src-tauri/core/src/export_ifc.rs | 768 ++++++++++++++++++++++ src-tauri/core/src/geo_rebase.rs | 158 +++++ src-tauri/core/src/js_fmt.rs | 70 ++ src-tauri/core/src/lib.rs | 3 + src-tauri/core/src/web/document.rs | 14 + src-tauri/core/src/web/export_ifc.rs | 15 + src-tauri/core/src/web/mod.rs | 1 + src/core/document.ts | 8 + src/export/exportIfc.ts | 933 +-------------------------- 10 files changed, 1056 insertions(+), 919 deletions(-) create mode 100644 src-tauri/core/src/export_ifc.rs create mode 100644 src-tauri/core/src/geo_rebase.rs create mode 100644 src-tauri/core/src/js_fmt.rs create mode 100644 src-tauri/core/src/web/export_ifc.rs diff --git a/TODO.md b/TODO.md index a436d307..c55427ae 100644 --- a/TODO.md +++ b/TODO.md @@ -135,7 +135,10 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern (`queries.rs`), nur die truck-Körper (async) fügt TS ein; TS-Sammler `toWalls3d/{bands,ceilings,columns,openings,stairs,roofs}.ts` gelöscht, unbenutzte Bindungen/Kodierer entfernt. Hin-und-her-Vergleich mit der TS-Fassung lief über Zufallsprojekte, danach prüft die bestehende Suite (2123 Tests) den neuen Weg. Das Modell ist tolerant (fehlende Felder = Standardwert). - Nächste: Plan/Schnitt/Ansicht-Sammler (generatePlan, toSection, toElevation), Export (IFC/DXF/SVG), Raumprogramm. + Pick-Geometrie und 2D-Boden-Spuren im 3D ebenfalls im Kern. **IFC-Export** (`export_ifc.rs`, `js_fmt.rs` für JS-`toFixed`, `geo_rebase.rs`) + byte-genau zur TS-Fassung (Vergleich über Zufallsprojekte; das Salz der GUID-Ableitung beginnt mit U+0001 — so seit jeher, bleibt für + stabile GUIDs). Modell verlustfrei (`Extra`-Felder), typisierte Sicht wird nach Ops feldweise nachgeführt. + Nächste: Export (Schedule/CSV, STL/OBJ, STEP), Plan/Schnitt/Ansicht-Sammler (generatePlan, toSection, toElevation) — hängt an Plan-Puffer v2. 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). - ○ **S3 Änderungen kommen aus Rust**: Befehle (Zustandsautomaten, Werkzeuge) erzeugen Ops im Kern; Undo/Redo, Validierung diff --git a/src-tauri/core/src/export_ifc.rs b/src-tauri/core/src/export_ifc.rs new file mode 100644 index 00000000..d805aabf --- /dev/null +++ b/src-tauri/core/src/export_ifc.rs @@ -0,0 +1,768 @@ +//! IFC4-Export (STEP Physical File, ISO-10303-21) des Modells ([K4] S2, vorher +//! `src/export/exportIfc.ts`): Project → Site → Building → Storeys; Wände als öffnungsgenaue +//! Dreiecks-Netze (gleicher Loch-Ausschnitt wie STL/OBJ), Decken/Treppen/Körper/Stützen/Räume als +//! Profil-Extrusionen, Dächer als Schicht-Netze, Wand-/Deckentypen mit Materialschichten. +//! GUIDs deterministisch aus der Element-ID (zwei FNV-1a-64-Läufe, IFC-Base64-Kompression). +//! Geometrie in realen Weltkoordinaten (LV95), wenn `geoAnchor` gesetzt ist. Einheit: Meter. +//! Byte-genau wie die TS-Fassung (Zahlenformat über [`crate::js_fmt::to_fixed`]). + +use crate::geo_rebase::project_to_world_coords; +use crate::js_fmt::to_fixed; +use crate::model::*; +use crate::model3d; +use crate::wall_mesh_cut::{is_watertight, wall_cut_mesh, CutWall}; +use std::collections::HashMap; + +// ── IFC-GUID ──────────────────────────────────────────────────────────────── + +const IFC_GUID_CHARS: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$"; + +fn guid_b64(v: u64, len: usize) -> String { + (0..len).rev().map(|i| IFC_GUID_CHARS[((v / 64u64.pow(i as u32)) % 64) as usize] as char).collect() +} + +fn compress_guid(bytes: [u8; 16]) -> String { + let mut out = guid_b64(bytes[0] as u64, 2); + let mut i = 1; + while i < 16 { + let v = ((bytes[i] as u64) << 16) + ((bytes[i + 1] as u64) << 8) + bytes[i + 2] as u64; + out.push_str(&guid_b64(v, 4)); + i += 3; + } + out +} + +fn fnv1a64(s: &str, seed: u64) -> u64 { + let mut hash = seed; + // Wie TS: über UTF-16-Code-Einheiten (`charCodeAt`). + for u in s.encode_utf16() { + hash ^= u as u64; + hash = hash.wrapping_mul(0x100000001b3); + } + hash +} + +/// Deterministische 22-stellige IFC-GUID aus einer beliebigen Element-ID. +pub fn ifc_guid(id: &str) -> String { + let h1 = fnv1a64(id, 0xcbf29ce484222325); + // Das Salz beginnt mit U+0001 (so steht es seit jeher in der TS-Fassung); beibehalten, damit + // GUIDs über Re-Exporte und Versionen stabil bleiben. + let h2 = fnv1a64(&format!("{id}\u{1}salt"), 0x9e3779b97f4a7c15); + let mut bytes = [0u8; 16]; + bytes[..8].copy_from_slice(&h1.to_be_bytes()); + bytes[8..].copy_from_slice(&h2.to_be_bytes()); + compress_guid(bytes) +} + +// ── STEP-Formatierung ─────────────────────────────────────────────────────── + +/// STEP-String-Literal: druckbares ASCII bleibt, `\` und `'` werden verdoppelt, alles andere als +/// `\X2\HHHH…\X0\` (BMP) bzw. `\X4\HHHHHHHH…\X0\`. +pub fn ifc_string(s: &str) -> String { + let mut out = String::new(); + let mut run: Vec = Vec::new(); + fn flush(out: &mut String, run: &mut Vec) { + if run.is_empty() { + return; + } + let wide = run.iter().any(|&c| c > 0xffff); + let hex: String = run.iter().map(|c| if wide { format!("{c:08X}") } else { format!("{c:04X}") }).collect(); + out.push_str(if wide { "\\X4\\" } else { "\\X2\\" }); + out.push_str(&hex); + out.push_str("\\X0\\"); + run.clear(); + } + for ch in s.chars() { + let c = ch as u32; + if (0x20..=0x7e).contains(&c) { + flush(&mut out, &mut run); + match ch { + '\\' => out.push_str("\\\\"), + '\'' => out.push_str("''"), + _ => out.push(ch), + } + } else { + if !run.is_empty() && (run[0] > 0xffff) != (c > 0xffff) { + flush(&mut out, &mut run); + } + run.push(c); + } + } + flush(&mut out, &mut run); + format!("'{out}'") +} + +fn s(x: &str) -> String { + ifc_string(x) +} + +/// STEP-REAL — immer mit Dezimalpunkt, ohne unnötige Nachkommastellen. +fn r(x: f64) -> String { + let v = if x == 0.0 { 0.0 } else { x }; + let mut t = to_fixed(v, 6); + let trimmed = t.trim_end_matches('0').len(); + t.truncate(trimmed); + if t.ends_with('.') { + t.push('0'); + } + if !t.contains('.') { + t.push_str(".0"); + } + t +} + +fn en(v: &str) -> String { + format!(".{v}.") +} + +fn list(items: &[String]) -> String { + format!("({})", items.join(",")) +} + +fn refs(ids: &[usize]) -> String { + list(&ids.iter().map(|i| format!("#{i}")).collect::>()) +} + +struct StepWriter { + lines: Vec, + next_id: usize, +} + +impl StepWriter { + fn add(&mut self, ty: &str, params: String) -> usize { + let id = self.next_id; + self.next_id += 1; + self.lines.push(format!("#{id}={ty}({params});")); + id + } +} + +// ── Geometrie-Helfer ──────────────────────────────────────────────────────── + +fn normalize(v: Vec2) -> Vec2 { + let len = crate::jsmath::hypot2(v.x, v.y); + let len = if len == 0.0 || len.is_nan() { 1.0 } else { len }; + Vec2 { x: v.x / len, y: v.y / len } +} + +fn left_normal(u: Vec2) -> Vec2 { + Vec2 { x: -u.y, y: u.x } +} + +fn add_scaled(p: Vec2, d: Vec2, k: f64) -> Vec2 { + Vec2 { x: p.x + d.x * k, y: p.y + d.y * k } +} + +/// Rechteck-Footprint einer Öffnung im Wandloch (volle Wanddicke tief), CCW. +fn opening_footprint(p: &Project, wall: &Wall, o: &Opening) -> Vec { + let u = normalize(Vec2 { x: wall.end.x - wall.start.x, y: wall.end.y - wall.start.y }); + let n = left_normal(u); + let t = p.wall_type(wall).map_or(0.0, |wt| Project::type_thickness(&wt.layers)); + let off = crate::joins::reference_offset(model3d_reference(wall), t); + let inner = -t / 2.0 + off; + let outer = t / 2.0 + off; + let a = add_scaled(wall.start, u, o.position); + let b = add_scaled(wall.start, u, o.position + o.width); + vec![add_scaled(a, n, inner), add_scaled(b, n, inner), add_scaled(b, n, outer), add_scaled(a, n, outer)] +} + +fn model3d_reference(w: &Wall) -> crate::joins::Reference { + use crate::joins::Reference; + match (w.reference_offset, w.reference_line) { + (Some(v), _) => Reference::Offset(v), + (None, Some(WallReferenceLine::Left)) => Reference::Left, + (None, Some(WallReferenceLine::Right)) => Reference::Right, + _ => Reference::Center, + } +} + +/// Vereinfachter Bounding-Footprint einer Treppe (Lauf-Rechteck bzw. Box der Kontrollpunkte). +fn stair_footprint(st: &Stair) -> Vec { + let half_w = st.width.max(0.0) / 2.0; + if st.shape == StairShape::Straight { + let u = normalize(st.dir); + let n = left_normal(u); + let end = add_scaled(st.start, u, st.run_length); + return vec![add_scaled(st.start, n, -half_w), add_scaled(end, n, -half_w), add_scaled(end, n, half_w), add_scaled(st.start, n, half_w)]; + } + let mut pts = vec![st.start]; + let u = normalize(st.dir); + let corner = add_scaled(st.start, u, st.run_length); + pts.push(corner); + if st.shape == StairShape::L { + if let (Some(run2), Some(turn)) = (st.run2_length.filter(|v| *v != 0.0), st.turn.filter(|v| *v != 0.0)) { + let n = left_normal(u); + let turn_dir = Vec2 { x: n.x * turn, y: n.y * turn }; + pts.push(add_scaled(corner, turn_dir, run2)); + } + } + if st.shape == StairShape::Spiral { + if let Some(c) = st.center { + let rr = st.radius.unwrap_or(0.0) + half_w; + return vec![ + Vec2 { x: c.x - rr, y: c.y - rr }, + Vec2 { x: c.x + rr, y: c.y - rr }, + Vec2 { x: c.x + rr, y: c.y + rr }, + Vec2 { x: c.x - rr, y: c.y + rr }, + ]; + } + } + let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for q in &pts { + min_x = min_x.min(q.x); + min_y = min_y.min(q.y); + max_x = max_x.max(q.x); + max_y = max_y.max(q.y); + } + min_x -= half_w; + min_y -= half_w; + max_x += half_w; + max_y += half_w; + vec![Vec2 { x: min_x, y: min_y }, Vec2 { x: max_x, y: min_y }, Vec2 { x: max_x, y: max_y }, Vec2 { x: min_x, y: max_y }] +} + +fn opening_label(o: &Opening) -> String { + format!("{} {}×{}", if o.kind == ElementKind::Door { "Tür" } else { "Fenster" }, to_fixed(o.width * 100.0, 0), to_fixed(o.height * 100.0, 0)) +} + +fn column_label(c: &Column) -> String { + match &c.profile { + ColumnProfile::Round { radius } => format!("Stütze Ø{}", to_fixed(radius * 200.0, 0)), + ColumnProfile::Rect { width, depth } => format!("Stütze {}×{}", to_fixed(width * 100.0, 0), to_fixed(depth * 100.0, 0)), + } +} + +#[derive(Clone, Copy)] +struct Structure { + entity_id: usize, + placement_id: usize, + base_elevation: f64, +} + +struct ElementTypeRef { + type_id: usize, + occurrences: Vec, +} + +/// Unix-Sekunden/ISO-Zeit aus Millisekunden seit 1970 (UTC), wie `Date.now()` / `toISOString()`. +fn iso_from_ms(ms: f64) -> String { + let secs = (ms / 1000.0).floor() as i64; + let days = secs.div_euclid(86_400); + let tod = secs.rem_euclid(86_400); + // Zivildatum aus Tagen (Howard Hinnant). + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = if m <= 2 { y + 1 } else { y }; + format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}", tod / 3600, (tod % 3600) / 60, tod % 60) +} + +/// Baut aus einem Projekt einen vollständigen IFC4-SPF-String. `now_ms`: Zeitpunkt des Exports +/// (ms seit 1970). Leeres Projekt ⇒ valider Minimal-IFC. `Err`: das Modell lässt sich nicht +/// ableiten (z. B. unbekannter Wandtyp bei der Verschneidung). +pub fn export_ifc_spf(project_in: &Project, now_ms: f64) -> Result { + let project = project_to_world_coords(project_in); + let p = &project; + let mut w = StepWriter { lines: Vec::new(), next_id: 1 }; + + let origin_point = w.add("IFCCARTESIANPOINT", list(&[r(0.0), r(0.0), r(0.0)])); + let extrude_dir = w.add("IFCDIRECTION", list(&[r(0.0), r(0.0), r(1.0)])); + let identity_axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{origin_point},$,$")); + + let org = w.add("IFCORGANIZATION", format!("$,{},$,$,$", s("dossier"))); + let person = w.add("IFCPERSON", format!("{},$,$,$,$,$,$,$", s("dossier"))); + let person_org = w.add("IFCPERSONANDORGANIZATION", format!("#{person},#{org},$")); + let app = w.add("IFCAPPLICATION", format!("#{org},{},{},{}", s("1.0"), s("dossier"), s("dossier"))); + let now = (now_ms / 1000.0).floor() as i64; + let owner_history = w.add("IFCOWNERHISTORY", format!("#{person_org},#{app},$,{},{now},$,$,{now}", en("ADDED"))); + + let len_unit = w.add("IFCSIUNIT", format!("*,{},$,{}", en("LENGTHUNIT"), en("METRE"))); + let area_unit = w.add("IFCSIUNIT", format!("*,{},$,{}", en("AREAUNIT"), en("SQUARE_METRE"))); + let vol_unit = w.add("IFCSIUNIT", format!("*,{},$,{}", en("VOLUMEUNIT"), en("CUBIC_METRE"))); + let angle_unit = w.add("IFCSIUNIT", format!("*,{},$,{}", en("PLANEANGLEUNIT"), en("RADIAN"))); + let unit_assignment = w.add("IFCUNITASSIGNMENT", refs(&[len_unit, area_unit, vol_unit, angle_unit])); + + let context = w.add("IFCGEOMETRICREPRESENTATIONCONTEXT", format!("$,{},3,{},#{identity_axis},$", s("Model"), r(0.00001))); + + if p.geo_anchor.is_some() { + let crs = w.add( + "IFCPROJECTEDCRS", + format!("{},{},{},$,{},$,#{len_unit}", s("EPSG:2056"), s("CH1903+ / LV95"), s("CH1903+"), s("Swiss Oblique Mercator")), + ); + w.add("IFCMAPCONVERSION", format!("#{context},#{crs},{},{},{},{},{},{}", r(0.0), r(0.0), r(0.0), r(1.0), r(0.0), r(1.0))); + } + + let site_axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{origin_point},$,$")); + let site_placement = w.add("IFCLOCALPLACEMENT", format!("$,#{site_axis}")); + let building_axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{origin_point},$,$")); + let building_placement = w.add("IFCLOCALPLACEMENT", format!("#{site_placement},#{building_axis}")); + + let project_id = w.add( + "IFCPROJECT", + format!( + "{},#{owner_history},{},$,$,$,$,{},#{unit_assignment}", + s(&ifc_guid(&format!("{}:project", p.id))), + s(if p.name.is_empty() { "Projekt" } else { &p.name }), + refs(&[context]) + ), + ); + let site_ref_elev = p.geo_anchor.as_ref().and_then(|a| a.height).map_or("$".to_string(), r); + let site_id = w.add( + "IFCSITE", + format!( + "{},#{owner_history},{},$,$,#{site_placement},$,$,{},$,$,{site_ref_elev},$,$", + s(&ifc_guid(&format!("{}:site", p.id))), + s("Standort"), + en("ELEMENT") + ), + ); + let building_id = w.add( + "IFCBUILDING", + format!( + "{},#{owner_history},{},$,$,#{building_placement},$,$,{},$,$,$", + s(&ifc_guid(&format!("{}:building", p.id))), + s(if p.name.is_empty() { "Gebäude" } else { &p.name }), + en("ELEMENT") + ), + ); + w.add("IFCRELAGGREGATES", format!("{},#{owner_history},$,$,#{project_id},{}", s(&ifc_guid(&format!("{}:agg-site", p.id))), refs(&[site_id]))); + w.add("IFCRELAGGREGATES", format!("{},#{owner_history},$,$,#{site_id},{}", s(&ifc_guid(&format!("{}:agg-building", p.id))), refs(&[building_id]))); + + let floors: Vec<&DrawingLevel> = p.drawing_levels.iter().filter(|l| l.kind == DrawingLevelKind::Floor).collect(); + let mut storey_by_floor: HashMap<&str, Structure> = HashMap::new(); + let mut storey_ids = Vec::new(); + for floor in &floors { + let base = floor.base_elevation.unwrap_or(0.0); + let pt = w.add("IFCCARTESIANPOINT", list(&[r(0.0), r(0.0), r(base)])); + let axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{pt},$,$")); + let placement_id = w.add("IFCLOCALPLACEMENT", format!("#{building_placement},#{axis}")); + let entity_id = w.add( + "IFCBUILDINGSTOREY", + format!("{},#{owner_history},{},$,$,#{placement_id},$,$,{},{}", s(&ifc_guid(&format!("{}:storey", floor.id))), s(&floor.name), en("ELEMENT"), r(base)), + ); + storey_by_floor.entry(floor.id.as_str()).or_insert(Structure { entity_id, placement_id, base_elevation: base }); + storey_ids.push(entity_id); + } + if !storey_ids.is_empty() { + w.add("IFCRELAGGREGATES", format!("{},#{owner_history},$,$,#{building_id},{}", s(&ifc_guid(&format!("{}:agg-storeys", p.id))), refs(&storey_ids))); + } + + let resolve_structure = |floor_id: &str| -> Structure { + storey_by_floor.get(floor_id).copied().unwrap_or(Structure { entity_id: building_id, placement_id: building_placement, base_elevation: 0.0 }) + }; + + // Räumliche Eingliederung je Trägerstruktur, in Einfüge-Reihenfolge. + let mut containment: Vec<(usize, Vec)> = Vec::new(); + let mut add_to_containment = |structure: usize, element: usize| match containment.iter_mut().find(|(k, _)| *k == structure) { + Some((_, v)) => v.push(element), + None => containment.push((structure, vec![element])), + }; + + macro_rules! emit_box_product { + ($footprint:expr, $z_bottom_rel:expr, $depth:expr, $placement_rel_to:expr) => {{ + let footprint: &[Vec2] = $footprint; + let mut closed: Vec = footprint.to_vec(); + closed.push(footprint[0]); + let pt_ids: Vec = closed.iter().map(|q| w.add("IFCCARTESIANPOINT", list(&[r(q.x), r(q.y)]))).collect(); + let polyline = w.add("IFCPOLYLINE", refs(&pt_ids)); + let profile = w.add("IFCARBITRARYCLOSEDPROFILEDEF", format!("{},$,#{polyline}", en("AREA"))); + let solid = w.add("IFCEXTRUDEDAREASOLID", format!("#{profile},#{identity_axis},#{extrude_dir},{}", r(($depth as f64).max(0.001)))); + let shape_rep = w.add("IFCSHAPEREPRESENTATION", format!("#{context},{},{},{}", s("Body"), s("SweptSolid"), refs(&[solid]))); + let shape = w.add("IFCPRODUCTDEFINITIONSHAPE", format!("$,$,{}", refs(&[shape_rep]))); + let elem_origin = w.add("IFCCARTESIANPOINT", list(&[r(0.0), r(0.0), r($z_bottom_rel)])); + let elem_axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{elem_origin},$,$")); + let placement = w.add("IFCLOCALPLACEMENT", format!("#{},#{elem_axis}", $placement_rel_to)); + (placement, shape) + }}; + } + + macro_rules! emit_triangulated_product { + ($positions:expr, $indices:expr, $placement_rel_to:expr, $closed:expr) => {{ + let positions: &[f64] = $positions; + let indices: &[u32] = $indices; + let coords: Vec = positions.chunks_exact(3).map(|c| format!("({},{},{})", r(c[0]), r(c[1]), r(c[2]))).collect(); + let point_list = w.add("IFCCARTESIANPOINTLIST3D", format!("({})", coords.join(","))); + let tris: Vec = indices.chunks_exact(3).map(|t| format!("({},{},{})", t[0] + 1, t[1] + 1, t[2] + 1)).collect(); + let closed_flag = if $closed { ".T." } else { "$" }; + let face_set = w.add("IFCTRIANGULATEDFACESET", format!("#{point_list},$,{closed_flag},({}),$", tris.join(","))); + let shape_rep = w.add("IFCSHAPEREPRESENTATION", format!("#{context},{},{},{}", s("Body"), s("Tessellation"), refs(&[face_set]))); + let shape = w.add("IFCPRODUCTDEFINITIONSHAPE", format!("$,$,{}", refs(&[shape_rep]))); + let elem_origin = w.add("IFCCARTESIANPOINT", list(&[r(0.0), r(0.0), r(0.0)])); + let elem_axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{elem_origin},$,$")); + let placement = w.add("IFCLOCALPLACEMENT", format!("#{},#{elem_axis}", $placement_rel_to)); + (placement, shape) + }}; + } + + macro_rules! emit_building_element { + ($ty:expr, $guid:expr, $name:expr, $placement:expr, $shape:expr, $predefined:expr) => { + w.add($ty, format!("{},#{owner_history},{},$,$,#{},#{},$,{}", s(&$guid), s(&$name), $placement, $shape, $predefined.unwrap_or_else(|| "$".to_string()))) + }; + } + + // ── Bauteiltypen mit Materialschichten ── + let mut material_by_component: HashMap = HashMap::new(); + let mut element_types: Vec<(String, ElementTypeRef)> = Vec::new(); + macro_rules! material_of { + ($component_id:expr) => {{ + let cid: &str = $component_id; + match material_by_component.get(cid) { + Some(&id) => id, + None => { + let name = p.component(cid).map_or(cid.to_string(), |c| c.name.clone()); + let id = w.add("IFCMATERIAL", format!("{},$,$", s(&name))); + material_by_component.insert(cid.to_string(), id); + id + } + } + }}; + } + macro_rules! type_for { + ($ifc_type:expr, $predefined:expr, $t_id:expr, $t_name:expr, $layers:expr) => {{ + let key = format!("{}:{}", $ifc_type, $t_id); + match element_types.iter().position(|(k, _)| *k == key) { + Some(i) => i, + None => { + let layers: &[Layer] = $layers; + let layer_ids: Vec = layers + .iter() + .map(|l| { + let mat = material_of!(&l.component_id); + let th = if l.thickness.is_finite() { l.thickness } else { 0.0 }; + w.add("IFCMATERIALLAYER", format!("#{mat},{},$,$,$,$,$", r(th.max(0.0)))) + }) + .collect(); + let type_id = w.add($ifc_type, format!("{},#{owner_history},{},$,$,$,$,$,$,{}", s(&ifc_guid(&key)), s($t_name), en($predefined))); + if !layer_ids.is_empty() { + let set = w.add("IFCMATERIALLAYERSET", format!("{},{},$", refs(&layer_ids), s($t_name))); + w.add("IFCRELASSOCIATESMATERIAL", format!("{},#{owner_history},$,$,{},#{set}", s(&ifc_guid(&format!("{key}:material"))), refs(&[type_id]))); + } + element_types.push((key, ElementTypeRef { type_id, occurrences: vec![] })); + element_types.len() - 1 + } + } + }}; + } + + // ── Wände (öffnungsgenaues Dreiecks-Mesh) ── + let bands = model3d::emit_walls(p, true)?; + let mut bands_by_wall: HashMap<&str, Vec> = HashMap::new(); + for (i, b) in bands.iter().enumerate() { + bands_by_wall.entry(b.wall_id.as_str()).or_default().push(i); + } + let mut wall_entity_by_id: HashMap<&str, usize> = HashMap::new(); + for wall in &p.walls { + let Some(idxs) = bands_by_wall.get(wall.id.as_str()).filter(|v| !v.is_empty()) else { continue }; + let structure = resolve_structure(&wall.floor_id); + let mut positions: Vec = Vec::new(); + let mut indices: Vec = Vec::new(); + for &bi in idxs { + let b = &bands[bi]; + let cw = CutWall { + start: b.start, + end: b.end, + thickness: b.thickness, + base_elevation: b.base_elevation, + height: b.height, + holes: b.holes.as_ref().map_or(vec![], |hs| hs.iter().map(|h| [h.from, h.to, h.z_bottom, h.z_top]).collect()), + }; + let finite = cw.start.iter().chain(&cw.end).all(|v| v.is_finite()) && [cw.thickness, cw.base_elevation, cw.height].iter().all(|v| v.is_finite()) && cw.holes.iter().flatten().all(|v| v.is_finite()); + let cut = if finite { wall_cut_mesh(&cw) } else { Vec::new() }; + let base = (positions.len() / 3) as u32; + for c in cut.chunks_exact(3) { + positions.extend([c[0], c[2], c[1] - structure.base_elevation]); + } + // Wicklung umkehren (Reflexions-Ausgleich des Achsentauschs): (a, b, c) → (a, c, b). + let n_tris = (cut.len() / 3) as u32 / 3; + for t in 0..n_tris { + let i = t * 3; + indices.extend([base + i, base + i + 2, base + i + 1]); + } + } + if indices.is_empty() { + continue; + } + let closed = is_watertight(&positions, &indices, 1e-6); + let (placement, shape) = emit_triangulated_product!(&positions, &indices, structure.placement_id, closed); + let mut name = wall.id.clone(); + let mut type_idx = None; + if let Some(wt) = p.wall_type(wall) { + name = wt.name.clone(); + type_idx = Some(type_for!("IFCWALLTYPE", "STANDARD", wt.id, &wt.name, &wt.layers)); + } + let entity = emit_building_element!("IFCWALL", ifc_guid(&wall.id), name, placement, shape, None::); + if let Some(i) = type_idx { + element_types[i].1.occurrences.push(entity); + } + wall_entity_by_id.insert(wall.id.as_str(), entity); + add_to_containment(structure.entity_id, entity); + } + + // ── Decken ── + for ceiling in p.ceilings.as_deref().unwrap_or(&[]) { + if ceiling.outline.len() < 3 { + continue; + } + let (z_bottom, z_top) = p.ceiling_vertical_extent(ceiling); + let structure = resolve_structure(&ceiling.floor_id); + let (placement, shape) = emit_box_product!(&ceiling.outline, z_bottom - structure.base_elevation, z_top - z_bottom, structure.placement_id); + let mut name = ceiling.id.clone(); + let mut type_idx = None; + if let Some((tid, tname, layers)) = ceiling_type_of(p, ceiling) { + name = tname.to_string(); + type_idx = Some(type_for!("IFCSLABTYPE", "FLOOR", tid, tname, layers)); + } + let entity = emit_building_element!("IFCSLAB", ifc_guid(&ceiling.id), name, placement, shape, Some(en("FLOOR"))); + if let Some(i) = type_idx { + element_types[i].1.occurrences.push(entity); + } + add_to_containment(structure.entity_id, entity); + } + + // ── Fenster/Türen als eigene Objekte ── + for opening in p.openings.as_deref().unwrap_or(&[]) { + let Some(wall) = p.walls.iter().find(|wl| wl.id == opening.host_wall_id) else { continue }; + if !wall_entity_by_id.contains_key(wall.id.as_str()) { + continue; + } + let (wall_z_bottom, _) = p.wall_vertical_extent(wall); + let structure = resolve_structure(&wall.floor_id); + let footprint = opening_footprint(p, wall, opening); + let z_sill_abs = wall_z_bottom + opening.sill_height; + let (fill_placement, fill_shape) = emit_box_product!(&footprint, z_sill_abs - structure.base_elevation, opening.height, structure.placement_id); + let fill_guid = ifc_guid(&format!("{}:fill", opening.id)); + let fill_name = opening_label(opening); + let entity = if opening.kind == ElementKind::Door { + w.add( + "IFCDOOR", + format!("{},#{owner_history},{},$,$,#{fill_placement},#{fill_shape},$,{},{},{},$,$", s(&fill_guid), s(&fill_name), r(opening.height), r(opening.width), en("DOOR")), + ) + } else { + w.add( + "IFCWINDOW", + format!("{},#{owner_history},{},$,$,#{fill_placement},#{fill_shape},$,{},{},{},$,$", s(&fill_guid), s(&fill_name), r(opening.height), r(opening.width), en("WINDOW")), + ) + }; + add_to_containment(structure.entity_id, entity); + } + + // ── Treppen ── + for stair in p.stairs.as_deref().unwrap_or(&[]) { + let footprint = stair_footprint(stair); + if footprint.len() < 3 { + continue; + } + let (z_bottom, z_top) = p.stair_vertical_extent(stair); + let structure = resolve_structure(&stair.floor_id); + let (placement, shape) = emit_box_product!(&footprint, z_bottom - structure.base_elevation, z_top - z_bottom, structure.placement_id); + let predefined = match stair.shape { + StairShape::Straight => en("STRAIGHT_RUN_STAIR"), + StairShape::Spiral => en("SPIRAL_STAIR"), + StairShape::L => en("QUARTER_TURN_STAIR"), + }; + let entity = emit_building_element!("IFCSTAIR", ifc_guid(&stair.id), "Treppe".to_string(), placement, shape, Some(predefined)); + add_to_containment(structure.entity_id, entity); + } + + // ── Extrudierte Körper ── + for solid in p.extruded_solids.as_deref().unwrap_or(&[]) { + if solid.points.len() < 3 { + continue; + } + let base = floors.iter().find(|f| f.id == solid.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0)); + let structure = resolve_structure(&solid.level_id); + let (placement, shape) = emit_box_product!(&solid.points, base - structure.base_elevation, solid.height, structure.placement_id); + let entity = emit_building_element!("IFCBUILDINGELEMENTPROXY", ifc_guid(&solid.id), "Extrusion".to_string(), placement, shape, None::); + add_to_containment(structure.entity_id, entity); + } + + // ── Räume → IfcSpace ── + let mut spaces_by_structure: Vec<(usize, Vec)> = Vec::new(); + for room in p.rooms.as_deref().unwrap_or(&[]) { + if room.boundary.len() < 3 { + continue; + } + let structure = resolve_structure(&room.floor_id); + let height = floors.iter().find(|f| f.id == room.floor_id).and_then(|f| f.floor_height).filter(|h| *h > 0.0).unwrap_or(2.5); + let (placement, shape) = emit_box_product!(&room.boundary, 0.0, height, structure.placement_id); + let number = room.stamp.as_ref().and_then(|st| st.number.as_deref()).filter(|n| !n.is_empty()).unwrap_or(&room.id); + let space_id = w.add( + "IFCSPACE", + format!("{},#{owner_history},{},$,$,#{placement},#{shape},{},{},{},$", s(&ifc_guid(&room.id)), s(number), s(&room.name), en("ELEMENT"), en("INTERNAL")), + ); + match spaces_by_structure.iter_mut().find(|(k, _)| *k == structure.entity_id) { + Some((_, v)) => v.push(space_id), + None => spaces_by_structure.push((structure.entity_id, vec![space_id])), + } + let pts: Vec<[f64; 2]> = room.boundary.iter().map(|v| [v.x, v.y]).collect(); + let area = crate::room_area::evaluate(&pts, 0.0); + let q_net = w.add("IFCQUANTITYAREA", format!("{},$,$,{},$", s("NetFloorArea"), r(area.net))); + let q_gross = w.add("IFCQUANTITYAREA", format!("{},$,$,{},$", s("GrossFloorArea"), r(area.gross))); + let q_height = w.add("IFCQUANTITYLENGTH", format!("{},$,$,{},$", s("Height"), r(height))); + let qto = w.add( + "IFCELEMENTQUANTITY", + format!("{},#{owner_history},{},$,$,{}", s(&ifc_guid(&format!("{}:qto", room.id))), s("Qto_SpaceBaseQuantities"), refs(&[q_net, q_gross, q_height])), + ); + w.add("IFCRELDEFINESBYPROPERTIES", format!("{},#{owner_history},$,$,{},#{qto}", s(&ifc_guid(&format!("{}:rel-qto", room.id))), refs(&[space_id]))); + let sia_name = serde_json::to_value(room.sia_category).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default(); + let sia = w.add("IFCPROPERTYSINGLEVALUE", format!("{},$,IFCLABEL({}),$", s("SIA416"), s(&sia_name))); + let pset = w.add("IFCPROPERTYSET", format!("{},#{owner_history},{},$,{}", s(&ifc_guid(&format!("{}:pset", room.id))), s("CH_Raum"), refs(&[sia]))); + w.add("IFCRELDEFINESBYPROPERTIES", format!("{},#{owner_history},$,$,{},#{pset}", s(&ifc_guid(&format!("{}:rel-pset", room.id))), refs(&[space_id]))); + } + for (structure_id, space_ids) in &spaces_by_structure { + w.add("IFCRELAGGREGATES", format!("{},#{owner_history},$,$,#{structure_id},{}", s(&ifc_guid(&format!("spaces:{structure_id}"))), refs(space_ids))); + } + + // ── Dächer → IfcRoof ── + for roof in p.roofs.as_deref().unwrap_or(&[]) { + let structure = resolve_structure(&roof.floor_id); + let mut positions: Vec = Vec::new(); + let mut indices: Vec = Vec::new(); + for mesh in model3d::emit_roofs(p, Some(&roof.id))? { + let base = (positions.len() / 3) as u32; + for c in mesh.positions.chunks_exact(3) { + positions.extend([c[0], c[1], c[2] - structure.base_elevation]); + } + indices.extend(mesh.indices.iter().map(|ix| base + ix)); + } + if indices.is_empty() { + continue; + } + let mut closed = is_watertight(&positions, &indices, 1e-6); + if !closed { + let flipped: Vec = indices.chunks_exact(3).flat_map(|t| [t[0], t[2], t[1]]).collect(); + if is_watertight(&positions, &flipped, 1e-6) { + indices = flipped; + closed = true; + } + } + let (placement, shape) = emit_triangulated_product!(&positions, &indices, structure.placement_id, closed); + let predefined = match roof.shape { + RoofShape::Flach => "FLAT_ROOF", + RoofShape::Pult => "SHED_ROOF", + RoofShape::Sattel => "GABLE_ROOF", + RoofShape::Walm => "HIP_ROOF", + RoofShape::Mansarde => "MANSARD_ROOF", + RoofShape::Zelt => "HIPPED_GABLE_ROOF", + }; + let roof_type = roof.roof_type_id.as_deref().and_then(|id| p.roof_types.as_deref()?.iter().find(|t| t.id == id)); + let name = roof_type.map_or("Dach".to_string(), |t| t.name.clone()); + let entity = emit_building_element!("IFCROOF", ifc_guid(&roof.id), name, placement, shape, Some(en(predefined))); + if let Some(rt) = roof_type { + let i = type_for!("IFCROOFTYPE", predefined, rt.id, &rt.name, &rt.layers); + element_types[i].1.occurrences.push(entity); + } + add_to_containment(structure.entity_id, entity); + } + + // ── Stützen → IfcColumn ── + let mut material_assoc: Vec<(usize, Vec)> = Vec::new(); + for col in p.columns.as_deref().unwrap_or(&[]) { + let footprint = model3d::column_footprint(col); + if footprint.len() < 3 { + continue; + } + let (z_bottom, z_top) = p.column_vertical_extent(col); + if !(z_top > z_bottom) { + continue; + } + let structure = resolve_structure(&col.floor_id); + let (placement, shape) = emit_box_product!(&footprint, z_bottom - structure.base_elevation, z_top - z_bottom, structure.placement_id); + let entity = emit_building_element!("IFCCOLUMN", ifc_guid(&col.id), column_label(col), placement, shape, Some(en("COLUMN"))); + add_to_containment(structure.entity_id, entity); + if let Some(cid) = col.component_id.as_deref().filter(|c| !c.is_empty()) { + let mat = material_of!(cid); + match material_assoc.iter_mut().find(|(k, _)| *k == mat) { + Some((_, v)) => v.push(entity), + None => material_assoc.push((mat, vec![entity])), + } + } + } + for (mat, ids) in &material_assoc { + w.add("IFCRELASSOCIATESMATERIAL", format!("{},#{owner_history},$,$,{},#{mat}", s(&ifc_guid(&format!("material:{mat}"))), refs(ids))); + } + + // ── Typ-Zuordnung ── + for (key, rf) in &element_types { + if rf.occurrences.is_empty() { + continue; + } + w.add("IFCRELDEFINESBYTYPE", format!("{},#{owner_history},$,$,{},#{}", s(&ifc_guid(&format!("{key}:occurrences"))), refs(&rf.occurrences), rf.type_id)); + } + + // ── Räumliche Eingliederung ── + for (structure_id, element_ids) in &containment { + w.add("IFCRELCONTAINEDINSPATIALSTRUCTURE", format!("{},#{owner_history},$,$,{},#{structure_id}", s(&ifc_guid(&format!("contain:{structure_id}"))), refs(element_ids))); + } + + // ── Kopf + Zusammenbau ── + let iso = iso_from_ms(now_ms); + let file_name = format!("{}.ifc", if p.name.is_empty() { "modell" } else { &p.name }); + let mut out = vec![ + "ISO-10303-21;".to_string(), + "HEADER;".to_string(), + format!("FILE_DESCRIPTION({},{});", list(&[s("")]), s("2;1")), + format!("FILE_NAME({},{},{},{},{},{},{});", s(&file_name), s(&iso), list(&[s("dossier")]), list(&[s("dossier")]), s("dossier"), s("dossier"), s("")), + "FILE_SCHEMA(('IFC4'));".to_string(), + "ENDSEC;".to_string(), + String::new(), + "DATA;".to_string(), + ]; + out.extend(w.lines); + out.push("ENDSEC;".to_string()); + out.push("END-ISO-10303-21;".to_string()); + Ok(out.join("\n") + "\n") +} + +/// Deckentyp (id, Name, Schichten): Deckentyp, sonst Wandtyp (`getCeilingType`). +fn ceiling_type_of<'a>(p: &'a Project, c: &Ceiling) -> Option<(&'a str, &'a str, &'a [Layer])> { + if let Some(id) = c.ceiling_type_id.as_deref() { + if let Some(t) = p.ceiling_types.as_deref().and_then(|v| v.iter().find(|t| t.id == id)) { + return Some((&t.id, &t.name, &t.layers)); + } + } + p.wall_types.iter().find(|t| t.id == c.wall_type_id).map(|t| (t.id.as_str(), t.name.as_str(), t.layers.as_slice())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn guid_ist_stabil_und_22_zeichen_lang() { + let g = ifc_guid("wall-1"); + assert_eq!(g.len(), 22); + assert_eq!(g, ifc_guid("wall-1")); + assert_ne!(g, ifc_guid("wall-2")); + } + + #[test] + fn string_und_zahl_literale() { + assert_eq!(ifc_string("A'b\\ü😀"), "'A''b\\\\\\X2\\00FC\\X0\\\\X4\\0001F600\\X0\\'"); + assert_eq!(r(1.0), "1.0"); + assert_eq!(r(-0.0), "0.0"); + assert_eq!(r(0.1234567), "0.123457"); + assert_eq!(r(2.5), "2.5"); + } + + #[test] + fn iso_datum() { + assert_eq!(iso_from_ms(0.0), "1970-01-01T00:00:00"); + assert_eq!(iso_from_ms(1_700_000_000_000.0), "2023-11-14T22:13:20"); + } + + #[test] + fn beispielprojekt_exportiert() { + let p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap(); + let ifc = export_ifc_spf(&p, 1_700_000_000_000.0).unwrap(); + assert!(ifc.starts_with("ISO-10303-21;\nHEADER;")); + assert!(ifc.contains("IFCWALL(")); + assert!(ifc.ends_with("END-ISO-10303-21;\n")); + } +} diff --git a/src-tauri/core/src/geo_rebase.rs b/src-tauri/core/src/geo_rebase.rs new file mode 100644 index 00000000..67bbf8f3 --- /dev/null +++ b/src-tauri/core/src/geo_rebase.rs @@ -0,0 +1,158 @@ +//! Ursprungs-Verschiebung des ganzen Projekts ([K4] S2, vorher `model/geoRebase.ts`): reine, +//! verlustfreie Translation aller Modell-Koordinaten um einen festen Vektor. `geoAnchor` wandert +//! mit, damit der LV95-Bezug exakt erhalten bleibt. Nur Translation — keine Rotation (Achsen- und +//! Winkelfelder blieben sonst falsch). Richtungsvektoren (z. B. `Stair.dir`) bleiben unangetastet. + +use crate::model::*; + +fn shift(p: Vec2, dx: f64, dy: f64) -> Vec2 { + Vec2 { x: p.x + dx, y: p.y + dy } +} + +fn shift_all(pts: &mut [Vec2], dx: f64, dy: f64) { + for p in pts { + *p = shift(*p, dx, dy); + } +} + +fn shift_geom(g: &mut Drawing2DGeom, dx: f64, dy: f64) { + use Drawing2DGeom::*; + match g { + Line { a, b } | Xline { a, b } | Ray { a, b } => { + *a = shift(*a, dx, dy); + *b = shift(*b, dx, dy); + } + Polyline { pts, .. } | Bezier { pts } | Spline { pts, .. } | Dimension { pts, .. } => shift_all(pts, dx, dy), + Rect { min, max } | Image { min, max, .. } => { + *min = shift(*min, dx, dy); + *max = shift(*max, dx, dy); + } + Circle { center, .. } | Arc { center, .. } | Ellipse { center, .. } => *center = shift(*center, dx, dy), + Kote { at, .. } | Detailref { at, .. } | Scalebar { at, .. } | Pointmarker { at } | Block { at, .. } => *at = shift(*at, dx, dy), + Text { at, leader_target, leader_bend_points, path_pts, .. } => { + *at = shift(*at, dx, dy); + if let Some(t) = leader_target { + *t = shift(*t, dx, dy); + } + if let Some(v) = leader_bend_points { + shift_all(v, dx, dy); + } + if let Some(v) = path_pts { + shift_all(v, dx, dy); + } + } + } +} + +fn shift_context(o: &mut ContextObject, dx: f64, dy: f64) { + match o { + ContextObject::ContourSet(s) => { + for c in &mut s.contours { + shift_all(&mut c.pts, dx, dy); + if let Some(cv) = &mut c.curve { + cv.cx += dx; + cv.cy += dy; + } + } + } + ContextObject::Image(i) => { + i.min = shift(i.min, dx, dy); + i.max = shift(i.max, dx, dy); + } + ContextObject::ImportedMesh(m) => shift_positions(&mut m.positions, dx, dy), + ContextObject::TerrainMesh(m) => shift_positions(&mut m.positions, dx, dy), + } +} + +/// Nur x/y (Grundriss) verschieben, die Höhe bleibt. +fn shift_positions(pos: &mut [f64], dx: f64, dy: f64) { + for c in pos.chunks_exact_mut(3) { + c[0] += dx; + c[1] += dy; + } +} + +/// Verschiebt sämtliche Modell-Koordinaten (`translateProject`). +pub fn translate_project(p: &Project, dx: f64, dy: f64) -> Project { + if dx == 0.0 && dy == 0.0 { + return p.clone(); + } + let mut out = p.clone(); + for w in &mut out.walls { + w.start = shift(w.start, dx, dy); + w.end = shift(w.end, dx, dy); + } + for c in out.ceilings.iter_mut().flatten() { + shift_all(&mut c.outline, dx, dy); + for h in c.openings.iter_mut().flatten() { + shift_all(h, dx, dy); + } + } + for r in out.roofs.iter_mut().flatten() { + shift_all(&mut r.outline, dx, dy); + } + for s in out.stairs.iter_mut().flatten() { + s.start = shift(s.start, dx, dy); + s.center = s.center.map(|c| shift(c, dx, dy)); + } + for r in out.rooms.iter_mut().flatten() { + shift_all(&mut r.boundary, dx, dy); + r.stamp_anchor = r.stamp_anchor.map(|a| shift(a, dx, dy)); + } + for c in out.columns.iter_mut().flatten() { + c.position = shift(c.position, dx, dy); + } + for s in out.extruded_solids.iter_mut().flatten() { + shift_all(&mut s.points, dx, dy); + if let Some(c) = &mut s.circle { + c.center = shift(c.center, dx, dy); + } + } + for d in &mut out.drawings2d { + shift_geom(&mut d.geom, dx, dy); + } + for o in out.context.iter_mut().flatten() { + shift_context(o, dx, dy); + } + for l in &mut out.drawing_levels { + if let Some(pts) = &mut l.line_points { + pts[0] = shift(pts[0], dx, dy); + pts[1] = shift(pts[1], dx, dy); + } + } + if let Some(a) = &mut out.geo_anchor { + a.model = shift(a.model, dx, dy); + } + out +} + +/// LV95-Ursprung: die reale Landeskoordinate, die auf den Modell-Nullpunkt abgebildet wird. +pub fn project_geo_origin(p: &Project) -> Option<(f64, f64)> { + let a = p.geo_anchor.as_ref()?; + Some((a.lv95.e - a.model.x, a.lv95.n - a.model.y)) +} + +/// Kopie mit Geometrie in realen Weltkoordinaten (LV95) für Modell-Exporte; ohne Bezug unverändert. +pub fn project_to_world_coords(p: &Project) -> Project { + match project_geo_origin(p) { + Some((e, n)) => translate_project(p, e, n), + None => p.clone(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn verschiebt_alles_und_haelt_den_anker() { + let mut p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap(); + p.geo_anchor = Some(ProjectGeoAnchor { lv95: ProjectGeoAnchorLv95 { e: 2_600_000.0, n: 1_200_000.0, ..Default::default() }, model: Vec2 { x: 1.0, y: 2.0 }, ..Default::default() }); + let w = project_to_world_coords(&p); + assert_eq!(w.walls[0].start.x, p.walls[0].start.x + 2_599_999.0); + assert_eq!(w.walls[0].start.y, p.walls[0].start.y + 1_199_998.0); + // Der Anker wandert mit: das verschobene Modell liegt bereits in Landeskoordinaten (Ursprung 0, 0). + assert_eq!(project_geo_origin(&w), Some((0.0, 0.0))); + assert_eq!(project_to_world_coords(&Project { geo_anchor: None, ..p.clone() }), Project { geo_anchor: None, ..p }); + } +} diff --git a/src-tauri/core/src/js_fmt.rs b/src-tauri/core/src/js_fmt.rs new file mode 100644 index 00000000..38f7febb --- /dev/null +++ b/src-tauri/core/src/js_fmt.rs @@ -0,0 +1,70 @@ +//! Zahlenformatierung wie JavaScript: `Number.prototype.toFixed` rundet exakte Halbwerte AUF +//! (`pick the larger n`), Rusts `{:.N}` zum geraden Nachbarn — bei dyadischen Werten wie 0.0078125 +//! (6 Nachkommastellen) verschieden. Exporte (IFC, CSV) müssen byteweise wie die TS-Fassung sein. + +/// `x.toFixed(d)` (|x| < 1e21). +pub fn to_fixed(x: f64, d: usize) -> String { + if x.is_nan() { + return "NaN".into(); + } + if x.is_infinite() { + return if x > 0.0 { "Infinity".into() } else { "-Infinity".into() }; + } + let neg = x < 0.0; + let ax = x.abs(); + if ax >= 1e21 { + return format!("{}{}", if neg { "-" } else { "" }, ax); + } + // 25 Stellen mehr als nötig: ein exakter Halbwert zeigt sich als '5' gefolgt von Nullen. + let wide = format!("{:.*}", d + 25, ax); + let (int_part, frac) = wide.split_once('.').expect("Nachkommastellen"); + let mut digits: Vec = int_part.bytes().chain(frac.bytes().take(d)).collect(); + let round_up = frac.as_bytes().get(d).is_some_and(|&c| c >= b'5'); + if round_up { + let mut i = digits.len(); + loop { + if i == 0 { + digits.insert(0, b'1'); + break; + } + i -= 1; + if digits[i] == b'9' { + digits[i] = b'0'; + } else { + digits[i] += 1; + break; + } + } + } + let int_len = digits.len() - d; + let mut s = String::new(); + if neg { + s.push('-'); + } + s.push_str(std::str::from_utf8(&digits[..int_len]).expect("ASCII")); + if d > 0 { + s.push('.'); + s.push_str(std::str::from_utf8(&digits[int_len..]).expect("ASCII")); + } + s +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rundet_halbwerte_auf_wie_js() { + assert_eq!(to_fixed(0.0078125, 6), "0.007813"); // JS: "0.007813"; Rust {:.6}: 0.007812 + assert_eq!(to_fixed(12.5, 0), "13"); + assert_eq!(to_fixed(-2.5, 0), "-3"); + assert_eq!(to_fixed(0.5, 0), "1"); + assert_eq!(to_fixed(1.0, 6), "1.000000"); + assert_eq!(to_fixed(0.0, 6), "0.000000"); + assert_eq!(to_fixed(-1e-7, 6), "-0.000000"); + assert_eq!(to_fixed(9.9999996, 6), "10.000000"); + assert_eq!(to_fixed(123.456, 2), "123.46"); + assert_eq!(to_fixed(2.675, 2), "2.67"); // 2.675 ist binär 2.67499999… — JS: "2.67" + assert_eq!(to_fixed(1e-9, 6), "0.000000"); + } +} diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 1de38036..e45ef88e 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -4,7 +4,9 @@ //! //! Datenübergabe: flache `f64`-Puffer (s. [`flat`]), kein JSON — schnell und ohne Serde-Kosten. +pub mod export_ifc; pub mod flat; +pub mod geo_rebase; pub mod flat_write; pub mod polygon_bool; pub mod roof; @@ -21,6 +23,7 @@ pub mod wall_bands; pub mod room_area; pub mod room_boundary; pub mod polygon_holes; +pub mod js_fmt; pub mod jsmath; pub mod stairs3d; pub mod mesh3d; diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index ad13f78a..f68b8657 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -90,3 +90,17 @@ pub fn doc_query_args(h: u32, name: &str, args: &[f64], text: &str) -> String { pub fn doc_drawing_line_verts(h: u32) -> Vec { with_doc(h, |d| d.project().ok().map(|p| crate::model3d::drawing_line_verts(&p))).flatten().unwrap_or_default() } + +/// IFC4-Datei des Projekts (`now_ms`: Zeitpunkt des Exports); Fehler mit vorangestelltem `\u{1}`. +#[wasm_bindgen] +pub fn doc_export_ifc(h: u32, now_ms: f64) -> String { + let result = with_doc(h, |d| { + let p = d.project().map_err(|e| format!("Projekt passt nicht zum Kern-Modell: {e}"))?; + crate::export_ifc::export_ifc_spf(p, now_ms) + }) + .unwrap_or_else(|| Err("Dokument nicht offen".to_string())); + match result { + Ok(text) => text, + Err(e) => format!("\u{1}{e}"), + } +} diff --git a/src-tauri/core/src/web/export_ifc.rs b/src-tauri/core/src/web/export_ifc.rs new file mode 100644 index 00000000..bec9a9b2 --- /dev/null +++ b/src-tauri/core/src/web/export_ifc.rs @@ -0,0 +1,15 @@ +//! Bindungen kleiner IFC-Bausteine (`crate::export_ifc`); die Datei selbst liefert `doc_export_ifc`. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Deterministische 22-stellige IFC-GUID aus einer Element-ID. +#[wasm_bindgen] +pub fn ifc_guid(id: &str) -> String { + crate::export_ifc::ifc_guid(id) +} + +/// STEP-String-Literal (ISO 10303-21) mit Escapes. +#[wasm_bindgen] +pub fn ifc_string(s: &str) -> String { + crate::export_ifc::ifc_string(s) +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index bf98c8a3..d48a1dee 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -24,6 +24,7 @@ mod plan_stairs; mod plan_walls; mod plan_openings; mod delaunay; +mod export_ifc; mod document; mod mesh_section; mod plan_elevation; diff --git a/src/core/document.ts b/src/core/document.ts index 21828f48..d3df730d 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -82,6 +82,14 @@ export class ProjectDocument { return out; } + /** IFC4-Datei (STEP-Text) des Projekts; `nowMs` = Zeitpunkt des Exports. */ + exportIfc(nowMs: number): string { + if (!this.handle) throw new Error("IFC-Export: Dokument nicht offen"); + const out = core().doc_export_ifc(this.handle, nowMs); + if (out.startsWith("\u0001")) throw new Error(out.slice(1)); + return out; + } + /** Boden-Spuren der 2D-Zeichnungen als LineList-Vertices `[px, py, pz, r, g, b]`. */ drawingLineVerts(): Float32Array { return this.handle ? core().doc_drawing_line_verts(this.handle) : new Float32Array(0); diff --git a/src/export/exportIfc.ts b/src/export/exportIfc.ts index e4504d91..798e6865 100644 --- a/src/export/exportIfc.ts +++ b/src/export/exportIfc.ts @@ -1,932 +1,29 @@ // IFC4-Export (STEP Physical File / ISO-10303-21) des semantischen Modells. -// Reiner Rechen-/Serialisierungskern: keine UI, kein Datei-IO, kein WASM, keine -// neue Dependency — IFC wird direkt als Text geschrieben (analog exportDxf.ts/ -// exportSchedule.ts). Der Download (Blob+Anchor) passiert im App-Layer. // -// Abbildung (erste vollständige Scheibe): -// Project → IfcProject → IfcSite → IfcBuilding → je "floor"-Geschoss ein -// IfcBuildingStorey (IfcRelAggregates-Kette). Bauteile hängen über -// IfcRelContainedInSpatialStructure am jeweiligen Geschoss (verwaiste -// Geschossreferenzen fallen defensiv auf IfcBuilding zurück). -// -// Decken/Treppen/Extrusionen als IfcExtrudedAreaSolid (unser Modell IST -// Extrusion): Profil = IfcArbitraryClosedProfileDef(IfcPolyline) in der -// XY-Ebene, extrudiert entlang +Z. Die horizontale Objekt-Platzierungskette -// (Site/Building/Storey/Element) trägt bewusst NUR die Z-Verschiebung -// (Geschoss-Elevation); die Profilpunkte tragen direkt die Welt-X/Y-Koordinaten. -// -// • Wand → IfcWall mit ÖFFNUNGSGENAUEM Dreiecks-Mesh (IfcTriangulatedFace -// Set, IFC4: IfcCartesianPointList3D + CoordIndex) statt einer Profil- -// Extrusion. Gespeist aus DEMSELBEN Loch-Ausschnitt-Mesh wie STL/OBJ -// (`pickGeometry` → `plan/wallMeshCut.ts`): Joins/Gehrungen UND ausgeschnittene -// Fenster/Türen (inkl. Laibungen) sind im Körper enthalten. ABWÄGUNG (bewusst, -// Nutzer-Priorität "so wie im 3D"): dadurch verliert die Wand die parametrische -// IfcWall-Profil-Extrusion + IfcOpeningElement-Void-Semantik zugunsten -// VISUELLER PARITÄT in JEDEM Viewer (der Loch schon im Mesh sieht, ohne eine -// Boolean-Subtraktion ausführen zu müssen — genau der Bug des Nutzers: "das -// Fenster ist als Objekt da im IFC, aber die Löcher sind nicht da"). -// • Decke → IfcSlab (outline-Polygon, PredefinedType FLOOR). -// • Öffnung → KEIN IfcOpeningElement/Void mehr (das Loch steckt im Wand-Mesh); -// Tür/Fenster bleiben als eigenes Objekt IfcDoor/IfcWindow mit eigener Box- -// Geometrie erhalten (füllt das ausgeschnittene Loch, "sieht aus wie 3D"). -// • Extrusion → IfcBuildingElementProxy aus points+height. -// • Dach → IfcRoof (Schicht-Meshes wie im 3D), Dachtyp → IfcRoofType mit Schichten. -// • Stütze → IfcColumn (Profil-Extrusion), Bauteil → IfcMaterial. -// • Raum → IfcSpace (im Geschoss aggregiert) mit Qto_SpaceBaseQuantities und SIA-416-Kategorie. -// • Treppe → IfcStair, GEOMETRISCH bewusst vereinfacht auf einen -// extrudierten Bounding-Footprint (Lauf-Rechteck bei "straight"; Achsen- -// ausgerichtete Bounding-Box der Kontrollpunkte bei "L"/"spiral") — die -// echte Stufengeometrie ist ausgelassen (siehe stairFootprint()). -// -// Material-Schichten: je Wand-/Deckentyp ein IfcWallType/IfcSlabType mit -// IfcMaterialLayerSet, die Exemplare erben ihn über IfcRelDefinesByType. KEIN -// IfcMaterialLayerSetUsage am Exemplar: Richtung/Versatz der Usage beziehen sich -// auf eine Achs-Darstellung, die das Wand-Mesh nicht hat. -// -// GUIDs: deterministisch aus der Element-ID über einen 128-Bit-Hash (zwei -// FNV-1a-64-Läufe) + Standard-IFC-GUID-Kompression (Base64-Variante, -// Zeichensatz 0-9,A-Z,a-z,_,$) — stabil über Re-Exporte hinweg. -// -// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). Einheit: METER. +// Gerechnet wird im Rust-Kern (`src-tauri/core/src/export_ifc.rs`, [K4] S2) auf dem Projekt-Dokument: +// Project → Site → Building → Storeys, Wände als öffnungsgenaue Dreiecks-Netze, Decken/Treppen/ +// Körper/Stützen/Räume als Profil-Extrusionen, Dächer als Schicht-Netze, Wand-/Deckentypen mit +// Materialschichten; GUIDs deterministisch aus der Element-ID; bei gesetztem `geoAnchor` in LV95- +// Weltkoordinaten. Der Download (Blob + Anchor) passiert im App-Layer. -import type { - Opening, - Project, - Stair, - Vec2, - Wall, -} from "../model/types"; -import { - columnLabel, - getCeilingType, - getWallType, - openingLabel, - wallTypeThickness, -} from "../model/types"; -import { projectToWorldCoords } from "../model/geoRebase"; -import { - ceilingVerticalExtent, - columnVerticalExtent, - stairVerticalExtent, - wallReferenceOffset, - wallVerticalExtent, -} from "../model/wall"; -import { pickGeometry } from "../plan/toWalls3d"; -import type { RWall } from "../plan/toWalls3d"; -import { isWatertight, wallCutMeshes, type CutMesh } from "../plan/wallMeshCut"; -import { evaluateRoom } from "../geometry/roomArea"; -import { columnFootprint } from "../geometry/column"; -import { roofMeshes } from "../plan/toWalls3d"; - -// ── IFC-GUID (Base64-Kompression, 22 Zeichen) ─────────────────────────────── -// Standard-Kompressionsalgorithmus (IfcOpenShell guid.compress): das erste -// Byte des 128-Bit-Werts wird auf 2 Zeichen abgebildet, die restlichen 15 -// Byte in 5 Dreiergruppen zu je 4 Zeichen — macht 2 + 5×4 = 22 Zeichen. - -const IFC_GUID_CHARS = - "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$"; - -/** Kodiert `v` big-endian in `len` IFC-GUID-Zeichen (Basis 64). */ -function ifcGuidB64(v: number, len: number): string { - let out = ""; - for (let i = len - 1; i >= 0; i--) { - out += IFC_GUID_CHARS[Math.floor(v / 64 ** i) % 64]; - } - return out; -} - -/** Komprimiert einen 128-Bit-Wert (32 Hex-Zeichen) zur 22-stelligen IFC-GUID. */ -function compressGuidHex(hex32: string): string { - const bytes: number[] = []; - for (let i = 0; i < 32; i += 2) bytes.push(parseInt(hex32.slice(i, i + 2), 16)); - let out = ifcGuidB64(bytes[0], 2); - for (let i = 1; i < 16; i += 3) { - const v = (bytes[i] << 16) + (bytes[i + 1] << 8) + bytes[i + 2]; - out += ifcGuidB64(v, 4); - } - return out; -} - -/** FNV-1a-64 (BigInt) — reines Determinismus-/Streuungs-Werkzeug, keine Kryptografie. */ -function fnv1a64(str: string, seed: bigint): bigint { - const prime = 0x100000001b3n; - const mask = 0xffffffffffffffffn; - let hash = seed & mask; - for (let i = 0; i < str.length; i++) { - hash ^= BigInt(str.charCodeAt(i)); - hash = (hash * prime) & mask; - } - return hash; -} - -/** Leitet aus einer stabilen Element-ID einen deterministischen 128-Bit-Hex-Wert ab. */ -function idToHex32(id: string): string { - const h1 = fnv1a64(id, 0xcbf29ce484222325n); - const h2 = fnv1a64(`${id}salt`, 0x9e3779b97f4a7c15n); - return h1.toString(16).padStart(16, "0") + h2.toString(16).padStart(16, "0"); -} +import type { Project } from "../model/types"; +import { core } from "../engine/coreWasm"; +import { documentFor } from "../core/document"; /** Deterministische 22-stellige IFC-GUID aus einer beliebigen Element-ID. */ export function ifcGuid(id: string): string { - return compressGuidHex(idToHex32(id)); + return core().ifc_guid(id); } -// ── STEP-Formatierung ─────────────────────────────────────────────────────── - -/** - * STEP-String-Literal (ISO 10303-21): druckbares ASCII bleibt, Backslash und Apostroph werden - * verdoppelt, alles andere (Umlaute, Steuerzeichen) als \X2\HHHH…\X0\ (BMP) bzw. - * \X4\HHHHHHHH…\X0\ (ausserhalb der BMP). Die Datei bleibt so reines ASCII. - */ +/** STEP-String-Literal (ISO 10303-21): druckbares ASCII bleibt, alles andere wird als \X2\…\X0\ kodiert. */ export function ifcString(s: string): string { - let out = ""; - let run: number[] = []; - const flush = () => { - if (run.length === 0) return; - const wide = run.some((c) => c > 0xffff); - const hex = run.map((c) => c.toString(16).toUpperCase().padStart(wide ? 8 : 4, "0")).join(""); - out += `${wide ? "\\X4\\" : "\\X2\\"}${hex}\\X0\\`; - run = []; - }; - for (const ch of s) { - const c = ch.codePointAt(0)!; - if (c >= 0x20 && c <= 0x7e) { - flush(); - out += ch === "\\" ? "\\\\" : ch === "'" ? "''" : ch; - } else { - // \X2\ und \X4\ nicht mischen: Wechsel der Breite beginnt einen neuen Block. - if (run.length > 0 && (run[0] > 0xffff) !== (c > 0xffff)) flush(); - run.push(c); - } - } - flush(); - return `'${out}'`; -} - -const S = ifcString; - -/** STEP-REAL-Literal — immer mit Dezimalpunkt, ohne unnötige Nachkommastellen. */ -function R(x: number): string { - const v = Object.is(x, -0) ? 0 : x; - let s = v.toFixed(6); - s = s.replace(/0+$/, ""); - if (s.endsWith(".")) s += "0"; - if (!s.includes(".")) s += ".0"; - return s; -} - -/** STEP-Enumerationswert `.WERT.`. */ -function ENUM(v: string): string { - return `.${v}.`; -} - -/** STEP-Liste `(a,b,c)`. */ -function LIST(items: string[]): string { - return `(${items.join(",")})`; -} - -// ── STEP-Writer ────────────────────────────────────────────────────────────── - -class StepWriter { - private lines: string[] = []; - private nextId = 1; - - /** Schreibt eine neue Entity-Zeile und liefert ihre `#id`. */ - add(type: string, params: string): number { - const id = this.nextId++; - this.lines.push(`#${id}=${type}(${params});`); - return id; - } - - get entityLines(): readonly string[] { - return this.lines; - } -} - -// ── Geometrie-Helfer (reines 2D-Vec2-Rechnen, Welt-Meter) ─────────────────── - -function sub(a: Vec2, b: Vec2): Vec2 { - return { x: a.x - b.x, y: a.y - b.y }; -} -function normalize(v: Vec2): Vec2 { - const len = Math.hypot(v.x, v.y) || 1; - return { x: v.x / len, y: v.y / len }; -} -function leftNormal(u: Vec2): Vec2 { - return { x: -u.y, y: u.x }; -} -function addScaled(p: Vec2, d: Vec2, s: number): Vec2 { - return { x: p.x + d.x * s, y: p.y + d.y * s }; -} - -/** Rechteck-Footprint einer Öffnung im Wandloch (volle Wanddicke tief), CCW. */ -function openingFootprint(project: Project, wall: Wall, opening: Opening): Vec2[] { - const u = normalize(sub(wall.end, wall.start)); - const n = leftNormal(u); - const t = wallTypeThickness(getWallType(project, wall)); - const off = wallReferenceOffset(wall, t); - const inner = -t / 2 + off; - const outer = t / 2 + off; - const a = addScaled(wall.start, u, opening.position); - const b = addScaled(wall.start, u, opening.position + opening.width); - return [ - addScaled(a, n, inner), - addScaled(b, n, inner), - addScaled(b, n, outer), - addScaled(a, n, outer), - ]; + return core().ifc_string(s); } /** - * Vereinfachter Bounding-Footprint einer Treppe (bewusst NICHT die echte - * Stufen-/Podestkontur, siehe Dateikopf): - * • "straight" — echtes, ausgerichtetes Lauf-Rechteck (Länge × Breite). - * • "L"/"spiral" — achsenausgerichtete Bounding-Box der Kontrollpunkte - * (Start/Eckpunkt/Ende bzw. Wendel-Zentrum±Radius), um die halbe - * Laufbreite erweitert. + * Baut aus einem Projekt einen vollständigen IFC4-SPF-String (STEP Physical File). Leeres Projekt ⇒ + * valider Minimal-IFC. Wirft, wenn sich das Modell nicht ableiten lässt (z. B. unbekannter Wandtyp). */ -function stairFootprint(stair: Stair): Vec2[] { - const halfW = Math.max(stair.width, 0) / 2; - if (stair.shape === "straight") { - const u = normalize(stair.dir); - const n = leftNormal(u); - const end = addScaled(stair.start, u, stair.runLength); - return [ - addScaled(stair.start, n, -halfW), - addScaled(end, n, -halfW), - addScaled(end, n, halfW), - addScaled(stair.start, n, halfW), - ]; - } - const pts: Vec2[] = [stair.start]; - const u = normalize(stair.dir); - const corner = addScaled(stair.start, u, stair.runLength); - pts.push(corner); - if (stair.shape === "L" && stair.run2Length && stair.turn) { - const n = leftNormal(u); - const turnDir: Vec2 = { x: n.x * stair.turn, y: n.y * stair.turn }; - pts.push(addScaled(corner, turnDir, stair.run2Length)); - } - if (stair.shape === "spiral" && stair.center) { - const r = (stair.radius ?? 0) + halfW; - const c = stair.center; - return [ - { x: c.x - r, y: c.y - r }, - { x: c.x + r, y: c.y - r }, - { x: c.x + r, y: c.y + r }, - { x: c.x - r, y: c.y + r }, - ]; - } - let minX = Infinity; - let minY = Infinity; - let maxX = -Infinity; - let maxY = -Infinity; - for (const p of pts) { - minX = Math.min(minX, p.x); - minY = Math.min(minY, p.y); - maxX = Math.max(maxX, p.x); - maxY = Math.max(maxY, p.y); - } - minX -= halfW; - minY -= halfW; - maxX += halfW; - maxY += halfW; - return [ - { x: minX, y: minY }, - { x: maxX, y: minY }, - { x: maxX, y: maxY }, - { x: minX, y: maxY }, - ]; -} - -// ── IFC4-Export ────────────────────────────────────────────────────────────── - -interface StoreyRef { - entityId: number; - placementId: number; - baseElevation: number; -} - -interface Structure { - entityId: number; - placementId: number; - baseElevation: number; -} - -/** - * Baut aus einem Projekt einen vollständigen IFC4-SPF-String (STEP Physical - * File). Reiner Rechenkern — kein Datei-IO. Leeres Projekt ⇒ valider Minimal- - * IFC (Project/Site/Building, kein Crash). - */ -export function exportIfcSpf(projectIn: Project): string { - // Georeferenziert exportieren: ist ein Standort-Bezug gesetzt (geoAnchor), - // wird die gesamte Geometrie auf die ECHTEN LV95-Weltkoordinaten verschoben, - // damit die IFC-Datei in anderer Software lagerichtig sitzt — auch wenn das - // Modell lokal nahe (0,0) bearbeitet wurde (s. projectToWorldCoords / der - // „Neuer Bezugspunkt"-Workflow). Ohne Bezug bleibt alles lokal (Identität). - const project = projectToWorldCoords(projectIn); - const w = new StepWriter(); - - // Geteilte Grundgeometrie: Ursprung, Z-Extrusionsrichtung, Identitäts- - // Placement (Position aller ExtrudedAreaSolid — Profile tragen direkt - // Welt-X/Y, siehe Dateikopf). - const originPoint = w.add("IFCCARTESIANPOINT", LIST([R(0), R(0), R(0)])); - const extrudeDir = w.add("IFCDIRECTION", LIST([R(0), R(0), R(1)])); - const identityAxis = w.add("IFCAXIS2PLACEMENT3D", `#${originPoint},$,$`); - - // Owner-History (minimal, aber vorhanden — manche Importer verlangen sie). - const org = w.add("IFCORGANIZATION", `$,${S("dossier")},$,$,$`); - const person = w.add( - "IFCPERSON", - `${S("dossier")},$,$,$,$,$,$,$`, - ); - const personOrg = w.add("IFCPERSONANDORGANIZATION", `#${person},#${org},$`); - const app = w.add( - "IFCAPPLICATION", - `#${org},${S("1.0")},${S("dossier")},${S("dossier")}`, - ); - // ChangeAction ADDED verlangt ein LastModifiedDate (IFC4-Regel IfcOwnerHistory.CorrectChangeAction): - // beim frischen Export ist es der Erstellungszeitpunkt. - const now = Math.floor(Date.now() / 1000); - const ownerHistory = w.add( - "IFCOWNERHISTORY", - `#${personOrg},#${app},$,${ENUM("ADDED")},${now},$,$,${now}`, - ); - - // Einheiten (Meter, Radiant, m², m³). - const lenUnit = w.add("IFCSIUNIT", `*,${ENUM("LENGTHUNIT")},$,${ENUM("METRE")}`); - const areaUnit = w.add("IFCSIUNIT", `*,${ENUM("AREAUNIT")},$,${ENUM("SQUARE_METRE")}`); - const volUnit = w.add("IFCSIUNIT", `*,${ENUM("VOLUMEUNIT")},$,${ENUM("CUBIC_METRE")}`); - const angleUnit = w.add( - "IFCSIUNIT", - `*,${ENUM("PLANEANGLEUNIT")},$,${ENUM("RADIAN")}`, - ); - const unitAssignment = w.add( - "IFCUNITASSIGNMENT", - LIST([`#${lenUnit}`, `#${areaUnit}`, `#${volUnit}`, `#${angleUnit}`]), - ); - - // Geometrischer Kontext (3D, Precision 1e-5). - const context = w.add( - "IFCGEOMETRICREPRESENTATIONCONTEXT", - `$,${S("Model")},3,${R(0.00001)},#${identityAxis},$`, - ); - - // Georeferenz: Die Geometrie liegt bereits in LV95-Weltkoordinaten (s. oben), die Abbildung - // lokal→Welt ist daher die Identität; das Koordinatensystem wird trotzdem deklariert, damit - // Importer die Datei als EPSG:2056 erkennen (IFC4 IfcProjectedCRS + IfcMapConversion). - if (project.geoAnchor) { - const crs = w.add( - "IFCPROJECTEDCRS", - `${S("EPSG:2056")},${S("CH1903+ / LV95")},${S("CH1903+")},$,${S("Swiss Oblique Mercator")},$,#${lenUnit}`, - ); - w.add("IFCMAPCONVERSION", `#${context},#${crs},${R(0)},${R(0)},${R(0)},${R(1)},${R(0)},${R(1)}`); - } - - // Räumliche Hierarchie: Project → Site → Building → Storeys. - const siteAxis = w.add("IFCAXIS2PLACEMENT3D", `#${originPoint},$,$`); - const sitePlacement = w.add("IFCLOCALPLACEMENT", `$,#${siteAxis}`); - const buildingAxis = w.add("IFCAXIS2PLACEMENT3D", `#${originPoint},$,$`); - const buildingPlacement = w.add( - "IFCLOCALPLACEMENT", - `#${sitePlacement},#${buildingAxis}`, - ); - - const projectId = w.add( - "IFCPROJECT", - `${S(ifcGuid(`${project.id}:project`))},#${ownerHistory},${S(project.name || "Projekt")},$,$,$,$,${LIST([`#${context}`])},#${unitAssignment}`, - ); - // RefElevation (m ü. M.): reale Datumshöhe des Standorts aus dem - // Georeferenzierungs-Bezug (wie ArchiCADs Vermessungspunkt). Rein informativ — - // die Geometrie wird NICHT verschoben (das Terrain trägt bereits reale Höhen). - const refElevation = project.geoAnchor?.height; - const siteRefElev = typeof refElevation === "number" ? R(refElevation) : "$"; - const siteId = w.add( - "IFCSITE", - `${S(ifcGuid(`${project.id}:site`))},#${ownerHistory},${S("Standort")},$,$,#${sitePlacement},$,$,${ENUM("ELEMENT")},$,$,${siteRefElev},$,$`, - ); - const buildingId = w.add( - "IFCBUILDING", - `${S(ifcGuid(`${project.id}:building`))},#${ownerHistory},${S(project.name || "Gebäude")},$,$,#${buildingPlacement},$,$,${ENUM("ELEMENT")},$,$,$`, - ); - w.add( - "IFCRELAGGREGATES", - `${S(ifcGuid(`${project.id}:agg-site`))},#${ownerHistory},$,$,#${projectId},${LIST([`#${siteId}`])}`, - ); - w.add( - "IFCRELAGGREGATES", - `${S(ifcGuid(`${project.id}:agg-building`))},#${ownerHistory},$,$,#${siteId},${LIST([`#${buildingId}`])}`, - ); - - // Je "floor"-Geschoss ein IfcBuildingStorey (Elevation = baseElevation). - const floors = project.drawingLevels.filter((l) => l.kind === "floor"); - const storeyByFloorId = new Map(); - const storeyEntityIds: number[] = []; - for (const floor of floors) { - const base = floor.baseElevation ?? 0; - const pt = w.add("IFCCARTESIANPOINT", LIST([R(0), R(0), R(base)])); - const axis = w.add("IFCAXIS2PLACEMENT3D", `#${pt},$,$`); - const placementId = w.add("IFCLOCALPLACEMENT", `#${buildingPlacement},#${axis}`); - const entityId = w.add( - "IFCBUILDINGSTOREY", - `${S(ifcGuid(`${floor.id}:storey`))},#${ownerHistory},${S(floor.name)},$,$,#${placementId},$,$,${ENUM("ELEMENT")},${R(base)}`, - ); - storeyByFloorId.set(floor.id, { entityId, placementId, baseElevation: base }); - storeyEntityIds.push(entityId); - } - if (storeyEntityIds.length > 0) { - w.add( - "IFCRELAGGREGATES", - `${S(ifcGuid(`${project.id}:agg-storeys`))},#${ownerHistory},$,$,#${buildingId},${LIST(storeyEntityIds.map((id) => `#${id}`))}`, - ); - } - - /** Geschoss → Trägerstruktur (Storey), oder defensiv das Gebäude (verwaiste floorId). */ - const resolveStructure = (floorId: string): Structure => { - const s = storeyByFloorId.get(floorId); - if (s) return { entityId: s.entityId, placementId: s.placementId, baseElevation: s.baseElevation }; - return { entityId: buildingId, placementId: buildingPlacement, baseElevation: 0 }; - }; - - // Räumliche Eingliederung sammelt sich je Trägerstruktur (Storey/Building) - // und wird am Ende in EINE IfcRelContainedInSpatialStructure je Struktur - // gebündelt (Öffnungen NICHT — die hängen nur über RelVoidsElement an ihrer - // Wand, wie in IFC üblich). - const containment = new Map(); - const addToContainment = (structureId: number, elementId: number): void => { - const arr = containment.get(structureId); - if (arr) arr.push(elementId); - else containment.set(structureId, [elementId]); - }; - - /** Baut Profil+Extrusion+Shape+Placement für einen geschlossenen Footprint. */ - const emitBoxProduct = ( - footprint: Vec2[], - zBottomRel: number, - depth: number, - placementRelTo: number, - ): { placementId: number; shapeId: number } => { - const closed = [...footprint, footprint[0]]; - const ptIds = closed.map((p) => w.add("IFCCARTESIANPOINT", LIST([R(p.x), R(p.y)]))); - const polylineId = w.add("IFCPOLYLINE", LIST(ptIds.map((id) => `#${id}`))); - const profileId = w.add( - "IFCARBITRARYCLOSEDPROFILEDEF", - `${ENUM("AREA")},$,#${polylineId}`, - ); - const solidId = w.add( - "IFCEXTRUDEDAREASOLID", - `#${profileId},#${identityAxis},#${extrudeDir},${R(Math.max(depth, 0.001))}`, - ); - const shapeRepId = w.add( - "IFCSHAPEREPRESENTATION", - `#${context},${S("Body")},${S("SweptSolid")},${LIST([`#${solidId}`])}`, - ); - const shapeId = w.add("IFCPRODUCTDEFINITIONSHAPE", `$,$,${LIST([`#${shapeRepId}`])}`); - const elemOrigin = w.add("IFCCARTESIANPOINT", LIST([R(0), R(0), R(zBottomRel)])); - const elemAxis = w.add("IFCAXIS2PLACEMENT3D", `#${elemOrigin},$,$`); - const placementId = w.add("IFCLOCALPLACEMENT", `#${placementRelTo},#${elemAxis}`); - return { placementId, shapeId }; - }; - - /** - * Baut aus einem Dreiecks-Mesh (`positions` flach x,y,z in IFC-Koordinaten — - * bereits Z-up und relativ zur `placementRelTo`-Herkunft, `indices` je 3 = - * 1-basiert-1 CoordIndex-Tripel) ein IfcTriangulatedFaceSet + Shape + Placement. - * IFC4-Tessellierung: IfcCartesianPointList3D (CoordList) + IfcTriangulatedFace - * Set (CoordIndex, 1-basiert). Das Element-Placement sitzt im Ursprung der - * Trägerstruktur (die Punkte tragen die Geometrie bereits absolut in deren Frame). - */ - const emitTriangulatedProduct = ( - positions: number[], - indices: number[], - placementRelTo: number, - closed: boolean, - ): { placementId: number; shapeId: number } => { - const coords: string[] = []; - for (let i = 0; i < positions.length; i += 3) { - coords.push(`(${R(positions[i])},${R(positions[i + 1])},${R(positions[i + 2])})`); - } - const pointListId = w.add("IFCCARTESIANPOINTLIST3D", `(${coords.join(",")})`); - const tris: string[] = []; - for (let i = 0; i < indices.length; i += 3) { - tris.push(`(${indices[i] + 1},${indices[i + 1] + 1},${indices[i + 2] + 1})`); - } - // Closed=.T. NUR wenn das Mesh nachweislich ein dichtes, aussen orientiertes - // Volumen ist (siehe isWatertight): Wände sind extrudierte Querschnitts- - // Polygone (Fenster = Durchgangsloch, Tür = umlaufende П-Kerbe) → geschlossene - // Körper → `.T.` (Viewer rendern sie als Solid statt als offene Fläche). Der - // Guard fängt echte Defekte ab (invertierte Wicklung → Volumen < 0 → `$`). - // Normals=$ (Viewer leitet sie aus der — jetzt aussen orientierten — Wicklung ab). - const closedFlag = closed ? ".T." : "$"; - const faceSetId = w.add("IFCTRIANGULATEDFACESET", `#${pointListId},$,${closedFlag},(${tris.join(",")}),$`); - const shapeRepId = w.add( - "IFCSHAPEREPRESENTATION", - `#${context},${S("Body")},${S("Tessellation")},${LIST([`#${faceSetId}`])}`, - ); - const shapeId = w.add("IFCPRODUCTDEFINITIONSHAPE", `$,$,${LIST([`#${shapeRepId}`])}`); - const elemOrigin = w.add("IFCCARTESIANPOINT", LIST([R(0), R(0), R(0)])); - const elemAxis = w.add("IFCAXIS2PLACEMENT3D", `#${elemOrigin},$,$`); - const placementId = w.add("IFCLOCALPLACEMENT", `#${placementRelTo},#${elemAxis}`); - return { placementId, shapeId }; - }; - - /** Baut ein IfcBuildingElement-Subtyp mit dem üblichen 9-Attribut-Flatten. */ - const emitBuildingElement = ( - type: string, - guid: string, - name: string, - placementId: number, - shapeId: number, - predefinedType: string | null, - ): number => - w.add( - type, - `${S(guid)},#${ownerHistory},${S(name)},$,$,#${placementId},#${shapeId},$,${predefinedType ?? "$"}`, - ); - - // ── Bauteiltypen mit Materialschichten ───────────────────────────────── - // Je Wand-/Deckentyp ein IfcWallType/IfcSlabType mit IfcMaterialLayerSet (Schichten in der - // Reihenfolge des Typs, Material = Bauteil). Die Wände/Decken erben ihn über - // IfcRelDefinesByType. Bewusst KEIN IfcMaterialLayerSetUsage am Exemplar: die Wand-Geometrie ist - // ein Mesh ohne Achs-Darstellung, eine Usage (Richtung/Versatz zur Bezugslinie) hätte keinen - // Bezug (s. Dateikopf). - const materialIdByComponent = new Map(); - const materialOf = (componentId: string): number => { - const hit = materialIdByComponent.get(componentId); - if (hit !== undefined) return hit; - const name = project.components.find((c) => c.id === componentId)?.name ?? componentId; - const id = w.add("IFCMATERIAL", `${S(name)},$,$`); - materialIdByComponent.set(componentId, id); - return id; - }; - interface ElementTypeRef { - typeId: number; - occurrences: number[]; - } - const elementTypes = new Map(); - const typeFor = ( - ifcType: "IFCWALLTYPE" | "IFCSLABTYPE" | "IFCROOFTYPE", - predefined: string, - t: { id: string; name: string; layers: { componentId: string; thickness: number }[] }, - ): ElementTypeRef => { - const key = `${ifcType}:${t.id}`; - const hit = elementTypes.get(key); - if (hit) return hit; - const layerIds = t.layers.map((l) => - w.add("IFCMATERIALLAYER", `#${materialOf(l.componentId)},${R(Math.max(0, Number.isFinite(l.thickness) ? l.thickness : 0))},$,$,$,$,$`), - ); - const typeId = w.add( - ifcType, - `${S(ifcGuid(key))},#${ownerHistory},${S(t.name)},$,$,$,$,$,$,${ENUM(predefined)}`, - ); - if (layerIds.length > 0) { - const setId = w.add("IFCMATERIALLAYERSET", `${LIST(layerIds.map((id) => `#${id}`))},${S(t.name)},$`); - w.add( - "IFCRELASSOCIATESMATERIAL", - `${S(ifcGuid(`${key}:material`))},#${ownerHistory},$,$,${LIST([`#${typeId}`])},#${setId}`, - ); - } - const ref = { typeId, occurrences: [] }; - elementTypes.set(key, ref); - return ref; - }; - - // ── Wände (öffnungsgenaues Dreiecks-Mesh statt Profil-Extrusion) ──────── - // Die Wand-Schicht-Bänder kommen aus DEMSELBEN geflachten Modell wie STL/OBJ - // (`pickGeometry`, Joins/Gehrungen + Öffnungs-`holes` bereits aufgelöst). Alle - // Bänder einer Wand-Id werden zu EINEM Face-Set vereint. IFC-Koordinaten: das - // Mesh liegt in Welt (Modell-x, Höhe, Modell-y) mit Y-up → IFC (x, y, z=Höhe) - // mit Z-up, also (mx, mz, my); Z relativ zur Geschoss-UK, damit die Storey- - // Placement-Elevation nicht doppelt zählt. - // - // WICHTIG — WICKLUNG: der Achsen-Swap (x,y,z)→(x,z,y) ist eine REFLEXION - // (Determinante −1) und KEHRT die Dreiecks-Wicklung UM → aus aussen orientierten - // würden innen orientierte Normalen, der Viewer cullt dann die Vorderseiten und - // die Wand wirkt HOHL/offen (genau der gemeldete Bug). Deshalb wird beim Swap - // die Wicklung jedes Dreiecks umgedreht (i0,i2,i1), damit die Aussen-Normalen - // aussen bleiben. Watertightness (isWatertight) misst das anschliessend am - // fertigen IFC-Mesh → treibt das Closed-Flag des Face-Sets. - const bandsByWallId = new Map(); - const allBands = pickGeometry(project).walls; - // Loch-Ausschnitte aller Bänder in EINEM Kern-Aufruf. - const cutOf = new Map(); - wallCutMeshes(allBands).forEach((m, i) => cutOf.set(allBands[i], m)); - for (const band of allBands) { - const list = bandsByWallId.get(band.wallId); - if (list) list.push(band); - else bandsByWallId.set(band.wallId, [band]); - } - const wallEntityIdByWallId = new Map(); - for (const wall of project.walls ?? []) { - const bands = bandsByWallId.get(wall.id); - if (!bands || bands.length === 0) continue; // degenerierte Wand / keine Geometrie - const structure = resolveStructure(wall.floorId); - const positions: number[] = []; - const indices: number[] = []; - for (const band of bands) { - const cut = cutOf.get(band); - if (!cut) continue; - const base = positions.length / 3; - for (let i = 0; i < cut.positions.length; i += 3) { - positions.push( - cut.positions[i], - cut.positions[i + 2], - cut.positions[i + 1] - structure.baseElevation, - ); - } - // Wicklung umkehren (Reflexions-Ausgleich, s. o.): (a,b,c) → (a,c,b). - for (let i = 0; i < cut.indices.length; i += 3) { - indices.push(base + cut.indices[i], base + cut.indices[i + 2], base + cut.indices[i + 1]); - } - } - if (indices.length === 0) continue; - const closed = isWatertight({ positions, indices }); - const { placementId, shapeId } = emitTriangulatedProduct(positions, indices, structure.placementId, closed); - let name = wall.id; - let wallType: ElementTypeRef | null = null; - try { - const wt = getWallType(project, wall); - name = wt.name; - wallType = typeFor("IFCWALLTYPE", "STANDARD", wt); - } catch { - /* verwaister Wandtyp — Roh-ID als Name, kein Typ */ - } - const entityId = emitBuildingElement("IFCWALL", ifcGuid(wall.id), name, placementId, shapeId, null); - wallType?.occurrences.push(entityId); - wallEntityIdByWallId.set(wall.id, entityId); - addToContainment(structure.entityId, entityId); - } - - // ── Decken ───────────────────────────────────────────────────────────── - for (const ceiling of project.ceilings ?? []) { - if (ceiling.outline.length < 3) continue; - const { zBottom, zTop } = ceilingVerticalExtent(project, ceiling); - const structure = resolveStructure(ceiling.floorId); - const { placementId, shapeId } = emitBoxProduct( - ceiling.outline, - zBottom - structure.baseElevation, - zTop - zBottom, - structure.placementId, - ); - let name: string = ceiling.id; - let slabType: ElementTypeRef | null = null; - try { - const ct = getCeilingType(project, ceiling); - name = ct.name; - slabType = typeFor("IFCSLABTYPE", "FLOOR", ct); - } catch { - /* verwaister Deckentyp — Roh-ID als Name, kein Typ */ - } - const entityId = emitBuildingElement( - "IFCSLAB", - ifcGuid(ceiling.id), - name, - placementId, - shapeId, - ENUM("FLOOR"), - ); - slabType?.occurrences.push(entityId); - addToContainment(structure.entityId, entityId); - } - - // ── Fenster/Türen als eigene Objekte (IfcDoor/IfcWindow) ──────────────── - // KEIN IfcOpeningElement/IfcRelVoidsElement/IfcRelFillsElement mehr: das Loch - // steckt bereits im Wand-Face-Set (s. o.). Eine Void-Relation beschriebe eine - // Boolean-Subtraktion gegen einen Swept-Solid, den es nicht mehr gibt — sie - // brächte in den Viewern nur Verwirrung (der Nutzer-Bug war genau, dass die - // Void nicht subtrahiert wurde). Tür/Fenster bleiben als EIGENES Objekt mit - // eigener Box-Geometrie erhalten, die das ausgeschnittene Loch füllt ("sieht - // aus wie 3D"): kein Blatt-/Rahmendetail (bewusste Vereinfachung). - for (const opening of project.openings ?? []) { - const wall = (project.walls ?? []).find((wl) => wl.id === opening.hostWallId); - if (!wall) continue; // verwaiste Wirtswand — keine Geometrie ableitbar - if (!wallEntityIdByWallId.has(wall.id)) continue; // Wirtswand übersprungen (degeneriert) - - const wallExtent = wallVerticalExtent(project, wall); - const structure = resolveStructure(wall.floorId); - const footprint = openingFootprint(project, wall, opening); - const zSillAbs = wallExtent.zBottom + opening.sillHeight; - - const { placementId: fillPlacement, shapeId: fillShape } = emitBoxProduct( - footprint, - zSillAbs - structure.baseElevation, - opening.height, - structure.placementId, - ); - const fillGuid = ifcGuid(`${opening.id}:fill`); - const fillName = openingLabel(opening); - const fillEntityId = - opening.kind === "door" - ? w.add( - "IFCDOOR", - `${S(fillGuid)},#${ownerHistory},${S(fillName)},$,$,#${fillPlacement},#${fillShape},$,${R(opening.height)},${R(opening.width)},${ENUM("DOOR")},$,$`, - ) - : w.add( - "IFCWINDOW", - `${S(fillGuid)},#${ownerHistory},${S(fillName)},$,$,#${fillPlacement},#${fillShape},$,${R(opening.height)},${R(opening.width)},${ENUM("WINDOW")},$,$`, - ); - addToContainment(structure.entityId, fillEntityId); - } - - // ── Treppen (vereinfachter Bounding-Footprint, siehe Dateikopf) ──────── - for (const stair of project.stairs ?? []) { - const footprint = stairFootprint(stair); - if (footprint.length < 3) continue; - const { zBottom, zTop } = stairVerticalExtent(project, stair); - const structure = resolveStructure(stair.floorId); - const { placementId, shapeId } = emitBoxProduct( - footprint, - zBottom - structure.baseElevation, - zTop - zBottom, - structure.placementId, - ); - const predefinedType = - stair.shape === "straight" - ? ENUM("STRAIGHT_RUN_STAIR") - : stair.shape === "spiral" - ? ENUM("SPIRAL_STAIR") - : ENUM("QUARTER_TURN_STAIR"); - const entityId = emitBuildingElement( - "IFCSTAIR", - ifcGuid(stair.id), - "Treppe", - placementId, - shapeId, - predefinedType, - ); - addToContainment(structure.entityId, entityId); - } - - // ── Extrudierte Körper (truck-Integration) → IfcBuildingElementProxy ─── - for (const solid of project.extrudedSolids ?? []) { - if (solid.points.length < 3) continue; - const floor = floors.find((f) => f.id === solid.levelId); - const base = floor?.baseElevation ?? 0; - const structure = resolveStructure(solid.levelId); - const { placementId, shapeId } = emitBoxProduct( - solid.points, - base - structure.baseElevation, - solid.height, - structure.placementId, - ); - const entityId = emitBuildingElement( - "IFCBUILDINGELEMENTPROXY", - ifcGuid(solid.id), - "Extrusion", - placementId, - shapeId, - null, - ); - addToContainment(structure.entityId, entityId); - } - - // ── Räume → IfcSpace ─────────────────────────────────────────────────── - // Je Raum ein IfcSpace (Name = Raumnummer, LongName = Raumname), als Extrusion der lichten - // Innenkontur über die lichte Geschosshöhe. Räume sind räumliche Elemente: sie werden im - // Geschoss AGGREGIERT (IfcRelAggregates), nicht enthalten. Dazu Basismengen - // (Qto_SpaceBaseQuantities) und die SIA-416-Kategorie als Eigenschaft. - const spacesByStructure = new Map(); - for (const room of project.rooms ?? []) { - if (room.boundary.length < 3) continue; - const structure = resolveStructure(room.floorId); - const floor = floors.find((f) => f.id === room.floorId); - const height = floor?.floorHeight && floor.floorHeight > 0 ? floor.floorHeight : 2.5; - const { placementId, shapeId } = emitBoxProduct(room.boundary, 0, height, structure.placementId); - const spaceId = w.add( - "IFCSPACE", - `${S(ifcGuid(room.id))},#${ownerHistory},${S(room.stamp?.number || room.id)},$,$,#${placementId},#${shapeId},${S(room.name)},${ENUM("ELEMENT")},${ENUM("INTERNAL")},$`, - ); - const list = spacesByStructure.get(structure.entityId); - if (list) list.push(spaceId); - else spacesByStructure.set(structure.entityId, [spaceId]); - - const area = evaluateRoom(room.boundary, room.siaCategory); - const qNet = w.add("IFCQUANTITYAREA", `${S("NetFloorArea")},$,$,${R(area.netArea)},$`); - const qGross = w.add("IFCQUANTITYAREA", `${S("GrossFloorArea")},$,$,${R(area.grossArea)},$`); - const qHeight = w.add("IFCQUANTITYLENGTH", `${S("Height")},$,$,${R(height)},$`); - const qto = w.add( - "IFCELEMENTQUANTITY", - `${S(ifcGuid(`${room.id}:qto`))},#${ownerHistory},${S("Qto_SpaceBaseQuantities")},$,$,${LIST([`#${qNet}`, `#${qGross}`, `#${qHeight}`])}`, - ); - w.add( - "IFCRELDEFINESBYPROPERTIES", - `${S(ifcGuid(`${room.id}:rel-qto`))},#${ownerHistory},$,$,${LIST([`#${spaceId}`])},#${qto}`, - ); - const sia = w.add("IFCPROPERTYSINGLEVALUE", `${S("SIA416")},$,IFCLABEL(${S(room.siaCategory)}),$`); - const pset = w.add( - "IFCPROPERTYSET", - `${S(ifcGuid(`${room.id}:pset`))},#${ownerHistory},${S("CH_Raum")},$,${LIST([`#${sia}`])}`, - ); - w.add( - "IFCRELDEFINESBYPROPERTIES", - `${S(ifcGuid(`${room.id}:rel-pset`))},#${ownerHistory},$,$,${LIST([`#${spaceId}`])},#${pset}`, - ); - } - for (const [structureId, spaceIds] of spacesByStructure) { - w.add( - "IFCRELAGGREGATES", - `${S(ifcGuid(`spaces:${structureId}`))},#${ownerHistory},$,$,#${structureId},${LIST(spaceIds.map((id) => `#${id}`))}`, - ); - } - - // ── Dächer → IfcRoof ─────────────────────────────────────────────────── - // Dieselben geschlossenen Schicht-Meshes wie das 3D (`roofMeshes`: Dachflächen je Schicht, - // an First/Grat gehrt), zu EINEM Face-Set je Dach vereint. Modell-Koordinaten sind bereits - // Z-oben (kein Achsentausch wie bei den Wänden); die Wicklung wird so gewählt, dass das Volumen - // positiv ist — nur dann ist das Face-Set als geschlossen markiert. - const ROOF_PREDEFINED: Record = { - flach: "FLAT_ROOF", - pult: "SHED_ROOF", - sattel: "GABLE_ROOF", - walm: "HIP_ROOF", - mansarde: "MANSARD_ROOF", - zelt: "HIPPED_GABLE_ROOF", - }; - for (const roof of project.roofs ?? []) { - const structure = resolveStructure(roof.floorId); - const positions: number[] = []; - const indices: number[] = []; - for (const mesh of roofMeshes(project, roof.id)) { - const base = positions.length / 3; - for (let i = 0; i < mesh.positions.length; i += 3) { - positions.push(mesh.positions[i], mesh.positions[i + 1], mesh.positions[i + 2] - structure.baseElevation); - } - for (const ix of mesh.indices) indices.push(base + ix); - } - if (indices.length === 0) continue; - let closed = isWatertight({ positions, indices }); - if (!closed) { - const flipped: number[] = []; - for (let i = 0; i < indices.length; i += 3) flipped.push(indices[i], indices[i + 2], indices[i + 1]); - if (isWatertight({ positions, indices: flipped })) { - indices.splice(0, indices.length, ...flipped); - closed = true; - } - } - const { placementId, shapeId } = emitTriangulatedProduct(positions, indices, structure.placementId, closed); - const predefined = ROOF_PREDEFINED[roof.shape] ?? "NOTDEFINED"; - const roofType = roof.roofTypeId ? (project.roofTypes ?? []).find((t) => t.id === roof.roofTypeId) : undefined; - const entityId = emitBuildingElement("IFCROOF", ifcGuid(roof.id), roofType?.name ?? "Dach", placementId, shapeId, ENUM(predefined)); - if (roofType) typeFor("IFCROOFTYPE", predefined, roofType).occurrences.push(entityId); - addToContainment(structure.entityId, entityId); - } - - // ── Stützen → IfcColumn (Profil-Extrusion, Material = Bauteil) ────────── - const materialAssoc = new Map(); - for (const col of project.columns ?? []) { - const footprint = columnFootprint(col); - if (footprint.length < 3) continue; - const { zBottom, zTop } = columnVerticalExtent(project, col); - if (!(zTop > zBottom)) continue; - const structure = resolveStructure(col.floorId); - const { placementId, shapeId } = emitBoxProduct(footprint, zBottom - structure.baseElevation, zTop - zBottom, structure.placementId); - const entityId = emitBuildingElement("IFCCOLUMN", ifcGuid(col.id), columnLabel(col), placementId, shapeId, ENUM("COLUMN")); - addToContainment(structure.entityId, entityId); - if (col.componentId) { - const mat = materialOf(col.componentId); - const list = materialAssoc.get(mat); - if (list) list.push(entityId); - else materialAssoc.set(mat, [entityId]); - } - } - for (const [mat, ids] of materialAssoc) { - w.add( - "IFCRELASSOCIATESMATERIAL", - `${S(ifcGuid(`material:${mat}`))},#${ownerHistory},$,$,${LIST(ids.map((id) => `#${id}`))},#${mat}`, - ); - } - - // ── Typ-Zuordnung (je Bauteiltyp eine IfcRelDefinesByType) ───────────── - for (const [key, ref] of elementTypes) { - if (ref.occurrences.length === 0) continue; - w.add( - "IFCRELDEFINESBYTYPE", - `${S(ifcGuid(`${key}:occurrences`))},#${ownerHistory},$,$,${LIST(ref.occurrences.map((id) => `#${id}`))},#${ref.typeId}`, - ); - } - - // ── Räumliche Eingliederung (gebündelt je Trägerstruktur) ────────────── - for (const [structureId, elementIds] of containment) { - w.add( - "IFCRELCONTAINEDINSPATIALSTRUCTURE", - `${S(ifcGuid(`contain:${structureId}`))},#${ownerHistory},$,$,${LIST(elementIds.map((id) => `#${id}`))},#${structureId}`, - ); - } - - // ── Kopf + Zusammenbau ─────────────────────────────────────────────────── - const iso = new Date().toISOString().replace(/\.\d+Z$/, ""); - const fileName = `${project.name || "modell"}.ifc`; - const header = [ - "ISO-10303-21;", - "HEADER;", - `FILE_DESCRIPTION(${LIST([S("")])},${S("2;1")});`, - `FILE_NAME(${S(fileName)},${S(iso)},${LIST([S("dossier")])},${LIST([S("dossier")])},${S("dossier")},${S("dossier")},${S("")});`, - "FILE_SCHEMA(('IFC4'));", - "ENDSEC;", - "", - "DATA;", - ]; - const footer = ["ENDSEC;", "END-ISO-10303-21;"]; - - return [...header, ...w.entityLines, ...footer].join("\n") + "\n"; +export function exportIfcSpf(project: Project): string { + return documentFor(project).exportIfc(Date.now()); } From f16cf44b6023edad14ff59eb44063942a1f5a3dd Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 02:22:31 +0100 Subject: [PATCH 27/31] [K4] S2: Bauteilliste (Zeilen und CSV) in Rust (export_schedule.rs); exportSchedule.ts nur noch Fassade --- src-tauri/core/src/export_ifc.rs | 12 +- src-tauri/core/src/export_schedule.rs | 257 ++++++++++++++++++++ src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/model3d.rs | 10 + src-tauri/core/src/queries.rs | 4 +- src/core/document.ts | 2 + src/export/exportSchedule.ts | 327 ++------------------------ 7 files changed, 290 insertions(+), 323 deletions(-) create mode 100644 src-tauri/core/src/export_schedule.rs diff --git a/src-tauri/core/src/export_ifc.rs b/src-tauri/core/src/export_ifc.rs index d805aabf..522a8e7a 100644 --- a/src-tauri/core/src/export_ifc.rs +++ b/src-tauri/core/src/export_ifc.rs @@ -514,7 +514,7 @@ pub fn export_ifc_spf(project_in: &Project, now_ms: f64) -> Result Result(p: &'a Project, c: &Ceiling) -> Option<(&'a str, &'a str, &'a [Layer])> { - if let Some(id) = c.ceiling_type_id.as_deref() { - if let Some(t) = p.ceiling_types.as_deref().and_then(|v| v.iter().find(|t| t.id == id)) { - return Some((&t.id, &t.name, &t.layers)); - } - } - p.wall_types.iter().find(|t| t.id == c.wall_type_id).map(|t| (t.id.as_str(), t.name.as_str(), t.layers.as_slice())) -} - #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/core/src/export_schedule.rs b/src-tauri/core/src/export_schedule.rs new file mode 100644 index 00000000..8f595905 --- /dev/null +++ b/src-tauri/core/src/export_schedule.rs @@ -0,0 +1,257 @@ +//! Bauteilliste ([K4] S2, vorher `src/export/exportSchedule.ts`): eine Zeile je Bauteil-Vorkommen +//! (Wand, Decke, Tür/Fenster, Treppe, Extrusion, Dach, Stütze) mit Kennwerten aus dem Modell, dazu +//! CSV-Ausgabe (RFC 4180, Feldtrenner `;`, Zeilenende CRLF) mit Aggregat je Bauteil-Typ. + +use crate::js_fmt::to_fixed; +use crate::jsmath::hypot2; +use crate::jsnum::round; +use crate::model::*; +use serde::Serialize; + +/// Eine ausgewertete Zeile (JSON-Form wie `ScheduleRow` in TS). +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ScheduleRow { + pub kind: &'static str, + pub id: String, + pub type_name: String, + pub floor: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub floor_id: Option, + pub length: Option, + pub height_m: Option, + pub thickness: Option, + pub area: Option, +} + +fn polygon_area(pts: &[Vec2]) -> f64 { + let flat: Vec<[f64; 2]> = pts.iter().map(|v| [v.x, v.y]).collect(); + crate::room_area::evaluate(&flat, 0.0).gross +} + +fn floor_name(p: &Project, floor_id: &str) -> String { + p.floor(floor_id).map_or(floor_id.to_string(), |f| f.name.clone()) +} + +/// Wertet ALLE Bauteil-Vorkommen aus: Wände, Decken, Öffnungen, Treppen, Extrusionen, Dächer, Stützen. +pub fn schedule_rows(p: &Project) -> Vec { + let mut rows = Vec::new(); + for w in &p.walls { + let (type_name, thickness) = match p.wall_type(w) { + Some(t) => (t.name.clone(), Project::type_thickness(&t.layers)), + None => (w.wall_type_id.clone(), 0.0), + }; + let length = hypot2(w.end.x - w.start.x, w.end.y - w.start.y); + rows.push(ScheduleRow { + kind: "Wand", + id: w.id.clone(), + type_name, + floor: floor_name(p, &w.floor_id), + floor_id: Some(w.floor_id.clone()), + length: Some(length), + height_m: Some(w.height), + thickness: Some(thickness), + area: Some(length * w.height), + }); + } + for c in p.ceilings.as_deref().unwrap_or(&[]) { + let type_name = match crate::model3d::ceiling_type_ref(p, c) { + Some((_, name, _)) => name.to_string(), + None => c.ceiling_type_id.clone().unwrap_or_else(|| c.wall_type_id.clone()), + }; + rows.push(ScheduleRow { + kind: "Decke", + id: c.id.clone(), + type_name, + floor: floor_name(p, &c.floor_id), + floor_id: Some(c.floor_id.clone()), + length: None, + height_m: None, + thickness: Some(p.ceiling_thickness(c)), + area: Some(polygon_area(&c.outline)), + }); + } + for o in p.openings.as_deref().unwrap_or(&[]) { + let kind = if o.kind == ElementKind::Window { "Fenster" } else { "Tür" }; + let host = p.walls.iter().find(|w| w.id == o.host_wall_id); + rows.push(ScheduleRow { + kind, + id: o.id.clone(), + type_name: kind.to_string(), + floor: host.map_or(o.host_wall_id.clone(), |w| floor_name(p, &w.floor_id)), + floor_id: host.map(|w| w.floor_id.clone()), + length: Some(o.width), + height_m: Some(o.height), + thickness: None, + area: Some(o.width * o.height), + }); + } + for s in p.stairs.as_deref().unwrap_or(&[]) { + rows.push(ScheduleRow { + kind: "Treppe", + id: s.id.clone(), + type_name: "Treppe".into(), + floor: floor_name(p, &s.floor_id), + floor_id: Some(s.floor_id.clone()), + length: Some(s.run_length + s.run2_length.unwrap_or(0.0)), + height_m: s.total_rise, + thickness: None, + area: None, + }); + } + for e in p.extruded_solids.as_deref().unwrap_or(&[]) { + rows.push(ScheduleRow { + kind: "Extrusion", + id: e.id.clone(), + type_name: "Extrusion".into(), + floor: floor_name(p, &e.level_id), + floor_id: Some(e.level_id.clone()), + length: None, + height_m: Some(e.height), + thickness: None, + area: Some(polygon_area(&e.points)), + }); + } + for r in p.roofs.as_deref().unwrap_or(&[]) { + let mut type_name = r.roof_type_id.clone().unwrap_or_else(|| shape_name(r.shape).to_string()); + if let Some(rt) = r.roof_type_id.as_deref().and_then(|id| p.roof_types.as_deref()?.iter().find(|t| t.id == id)) { + type_name = rt.name.clone(); + } + rows.push(ScheduleRow { + kind: "Dach", + id: r.id.clone(), + type_name, + floor: floor_name(p, &r.floor_id), + floor_id: Some(r.floor_id.clone()), + length: None, + height_m: None, + thickness: Some(r.thickness), + area: Some(polygon_area(&r.outline)), + }); + } + for c in p.columns.as_deref().unwrap_or(&[]) { + let (type_name, length, thickness) = match &c.profile { + ColumnProfile::Round { radius } => ("Rund", None, radius * 2.0), + ColumnProfile::Rect { width, depth } => ("Rechteck", Some(*width), *depth), + }; + rows.push(ScheduleRow { + kind: "Stütze", + id: c.id.clone(), + type_name: type_name.into(), + floor: floor_name(p, &c.floor_id), + floor_id: Some(c.floor_id.clone()), + length, + height_m: Some(c.height), + thickness: Some(thickness), + area: None, + }); + } + rows +} + +fn shape_name(s: RoofShape) -> &'static str { + match s { + RoofShape::Flach => "flach", + RoofShape::Pult => "pult", + RoofShape::Sattel => "sattel", + RoofShape::Walm => "walm", + RoofShape::Mansarde => "mansarde", + RoofShape::Zelt => "zelt", + } +} + +/// Ein Feld CSV-sicher quoten: „…" bei , " \n \r ; — `"` wird verdoppelt. +fn csv_field(v: &str) -> String { + if v.contains(['"', ',', '\n', '\r', ';']) { + format!("\"{}\"", v.replace('"', "\"\"")) + } else { + v.to_string() + } +} + +/// Zahl auf 2 Nachkommastellen, Punkt; leer bei `None`/nicht endlich. +fn fmt_num(v: Option) -> String { + match v { + Some(x) if x.is_finite() => to_fixed(round(x * 100.0) / 100.0, 2), + _ => String::new(), + } +} + +struct Aggregate { + kind: &'static str, + type_name: String, + count: usize, + total_length: f64, + total_area: f64, +} + +/// Bauteilliste als CSV (`exportScheduleCsv`): Kopfzeile, eine Zeile je Bauteil, optional Aggregat. +pub fn export_schedule_csv(p: &Project, delimiter: &str, include_summary: bool) -> String { + let rows = schedule_rows(p); + let d = delimiter; + let mut lines: Vec = Vec::new(); + let header = ["Typ", "ID", "Bauteil", "Geschoss", "Länge [m]", "Höhe [m]", "Dicke [m]", "Fläche [m²]"]; + lines.push(header.iter().map(|h| csv_field(h)).collect::>().join(d)); + for r in &rows { + lines.push( + [csv_field(r.kind), csv_field(&r.id), csv_field(&r.type_name), csv_field(&r.floor), fmt_num(r.length), fmt_num(r.height_m), fmt_num(r.thickness), fmt_num(r.area)].join(d), + ); + } + if include_summary && !rows.is_empty() { + lines.push(String::new()); + lines.push([csv_field("Zusammenfassung (je Bauteil-Typ)"), "".into(), "".into(), "".into(), "".into(), "".into(), "".into(), "".into()].join(d)); + let mut aggs: Vec = Vec::new(); + for r in &rows { + let i = match aggs.iter().position(|a| a.kind == r.kind && a.type_name == r.type_name) { + Some(i) => i, + None => { + aggs.push(Aggregate { kind: r.kind, type_name: r.type_name.clone(), count: 0, total_length: 0.0, total_area: 0.0 }); + aggs.len() - 1 + } + }; + aggs[i].count += 1; + aggs[i].total_length += r.length.unwrap_or(0.0); + aggs[i].total_area += r.area.unwrap_or(0.0); + } + for a in &aggs { + lines.push( + [ + csv_field(a.kind), + String::new(), + csv_field(&a.type_name), + csv_field(&format!("{} Stk", a.count)), + if a.total_length > 0.0 { fmt_num(Some(a.total_length)) } else { String::new() }, + String::new(), + String::new(), + if a.total_area > 0.0 { fmt_num(Some(a.total_area)) } else { String::new() }, + ] + .join(d), + ); + } + } + lines.join("\r\n") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn beispielprojekt_hat_zeilen_und_csv() { + let p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap(); + let rows = schedule_rows(&p); + assert!(rows.iter().any(|r| r.kind == "Wand")); + let csv = export_schedule_csv(&p, ";", true); + assert!(csv.starts_with("Typ;ID;Bauteil;Geschoss;Länge [m];Höhe [m];Dicke [m];Fläche [m²]\r\n")); + assert!(csv.contains("Zusammenfassung (je Bauteil-Typ)")); + assert_eq!(export_schedule_csv(&Project::default(), ";", true), "Typ;ID;Bauteil;Geschoss;Länge [m];Höhe [m];Dicke [m];Fläche [m²]"); + } + + #[test] + fn csv_quoting() { + assert_eq!(csv_field("a;b"), "\"a;b\""); + assert_eq!(csv_field("a\"b"), "\"a\"\"b\""); + assert_eq!(fmt_num(Some(1.005)), "1.00"); + assert_eq!(fmt_num(None), ""); + } +} diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index e45ef88e..b1010158 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -5,6 +5,7 @@ //! Datenübergabe: flache `f64`-Puffer (s. [`flat`]), kein JSON — schnell und ohne Serde-Kosten. pub mod export_ifc; +pub mod export_schedule; pub mod flat; pub mod geo_rebase; pub mod flat_write; diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index 7207b9b3..f0c04356 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -59,6 +59,16 @@ pub struct RMesh { // ── Decken ────────────────────────────────────────────────────────────────── +/// Deckentyp (id, Name, Schichten): Deckentyp, sonst Wandtyp (`getCeilingType`). +pub fn ceiling_type_ref<'a>(p: &'a Project, c: &Ceiling) -> Option<(&'a str, &'a str, &'a [Layer])> { + if let Some(id) = c.ceiling_type_id.as_deref() { + if let Some(t) = p.ceiling_types.as_deref().and_then(|v| v.iter().find(|t| t.id == id)) { + return Some((&t.id, &t.name, &t.layers)); + } + } + p.wall_types.iter().find(|t| t.id == c.wall_type_id).map(|t| (t.id.as_str(), t.name.as_str(), t.layers.as_slice())) +} + fn ceiling_layers<'a>(p: &'a Project, c: &Ceiling) -> Option<&'a [Layer]> { if let Some(id) = c.ceiling_type_id.as_deref() { if let Some(t) = p.ceiling_types.as_deref().and_then(|v| v.iter().find(|t| t.id == id)) { diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs index 4c2890f8..b4a31003 100644 --- a/src-tauri/core/src/queries.rs +++ b/src-tauri/core/src/queries.rs @@ -2,7 +2,7 @@ //! antwortet. TS ruft sie über `ProjectDocument.query(name, args, text)`. use crate::model::Project; -use crate::{kennzahlen, model3d, site_rules, sun}; +use crate::{export_schedule, kennzahlen, model3d, site_rules, sun}; fn json(v: &T) -> Result { serde_json::to_string(v).map_err(|e| e.to_string()) @@ -26,6 +26,8 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result json(&model3d::emit_stair_railings(p)), ("roofMeshes", _) => json(&model3d::emit_roofs(p, if text.is_empty() { None } else { Some(text) })?), ("roofCutLayers", _) => json(&model3d::emit_roof_cut_layers(p)?), + ("scheduleRows", _) => 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)?), ("model3dParts", 3) => json(&model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?), _ => Err(format!("Unbekannte Abfrage: {name}")), diff --git a/src/core/document.ts b/src/core/document.ts index d3df730d..c5aca728 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -25,6 +25,8 @@ export type QueryName = | "stairRailings" | "roofMeshes" | "roofCutLayers" + | "scheduleRows" + | "scheduleCsv" | "pickGeometry" | "model3dParts"; diff --git a/src/export/exportSchedule.ts b/src/export/exportSchedule.ts index c2c2ca1c..1b67bb40 100644 --- a/src/export/exportSchedule.ts +++ b/src/export/exportSchedule.ts @@ -1,60 +1,12 @@ -// Bauteil-Schedule (Bauteilliste) — CSV-Export einer Bauteilaufstellung des -// Projekts (AUDIT A6, DOSSIER-Parität). Reiner Rechen-/Serialisierungskern: -// keine UI, kein Datei-IO — nur Modell → CSV-String (unit-testbar). Der -// Download (Blob + Anchor) passiert im App-Layer, analog zum Raum-CSV -// (geometry/roomArea → roomsToCsv) und zum Projekt-JSON-Speichern. -// -// Granularität: EINE Zeile je Bauteil-VORKOMMEN (Wand, Decke, Tür, Fenster/ -// Öffnung, Treppe, Extrusion). Räume sind bewusst NICHT enthalten — die haben -// ihren eigenen CSV-Export (geometry/roomArea → roomsToCsv), keine Duplikation. -// Optional folgt darunter ein Aggregat-Block je Bauteil-Typ. -// Bezeichner englisch, Labels/Kommentare deutsch (CONVENTIONS.md). Einheit: METER. +// Bauteil-Schedule (Bauteilliste) — CSV-Export einer Bauteilaufstellung des Projekts +// (AUDIT A6, DOSSIER-Parität). Gerechnet wird im Rust-Kern (`src-tauri/core/src/export_schedule.rs`, +// [K4] S2) auf dem Projekt-Dokument: EINE Zeile je Bauteil-VORKOMMEN (Wand, Decke, Tür, Fenster, +// Treppe, Extrusion, Dach, Stütze); Räume sind bewusst nicht enthalten (eigener CSV-Export in +// `geometry/roomArea`). Optional folgt ein Aggregat-Block je Bauteil-Typ. Der Download +// (Blob + Anchor) passiert im App-Layer. Einheit: METER. -import type { - Project, - Wall, - Ceiling, - Opening, - Stair, - ExtrudedSolid, - Roof, - Column, -} from "../model/types"; -import { - getWallType, - getCeilingType, - wallTypeThickness, - ceilingThickness, -} from "../model/types"; -import { polygonArea } from "../geometry/roomArea"; - -// ── CSV-Primitive (RFC 4180, gespiegelt vom Raum-CSV) ─────────────────────── - -/** Ein Feld CSV-sicher quoten: „..." bei , " \n \r ; → " wird verdoppelt. */ -function csvField(value: string): string { - if (/[",\n\r;]/.test(value)) { - return `"${value.replace(/"/g, '""')}"`; - } - return value; -} - -/** Zahl auf 2 Nachkommastellen, Punkt als Dezimaltrenner. Leer bei null. */ -function fmtNum(value: number | null | undefined): string { - if (value == null || !Number.isFinite(value)) return ""; - return (Math.round(value * 100) / 100).toFixed(2); -} - -// ── Kennwert-Ableitung (aus dem Modell, keine erfundenen Felder) ──────────── - -/** Achslänge einer Wand (Meter) = Abstand Start→End der Centerline. */ -function wallLength(wall: Wall): number { - return Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y); -} - -/** Anzeigename eines Geschosses (oder die roh-ID, wenn unbekannt). */ -function floorNameOf(project: Project, floorId: string): string { - return project.drawingLevels.find((z) => z.id === floorId)?.name ?? floorId; -} +import type { Project } from "../model/types"; +import { documentFor } from "../core/document"; /** Bauteilklassen der Bauteilliste. */ export type ScheduleKind = @@ -79,10 +31,8 @@ export interface ScheduleRow { /** Geschoss-Name. */ floor: string; /** - * Geschoss-ID (rohe DrawingLevel-Referenz, additiv für Konsumenten wie das - * Elemente-Panel — NICHT Teil der CSV-Spalten, siehe exportScheduleCsv). - * `undefined` bei verwaister/nicht auflösbarer Referenz (z. B. Tür/Öffnung - * mit gelöschter Wirtswand). + * Geschoss-ID (rohe DrawingLevel-Referenz, additiv für Konsumenten wie das Elemente-Panel — NICHT + * Teil der CSV-Spalten). Fehlt bei verwaister Referenz (z. B. Öffnung mit gelöschter Wirtswand). */ floorId?: string; /** Achslänge bzw. lichte Breite in Metern (null wo nicht verlässlich ableitbar). */ @@ -95,200 +45,14 @@ export interface ScheduleRow { area: number | null; } -/** Wertet eine Wand für die Bauteilliste aus (defensiv gegen fehlende Typen). */ -function evalWall(project: Project, wall: Wall): ScheduleRow { - let typeName = wall.wallTypeId; - let thickness = 0; - try { - const wt = getWallType(project, wall); - typeName = wt.name; - thickness = wallTypeThickness(wt); - } catch { - /* verwaister Wandtyp — Roh-ID + Dicke 0 */ - } - const length = wallLength(wall); - return { - kind: "Wand", - id: wall.id, - typeName, - floor: floorNameOf(project, wall.floorId), - floorId: wall.floorId, - length, - heightM: wall.height, - thickness, - area: length * wall.height, - }; -} - -/** Wertet eine Decke für die Bauteilliste aus (defensiv gegen fehlende Typen). */ -function evalCeiling(project: Project, ceiling: Ceiling): ScheduleRow { - let typeName = ceiling.ceilingTypeId ?? ceiling.wallTypeId; - try { - typeName = getCeilingType(project, ceiling).name; - } catch { - /* verwaister Deckentyp — Roh-ID */ - } - return { - kind: "Decke", - id: ceiling.id, - typeName, - floor: floorNameOf(project, ceiling.floorId), - floorId: ceiling.floorId, - length: null, - heightM: null, - thickness: ceilingThickness(project, ceiling), - area: polygonArea(ceiling.outline), - }; -} - -/** Geschoss eines wandgehosteten Elements (Tür/Öffnung) über die Wirtswand. */ -function floorOfHostWall(project: Project, hostWallId: string): string { - const wall = project.walls.find((w) => w.id === hostWallId); - if (!wall) return hostWallId; // verwaiste Wirtswand — Roh-ID, analog verwaister Typreferenzen - return floorNameOf(project, wall.floorId); -} - -/** Rohe Geschoss-ID eines wandgehosteten Elements (Tür/Öffnung), oder `undefined` bei verwaister Wirtswand. */ -function floorIdOfHostWall(project: Project, hostWallId: string): string | undefined { - return project.walls.find((w) => w.id === hostWallId)?.floorId; -} - -/** Wertet eine Öffnung (Fenster oder Tür-Öffnung) für die Bauteilliste aus. */ -function evalOpening(project: Project, opening: Opening): ScheduleRow { - const kind = opening.kind === "window" ? "Fenster" : "Tür"; - return { - kind, - id: opening.id, - typeName: kind, - floor: floorOfHostWall(project, opening.hostWallId), - floorId: floorIdOfHostWall(project, opening.hostWallId), - length: opening.width, - heightM: opening.height, - thickness: null, - area: opening.width * opening.height, - }; -} - /** - * Wertet eine Treppe für die Bauteilliste aus. Fläche bleibt bewusst leer — - * eine echte Footprint-Fläche bräuchte stairGeometry() (geometry/stair.ts) - * samt dessen Geschosshöhen-Fallback, den wir hier nicht koppeln wollen. - */ -function evalStair(project: Project, stair: Stair): ScheduleRow { - return { - kind: "Treppe", - id: stair.id, - typeName: "Treppe", - floor: floorNameOf(project, stair.floorId), - floorId: stair.floorId, - length: stair.runLength + (stair.run2Length ?? 0), - heightM: stair.totalRise ?? null, - thickness: null, - area: null, - }; -} - -/** Wertet einen extrudierten Körper für die Bauteilliste aus. */ -function evalExtrudedSolid(project: Project, solid: ExtrudedSolid): ScheduleRow { - return { - kind: "Extrusion", - id: solid.id, - typeName: "Extrusion", - floor: floorNameOf(project, solid.levelId), - floorId: solid.levelId, - length: null, - heightM: solid.height, - thickness: null, - area: polygonArea(solid.points), - }; -} - -/** Wertet ein Dach für die Bauteilliste aus (defensiv gegen fehlenden Dachtyp). */ -function evalRoof(project: Project, roof: Roof): ScheduleRow { - let typeName = roof.roofTypeId ?? roof.shape; - if (roof.roofTypeId) { - const rt = (project.roofTypes ?? []).find((t) => t.id === roof.roofTypeId); - if (rt) typeName = rt.name; - } - return { - kind: "Dach", - id: roof.id, - typeName, - floor: floorNameOf(project, roof.floorId), - floorId: roof.floorId, - length: null, - heightM: null, - thickness: roof.thickness, - area: polygonArea(roof.outline), - }; -} - -/** Wertet eine Stütze für die Bauteilliste aus (Querschnitt als „Dicke", Rechteck-Breite als „Länge"). */ -function evalColumn(project: Project, column: Column): ScheduleRow { - return { - kind: "Stütze", - id: column.id, - typeName: column.profile.kind === "round" ? "Rund" : "Rechteck", - floor: floorNameOf(project, column.floorId), - floorId: column.floorId, - length: column.profile.kind === "rect" ? column.profile.width : null, - heightM: column.height, - thickness: - column.profile.kind === "rect" ? column.profile.depth : column.profile.radius * 2, - area: null, - }; -} - -/** - * Wertet ALLE Bauteil-Vorkommen eines Projekts aus (Wände, Decken, Türen, - * Fenster/Öffnungen, Treppen, Extrusionen, Dächer, Stützen — Räume bewusst - * ausgenommen, siehe Dateikopf). Reine Ableitung aus dem Modell — nichts wird - * gespeichert. Reihenfolge: Wände, Decken, Türen, Öffnungen, Treppen, + * Wertet ALLE Bauteil-Vorkommen eines Projekts aus. Reihenfolge: Wände, Decken, Öffnungen, Treppen, * Extrusionen, Dächer, Stützen (je in Dokumentreihenfolge). */ export function scheduleRows(project: Project): ScheduleRow[] { - const rows: ScheduleRow[] = []; - for (const w of project.walls ?? []) rows.push(evalWall(project, w)); - for (const c of project.ceilings ?? []) rows.push(evalCeiling(project, c)); - for (const o of project.openings ?? []) rows.push(evalOpening(project, o)); - for (const s of project.stairs ?? []) rows.push(evalStair(project, s)); - for (const e of project.extrudedSolids ?? []) rows.push(evalExtrudedSolid(project, e)); - for (const r of project.roofs ?? []) rows.push(evalRoof(project, r)); - for (const c of project.columns ?? []) rows.push(evalColumn(project, c)); - return rows; + return documentFor(project).query("scheduleRows"); } -// ── Aggregat je Bauteil-Typ ───────────────────────────────────────────────── - -interface TypeAggregate { - kind: ScheduleKind; - typeName: string; - count: number; - /** Summe der Längen (Meter) — Bauteile ohne Länge tragen 0 bei. */ - totalLength: number; - /** Summe der Flächen (m²) — Bauteile ohne Fläche tragen 0 bei. */ - totalArea: number; -} - -/** Rollt die Zeilen je (Klasse + Typname) zu Zwischensummen zusammen. */ -function aggregateByType(rows: ScheduleRow[]): TypeAggregate[] { - const map = new Map(); - for (const r of rows) { - const key = `${r.kind} ${r.typeName}`; - let agg = map.get(key); - if (!agg) { - agg = { kind: r.kind, typeName: r.typeName, count: 0, totalLength: 0, totalArea: 0 }; - map.set(key, agg); - } - agg.count += 1; - agg.totalLength += r.length ?? 0; - agg.totalArea += r.area ?? 0; - } - return [...map.values()]; -} - -// ── CSV-Serialisierung ─────────────────────────────────────────────────────── - export interface ScheduleCsvOptions { /** Feldtrenner. Default „;" (Excel-DE-freundlich, wie der Raum-CSV). */ delimiter?: string; @@ -296,69 +60,10 @@ export interface ScheduleCsvOptions { includeSummary?: boolean; } -/** Spaltenüberschriften der Bauteilliste (fix Deutsch, wie der Raum-CSV). */ -const HEADER = [ - "Typ", - "ID", - "Bauteil", - "Geschoss", - "Länge [m]", - "Höhe [m]", - "Dicke [m]", - "Fläche [m²]", -]; - /** - * Baut die Bauteilliste des Projekts als CSV-String (kein Datei-IO). Eine Zeile - * je Bauteil-Vorkommen mit den aus dem Modell verlässlich ableitbaren - * Kennwerten; optional ein Aggregat-Block je Bauteil-Typ. - * - * Leeres Projekt ⇒ nur die Kopfzeile (kein Crash). + * Baut die Bauteilliste des Projekts als CSV-String (kein Datei-IO). Leeres Projekt ⇒ nur die + * Kopfzeile (kein Crash). */ -export function exportScheduleCsv( - project: Project, - options: ScheduleCsvOptions = {}, -): string { - const d = options.delimiter ?? ";"; - const includeSummary = options.includeSummary ?? true; - const rows = scheduleRows(project); - const lines: string[] = []; - - lines.push(HEADER.map(csvField).join(d)); - - for (const r of rows) { - lines.push( - [ - csvField(r.kind), - csvField(r.id), - csvField(r.typeName), - csvField(r.floor), - fmtNum(r.length), - fmtNum(r.heightM), - fmtNum(r.thickness), - fmtNum(r.area), - ].join(d), - ); - } - - if (includeSummary && rows.length > 0) { - lines.push(""); // Leerzeile trennt Liste von Aggregat - lines.push([csvField("Zusammenfassung (je Bauteil-Typ)"), "", "", "", "", "", "", ""].join(d)); - for (const agg of aggregateByType(rows)) { - lines.push( - [ - csvField(agg.kind), - "", - csvField(agg.typeName), - csvField(`${agg.count} Stk`), - agg.totalLength > 0 ? fmtNum(agg.totalLength) : "", - "", - "", - agg.totalArea > 0 ? fmtNum(agg.totalArea) : "", - ].join(d), - ); - } - } - - return lines.join("\r\n"); +export function exportScheduleCsv(project: Project, options: ScheduleCsvOptions = {}): string { + return documentFor(project).queryJson("scheduleCsv", [options.includeSummary ?? true ? 1 : 0], options.delimiter ?? ";"); } From 96a5c219ec3437db310ada7703dde3c0ba8e0d9b Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 02:24:13 +0100 Subject: [PATCH 28/31] [K4] S2: OBJ/STL-Export in Rust (export_mesh.rs); exportMesh.ts nur noch Fassade --- src-tauri/core/src/export_mesh.rs | 256 +++++++++++++++++++++ src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/queries.rs | 4 +- src/core/document.ts | 2 + src/export/exportMesh.ts | 361 ++---------------------------- 5 files changed, 278 insertions(+), 346 deletions(-) create mode 100644 src-tauri/core/src/export_mesh.rs diff --git a/src-tauri/core/src/export_mesh.rs b/src-tauri/core/src/export_mesh.rs new file mode 100644 index 00000000..7c943570 --- /dev/null +++ b/src-tauri/core/src/export_mesh.rs @@ -0,0 +1,256 @@ +//! OBJ-/STL-Export des 3D-Gebäudemodells als reines Dreiecks-Netz ([K4] S2, vorher +//! `src/export/exportMesh.ts`). Wände: dieselben Schicht-Bänder wie der 3D-Viewer, gelochte Bänder +//! öffnungsgenau ausgeschnitten (`wall_mesh_cut`); Decken und Extrusionen als Umriss-Prismen +//! (Ear-Clipping-Kappen, Seitenmantel, optional verjüngt). Achsen: Modell (x, y) → Welt (x, Höhe, y), +//! Y-up, rechtshändig, Meter. + +use crate::js_fmt::to_fixed; +use crate::model::*; +use crate::model3d; +use crate::wall_mesh_cut::{wall_cut_mesh, CutWall}; + +struct MeshGroup { + name: String, + positions: Vec, + indices: Vec, +} + +/// OBJ-Gruppennamen dürfen keine Whitespaces/Sonderzeichen enthalten. +fn sanitize_name(id: &str) -> String { + let s: String = id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' }).collect(); + if s.is_empty() { + "x".into() + } else { + s + } +} + +/// Die 6 Quader-Seiten als Eckpunkt-Quadrupel, nach aussen gewunden. +const BOX_QUADS: [[u32; 4]; 6] = [[4, 6, 7, 5], [1, 3, 2, 0], [2, 3, 7, 6], [4, 5, 1, 0], [1, 5, 7, 3], [2, 6, 4, 0]]; + +fn push_wall_box(g: &mut MeshGroup, w: &model3d::RWall) { + let [sx, sy] = w.start; + let [ex, ey] = w.end; + let dx = ex - sx; + let dz = ey - sy; + let len = crate::jsmath::hypot2(dx, dz); + if len < 1e-9 || w.height <= 1e-9 || w.thickness <= 1e-9 { + return; + } + let (ax, az) = (dx / len, dz / len); + let (nx, nz) = (az, -ax); + let (half_len, half_height, half_thick) = (len / 2.0, w.height / 2.0, w.thickness / 2.0); + let (cx, cz) = ((sx + ex) / 2.0, (sy + ey) / 2.0); + let cy = w.base_elevation + w.height / 2.0; + let base = (g.positions.len() / 3) as u32; + for i in 0..8u32 { + let s_l = if i & 1 != 0 { 1.0 } else { -1.0 }; + let s_h = if i & 2 != 0 { 1.0 } else { -1.0 }; + let s_t = if i & 4 != 0 { 1.0 } else { -1.0 }; + g.positions.extend([cx + s_l * half_len * ax + s_t * half_thick * nx, cy + s_h * half_height, cz + s_l * half_len * az + s_t * half_thick * nz]); + } + for [a, b, c, d] in BOX_QUADS { + g.indices.extend([base + a, base + b, base + c, base + a, base + c, base + d]); + } +} + +fn signed_area_xy(pts: &[Vec2]) -> f64 { + let mut a = 0.0; + let mut j = pts.len().wrapping_sub(1); + for i in 0..pts.len() { + a += pts[j].x * pts[i].y - pts[i].x * pts[j].y; + j = i; + } + a / 2.0 +} + +fn push_prism(g: &mut MeshGroup, outline: &[Vec2], z_bottom: f64, z_top: f64, taper: f64) { + if outline.len() < 3 || z_top - z_bottom <= 1e-9 { + return; + } + let ccw: Vec = if signed_area_xy(outline) >= 0.0 { outline.to_vec() } else { outline.iter().rev().copied().collect() }; + let n = ccw.len() as u32; + let (mut cx, mut cy_model) = (0.0, 0.0); + for p in &ccw { + cx += p.x; + cy_model += p.y; + } + cx /= n as f64; + cy_model /= n as f64; + let t = taper.clamp(0.0, 1.0); + let base = (g.positions.len() / 3) as u32; + for p in &ccw { + g.positions.extend([p.x, z_bottom, p.y]); + } + for p in &ccw { + let tx = cx + (p.x - cx) * (1.0 - t); + let ty = cy_model + (p.y - cy_model) * (1.0 - t); + g.positions.extend([tx, z_top, ty]); + } + let pts: Vec = ccw.iter().map(|p| crate::hatch::V2 { x: p.x, y: p.y }).collect(); + let cap = crate::gpu_compile::triangulate(&pts); + for tri in cap.chunks_exact(3) { + let (a, b, c) = (tri[0], tri[1], tri[2]); + g.indices.extend([base + a, base + b, base + c]); + g.indices.extend([base + n + a, base + n + c, base + n + b]); + } + for i in 0..n { + let j = (i + 1) % n; + let (bi, bj, ti, tj) = (base + i, base + j, base + n + i, base + n + j); + g.indices.extend([bi, ti, tj]); + g.indices.extend([bi, tj, bj]); + } +} + +fn build_groups(p: &Project) -> Result, String> { + let mut groups: Vec = Vec::new(); + let walls = model3d::emit_walls(p, true)?; + let mut by_id: Vec<(String, usize)> = Vec::new(); + for w in &walls { + let gi = match by_id.iter().find(|(id, _)| *id == w.wall_id) { + Some((_, gi)) => *gi, + None => { + groups.push(MeshGroup { name: format!("Wand_{}", sanitize_name(&w.wall_id)), positions: vec![], indices: vec![] }); + by_id.push((w.wall_id.clone(), groups.len() - 1)); + groups.len() - 1 + } + }; + let g = &mut groups[gi]; + if w.holes.as_ref().is_some_and(|h| !h.is_empty()) { + let cw = CutWall { + start: w.start, + end: w.end, + thickness: w.thickness, + base_elevation: w.base_elevation, + height: w.height, + holes: w.holes.as_ref().map_or(vec![], |hs| hs.iter().map(|h| [h.from, h.to, h.z_bottom, h.z_top]).collect()), + }; + let finite = cw.start.iter().chain(&cw.end).all(|v| v.is_finite()) && [cw.thickness, cw.base_elevation, cw.height].iter().all(|v| v.is_finite()) && cw.holes.iter().flatten().all(|v| v.is_finite()); + let cut = if finite { wall_cut_mesh(&cw) } else { Vec::new() }; + let base = (g.positions.len() / 3) as u32; + g.positions.extend_from_slice(&cut); + g.indices.extend((0..(cut.len() / 3) as u32).map(|i| base + i)); + } else { + push_wall_box(g, w); + } + } + for s in model3d::emit_slabs(p) { + let mut g = MeshGroup { name: format!("Decke_{}", sanitize_name(&s.ceiling_id)), positions: vec![], indices: vec![] }; + let outline: Vec = s.outline.iter().map(|&[x, y]| Vec2 { x, y }).collect(); + push_prism(&mut g, &outline, s.z_bottom, s.z_top, 0.0); + groups.push(g); + } + for solid in p.extruded_solids.as_deref().unwrap_or(&[]) { + if solid.points.len() < 3 || solid.height <= 0.0 { + continue; + } + let base_z = p.floor(&solid.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0)); + let mut g = MeshGroup { name: format!("Extrusion_{}", sanitize_name(&solid.id)), positions: vec![], indices: vec![] }; + push_prism(&mut g, &solid.points, base_z, base_z + solid.height, solid.taper.unwrap_or(0.0)); + groups.push(g); + } + Ok(groups.into_iter().filter(|g| !g.indices.is_empty()).collect()) +} + +/// Kompakte Zahlformatierung (bis 6 Nachkommastellen, ohne Nullen, mindestens `.0`). +fn fmt(v: f64) -> String { + if !v.is_finite() { + return "0.0".into(); + } + let mut s = to_fixed(v, 6); + let trimmed = s.trim_end_matches('0').len(); + s.truncate(trimmed); + if s.ends_with('.') { + s.push('0'); + } + s +} + +/// Wavefront-OBJ des Gebäudemodells. +pub fn export_obj(p: &Project) -> Result { + let groups = build_groups(p)?; + let mut lines: Vec = vec![ + "# DOSSIER OBJ-Export - Dreiecks-Mesh des 3D-Gebaeudemodells".into(), + "# Achsen: rechtshaendig, Y-up (Y = Hoehe ueber OKFF), wie der 3D-Viewer.".into(), + "# Waende: Schicht-Baender mit oeffnungsgenau ausgeschnittenen Loechern (inkl. Laibungen).".into(), + "# Decken/Extrusionen: Umriss-Prisma (Ear-Clipping-Triangulierung).".into(), + ]; + let mut offset = 0u32; + for g in &groups { + let vert_count = (g.positions.len() / 3) as u32; + if vert_count == 0 { + continue; + } + lines.push(format!("o {}", g.name)); + for c in g.positions.chunks_exact(3) { + lines.push(format!("v {} {} {}", fmt(c[0]), fmt(c[1]), fmt(c[2]))); + } + for t in g.indices.chunks_exact(3) { + lines.push(format!("f {} {} {}", t[0] + 1 + offset, t[1] + 1 + offset, t[2] + 1 + offset)); + } + offset += vert_count; + } + Ok(lines.join("\n") + "\n") +} + +/// ASCII-STL des Gebäudemodells. +pub fn export_stl(p: &Project) -> Result { + let groups = build_groups(p)?; + let mut lines: Vec = vec!["solid dossier".into()]; + for g in &groups { + for t in g.indices.chunks_exact(3) { + let pt = |i: u32| -> [f64; 3] { + let k = i as usize * 3; + [g.positions[k], g.positions[k + 1], g.positions[k + 2]] + }; + let (a, b, c) = (pt(t[0]), pt(t[1]), pt(t[2])); + let (ux, uy, uz) = (b[0] - a[0], b[1] - a[1], b[2] - a[2]); + let (vx, vy, vz) = (c[0] - a[0], c[1] - a[1], c[2] - a[2]); + let (mut nx, mut ny, mut nz) = (uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx); + let len = crate::jsmath::hypot(&[nx, ny, nz]); + if len > 1e-12 { + nx /= len; + ny /= len; + nz /= len; + } else { + nx = 0.0; + ny = 0.0; + nz = 0.0; + } + lines.push(format!("facet normal {} {} {}", fmt(nx), fmt(ny), fmt(nz))); + lines.push("outer loop".into()); + for v in [a, b, c] { + lines.push(format!("vertex {} {} {}", fmt(v[0]), fmt(v[1]), fmt(v[2]))); + } + lines.push("endloop".into()); + lines.push("endfacet".into()); + } + } + lines.push("endsolid dossier".into()); + Ok(lines.join("\n") + "\n") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn zahlformat() { + assert_eq!(fmt(1.0), "1.0"); + assert_eq!(fmt(1.5), "1.5"); + assert_eq!(fmt(0.0), "0.0"); + assert_eq!(fmt(10.0), "10.0"); + assert_eq!(fmt(0.1234567), "0.123457"); + assert_eq!(fmt(f64::NAN), "0.0"); + } + + #[test] + fn beispielprojekt() { + let p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap(); + let obj = export_obj(&p).unwrap(); + assert!(obj.contains("\no Wand_")); + let stl = export_stl(&p).unwrap(); + assert!(stl.starts_with("solid dossier\n") && stl.ends_with("endsolid dossier\n")); + assert!(export_obj(&Project::default()).unwrap().lines().count() == 4); + } +} diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index b1010158..70f0203a 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -5,6 +5,7 @@ //! Datenübergabe: flache `f64`-Puffer (s. [`flat`]), kein JSON — schnell und ohne Serde-Kosten. pub mod export_ifc; +pub mod export_mesh; pub mod export_schedule; pub mod flat; pub mod geo_rebase; diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs index b4a31003..d28ee716 100644 --- a/src-tauri/core/src/queries.rs +++ b/src-tauri/core/src/queries.rs @@ -2,7 +2,7 @@ //! antwortet. TS ruft sie über `ProjectDocument.query(name, args, text)`. use crate::model::Project; -use crate::{export_schedule, kennzahlen, model3d, site_rules, sun}; +use crate::{export_mesh, export_schedule, kennzahlen, model3d, site_rules, sun}; fn json(v: &T) -> Result { serde_json::to_string(v).map_err(|e| e.to_string()) @@ -28,6 +28,8 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result json(&model3d::emit_roof_cut_layers(p)?), ("scheduleRows", _) => json(&export_schedule::schedule_rows(p)), ("scheduleCsv", 1) => Ok(export_schedule::export_schedule_csv(p, text, args[0] != 0.0)), + ("objFile", _) => Ok(export_mesh::export_obj(p)?), + ("stlFile", _) => Ok(export_mesh::export_stl(p)?), ("pickGeometry", _) => json(&model3d::pick_geometry(p)?), ("model3dParts", 3) => json(&model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?), _ => Err(format!("Unbekannte Abfrage: {name}")), diff --git a/src/core/document.ts b/src/core/document.ts index c5aca728..d5a7e116 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -27,6 +27,8 @@ export type QueryName = | "roofCutLayers" | "scheduleRows" | "scheduleCsv" + | "objFile" + | "stlFile" | "pickGeometry" | "model3dParts"; diff --git a/src/export/exportMesh.ts b/src/export/exportMesh.ts index f6844be2..bdcb48e4 100644 --- a/src/export/exportMesh.ts +++ b/src/export/exportMesh.ts @@ -1,356 +1,27 @@ -// OBJ-/STL-Export des 3D-Gebäudemodells als reines Dreiecks-Mesh. Pures Modul -// (kein Datei-IO, kein WASM) — Architektur wie exportDxf.ts/exportSchedule.ts: -// buildGroups() liest das Projekt und liefert reine Zahlen-Arrays, exportObj()/ -// exportStl() serialisieren sie synchron zu Text. -// -// TRIANGEL-QUELLE (bewusste v1-Entscheidung, siehe PENDENZEN): -// • Wände: pickGeometry() aus toWalls3d.ts liefert dieselben Schicht-Bänder, -// die auch der 3D-Viewer zeichnet (EIN RWall je Materiallage/Achsen- -// Teilstück, bereits mit End-Cuts/Gehrungen/Decken-Dominanz aufgelöst). -// Bänder mit Öffnungs-`holes` werden über den gemeinsamen Loch-Ausschnitt- -// Generator (`plan/wallMeshCut.ts` → Rust-Kern, Gitter-Zerlegung wie render3ds -// `extrude_layer_segment_with_holes`) ÖFFNUNGSGENAU trianguliert — die -// Fenster/Türen sind sichtbar ausgestanzt inkl. Laibungsflächen, genau wie -// im 3D-Viewer. Lochlose Bänder bleiben die klassische geteilte 8-Ecken-Box. -// • Decken: pickGeometry() liefert den Umriss + zBottom/zTop je Decke; -// der Umriss wird mit dem vorhandenen Ear-Clipping-Triangulator -// (`triangulate` aus plan/glPlan/glPlanCompile.ts, bereits getestet und -// konkav-fähig) zu Boden-/Deckenkappen trianguliert, dazwischen ein -// Seitenmantel — ein einfaches Umriss-Prisma. -// • ExtrudedSolids (truck-Profile): `src/engine/truckSolid.ts` liefert zwar -// "echte" truck-Dreiecke, ABER nur asynchron über WASM -// (`extrudePolygon`/`extrudeCircle` geben Promises zurück). Das würde die -// geforderte SYNCHRONE, WASM-freie Signatur `exportObj(project): string` -// brechen. Deshalb nutzt dieser Export stattdessen DIESELBE Prisma- -// Triangulierung wie die Decken (Umriss aus `solid.points` — bei -// Kreisprofilen bereits eine 48-Eck-Tessellierung, siehe -// `ExtrudedSolid.points`-Doc) inkl. `taper`-Verjüngung (linear zum -// Schwerpunkt skaliert, wie die truck-Extrusion es tut). Das ist eine -// bewusste Abweichung vom ursprünglichen Plan ("truckSolid-Dreiecke") zu- -// gunsten der pure-Modul-Architektur — ehrlich dokumentiert, kein -// Stillschweigen. -// -// ACHSEN-KONVENTION: identisch zur bestehenden 3D-Pick-/Highlight-Geometrie -// (siehe `selectionHighlightLines` in toWalls3d.ts): Modell (x, y) → Welt -// (x, Höhe, y), Y-UP, rechtshändig. Ein Weltvertex (vx,vy,vz) entspricht also -// (Modell-x, Meter-Höhe, Modell-y) — exakt wie im 3D-Viewer. +// OBJ-/STL-Export des 3D-Gebäudemodells als reines Dreiecks-Mesh. Gerechnet wird im Rust-Kern +// (`src-tauri/core/src/export_mesh.rs`, [K4] S2) auf dem Projekt-Dokument: +// • Wände: dieselben Schicht-Bänder wie der 3D-Viewer (Gehrungen, Decken-Dominanz); Bänder mit +// Öffnungs-Löchern öffnungsgenau ausgeschnitten (inkl. Laibungen), lochlose als Box. +// • Decken und extrudierte Profile (truck): Umriss-Prisma mit Ear-Clipping-Kappen, Seitenmantel, +// `taper` linear zum Schwerpunkt. (Bewusst nicht die asynchronen truck-Dreiecke: der Export +// bleibt synchron.) +// Achsen: Modell (x, y) → Welt (x, Höhe, y), Y-up, rechtshändig, Meter — wie der 3D-Viewer. -import type { Project, Vec2 } from "../model/types"; -import { getFloor } from "../model/types"; -import { pickGeometry } from "../plan/toWalls3d"; -import type { RWall } from "../plan/toWalls3d"; -import { wallCutMeshes, type CutMesh } from "../plan/wallMeshCut"; -import { triangulate } from "../plan/glPlan/glPlanCompile"; +import type { Project } from "../model/types"; +import { documentFor } from "../core/document"; /** - * Eine Mesh-Gruppe (ein Bauteil-Vorkommen: Wand/Decke/Extrusion) mit LOKALEN - * (0-basierten) Vertex-/Dreiecks-Indizes. `exportObj` verschiebt die Indizes - * beim Serialisieren auf die globale, 1-basierte OBJ-Nummerierung; `exportStl` - * braucht gar keine Indizes über Gruppen hinweg (STL ist unindiziert). - */ -interface MeshGroup { - name: string; - /** Flaches Weltkoordinaten-Array (x,y,z, x,y,z, …), Meter, Y-up. */ - positions: number[]; - /** Dreiecks-Indizes (3 je Dreieck), 0-basiert relativ zu `positions`. */ - indices: number[]; -} - -function newGroup(name: string): MeshGroup { - return { name, positions: [], indices: [] }; -} - -/** OBJ-Gruppennamen dürfen keine Whitespaces/Sonderzeichen enthalten. */ -function sanitizeName(id: string): string { - return id.replace(/[^A-Za-z0-9_-]/g, "_") || "x"; -} - -/** - * Die 6 Quader-Seiten als Eckpunkt-Quadrupel (Index-Bits: bit0=Achse −/+, - * bit1=Höhe −/+, bit2=Dicke −/+ — dieselbe Konvention wie `emitOpeningMeshes`/ - * `selectionHighlightLines` in toWalls3d.ts), in nach AUSSEN gewundener - * Reihenfolge (für ein rechtshändiges Dreibein Achse×Höhe=Dicke-Normale, wie - * es die Wandbox-Konstruktion unten aufspannt). Jedes Quadrupel wird zu 2 - * Dreiecken (0,1,2)+(0,2,3). - */ -const BOX_QUADS: Array<[number, number, number, number]> = [ - [4, 6, 7, 5], // Dicke + - [1, 3, 2, 0], // Dicke − - [2, 3, 7, 6], // Höhe + (Wandkopf) - [4, 5, 1, 0], // Höhe − (Wand-UK) - [1, 5, 7, 3], // Achse + (Wandende) - [2, 6, 4, 0], // Achse − (Wandanfang) -]; - -/** - * Hängt EIN Wand-Schicht-Band (`RWall`, siehe toWalls3d.ts) an eine Mesh-Gruppe - * an: hat das Band echte Öffnungs-`holes`, wird das öffnungsgenaue Loch-Ausschnitt- - * Mesh `cut` (vorab für alle Bänder über {@link wallCutMeshes}) verwendet — die - * Fenster/Türen sind sichtbar ausgestanzt inkl. Laibungen, exakt wie im 3D-Viewer. - * Ohne Löcher bleibt es die klassische, geteilte 8-Ecken-Box ({@link pushWallBox}) - * (Joins/Gehrungen stecken schon in `start`/`end`). - */ -function pushWall(group: MeshGroup, w: RWall, cut: CutMesh | undefined): void { - if (cut) { - const base = group.positions.length / 3; - for (const p of cut.positions) group.positions.push(p); - for (const idx of cut.indices) group.indices.push(base + idx); - return; - } - pushWallBox(group, w); -} - -/** - * Hängt EINEN vollen Wand-Schicht-Quader (`RWall`) an eine Mesh-Gruppe an — Box - * über Achse×Höhe×Dicke, OHNE Öffnungs-Ausschnitt (nur für lochlose Bänder, siehe - * {@link pushWall}). Degenerierte Bänder (Länge/Höhe/Dicke ≤ 0) werden übersprungen. - */ -function pushWallBox(group: MeshGroup, w: RWall): void { - const [sx, sy] = w.start; - const [ex, ey] = w.end; - const dx = ex - sx; - const dz = ey - sy; - const len = Math.hypot(dx, dz); - if (len < 1e-9 || w.height <= 1e-9 || w.thickness <= 1e-9) return; - const ax = dx / len; - const az = dz / len; - // Normale = Welt-Hoch × Achse (rechtshändig), dieselbe Konvention wie - // `selectionHighlightLines`: normal = (az, 0, −ax). - const nx = az; - const nz = -ax; - const halfLen = len / 2; - const halfHeight = w.height / 2; - const halfThick = w.thickness / 2; - const cx = (sx + ex) / 2; - const cz = (sy + ey) / 2; - const cy = w.baseElevation + w.height / 2; - const base = group.positions.length / 3; - for (let i = 0; i < 8; i++) { - const sL = i & 1 ? 1 : -1; - const sH = i & 2 ? 1 : -1; - const sT = i & 4 ? 1 : -1; - group.positions.push( - cx + sL * halfLen * ax + sT * halfThick * nx, - cy + sH * halfHeight, - cz + sL * halfLen * az + sT * halfThick * nz, - ); - } - for (const [a, b, c, d] of BOX_QUADS) { - group.indices.push(base + a, base + b, base + c, base + a, base + c, base + d); - } -} - -/** Signierte Fläche eines Modell-XY-Umrisses (Shoelace); ≥0 = CCW. */ -function signedAreaXY(pts: Vec2[]): number { - let a = 0; - for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { - a += pts[j].x * pts[i].y - pts[i].x * pts[j].y; - } - return a / 2; -} - -/** - * Hängt ein extrudiertes Umriss-Prisma (Decke ODER truck-Profil-Extrusion, - * siehe Moduldoc) an eine Mesh-Gruppe an: Boden-/Deckkappe (Ear-Clipping- - * Triangulierung via `triangulate`) + Seitenmantel. `taper` (0..1) verjüngt - * den OBEREN Ring linear zum Flächenschwerpunkt — dieselbe Semantik wie - * `ExtrudedSolid.taper`/die truck-Extrusion (0 = Prisma, 1 = Spitze/Pyramide). - * Der Umriss wird intern auf CCW (Modell-XY) normalisiert, damit die - * Seitenmantel-Normalen unabhängig von der Eingabe-Wicklung nach außen zeigen. - */ -function pushPrism( - group: MeshGroup, - outline: Vec2[], - zBottom: number, - zTop: number, - taper = 0, -): void { - if (outline.length < 3 || zTop - zBottom <= 1e-9) return; - const ccw = signedAreaXY(outline) >= 0 ? outline : [...outline].reverse(); - const n = ccw.length; - let cx = 0; - let cyModel = 0; - for (const p of ccw) { - cx += p.x; - cyModel += p.y; - } - cx /= n; - cyModel /= n; - const t = Math.min(1, Math.max(0, taper)); - const base = group.positions.length / 3; - // Unterer Ring (base + 0..n-1), oberer Ring (base + n..2n-1). - for (const p of ccw) group.positions.push(p.x, zBottom, p.y); - for (const p of ccw) { - const tx = cx + (p.x - cx) * (1 - t); - const ty = cyModel + (p.y - cyModel) * (1 - t); - group.positions.push(tx, zTop, ty); - } - // Kappen: `triangulate` liefert bei CCW-Eingabe stets CCW-in-Modell-XY- - // Dreiecke — eingebettet in die Weltebene (x, const, y) entspricht das einer - // nach UNTEN (−Y) zeigenden Flächennormale (Kreuzprodukt-Herleitung siehe - // Moduldoc-Kommentar oben). Die Bodenkappe nutzt diese Wicklung direkt - // (Normale zeigt nach unten = nach außen), die Deckkappe braucht die - // umgekehrte Wicklung (Normale nach oben). - const capTris = triangulate(ccw); - for (let i = 0; i < capTris.length; i += 3) { - const a = capTris[i]; - const b = capTris[i + 1]; - const c = capTris[i + 2]; - group.indices.push(base + a, base + b, base + c); - group.indices.push(base + n + a, base + n + c, base + n + b); - } - // Seitenmantel: je Umrisskante ein Quad (2 Dreiecke), Wicklung so, dass die - // Normale nach außen zeigt (siehe Moduldoc-Herleitung). - for (let i = 0; i < n; i++) { - const j = (i + 1) % n; - const bi = base + i; - const bj = base + j; - const ti = base + n + i; - const tj = base + n + j; - group.indices.push(bi, ti, tj); - group.indices.push(bi, tj, bj); - } -} - -/** Baut alle Mesh-Gruppen (Wände, Decken, Extrusionen) des Projekts. */ -function buildGroups(project: Project): MeshGroup[] { - const groups: MeshGroup[] = []; - const { walls, slabs } = pickGeometry(project); - - // Wände: alle Schicht-Bänder DERSELBEN Wand-Id in EINE Gruppe (mehrere - // Materiallagen ergeben mehrere Boxen im selben Bauteil-Vorkommen). - const wallGroups = new Map(); - // Loch-Ausschnitte aller gelochten Bänder in EINEM Kern-Aufruf. - const holed = walls.filter((w) => w.holes && w.holes.length > 0); - const cuts = new Map(); - wallCutMeshes(holed).forEach((m, i) => cuts.set(holed[i], m)); - for (const w of walls) { - let g = wallGroups.get(w.wallId); - if (!g) { - g = newGroup(`Wand_${sanitizeName(w.wallId)}`); - wallGroups.set(w.wallId, g); - groups.push(g); - } - pushWall(g, w, cuts.get(w)); - } - - // Decken: ein Prisma je Decke. - for (const s of slabs) { - const g = newGroup(`Decke_${sanitizeName(s.ceilingId)}`); - const outline: Vec2[] = s.outline.map(([x, y]) => ({ x, y })); - pushPrism(g, outline, s.zBottom, s.zTop); - groups.push(g); - } - - // Extrudierte Profile (truck-Integration): eigenes Prisma je Körper (siehe - // Moduldoc — bewusst NICHT die truck-WASM-Dreiecke, aus Sync-/Pure-Gründen). - for (const solid of project.extrudedSolids ?? []) { - if (solid.points.length < 3 || solid.height <= 0) continue; - let baseZ = 0; - try { - baseZ = getFloor(project, solid.levelId).baseElevation ?? 0; - } catch { - // Geschoss nicht (mehr) auflösbar: bei UK 0 extrudieren (Fallback, wie toWalls3d). - } - const g = newGroup(`Extrusion_${sanitizeName(solid.id)}`); - pushPrism(g, solid.points, baseZ, baseZ + solid.height, solid.taper ?? 0); - groups.push(g); - } - - return groups.filter((g) => g.indices.length > 0); -} - -/** Kompakte, verlustarme Zahlformatierung (bis 6 Nachkommastellen, ohne Nullen). */ -function fmt(v: number): string { - if (!Number.isFinite(v)) return "0.0"; - const s = v.toFixed(6); - return s.replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, ".0"); -} - -/** - * Baut einen vollständigen Wavefront-OBJ-String des 3D-Gebäudemodells (Meter, - * rechtshändig, Y-up — siehe Moduldoc). Ein `o`-Objekt je Bauteil-Vorkommen - * (Wand/Decke/Extrusion). Leeres Projekt ⇒ gültige Datei nur mit Kopf- - * Kommentaren, kein `v`/`f` (kein Crash). + * Vollständiger Wavefront-OBJ-String (Meter, rechtshändig, Y-up). Ein `o`-Objekt je Bauteil- + * Vorkommen. Leeres Projekt ⇒ gültige Datei nur mit Kopf-Kommentaren. */ export function exportObj(project: Project): string { - const groups = buildGroups(project); - const lines: string[] = [ - "# DOSSIER OBJ-Export - Dreiecks-Mesh des 3D-Gebaeudemodells", - "# Achsen: rechtshaendig, Y-up (Y = Hoehe ueber OKFF), wie der 3D-Viewer.", - "# Waende: Schicht-Baender mit oeffnungsgenau ausgeschnittenen Loechern (inkl. Laibungen).", - "# Decken/Extrusionen: Umriss-Prisma (Ear-Clipping-Triangulierung).", - ]; - let offset = 0; - for (const g of groups) { - const vertCount = g.positions.length / 3; - if (vertCount === 0) continue; - lines.push(`o ${g.name}`); - for (let i = 0; i < g.positions.length; i += 3) { - lines.push(`v ${fmt(g.positions[i])} ${fmt(g.positions[i + 1])} ${fmt(g.positions[i + 2])}`); - } - for (let i = 0; i < g.indices.length; i += 3) { - const a = g.indices[i] + 1 + offset; - const b = g.indices[i + 1] + 1 + offset; - const c = g.indices[i + 2] + 1 + offset; - lines.push(`f ${a} ${b} ${c}`); - } - offset += vertCount; - } - return lines.join("\n") + "\n"; + return documentFor(project).queryJson("objFile"); } /** - * Baut einen vollständigen ASCII-STL-String des 3D-Gebäudemodells (Meter, - * dieselbe Achsen-Konvention wie {@link exportObj}). Jedes Dreieck trägt eine - * aus dem Kreuzprodukt berechnete Facettennormale (konsistente Winding, siehe - * `pushWallBox`/`pushPrism`). Leeres Projekt ⇒ gültiges leeres `solid`-Gerüst. + * Vollständiger ASCII-STL-String (Meter, dieselbe Achsen-Konvention). Jedes Dreieck trägt eine aus + * dem Kreuzprodukt berechnete Facettennormale. Leeres Projekt ⇒ gültiges leeres `solid`-Gerüst. */ export function exportStl(project: Project): string { - const groups = buildGroups(project); - const lines: string[] = ["solid dossier"]; - for (const g of groups) { - for (let i = 0; i < g.indices.length; i += 3) { - const ia = g.indices[i] * 3; - const ib = g.indices[i + 1] * 3; - const ic = g.indices[i + 2] * 3; - const ax = g.positions[ia]; - const ay = g.positions[ia + 1]; - const az = g.positions[ia + 2]; - const bx = g.positions[ib]; - const by = g.positions[ib + 1]; - const bz = g.positions[ib + 2]; - const cx = g.positions[ic]; - const cy = g.positions[ic + 1]; - const cz = g.positions[ic + 2]; - const ux = bx - ax; - const uy = by - ay; - const uz = bz - az; - const vx = cx - ax; - const vy = cy - ay; - const vz = cz - az; - let nx = uy * vz - uz * vy; - let ny = uz * vx - ux * vz; - let nz = ux * vy - uy * vx; - const len = Math.hypot(nx, ny, nz); - if (len > 1e-12) { - nx /= len; - ny /= len; - nz /= len; - } else { - nx = 0; - ny = 0; - nz = 0; - } - lines.push(`facet normal ${fmt(nx)} ${fmt(ny)} ${fmt(nz)}`); - lines.push("outer loop"); - lines.push(`vertex ${fmt(ax)} ${fmt(ay)} ${fmt(az)}`); - lines.push(`vertex ${fmt(bx)} ${fmt(by)} ${fmt(bz)}`); - lines.push(`vertex ${fmt(cx)} ${fmt(cy)} ${fmt(cz)}`); - lines.push("endloop"); - lines.push("endfacet"); - } - } - lines.push("endsolid dossier"); - return lines.join("\n") + "\n"; + return documentFor(project).queryJson("stlFile"); } From e02c01d3a5f81b1f9ae2fe42ea95c262930ee2b0 Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 02:27:03 +0100 Subject: [PATCH 29/31] [K4] Projektdatei-Format (Parser, Migration, Serialisierung) in Rust (project_format.rs); projectFormat.ts nur noch Fassade --- src-tauri/core/src/document.rs | 5 + src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/project_format.rs | 261 +++++++++++++++++++++++ src-tauri/core/src/web/document.rs | 6 + src-tauri/core/src/web/mod.rs | 1 + src-tauri/core/src/web/project_format.rs | 22 ++ src/core/document.ts | 5 + src/io/projectFormat.test.ts | 4 + src/io/projectFormat.ts | 132 ++---------- 9 files changed, 317 insertions(+), 120 deletions(-) create mode 100644 src-tauri/core/src/project_format.rs create mode 100644 src-tauri/core/src/web/project_format.rs diff --git a/src-tauri/core/src/document.rs b/src-tauri/core/src/document.rs index b9693ce2..af21c18b 100644 --- a/src-tauri/core/src/document.rs +++ b/src-tauri/core/src/document.rs @@ -107,6 +107,11 @@ impl Document { } } + /// Datei-Text des Projekts (`serializeProject`): Formatversion vorn, Einrückung 2. + pub fn serialize(&self) -> String { + crate::project_format::serialize_project(&self.root) + } + pub fn to_json(&self) -> String { serde_json::to_string(&self.root).unwrap_or_default() } diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 70f0203a..1ebb942c 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -38,6 +38,7 @@ pub mod jsnum; pub mod hatch; pub mod hatch_flat; pub mod plan_buf; +pub mod project_format; pub mod queries; pub mod gpu_compile; pub mod plan_stairs; diff --git a/src-tauri/core/src/project_format.rs b/src-tauri/core/src/project_format.rs new file mode 100644 index 00000000..4f1076c0 --- /dev/null +++ b/src-tauri/core/src/project_format.rs @@ -0,0 +1,261 @@ +//! Projektdatei-Format (`.obp`/`.obpt`/Alt-`.json`) ([K4] S4-Vorarbeit, vorher +//! `src/io/projectFormat.ts`): Versionierung, Migration und EIN Parser für alle Ladestellen. +//! +//! Regeln: jede gespeicherte Datei trägt `formatVersion`; ältere Dateien (auch ohne = Version 0) +//! laufen durch die Migrationskette; neuere werden mit klarer Meldung ABGELEHNT; tolerant gelesen +//! (fehlende Listen leer ergänzt, unbekannte Felder bleiben erhalten und werden gemeldet). Alles +//! arbeitet auf dem rohen JSON-Baum — das Modell wird erst danach typisiert. + +use serde_json::{Map, Value}; + +/// Aktuelle Version des Dateiformats. Bei jeder Formatänderung erhöhen + Migration anhängen. +pub const PROJECT_FORMAT_VERSION: u64 = 2; + +const REQUIRED_ARRAYS: [&str; 3] = ["walls", "layers", "drawingLevels"]; +const DEFAULT_ARRAYS: [&str; 5] = ["lineStyles", "hatches", "components", "wallTypes", "drawings2d"]; + +/// Bekannte Felder von `Project` (für die Meldung unbekannter Felder). +const KNOWN_KEYS: [&str; 46] = [ + "formatVersion", "id", "name", "lineStyles", "textStyles", "hatches", "components", "wallTypes", + "ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens", + "penSets", "activePenSetId", "customPalettes", "builtinPaletteBanks", "drawingLevels", "layers", + "walls", "ceilings", "roofs", "openings", "stairs", "rooms", "drawings2d", "context", + "extrudedSolids", "columns", "groups", "parametricWalls", "overrideRules", "viewSnapshots", + "viewSnapshotFolders", "layouts", "masterLayouts", "layoutFolders", "referenceElevationMasl", + "geoAnchor", "roomProgram", "parcelArea", "sunStudy", "siteRules", "scaleLineWeights", +]; + +/// Ergebnis des Einlesens. +#[derive(Debug, PartialEq)] +pub enum Parsed { + Ok { project: Map, warnings: Vec, migrated_from: Option }, + Err(String), +} + +/// JS-`String(v)` für die Meldungen. +fn js_string(v: &Value) -> String { + match v { + Value::Null => "null".into(), + Value::Bool(b) => b.to_string(), + Value::Number(n) => n.as_f64().map_or(n.to_string(), |f| if f.fract() == 0.0 && f.abs() < 1e21 { format!("{}", f as i64) } else { f.to_string() }), + Value::String(s) => s.clone(), + Value::Array(a) => a.iter().map(|x| if x.is_null() { String::new() } else { js_string(x) }).collect::>().join(","), + Value::Object(_) => "[object Object]".into(), + } +} + +/// 1 → 2: Legacy-Türen (`doors`) werden zu Öffnungen (`openings`, kind `door`). +fn migrate_doors(mut raw: Map) -> Map { + let doors: Vec = raw.get("doors").and_then(Value::as_array).cloned().unwrap_or_default(); + raw.shift_remove("doors"); + if doors.is_empty() { + return raw; + } + let mut openings: Vec = raw.get("openings").and_then(Value::as_array).cloned().unwrap_or_default(); + let mut taken: std::collections::HashSet = openings.iter().map(|o| o.get("id").map_or("undefined".to_string(), js_string)).collect(); + let door_type_id = raw + .get("doorTypes") + .and_then(Value::as_array) + .and_then(|a| a.first()) + .and_then(|t| t.get("id")) + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + for d in &doors { + let mut id = d.get("id").map_or("undefined".to_string(), js_string); + while taken.contains(&id) { + id = format!("{id}-t"); + } + taken.insert(id.clone()); + let mut o = Map::new(); + o.insert("id".into(), Value::String(id)); + o.insert("type".into(), "opening".into()); + for (k, src) in [("hostWallId", "hostWallId"), ("categoryCode", "categoryCode")] { + if let Some(v) = d.get(src) { + o.insert(k.into(), v.clone()); + } + } + o.insert("kind".into(), "door".into()); + for k in ["position", "width", "height"] { + if let Some(v) = d.get(k) { + o.insert(k.into(), v.clone()); + } + } + o.insert("sillHeight".into(), 0.into()); + for k in ["swing", "hinge"] { + if let Some(v) = d.get(k) { + o.insert(k.into(), v.clone()); + } + } + if let Some(t) = &door_type_id { + o.insert("typeId".into(), Value::String(t.clone())); + } + openings.push(Value::Object(o)); + } + raw.insert("openings".into(), Value::Array(openings)); + raw +} + +/// Liest eine Projektdatei (Text) tolerant ein, migriert und prüft sie. `now_ms`: Zeitpunkt für +/// eine Ersatz-ID, falls die Datei keine trägt. +pub fn parse_project_file(text: &str, now_ms: f64) -> Parsed { + match serde_json::from_str::(text) { + Ok(raw) => parse_project_object(raw, now_ms), + Err(e) => Parsed::Err(format!("Die Datei ist kein gültiges JSON ({e}).")), + } +} + +/// Wie [`parse_project_file`], für ein bereits geparstes Objekt. +pub fn parse_project_object(raw: Value, now_ms: f64) -> Parsed { + let Value::Object(mut obj) = raw else { return Parsed::Err("Die Datei enthält kein Dossier-Projekt.".into()) }; + let mut warnings: Vec = Vec::new(); + + let mut version: u64 = 0; + if let Some(v) = obj.get("formatVersion") { + match v.as_f64() { + Some(f) if f.fract() == 0.0 && f >= 0.0 => version = f as u64, + _ => return Parsed::Err(format!("Ungültige Formatversion „{}\".", js_string(v))), + } + } + if version > PROJECT_FORMAT_VERSION { + return Parsed::Err(format!( + "Die Datei wurde mit einer neueren Dossier-Version gespeichert (Format {version}, dieses Programm kennt bis {PROJECT_FORMAT_VERSION}). Bitte Dossier aktualisieren." + )); + } + for key in REQUIRED_ARRAYS { + if !obj.get(key).is_some_and(Value::is_array) { + return Parsed::Err(format!("Die Datei enthält kein Dossier-Projekt (Liste „{key}\" fehlt).")); + } + } + + let migrated_from = (version < PROJECT_FORMAT_VERSION).then_some(version); + for i in version..PROJECT_FORMAT_VERSION { + obj = match i { + 1 => migrate_doors(obj), + _ => obj, // 0 → 1: Einführung von `formatVersion`; Inhalt unverändert. + }; + } + obj.insert("formatVersion".into(), PROJECT_FORMAT_VERSION.into()); + + for key in DEFAULT_ARRAYS { + match obj.get(key) { + None => { + obj.insert(key.into(), Value::Array(vec![])); + } + Some(Value::Array(_)) => {} + Some(_) => { + warnings.push(format!("Feld „{key}\" ist keine Liste und wurde geleert.")); + obj.insert(key.into(), Value::Array(vec![])); + } + } + } + if !obj.get("id").and_then(Value::as_str).is_some_and(|s| !s.is_empty()) { + obj.insert("id".into(), Value::String(format!("project-{}", to_base36(now_ms.max(0.0) as u64)))); + } + if !obj.get("name").is_some_and(Value::is_string) { + obj.insert("name".into(), Value::String(String::new())); + } + let unknown: Vec<&str> = obj.keys().map(String::as_str).filter(|k| !KNOWN_KEYS.contains(k)).collect(); + if !unknown.is_empty() { + warnings.push(format!("Unbekannte Felder behalten: {}.", unknown.join(", "))); + } + Parsed::Ok { project: obj, warnings, migrated_from } +} + +fn to_base36(mut n: u64) -> String { + if n == 0 { + return "0".into(); + } + let mut digits = Vec::new(); + while n > 0 { + digits.push(b"0123456789abcdefghijklmnopqrstuvwxyz"[(n % 36) as usize]); + n /= 36; + } + digits.reverse(); + String::from_utf8(digits).expect("ASCII") +} + +/// Serialisiert ein Projekt für die Datei: aktuelle Formatversion vorne, Einrückung 2. +pub fn serialize_project(project: &Map) -> String { + let mut out = Map::new(); + out.insert("formatVersion".into(), PROJECT_FORMAT_VERSION.into()); + for (k, v) in project { + if k != "formatVersion" { + out.insert(k.clone(), v.clone()); + } + } + serde_json::to_string_pretty(&Value::Object(out)).unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn minimal() -> Value { + json!({"id":"p","name":"N","walls":[],"layers":[],"drawingLevels":[]}) + } + + #[test] + fn alte_datei_wird_migriert_und_ergaenzt() { + let Parsed::Ok { project, warnings, migrated_from } = parse_project_object(minimal(), 0.0) else { panic!() }; + assert_eq!(migrated_from, Some(0)); + assert_eq!(project["formatVersion"], 2); + assert_eq!(project["lineStyles"], json!([])); + assert!(warnings.is_empty()); + } + + #[test] + fn neuere_und_kaputte_dateien_werden_abgelehnt() { + let mut v = minimal(); + v["formatVersion"] = json!(99); + assert!(matches!(parse_project_object(v, 0.0), Parsed::Err(m) if m.contains("neueren"))); + let mut v = minimal(); + v["formatVersion"] = json!("x"); + assert_eq!(parse_project_object(v, 0.0), Parsed::Err("Ungültige Formatversion „x\".".into())); + assert!(matches!(parse_project_object(json!([1]), 0.0), Parsed::Err(_))); + assert!(matches!(parse_project_object(json!({"walls":[]}), 0.0), Parsed::Err(m) if m.contains("layers"))); + assert!(matches!(parse_project_file("{", 0.0), Parsed::Err(m) if m.starts_with("Die Datei ist kein gültiges JSON"))); + } + + #[test] + fn tueren_werden_zu_oeffnungen() { + let mut v = minimal(); + v["doors"] = json!([{"id":"D1","hostWallId":"W","categoryCode":"21","position":1,"width":0.9,"height":2,"swing":"left","hinge":"start"},{"id":"O1","hostWallId":"W","position":0,"width":1,"height":2}]); + v["openings"] = json!([{"id":"O1"}]); + v["doorTypes"] = json!([{"id":"dt"}]); + let Parsed::Ok { project, .. } = parse_project_object(v, 0.0) else { panic!() }; + assert!(!project.contains_key("doors")); + let o = project["openings"].as_array().unwrap(); + assert_eq!(o.len(), 3); + assert_eq!(o[1]["id"], "D1"); + assert_eq!(o[1]["kind"], "door"); + assert_eq!(o[1]["typeId"], "dt"); + assert_eq!(o[2]["id"], "O1-t"); + } + + #[test] + fn unbekannte_felder_bleiben_und_werden_gemeldet() { + let mut v = minimal(); + v["zukunft"] = json!(1); + v["hatches"] = json!("kaputt"); + let Parsed::Ok { project, warnings, .. } = parse_project_object(v, 0.0) else { panic!() }; + assert_eq!(project["zukunft"], 1); + assert_eq!(warnings.len(), 2); + } + + #[test] + fn ersatz_id_aus_zeit() { + let mut v = minimal(); + v["id"] = json!(""); + let Parsed::Ok { project, .. } = parse_project_object(v, 36.0 * 36.0 + 5.0) else { panic!() }; + assert_eq!(project["id"], "project-105"); + } + + #[test] + fn serialisierung_setzt_version_nach_vorn() { + let Value::Object(m) = minimal() else { panic!() }; + let s = serialize_project(&m); + assert!(s.starts_with("{\n \"formatVersion\": 2,\n \"id\": \"p\"")); + } +} diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index f68b8657..47a4972b 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -104,3 +104,9 @@ pub fn doc_export_ifc(h: u32, now_ms: f64) -> String { Err(e) => format!("\u{1}{e}"), } } + +/// Das Projekt als Datei-Text (Formatversion vorn, Einrückung 2); leer, wenn das Dokument nicht offen ist. +#[wasm_bindgen] +pub fn doc_serialize(h: u32) -> String { + with_doc(h, |d| d.serialize()).unwrap_or_default() +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index d48a1dee..c519e2a1 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -19,6 +19,7 @@ mod polygon_holes; mod drawing2d_3d; mod wall_mesh_cut; mod plan_buf; +mod project_format; mod gpu_compile; mod plan_stairs; mod plan_walls; diff --git a/src-tauri/core/src/web/project_format.rs b/src-tauri/core/src/web/project_format.rs new file mode 100644 index 00000000..73277525 --- /dev/null +++ b/src-tauri/core/src/web/project_format.rs @@ -0,0 +1,22 @@ +//! Bindungen des Projektdatei-Formats (`crate::project_format`). + +use crate::project_format::{parse_project_file, Parsed}; +use serde_json::{json, Value}; +use wasm_bindgen::prelude::wasm_bindgen; + +/// Liest eine Projektdatei (Text). Antwort als JSON: +/// `{"ok":true,"project":{…},"warnings":[…],"migratedFrom":null|n}` oder `{"ok":false,"error":"…"}`. +#[wasm_bindgen] +pub fn project_parse(text: &str, now_ms: f64) -> String { + let v: Value = match parse_project_file(text, now_ms) { + Parsed::Ok { project, warnings, migrated_from } => json!({"ok": true, "project": project, "warnings": warnings, "migratedFrom": migrated_from}), + Parsed::Err(error) => json!({"ok": false, "error": error}), + }; + v.to_string() +} + +/// Aktuelle Version des Dateiformats. +#[wasm_bindgen] +pub fn project_format_version() -> u32 { + crate::project_format::PROJECT_FORMAT_VERSION as u32 +} diff --git a/src/core/document.ts b/src/core/document.ts index d5a7e116..f75b3875 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -94,6 +94,11 @@ export class ProjectDocument { return out; } + /** Datei-Text des Projekts (Formatversion vorn, Einrückung 2). */ + serialize(): string { + return this.handle ? core().doc_serialize(this.handle) : ""; + } + /** Boden-Spuren der 2D-Zeichnungen als LineList-Vertices `[px, py, pz, r, g, b]`. */ drawingLineVerts(): Float32Array { return this.handle ? core().doc_drawing_line_verts(this.handle) : new Float32Array(0); diff --git a/src/io/projectFormat.test.ts b/src/io/projectFormat.test.ts index 3d47cff6..6831c7f7 100644 --- a/src/io/projectFormat.test.ts +++ b/src/io/projectFormat.test.ts @@ -1,8 +1,12 @@ import { describe, expect, it } from "vitest"; import { sampleProject } from "../model/sampleProject"; +import { core } from "../engine/coreWasm"; import { parseProjectFile, PROJECT_FORMAT_VERSION, serializeProject } from "./projectFormat"; describe("Projektdatei-Format", () => { + it("Formatversion in TS und Kern stimmt überein", () => { + expect(core().project_format_version()).toBe(PROJECT_FORMAT_VERSION); + }); it("Speichern setzt die Formatversion, Laden liefert dasselbe Projekt zurueck", () => { const text = serializeProject(sampleProject); expect(JSON.parse(text).formatVersion).toBe(PROJECT_FORMAT_VERSION); diff --git a/src/io/projectFormat.ts b/src/io/projectFormat.ts index f8bfc25d..0468be39 100644 --- a/src/io/projectFormat.ts +++ b/src/io/projectFormat.ts @@ -1,145 +1,37 @@ -// Projektdatei-Format (`.obp`/`.obpt`/Alt-`.json`): Versionierung, Migration und EIN -// Parser für alle Ladestellen. +// Projektdatei-Format (`.obp`/`.obpt`/Alt-`.json`): Versionierung, Migration und EIN Parser für alle +// Ladestellen. Gerechnet wird im Rust-Kern (`src-tauri/core/src/project_format.rs`, [K4]). // // Regeln: // • Jede gespeicherte Datei trägt `formatVersion` (s. {@link PROJECT_FORMAT_VERSION}). // • Ältere Dateien (auch ohne `formatVersion` = Version 0) laufen durch die Migrationskette. -// • Neuere Dateien werden mit klarer Meldung ABGELEHNT (ein altes Programm würde Felder, die -// es nicht kennt, beim nächsten Speichern verlieren). +// • Neuere Dateien werden mit klarer Meldung ABGELEHNT (ein altes Programm würde Felder, die es +// nicht kennt, beim nächsten Speichern verlieren). // • Tolerant lesen: fehlende Listen werden leer ergänzt, unbekannte Felder bleiben erhalten und -// werden gemeldet (nicht gelöscht — die Liste bekannter Felder kann hinter dem Typ -// zurückliegen, Löschen wäre dann Datenverlust). -// • Was kein Dossier-Projekt ist (kein JSON-Objekt, keine Wände/Ebenen/Geschossliste), ist ein -// Fehler mit Meldung — nie ein stilles `console.warn`. +// werden gemeldet (nicht gelöscht). +// • Was kein Dossier-Projekt ist, ist ein Fehler mit Meldung — nie ein stilles `console.warn`. import type { Project } from "../model/types"; +import { core } from "../engine/coreWasm"; +import { documentFor } from "../core/document"; -/** Aktuelle Version des Dateiformats. Bei jeder Formatänderung erhöhen + Migration anhängen. */ +/** Aktuelle Version des Dateiformats (muss `PROJECT_FORMAT_VERSION` im Kern entsprechen — Test). */ export const PROJECT_FORMAT_VERSION = 2; -/** - * Migrationen: `MIGRATIONS[i]` hebt eine Datei von Version `i` auf `i + 1`. Arbeitet auf dem - * rohen JSON-Objekt (kopiert, nie das Original verändern). - */ -const MIGRATIONS: Array<(raw: Record) => Record> = [ - // 0 → 1: Einführung von `formatVersion`; Inhalt unverändert. - (raw) => raw, - // 1 → 2: Legacy-Türen (`doors`) werden zu Öffnungen (`openings`, kind "door"). Es gibt nur noch - // EINEN Datensatz-Typ für Türen und Fenster. - (raw) => { - const doors = Array.isArray(raw.doors) ? (raw.doors as Array>) : []; - const { doors: _drop, ...rest } = raw; - if (doors.length === 0) return rest; - const openings = Array.isArray(rest.openings) ? [...(rest.openings as Array>)] : []; - const taken = new Set(openings.map((o) => String(o.id))); - const doorTypes = Array.isArray(rest.doorTypes) ? (rest.doorTypes as Array<{ id?: string }>) : []; - for (const d of doors) { - let id = String(d.id); - while (taken.has(id)) id = `${id}-t`; - taken.add(id); - openings.push({ - id, - type: "opening", - hostWallId: d.hostWallId, - categoryCode: d.categoryCode, - kind: "door", - position: d.position, - width: d.width, - height: d.height, - sillHeight: 0, - swing: d.swing, - hinge: d.hinge, - ...(doorTypes[0]?.id ? { typeId: doorTypes[0].id } : {}), - }); - } - return { ...rest, openings }; - }, -]; - -/** Pflichtlisten: fehlen sie, ist es kein Dossier-Projekt. */ -const REQUIRED_ARRAYS = ["walls", "layers", "drawingLevels"] as const; -/** Listen, die bei Fehlen leer ergänzt werden. */ -const DEFAULT_ARRAYS = ["lineStyles", "hatches", "components", "wallTypes", "drawings2d"] as const; - -/** Bekannte Felder von `Project` (für die Meldung unbekannter Felder). */ -const KNOWN_KEYS = new Set([ - "formatVersion", "id", "name", "lineStyles", "textStyles", "hatches", "components", "wallTypes", - "ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens", - "penSets", "activePenSetId", "customPalettes", "builtinPaletteBanks", "drawingLevels", "layers", - "walls", "ceilings", "roofs", "openings", "stairs", "rooms", "drawings2d", "context", - "extrudedSolids", "columns", "groups", "parametricWalls", "overrideRules", "viewSnapshots", - "viewSnapshotFolders", "layouts", "masterLayouts", "layoutFolders", "referenceElevationMasl", - "geoAnchor", "roomProgram", "parcelArea", "sunStudy", "siteRules", "scaleLineWeights", -]); - export type ParseProjectResult = | { ok: true; project: Project; warnings: string[]; migratedFrom: number | null } | { ok: false; error: string }; /** Liest eine Projektdatei (Text) tolerant ein, migriert und prüft sie. */ export function parseProjectFile(text: string): ParseProjectResult { - let raw: unknown; - try { - raw = JSON.parse(text); - } catch (e) { - return { ok: false, error: `Die Datei ist kein gültiges JSON (${e instanceof Error ? e.message : String(e)}).` }; - } - return parseProjectObject(raw); + return JSON.parse(core().project_parse(text, Date.now())) as ParseProjectResult; } /** Wie {@link parseProjectFile}, für ein bereits geparstes Objekt. */ export function parseProjectObject(raw: unknown): ParseProjectResult { - if (raw === null || typeof raw !== "object" || Array.isArray(raw)) { - return { ok: false, error: "Die Datei enthält kein Dossier-Projekt." }; - } - let obj = { ...(raw as Record) }; - const warnings: string[] = []; - - const v = obj.formatVersion; - let version = 0; - if (v !== undefined) { - if (typeof v !== "number" || !Number.isInteger(v) || v < 0) { - return { ok: false, error: `Ungültige Formatversion „${String(v)}".` }; - } - version = v; - } - if (version > PROJECT_FORMAT_VERSION) { - return { - ok: false, - error: - `Die Datei wurde mit einer neueren Dossier-Version gespeichert (Format ${version}, ` + - `dieses Programm kennt bis ${PROJECT_FORMAT_VERSION}). Bitte Dossier aktualisieren.`, - }; - } - - for (const key of REQUIRED_ARRAYS) { - if (!Array.isArray(obj[key])) { - return { ok: false, error: `Die Datei enthält kein Dossier-Projekt (Liste „${key}" fehlt).` }; - } - } - - const migratedFrom = version < PROJECT_FORMAT_VERSION ? version : null; - for (let i = version; i < PROJECT_FORMAT_VERSION; i++) obj = MIGRATIONS[i]({ ...obj }); - obj.formatVersion = PROJECT_FORMAT_VERSION; - - for (const key of DEFAULT_ARRAYS) { - if (obj[key] === undefined) obj[key] = []; - else if (!Array.isArray(obj[key])) { - warnings.push(`Feld „${key}" ist keine Liste und wurde geleert.`); - obj[key] = []; - } - } - if (typeof obj.id !== "string" || !obj.id) obj.id = `project-${Date.now().toString(36)}`; - if (typeof obj.name !== "string") obj.name = ""; - - const unknown = Object.keys(obj).filter((k) => !KNOWN_KEYS.has(k)); - if (unknown.length) warnings.push(`Unbekannte Felder behalten: ${unknown.join(", ")}.`); - - return { ok: true, project: obj as unknown as Project, warnings, migratedFrom }; + return parseProjectFile(JSON.stringify(raw ?? null)); } /** Serialisiert ein Projekt für die Datei (mit aktueller Formatversion vorne). */ export function serializeProject(project: Project): string { - const { formatVersion: _old, ...rest } = project as Project & { formatVersion?: number }; - return JSON.stringify({ formatVersion: PROJECT_FORMAT_VERSION, ...rest }, null, 2); + return documentFor(project).serialize(); } From af0e0fc49bec4fd7eb82825262f8185ec27ad643 Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 02:28:41 +0100 Subject: [PATCH 30/31] [K4] Modell: unbekannte Enum-Werte lesen sich als Unknown statt das Projekt abzulehnen --- scripts/gen-rust-model.py | 2 + src-tauri/core/src/export_ifc.rs | 3 +- src-tauri/core/src/export_schedule.rs | 1 + src-tauri/core/src/kennzahlen.rs | 1 + src-tauri/core/src/model/generated.rs | 104 ++++++++++++++++++++++++++ src-tauri/core/src/model/helpers.rs | 4 +- src-tauri/core/src/model3d.rs | 1 + 7 files changed, 113 insertions(+), 3 deletions(-) diff --git a/scripts/gen-rust-model.py b/scripts/gen-rust-model.py index db536a76..3db271ef 100644 --- a/scripts/gen-rust-model.py +++ b/scripts/gen-rust-model.py @@ -156,6 +156,8 @@ def rust_enum(name, lits): seen.add(v) lines.append(f' #[serde(rename = {json.dumps(l, ensure_ascii=False)})]\n {v},') lines[0] = " #[default]\n" + lines[0] + # Unbekannte Werte (ältere/neuere Dateien) lesen sich als `Unknown`, statt das ganze Projekt abzulehnen. + lines.append(" #[serde(other)]\n Unknown,") return ("#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]\n" f"pub enum {name} {{\n" + "\n".join(lines) + "\n}\n") diff --git a/src-tauri/core/src/export_ifc.rs b/src-tauri/core/src/export_ifc.rs index 522a8e7a..daae0f98 100644 --- a/src-tauri/core/src/export_ifc.rs +++ b/src-tauri/core/src/export_ifc.rs @@ -564,7 +564,7 @@ pub fn export_ifc_spf(project_in: &Project, now_ms: f64) -> Result en("STRAIGHT_RUN_STAIR"), StairShape::Spiral => en("SPIRAL_STAIR"), - StairShape::L => en("QUARTER_TURN_STAIR"), + _ => en("QUARTER_TURN_STAIR"), }; let entity = emit_building_element!("IFCSTAIR", ifc_guid(&stair.id), "Treppe".to_string(), placement, shape, Some(predefined)); add_to_containment(structure.entity_id, entity); @@ -650,6 +650,7 @@ pub fn export_ifc_spf(project_in: &Project, now_ms: f64) -> Result "HIP_ROOF", RoofShape::Mansarde => "MANSARD_ROOF", RoofShape::Zelt => "HIPPED_GABLE_ROOF", + RoofShape::Unknown => "NOTDEFINED", }; let roof_type = roof.roof_type_id.as_deref().and_then(|id| p.roof_types.as_deref()?.iter().find(|t| t.id == id)); let name = roof_type.map_or("Dach".to_string(), |t| t.name.clone()); diff --git a/src-tauri/core/src/export_schedule.rs b/src-tauri/core/src/export_schedule.rs index 8f595905..7bb71a5b 100644 --- a/src-tauri/core/src/export_schedule.rs +++ b/src-tauri/core/src/export_schedule.rs @@ -157,6 +157,7 @@ fn shape_name(s: RoofShape) -> &'static str { RoofShape::Walm => "walm", RoofShape::Mansarde => "mansarde", RoofShape::Zelt => "zelt", + RoofShape::Unknown => "", } } diff --git a/src-tauri/core/src/kennzahlen.rs b/src-tauri/core/src/kennzahlen.rs index 7c2e6f0c..1d9de994 100644 --- a/src-tauri/core/src/kennzahlen.rs +++ b/src-tauri/core/src/kennzahlen.rs @@ -170,6 +170,7 @@ fn category_index(c: SiaCategory) -> usize { SiaCategory::FF => 3, SiaCategory::KGF => 4, SiaCategory::AGF => 5, + SiaCategory::Unknown => CATEGORIES, // zählt nicht } } diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs index 757552be..f696979c 100644 --- a/src-tauri/core/src/model/generated.rs +++ b/src-tauri/core/src/model/generated.rs @@ -13,6 +13,8 @@ pub enum LineStyleKind { Zigzag, #[serde(rename = "custom")] Custom, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -96,6 +98,8 @@ pub enum HatchStyleKind { Image, #[serde(rename = "gradient")] Gradient, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -105,6 +109,8 @@ pub enum HatchStyleLines { Parallel, #[serde(rename = "random")] Random, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -127,6 +133,8 @@ pub enum HatchStyleGradientType { Linear, #[serde(rename = "radial")] Radial, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -155,6 +163,8 @@ pub enum HatchPattern { Crosshatch, #[serde(rename = "custom")] Custom, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -317,6 +327,8 @@ pub enum DoorTypeKind { Schiebe, #[serde(rename = "wandoeffnung")] Wandoeffnung, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -328,6 +340,8 @@ pub enum DoorTypeLeafStyle { Kassette, #[serde(rename = "glas")] Glas, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -337,6 +351,8 @@ pub enum DoorTypeFrameKind { Zarge, #[serde(rename = "blockrahmen")] Blockrahmen, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -348,6 +364,8 @@ pub enum FrameCornerJoin { Horizontal, #[serde(rename = "gehrung")] Gehrung, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -357,6 +375,8 @@ pub enum DoorTypeInsetFace { Aussen, #[serde(rename = "innen")] Innen, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -414,6 +434,8 @@ pub enum OpeningKind { Fest, #[serde(rename = "schiebe")] Schiebe, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -423,6 +445,8 @@ pub enum SashDefKind { Fluegel, #[serde(rename = "pfosten")] Pfosten, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -432,6 +456,8 @@ pub enum SashDefHingeSide { Left, #[serde(rename = "right")] Right, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -461,6 +487,8 @@ pub enum WindowShadingKind { Raffstore, #[serde(rename = "markise")] Markise, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -492,6 +520,8 @@ pub enum WindowTypeGlazing { Zweifach, #[serde(rename = "dreifach")] Dreifach, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -501,6 +531,8 @@ pub enum WindowTypeInsetFace { Aussen, #[serde(rename = "innen")] Innen, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -512,6 +544,8 @@ pub enum WindowTypeSillLineFaces { Innen, #[serde(rename = "beide")] Beide, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -521,6 +555,8 @@ pub enum WindowTypeSillLineView { Auf, #[serde(rename = "unter")] Unter, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -543,6 +579,8 @@ pub enum WindowTypeSillBoard { Aussen, #[serde(rename = "beide")] Beide, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -607,6 +645,8 @@ pub enum StairTypeStructure { Aufgesattelt, #[serde(rename = "spindel")] Spindel, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -620,6 +660,8 @@ pub enum StairTypeRailing { Rechts, #[serde(rename = "beide")] Beide, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -708,6 +750,8 @@ pub enum DrawingLevelKind { Elevation, #[serde(rename = "drawing")] Drawing, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -757,6 +801,8 @@ pub enum SiaCategory { KGF, #[serde(rename = "AGF")] AGF, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -834,6 +880,8 @@ pub enum AttributeSource { Layer, #[serde(rename = "object")] Object, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -845,6 +893,8 @@ pub enum WallReferenceLine { Center, #[serde(rename = "right")] Right, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -856,6 +906,8 @@ pub enum SliceTermination { Below, #[serde(rename = "above")] Above, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -979,6 +1031,8 @@ pub enum RoofShape { Mansarde, #[serde(rename = "zelt")] Zelt, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -990,6 +1044,8 @@ pub enum RoofMansardType { Walm, #[serde(rename = "zelt")] Zelt, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -999,6 +1055,8 @@ pub enum RoofRidgeAxis { X, #[serde(rename = "y")] Y, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -1049,6 +1107,8 @@ pub enum ElementKind { Window, #[serde(rename = "door")] Door, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1058,6 +1118,8 @@ pub enum OpeningDoorType { Normal, #[serde(rename = "wandoeffnung")] Wandoeffnung, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1067,6 +1129,8 @@ pub enum OpeningHinge { Start, #[serde(rename = "end")] End, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1076,6 +1140,8 @@ pub enum SwingSide { Left, #[serde(rename = "right")] Right, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1085,6 +1151,8 @@ pub enum OpeningOpeningDir { In, #[serde(rename = "out")] Out, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1098,6 +1166,8 @@ pub enum OpeningLintelLines { Aussen, #[serde(rename = "beide")] Beide, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1109,6 +1179,8 @@ pub enum DetailLevel { Mittel, #[serde(rename = "fein")] Fein, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -1184,6 +1256,8 @@ pub enum StairShape { L, #[serde(rename = "spiral")] Spiral, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1195,6 +1269,8 @@ pub enum StairReferenz { Mitte, #[serde(rename = "rechts")] Rechts, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1204,6 +1280,8 @@ pub enum StairArrowStyle { Line, #[serde(rename = "filled")] Filled, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -1273,6 +1351,8 @@ pub enum Align { Center, #[serde(rename = "right")] Right, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -1369,6 +1449,8 @@ pub enum EndMark { Tick, #[serde(rename = "square")] Square, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -1589,6 +1671,8 @@ pub enum OverrideConditionType { LayerName, #[serde(rename = "object_name")] ObjectName, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1602,6 +1686,8 @@ pub enum OverrideOperator { StartsWith, #[serde(rename = "not_equals")] NotEquals, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -1646,6 +1732,8 @@ pub enum ViewType { Grundriss, #[serde(rename = "perspektive")] Perspektive, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1671,6 +1759,8 @@ pub enum View3d { IsoBackLeft, #[serde(rename = "perspective")] Perspective, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -1748,6 +1838,8 @@ pub enum LayoutPaperFormat { B5, #[serde(rename = "b6")] B6, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -1757,6 +1849,8 @@ pub enum LayoutOrientation { Portrait, #[serde(rename = "landscape")] Landscape, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -1848,6 +1942,8 @@ pub enum LayoutFolderKind { Layout, #[serde(rename = "master")] Master, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -1986,6 +2082,8 @@ pub enum GridRuleDirections { Y, #[serde(rename = "both")] Both, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -2015,6 +2113,8 @@ pub enum ModuleRuleDirection { X, #[serde(rename = "y")] Y, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -2042,6 +2142,8 @@ pub enum ConditionalThicknessRuleLogic { And, #[serde(rename = "or")] Or, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] @@ -2098,6 +2200,8 @@ pub enum ContourCurveKind { Circle, #[serde(rename = "arc")] Arc, + #[serde(other)] + Unknown, } #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] diff --git a/src-tauri/core/src/model/helpers.rs b/src-tauri/core/src/model/helpers.rs index 3a44c458..8ab1042c 100644 --- a/src-tauri/core/src/model/helpers.rs +++ b/src-tauri/core/src/model/helpers.rs @@ -159,7 +159,7 @@ impl Roof { RoofParams { outline: self.outline.iter().map(|v| [v.x, v.y]).collect(), shape: match self.shape { - RoofShape::Flach => Shape::Flach, + RoofShape::Flach | RoofShape::Unknown => Shape::Flach, RoofShape::Pult => Shape::Pult, RoofShape::Sattel => Shape::Sattel, RoofShape::Walm => Shape::Walm, @@ -188,7 +188,7 @@ impl Stair { let n = |v: Option| v.unwrap_or(f64::NAN); [ match self.shape { - StairShape::Straight => 0.0, + StairShape::Straight | StairShape::Unknown => 0.0, StairShape::L => 1.0, StairShape::Spiral => 2.0, }, diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index f0c04356..0d252bed 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -593,6 +593,7 @@ fn opening_kind_code(k: Option) -> f64 { Some(OpeningKind::Drehkipp) => 3.0, Some(OpeningKind::Fest) => 4.0, Some(OpeningKind::Schiebe) => 5.0, + Some(OpeningKind::Unknown) => 6.0, } } From 976acbee88130719073d986fcbf73ba2a5fbd54c Mon Sep 17 00:00:00 2001 From: karim Date: Wed, 28 Oct 2026 02:31:54 +0100 Subject: [PATCH 31/31] =?UTF-8?q?[K3d]=20Plan=20in=20Rust:=20Primitive-Typ?= =?UTF-8?q?=20(JSON=20wie=20TS)=20und=20Attribut-/Schraffur-Aufl=C3=B6sung?= =?UTF-8?q?=20als=20Grundlage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.md | 3 + src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/plan/mod.rs | 5 + src-tauri/core/src/plan/prim.rs | 198 +++++++++++++++++++++++++++++++ src-tauri/core/src/plan/style.rs | 162 +++++++++++++++++++++++++ 5 files changed, 369 insertions(+) create mode 100644 src-tauri/core/src/plan/mod.rs create mode 100644 src-tauri/core/src/plan/prim.rs create mode 100644 src-tauri/core/src/plan/style.rs diff --git a/TODO.md b/TODO.md index c55427ae..48864e39 100644 --- a/TODO.md +++ b/TODO.md @@ -117,6 +117,9 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern - ○ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. Hängt an [K4]: Rust braucht das typisierte Modell (Bauteil-Typen, Schraffuren, Linienstile, Kategorien) und einen Plan-Puffer v2 mit Pick-IDs + vollem `Primitive`-Umfang (Text, Schraffur-Optionen, Zickzack/Motiv); die Verbraucher von `Primitive[]` (SVG/PDF/DXF, Auswahl, Overlay) lesen dann den Puffer. + Stand 28.10.: Rust-Grundlage `core/src/plan/{prim,style}.rs` (Primitive-Typ mit TS-gleicher JSON-Form, Auflösung By-Layer/By-Object, + `resolve_hatch`). Offen: Overrides-Engine, Raum-Stempel/richText, Domänen (Decken, Dächer, Räume, Wände+Öffnungen, Treppen, Stützen, + Körper, Kontext, Schnittlinien), Orchestrator (drawings2d bleibt vorerst TS), Plan-Puffer v2 (GPU-Chunk-Cache braucht Inhalts-Hash statt Objekt-Identität). 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 diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 1ebb942c..aed2b41f 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -37,6 +37,7 @@ pub mod wall_mesh_cut; pub mod jsnum; pub mod hatch; pub mod hatch_flat; +pub mod plan; pub mod plan_buf; pub mod project_format; pub mod queries; diff --git a/src-tauri/core/src/plan/mod.rs b/src-tauri/core/src/plan/mod.rs new file mode 100644 index 00000000..72ca2edd --- /dev/null +++ b/src-tauri/core/src/plan/mod.rs @@ -0,0 +1,5 @@ +//! Plan-Erzeugung auf dem Projekt-Dokument ([K3d]/[K4]): Rust-Gegenstück zu `src/plan/generatePlan.ts` +//! und `generatePlan/*.ts`. + +pub mod prim; +pub mod style; diff --git a/src-tauri/core/src/plan/prim.rs b/src-tauri/core/src/plan/prim.rs new file mode 100644 index 00000000..3d2172b3 --- /dev/null +++ b/src-tauri/core/src/plan/prim.rs @@ -0,0 +1,198 @@ +//! Plan-Primitive ([K3d]/[K4]): das Austauschformat zwischen Plan-Erzeugung und allen Verbrauchern +//! (Gegenstück zu `Primitive` in `src/plan/generatePlan/shared.ts`). Die JSON-Form ist +//! Zeichen für Zeichen die der TS-Objekte (camelCase, fehlende Felder fehlen). + +use crate::model::*; +use serde::Serialize; + +/// Aufgelöste Schraffur eines Polygons (`HatchRender`). +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct HatchRender { + pub pattern: HatchPattern, + pub scale: f64, + pub angle: f64, + #[serde(skip_serializing_if = "Option::is_none")] + pub origin: Option, + pub color: String, + pub line_weight: f64, + pub dash: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub kind: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub lines: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub image: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub gradient: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub seed: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub density: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub length_min: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub length_max: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub motif: Option, +} + +/// Zeile unter dem Raum-Stempel. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct StampLine { + pub text: String, + pub align: Align, +} + +/// `dash?: number[] | null`: fehlt (`None`), `null` (`Some(None)`) oder Muster. +pub type Dash = Option>>; + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(tag = "kind")] +pub enum Primitive { + #[serde(rename = "polygon", rename_all = "camelCase")] + Polygon { + pts: Vec, + fill: String, + stroke: String, + stroke_width_mm: f64, + hatch: HatchRender, + #[serde(skip_serializing_if = "Option::is_none")] + greyed: Option, + #[serde(skip_serializing_if = "Option::is_none")] + opacity: Option, + #[serde(skip_serializing_if = "Option::is_none")] + no_stroke_edges: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + wall_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + drawing_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + ceiling_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + opening_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + stair_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + room_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + extruded_solid_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + context_object_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + column_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + roof_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + section_line_id: Option, + }, + #[serde(rename = "line", rename_all = "camelCase")] + Line { + a: Vec2, + b: Vec2, + cls: String, + weight_mm: f64, + #[serde(skip_serializing_if = "Option::is_none")] + dash: Dash, + #[serde(skip_serializing_if = "Option::is_none")] + zigzag: Option, + #[serde(skip_serializing_if = "Option::is_none")] + motif: Option, + #[serde(skip_serializing_if = "Option::is_none")] + color: Option, + #[serde(skip_serializing_if = "Option::is_none")] + drawing_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + opening_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + stair_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + greyed: Option, + #[serde(skip_serializing_if = "Option::is_none")] + opacity: Option, + }, + #[serde(rename = "arc", rename_all = "camelCase")] + Arc { + center: Vec2, + from: Vec2, + to: Vec2, + r: f64, + cls: String, + weight_mm: f64, + #[serde(skip_serializing_if = "Option::is_none")] + dash: Dash, + #[serde(skip_serializing_if = "Option::is_none")] + opening_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + stair_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + greyed: Option, + #[serde(skip_serializing_if = "Option::is_none")] + opacity: Option, + }, + #[serde(rename = "text", rename_all = "camelCase")] + Text { + at: Vec2, + doc: RichTextDoc, + extra_lines: Vec, + base_pt: f64, + color: String, + #[serde(skip_serializing_if = "Option::is_none")] + room_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + greyed: Option, + #[serde(skip_serializing_if = "Option::is_none")] + opacity: Option, + }, + #[serde(rename = "drawingText", rename_all = "camelCase")] + DrawingText { + at: Vec2, + text: String, + height_m: f64, + angle: f64, + color: String, + #[serde(skip_serializing_if = "Option::is_none")] + marks: Option, + #[serde(skip_serializing_if = "Option::is_none")] + wrap_width: Option, + #[serde(skip_serializing_if = "Option::is_none")] + doc: Option, + #[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), + } + self + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::plan::style::no_hatch; + + #[test] + fn line_dash_null_und_fehlend_unterscheiden_sich() { + let mk = |dash: Dash| Primitive::Line { a: Vec2 { x: 0.0, y: 0.0 }, b: Vec2 { x: 1.0, y: 0.0 }, cls: "c".into(), weight_mm: 0.1, dash, zigzag: None, motif: None, color: None, drawing_id: None, opening_id: None, stair_id: None, greyed: None, opacity: None }; + assert!(!serde_json::to_string(&mk(None)).unwrap().contains("dash")); + assert!(serde_json::to_string(&mk(Some(None))).unwrap().contains("\"dash\":null")); + assert!(serde_json::to_string(&mk(Some(Some(vec![0.4])))).unwrap().contains("\"dash\":[0.4]")); + } + + #[test] + fn polygon_tragt_kind_und_camel_case() { + let p = Primitive::Polygon { pts: vec![], fill: "#fff".into(), stroke: "#000".into(), stroke_width_mm: 0.2, hatch: no_hatch(), greyed: None, opacity: None, no_stroke_edges: None, wall_id: Some("w".into()), drawing_id: None, ceiling_id: None, 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 }; + let s = serde_json::to_string(&p).unwrap(); + assert!(s.contains("\"kind\":\"polygon\"") && s.contains("strokeWidthMm") && s.contains("\"wallId\":\"w\"")); + } +} diff --git a/src-tauri/core/src/plan/style.rs b/src-tauri/core/src/plan/style.rs new file mode 100644 index 00000000..80176473 --- /dev/null +++ b/src-tauri/core/src/plan/style.rs @@ -0,0 +1,162 @@ +//! Attribut-Auflösung (By-Layer / By-Object) und Schraffur-Auflösung des Grundriss-Generators — +//! Gegenstück zu `src/plan/generatePlan/shared.ts`. + +use super::prim::HatchRender; +use crate::model::*; + +pub const POCHE_STROKE: &str = "#1a1a1a"; +pub const MONO_INK: &str = "#111111"; +pub const LAYER_LINE_MM: f64 = 0.02; +pub const SYMBOL_HAIRLINE_MM: f64 = 0.02; +pub const OVERHEAD_DASH: [f64; 2] = [0.4, 0.25]; +pub const ROOF_EAVES_MM: f64 = 0.13; +pub const ROOF_RIDGE_MM: f64 = 0.25; +pub const ROOF_HIP_MM: f64 = 0.18; +pub const ROOF_BREAK_MM: f64 = 0.09; +pub const ROOF_BREAK_DASH: [f64; 2] = [0.12, 0.08]; +pub const WALL_FALLBACK_MM: f64 = 0.18; +pub const HATCH_PAPER: &str = "#f0f0f0"; +pub const HATCH_INK: &str = "#0f0f0f"; + +/// Detailgrad der Plan-Darstellung. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Detail { + Grob, + Mittel, + Fein, +} + +impl Detail { + pub fn parse(s: &str) -> Detail { + match s { + "grob" => Detail::Grob, + "fein" => Detail::Fein, + _ => Detail::Mittel, + } + } + + /// Stärke der Wand-Umrisslinie als Faktor auf die Ebenen-lw. + pub fn outline_factor(self) -> f64 { + match self { + Detail::Grob => 1.6, + Detail::Mittel => 1.0, + Detail::Fein => 0.6, + } + } + + /// Stärke der Schichtfugen. + pub fn layer_factor(self) -> f64 { + match self { + Detail::Fein => 0.7, + _ => 1.0, + } + } +} + +/// Schraffur-Platzhalter „ohne" (für reine Umriss-/Sammelflächen). +pub fn no_hatch() -> HatchRender { + HatchRender { + pattern: HatchPattern::None, + scale: 1.0, + angle: 0.0, + origin: None, + color: POCHE_STROKE.into(), + line_weight: LAYER_LINE_MM, + dash: None, + kind: None, + lines: None, + image: None, + gradient: None, + seed: None, + density: None, + length_min: None, + length_max: None, + motif: None, + } +} + +/// Neutrale Poché-Füllfarbe für ein Muster: „solid" → Tinte, sonst Papier. +pub fn poche_fill(p: HatchPattern) -> &'static str { + if p == HatchPattern::Solid { + HATCH_INK + } else { + HATCH_PAPER + } +} + +/// `resolveHatch`: `None`, wenn Schraffur oder ihr Linienstil fehlen (TS wirft dort — Aufrufer fängt). +pub fn resolve_hatch(p: &Project, hatch_id: &str, wall_angle_deg: Option, foreground: Option<&str>, placement: Option<(Option, Option, Option)>) -> Option { + let h = p.hatch(hatch_id)?; + let ls = match h.line_style_id.as_deref().filter(|s| !s.is_empty()) { + Some(id) => Some(p.line_style(id)?), + None => None, + }; + let (p_angle, p_scale, p_origin) = placement.unwrap_or((None, None, None)); + let base_angle = p_angle.unwrap_or(h.angle); + let angle = match wall_angle_deg { + Some(w) if h.relative_to_wall == Some(true) => base_angle - w, + _ => base_angle, + }; + Some(HatchRender { + pattern: h.pattern, + scale: h.scale * p_scale.unwrap_or(1.0), + angle, + origin: p_origin, + color: foreground.unwrap_or(HATCH_INK).to_string(), + line_weight: ls.map_or(0.13, |l| l.weight), + dash: ls.and_then(|l| l.dash.clone()), + kind: h.kind, + lines: h.lines, + image: h.image.clone(), + gradient: h.gradient.clone(), + seed: h.seed, + density: h.density, + length_min: h.length_min, + length_max: h.length_max, + motif: h.motif.clone(), + }) +} + +/// Vordergrundfarbe der Schraffur: Override ?? (Quelle „layer" ⇒ Kategorie-Farbe) ?? Bauteil. +pub fn resolve_foreground<'a>(comp: &'a Component, override_: Option<&'a str>, category: Option<&'a LayerCategory>, source: Option) -> Option<&'a str> { + if let Some(o) = override_ { + return Some(o); + } + if source == Some(AttributeSource::Layer) { + return category.map(|c| c.color.as_str()).or(comp.foreground.as_deref()); + } + comp.foreground.as_deref() +} + +/// Hintergrund-/Füllfarbe (Poché-Override), analog [`resolve_foreground`]. +pub fn resolve_background<'a>(comp: &'a Component, override_: Option<&'a str>, category: Option<&'a LayerCategory>, source: Option) -> Option<&'a str> { + if let Some(o) = override_ { + return Some(o); + } + if source == Some(AttributeSource::Layer) { + return category.map(|c| c.color.as_str()).or(comp.background.as_deref()); + } + comp.background.as_deref() +} + +/// Schraffur-Referenz: Override ?? (Quelle „layer" ⇒ Kategorie-Schraffur) ?? Rückfall. +pub fn resolve_hatch_id<'a>(override_: Option<&'a str>, source: Option, category: Option<&'a LayerCategory>, fallback: Option<&'a str>) -> Option<&'a str> { + if let Some(o) = override_ { + return Some(o); + } + if source == Some(AttributeSource::Layer) { + return category.and_then(|c| c.hatch.as_deref()).or(fallback); + } + fallback +} + +/// Strichstärke: Override ?? (Quelle „layer" ⇒ Kategorie-lw) ?? Rückfall. +pub fn resolve_stroke_weight(override_: Option, source: Option, category: Option<&LayerCategory>, fallback: f64) -> f64 { + if let Some(o) = override_ { + return o; + } + if source == Some(AttributeSource::Layer) { + return category.map_or(fallback, |c| c.lw); + } + fallback +}