diff --git a/TODO.md b/TODO.md index 90c2717c..c166349e 100644 --- a/TODO.md +++ b/TODO.md @@ -491,13 +491,35 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern Leseansicht). Abweichungen (gewollt): ein Griff-Index ohne Punkt (negativ, gebrochen, zu gross) ändert nichts (TS warf beim Lesen von `undefined`, 38 000 der Zufallsfälle); gerechnet wird auf dem Dokument — ein dort als `null` gespeichertes NaN rechnet wie `null` in JS (0) und kommt als `null` in die Leseansicht (vorher blieb dort NaN); Griff-Listen liefern −0 als 0. - Messung (vitest, 3000 Wände + 2000 Polylinien, alt/neu abwechselnd, Median, Container unter Last): Wand-Griff an Position - 10/1500/2990 39–43/198–218/324–348 µs → 40–44/192–193/318–337 µs (dominiert von der linearen id-Suche), Polylinien-Griff - 97–122 → 102–122 µs, Polylinien-Kante 108–138 → 109 µs, Wand verschieben 146–200 → 149–206 µs (gleich im Rahmen der - Streuung), Griff an einer 5000-Punkte-Polylinie 16–18 → 13–14 ms; Griff-Liste der 5000-Punkte-Polylinie 2,7 → 1,1 ms - (kleine Polylinie 2 → 4,5 µs). Nicht in der Tauri-App geprüft (vitest/Linux, e2e im Browser). Offen: `setPolylineVertexType` + Messung (vitest, Store, 3000 Wände + 2000 Polylinien, alt/neu abwechselnd, kleinster Wert aus drei Läufen, Container unter + Last; Stand nach dem Nachtrag unten): Wand-Griff an Position 10/1500/2990 32/150/315 µs → 28/116/262 µs (dominiert von der + linearen id-Suche), Polylinien-Griff 78 → 58 µs, Polylinien-Kante 72 → 57 µs, Wand verschieben 131 → 115 µs, Griff an einer + 5000-Punkte-Polylinie 13,7 → 9,1 ms; Griff-Liste der 5000-Punkte-Polylinie 2,7 → 1,1 ms (kleine Polylinie 2 µs, gleich). + Nicht in der Tauri-App geprüft (vitest/Linux, e2e im Browser). Offen: `setPolylineVertexType` (rechnet in `geometry/polylineVertexType.ts`), die lineare id-Suche je Mausschritt (im Kern beim Rechnen und beim Commit, - in TS in `applyOps`) und der Commit grosser Polylinien (~12 ms bei 5000 Punkten: Verlauf/Prüfung in `document.rs`/`ops.rs`). + in TS in `applyOps`) und der Commit grosser Polylinien (~9 ms bei 5000 Punkten: Verlauf/Prüfung in `document.rs`/`ops.rs`). + **Objekt-Info im Kern (29.10.)** — erledigt damit (4): `selection_info.rs` (vorher `deriveSelection` in `state/selectionInfo.ts`, + ~800 Zeilen Rechnung) liefert als Wurzel-Abfrage `selectionInfo` den Kontrakt `Selection` für das erste gewählte Element + (Vorrang wie bisher): effektive Farbe/Strichstärke/Schraffur/Vorder-/Hintergrund (Element → Linienstil → Ebene → Bauteil), + bbox, Wand (Referenzlinie, Fugen der Schichten, Typ-Liste mit `wallTypeLabel`, Geschosse, Geschoss darüber, UK/OK, Länge, + Brutto-/Öffnungs-/Nettovolumen), Decke (Typ, Fläche, Volumen, Aussparungen), Dach (Firsthöhe aus `roof.rs`, Kantenliste + `roofEdgeList`, Höfe), Öffnung (Lücke `opening_geom`, UK/OK), Treppe (`stair.rs`), Raum, Extrusion, Stütze, Kontext-Objekt + (LV95-Mitte), Detailverweis; `geomBBox` (auch für Ausrichten/Verteilen: Abfrage `drawingBBoxes`, `editors/align.ts`). Rechnung + auf der rohen Wurzel (verlustfrei, Schlüsselreihenfolge wie die früheren Objekt-Literale, keine typisierte Sicht des ganzen + Projekts); nur Dach/Treppe/Stütze werden für die schon typisierte Geometrie einzeln gelesen. Die Antwort wird direkt als Text + geschrieben; Felder kleiner Objekte linear gesucht statt über den SipHash der `IndexMap` (`grips::field`, auch in den Griffen); + die Fassade gibt die Lage des Elements aus der Leseansicht mit (spart dem Kern die lineare Suche). `state/selectionInfo.ts` + hält den Kontrakt (Typen) und die Fassade; die B-Rep-Beschreibung einer Extrusion (`spec`, truck) setzt sie aus + `extrudedSolidSpec`. `js_fmt::to_fixed` hat einen Schnellweg (nur exakte Halbwerte gehen den langen, genauen Weg; Test + gegen den genauen Weg über 1,6 Mio. Werte). Gelöscht: die TS-Rechnung, `geomBBox`. Gleichheit (einmalig, Test gelöscht): + 174 360 Auswahlen über 10 000 Zufallsprojekte (alle Bauteilarten, fehlende/null-Felder, Bindungen UK/OK, unbekannte + Typen/Bauteile, LV95, mehrere Arten gleichzeitig) zeichengleich zur alten Fassung (JSON mit NaN-Marken), 20 489 Fälle mit + derselben Fehlermeldung; Beispielprojekt alle Elemente; 24 000 Ausrichten/Verteilen-Fälle gleich. Abweichung (gewollt): ein + Element, das das Kern-Modell nicht lesen kann (Dach/Treppe/Stütze mit kaputten Pflichtfeldern), ergibt `null` mit Warnung + statt eines Werts. Messung (vitest, Store mit 3000 Wänden und 20 000 Zeichnungen, Container unter Last): Wand 36–67 → + 96–138 µs, Zeichnung (Position 10 000) 150–300 → 160–390 µs, Dach 5 → 30–60 µs (TS merkte sich die Dachgeometrie je + Objekt; im Kern ist sie für die letzten 16 Dächer gemerkt, der Rest ist die JSON-Übergabe), Griff-Schritt samt Objekt-Info + 1,6–2,6 ms → 1,5–2,4 ms; je Darstellung also ~0,05 ms mehr. Nicht in der Tauri-App geprüft. - ◐ **S4 Typen aus Rust**: `types.ts` wird aus den Rust-Strukturen erzeugt (ts-rs); Datei-I/O (`projectFormat`, Migration, IFC/DXF/ STEP-Ex- und -Import) im Kern. **Typen (28.10.):** Das Rust-Modell (`core/src/model/generated.rs`, `manual.rs`) ist die Quelle; ts-rs 12 (MIT, nur diff --git a/src-tauri/core/src/grips.rs b/src-tauri/core/src/grips.rs index 9a7cd790..687bf3c3 100644 --- a/src-tauri/core/src/grips.rs +++ b/src-tauri/core/src/grips.rs @@ -21,6 +21,18 @@ use serde_json::{Map, Value}; // ── JS-Zahlen in JSON ──────────────────────────────────────────────────────── +/// Feld `k` eines Objekts. Kleine Objekte (Punkte, Elemente) werden linear durchsucht: das ist deutlich +/// billiger als der Hash (SipHash) der `IndexMap` je Zugriff — die Griff- und Objekt-Info-Rechnung liest +/// Dutzende Felder je Aufruf. +#[inline] +pub fn field<'a>(v: &'a Value, k: &str) -> Option<&'a Value> { + match v { + Value::Object(m) if m.len() <= 32 => m.iter().find(|(kk, _)| kk.as_str() == k).map(|(_, x)| x), + Value::Object(m) => m.get(k), + _ => None, + } +} + /// Zahl als JSON-Wert wie nach `JSON.stringify` → `serde_json`: ganze Zahlen als Ganzzahl, sonst f64; /// NaN/±∞ als Marke (`"\u{1}NaN"` …), −0 als 0. pub fn js_num(x: f64) -> Value { @@ -90,7 +102,7 @@ pub fn pt(x: f64, y: f64) -> Value { /// `(x, y)` eines Punkt-Werts (fehlende Koordinaten NaN). pub fn xy(v: &Value) -> (f64, f64) { - (num_of(v.get("x")), num_of(v.get("y"))) + (num_of(field(v, "x")), num_of(field(v, "y"))) } /// `{...v, key: val}` (vorhandener Schlüssel behält seine Stelle). Der ersetzte Wert wird nicht kopiert @@ -189,20 +201,103 @@ fn with_geom(d: &Value, g: Value) -> Value { // ── Anfrage ────────────────────────────────────────────────────────────────── -/// Eine Änderung aus den Griff-Aktionen des Stores (JSON, Zahlen mit Nicht-endlich-Marken). -pub struct Request<'a>(&'a Value); +/// Zahl der Anfrage: Zahl oder Nicht-endlich-Marke, `null` = 0 (wie `num_of`), fehlend = NaN. +#[derive(Clone, Copy, Debug)] +pub struct N(pub f64); -impl<'a> Request<'a> { - fn n(&self, k: &str) -> f64 { - num_of(self.0.get(k)) +impl Default for N { + fn default() -> Self { + N(f64::NAN) } - fn s(&self, k: &str) -> Option<&'a str> { - self.0.get(k).and_then(Value::as_str).filter(|s| !s.is_empty()) +} + +impl<'de> serde::Deserialize<'de> for N { + fn deserialize>(d: D) -> Result { + struct V; + impl serde::de::Visitor<'_> for V { + type Value = N; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("Zahl") + } + fn visit_f64(self, v: f64) -> Result { + Ok(N(v)) + } + fn visit_i64(self, v: i64) -> Result { + Ok(N(v as f64)) + } + fn visit_u64(self, v: u64) -> Result { + Ok(N(v as f64)) + } + fn visit_str(self, v: &str) -> Result { + Ok(N(num_of(Some(&Value::String(v.to_owned()))))) + } + fn visit_unit(self) -> Result { + Ok(N(0.0)) + } + fn visit_bool(self, _: bool) -> Result { + Ok(N(f64::NAN)) + } + } + d.deserialize_any(V) + } +} + +/// Eine Änderung aus den Griff-Aktionen des Stores (`GripRequest` in `geometry/grips.ts`); Zahlen dürfen +/// Nicht-endlich-Marken sein. Typisiert gelesen (je Mausschritt billiger als ein JSON-Baum). +#[derive(serde::Deserialize, Default, Debug)] +#[serde(default, rename_all = "camelCase")] +pub struct Request { + pub op: String, + drawing_id: Option, + wall_id: Option, + id: Option, + kind: Option, + new_id: Option, + new_name: Value, + index: N, + a: N, + b: N, + seg: N, + scale: N, + w: N, + h: N, + fx: N, + fy: N, + thickness: N, + pt: [N; 2], + delta: [N; 2], +} + +impl Request { + fn n(&self, k: &str) -> f64 { + match k { + "index" => self.index.0, + "a" => self.a.0, + "b" => self.b.0, + "seg" => self.seg.0, + "scale" => self.scale.0, + "w" => self.w.0, + "h" => self.h.0, + "fx" => self.fx.0, + "fy" => self.fy.0, + _ => self.thickness.0, + } + } + /// Text-Feld; leer = fehlend (JS-Wahrheitswert der ids). + fn s(&self, k: &str) -> Option<&str> { + let v = match k { + "drawingId" => &self.drawing_id, + "wallId" => &self.wall_id, + "kind" => &self.kind, + "newId" => &self.new_id, + _ => &self.id, + }; + v.as_deref().filter(|s| !s.is_empty()) } /// Punkt als `[x, y]`. fn p(&self, k: &str) -> (f64, f64) { - let a = arr(self.0.get(k)); - (num_of(a.first()), num_of(a.get(1))) + let [x, y] = if k == "pt" { self.pt } else { self.delta }; + (x.0, y.0) } } @@ -221,35 +316,37 @@ impl From> for GripResult { /// Antwort-JSON `{"ops": […], "notice": …}` (Ops wie `CoreOp` in TS; `replace` ohne Kopie des Elements). pub fn result_json(r: &GripResult) -> String { - let mut out = String::from("{\"ops\":["); + // Direkt in einen Puffer (`to_writer`; `to_string` ginge über `fmt::Display` und wäre langsamer). + let mut out: Vec = b"{\"ops\":[".to_vec(); for (i, op) in r.ops.iter().enumerate() { if i > 0 { - out.push(','); + out.push(b','); } - match op { + let _ = match op { Op::Replace { collection, entity } => { - out.push_str("{\"kind\":\"replace\",\"collection\":"); - out.push_str(&Value::from(collection.as_str()).to_string()); - out.push_str(",\"entity\":"); - out.push_str(&entity.to_string()); - out.push('}'); + out.extend_from_slice(b"{\"kind\":\"replace\",\"collection\":"); + let _ = serde_json::to_writer(&mut out, collection); + out.extend_from_slice(b",\"entity\":"); + let w = serde_json::to_writer(&mut out, entity); + out.push(b'}'); + w } - op => out.push_str(&op.to_json().to_string()), - } + op => serde_json::to_writer(&mut out, &op.to_json()), + }; } - out.push(']'); + out.push(b']'); if let Some(n) = r.notice { - out.push_str(",\"notice\":"); - out.push_str(&Value::from(n).to_string()); + out.extend_from_slice(b",\"notice\":"); + let _ = serde_json::to_writer(&mut out, n); } - out.push('}'); - out + out.push(b'}'); + String::from_utf8(out).unwrap_or_default() } /// Führt eine Griff-Änderung aus (`req.op` wählt die Art, s. `src/state/gripOps.ts`). -pub fn run(root: &Map, req: &Value) -> Result { - let r = Request(req); - let op = req.get("op").and_then(Value::as_str).unwrap_or(""); +pub fn run(root: &Map, req: &Request) -> Result { + let r = req; + let op = req.op.as_str(); let patch = |coll: &str, id: Option<&str>, f: &dyn Fn(&Value) -> Option| -> Vec { id.and_then(|id| find(root, coll, id)).and_then(f).map(|e| vec![replace(coll, e)]).unwrap_or_default() }; @@ -260,7 +357,7 @@ pub fn run(root: &Map, req: &Value) -> Result let d = did.and_then(|i| find(root, "drawings2d", i)); let w = wid.and_then(|i| find(root, "walls", i)); // Objekt-Sperre: gesperrte Elemente lassen sich anwählen, aber nicht ziehen. - if d.is_some_and(|d| truthy(d.get("locked"))) || w.is_some_and(|w| truthy(w.get("locked"))) { + if d.is_some_and(|d| truthy(field(d, "locked"))) || w.is_some_and(|w| truthy(field(w, "locked"))) { return Ok(GripResult::default()); } let f: Box Option> = match op { @@ -284,11 +381,11 @@ pub fn run(root: &Map, req: &Value) -> Result "resize" => { let (w, h, fx, fy) = (r.n("w"), r.n("h"), r.n("fx"), r.n("fy")); if r.s("kind") == Some("drawing2d") { - patch("drawings2d", r.s("id"), &|d| resize_geom(d.get("geom")?, w, h, fx, fy).map(|g| with_geom(d, g))).into() + patch("drawings2d", r.s("id"), &|d| resize_geom(field(d, "geom")?, w, h, fx, fy).map(|g| with_geom(d, g))).into() } else { patch("walls", r.s("id"), &|wall| { - let s = xy(wall.get("start").unwrap_or(&Value::Null)); - let e = xy(wall.get("end").unwrap_or(&Value::Null)); + let s = xy(field(wall, "start").unwrap_or(&Value::Null)); + let e = xy(field(wall, "end").unwrap_or(&Value::Null)); let (ax, ay, sx, sy) = scale_around(bbox(&[s, e]), w, h, fx, fy); let f = |p: (f64, f64)| pt(ax + (p.0 - ax) * sx, ay + (p.1 - ay) * sy); Some(with_all(wall, vec![("start", f(s)), ("end", f(e))])) @@ -304,7 +401,7 @@ pub fn run(root: &Map, req: &Value) -> Result "ceilingBy" | "roofBy" => { let coll = if op == "ceilingBy" { "ceilings" } else { "roofs" }; let (dx, dy) = r.p("delta"); - patch(coll, r.s("id"), &|e| Some(with(e, "outline", moved_all(e.get("outline")?.as_array()?, dx, dy)))).into() + patch(coll, r.s("id"), &|e| Some(with(e, "outline", moved_all(field(e, "outline")?.as_array()?, dx, dy)))).into() } "ceilingEdge" | "roomEdge" => { let (coll, field) = if op == "ceilingEdge" { ("ceilings", "outline") } else { ("rooms", "boundary") }; @@ -318,8 +415,8 @@ pub fn run(root: &Map, req: &Value) -> Result "stairBy" => { let (dx, dy) = r.p("delta"); patch("stairs", r.s("id"), &|s| { - let mut out = with(s, "start", moved(s.get("start").unwrap_or(&Value::Null), dx, dy)); - if truthy(s.get("center")) { + let mut out = with(s, "start", moved(field(s, "start").unwrap_or(&Value::Null), dx, dy)); + if truthy(field(s, "center")) { out = with(&out, "center", moved(&s["center"], dx, dy)); } Some(out) @@ -329,8 +426,8 @@ pub fn run(root: &Map, req: &Value) -> Result "roomBy" => { let (dx, dy) = r.p("delta"); patch("rooms", r.s("id"), &|rm| { - let mut out = with(rm, "boundary", moved_all(rm.get("boundary")?.as_array()?, dx, dy)); - if truthy(rm.get("stampAnchor")) { + let mut out = with(rm, "boundary", moved_all(field(rm, "boundary")?.as_array()?, dx, dy)); + if truthy(field(rm, "stampAnchor")) { out = with(&out, "stampAnchor", moved(&rm["stampAnchor"], dx, dy)); } Some(out) @@ -340,10 +437,10 @@ pub fn run(root: &Map, req: &Value) -> Result "roomStamp" => { let (dx, dy) = r.p("delta"); patch("rooms", r.s("id"), &|rm| { - let base = match rm.get("stampAnchor") { + let base = match field(rm, "stampAnchor") { Some(a) if !a.is_null() => xy(a), _ => { - let ring: Vec<[f64; 2]> = arr(rm.get("boundary")).iter().map(|p| xy(p).into()).collect(); + let ring: Vec<[f64; 2]> = arr(field(rm, "boundary")).iter().map(|p| xy(p).into()).collect(); let c = crate::room_area::evaluate(&ring, 0.0).centroid; (c[0], c[1]) } @@ -359,12 +456,12 @@ pub fn run(root: &Map, req: &Value) -> Result "deletePoint" => { let index = r.n("index"); let Some(d) = r.s("id").and_then(|i| find(root, "drawings2d", i)) else { return Ok(GripResult::default()) }; - let g = d.get("geom").unwrap_or(&Value::Null); - if g.get("shape").and_then(Value::as_str) != Some("polyline") { + let g = field(d, "geom").unwrap_or(&Value::Null); + if field(g, "shape").and_then(Value::as_str) != Some("polyline") { return Ok(GripResult::default()); } - let pts = arr(g.get("pts")); - let min = if truthy(g.get("closed")) { 4 } else { 3 }; + let pts = arr(field(g, "pts")); + let min = if truthy(field(g, "closed")) { 4 } else { 3 }; if pts.len() < min { return Ok(GripResult { ops: vec![], notice: Some("alert.polylineMinPoints") }); } @@ -373,13 +470,13 @@ pub fn run(root: &Map, req: &Value) -> Result // seinen (die genaue Bogenform lässt sich ohne den Stützpunkt nicht erhalten). let drop = |l: &[Value]| Value::Array(l.iter().enumerate().filter(|(i, _)| *i != k).map(|(_, v)| v.clone()).collect()); let mut fields = vec![("pts", drop(pts))]; - if truthy(g.get("bulge")) { - fields.push(("bulge", drop(arr(g.get("bulge"))))); + if truthy(field(g, "bulge")) { + fields.push(("bulge", drop(arr(field(g, "bulge"))))); } vec![replace("drawings2d", with_geom(d, with_all(g, fields)))].into() } - "wallThickness" => wall_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.get("newName").cloned().unwrap_or(Value::Null)).into(), - "ceilingThickness" => ceiling_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.get("newName").cloned().unwrap_or(Value::Null)).into(), + "wallThickness" => wall_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.new_name.clone()).into(), + "ceilingThickness" => ceiling_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.new_name.clone()).into(), other => return Err(format!("Unbekannte Griff-Änderung: {other}")), }) } @@ -391,15 +488,15 @@ fn wall_grip(w: &Value, index: f64, x: f64, y: f64) -> Value { } fn wall_moved(w: &Value, dx: f64, dy: f64) -> Value { - let s = moved(w.get("start").unwrap_or(&Value::Null), dx, dy); - let e = moved(w.get("end").unwrap_or(&Value::Null), dx, dy); + let s = moved(field(w, "start").unwrap_or(&Value::Null), dx, dy); + let e = moved(field(w, "end").unwrap_or(&Value::Null), dx, dy); with_all(w, vec![("start", s), ("end", e)]) } // ── 2D-Zeichnungen ─────────────────────────────────────────────────────────── fn shape(g: &Value) -> &str { - g.get("shape").and_then(Value::as_str).unwrap_or("") + field(g, "shape").and_then(Value::as_str).unwrap_or("") } /// Kreis, solange rx≈ry (relative Toleranz 0.5 %) — sonst Ellipse (rotation 0). Neues Objekt (weitere @@ -456,18 +553,18 @@ fn dim_text_pos(a: (f64, f64), b: (f64, f64), offset: f64, h: f64, along: f64, p /// Schrifthöhe der Masszahl in Modell-Metern. fn dim_height(g: &Value, scale: f64) -> f64 { - mm_to_model(num_or(g.get("textHeightMm"), DIM_TEXT_HEIGHT_MM), scale) + mm_to_model(num_or(field(g, "textHeightMm"), DIM_TEXT_HEIGHT_MM), scale) } /// Griff `index` einer 2D-Zeichnung auf (x, y) (`moveGrip`); `None` = keine Änderung. fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option { - let g = d.get("geom")?; + let g = field(d, "geom")?; let p = pt(x, y); let set = |k: &str, v: Value| Some(with_geom(d, with(g, k, v))); match shape(g) { "line" | "xline" | "ray" => set(if index == 0.0 { "a" } else { "b" }, p), "polyline" => { - let pts = arr(g.get("pts")); + let pts = arr(field(g, "pts")); let n = pts.len(); if index < n as f64 { return set("pts", replace_at(pts, index, &p)); @@ -478,16 +575,16 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option = arr(g.get("bulge")).to_vec(); + let mut bulge: Vec = arr(field(g, "bulge")).to_vec(); while bulge.len() <= k { bulge.push(Value::from(0u64)); } bulge[k] = js_num(val); set("bulge", Value::Array(bulge)) } - "bezier" | "spline" => set("pts", replace_at(arr(g.get("pts")), index, &p)), + "bezier" | "spline" => set("pts", replace_at(arr(field(g, "pts")), index, &p)), "dimension" => { - let pts = arr(g.get("pts")); + let pts = arr(field(g, "pts")); let n = pts.len(); if index < n as f64 { return set("pts", replace_at(pts, index, &p)); @@ -507,7 +604,7 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option Option = (0..n - 1) .map(|i| { if i == k { @@ -541,11 +638,11 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option { - if truthy(g.get("pathPts")) { - return set("pathPts", replace_at(arr(g.get("pathPts")), index, &p)); + if truthy(field(g, "pathPts")) { + return set("pathPts", replace_at(arr(field(g, "pathPts")), index, &p)); } - if truthy(g.get("leaderTarget")) { - let bends = arr(g.get("leaderBendPoints")); + if truthy(field(g, "leaderTarget")) { + let bends = arr(field(g, "leaderBendPoints")); let tip = bends.len() as f64 + 1.0; if index == 0.0 { return set("at", p); @@ -559,12 +656,12 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option 0.0 && index >= 0.0 && index < 4.0 { + let width = num_of(field(g, "width")); + if truthy(field(g, "width")) && width > 0.0 && index >= 0.0 && index < 4.0 { // Nur die Spaltenbreite ändert sich (InDesign-Textrahmen); Zug auf die lokale x-Achse. - let angle = num_of(g.get("angle")); + let angle = num_of(field(g, "angle")); let (cos, sin) = (jsnum::cos(angle), jsnum::sin(angle)); - let (ax, ay) = xy(g.get("at").unwrap_or(&Value::Null)); + let (ax, ay) = xy(field(g, "at").unwrap_or(&Value::Null)); let local_x = (x - ax) * cos + (y - ay) * sin; const MIN_WIDTH: f64 = 0.1; if index == 0.0 || index == 3.0 { @@ -578,30 +675,30 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option set("at", p), "circle" => { - let (cx, cy) = xy(g.get("center").unwrap_or(&Value::Null)); - let r = pass(g.get("r")); + let (cx, cy) = xy(field(g, "center").unwrap_or(&Value::Null)); + let r = pass(field(g, "r")); let (rx, ry) = if index == 0.0 { (calc(jsnum::max(1e-3, (x - cx).abs())), r) } else { (r, calc(jsnum::max(1e-3, (y - cy).abs()))) }; - Some(with_geom(d, ellipse_or_circle(g.get("center"), rx, ry))) + Some(with_geom(d, ellipse_or_circle(field(g, "center"), rx, ry))) } "arc" => { - let (cx, cy) = xy(g.get("center").unwrap_or(&Value::Null)); + let (cx, cy) = xy(field(g, "center").unwrap_or(&Value::Null)); if index == 2.0 { return set("r", js_num(jsnum::max(1e-3, hypot2(x - cx, y - cy)))); } set(if index == 0.0 { "a0" } else { "a1" }, js_num(jsnum::atan2(y - cy, x - cx))) } "ellipse" => { - let rot = num_of(g.get("rotation")); + let rot = num_of(field(g, "rotation")); let (c, s) = (jsnum::cos(rot), jsnum::sin(rot)); - let (cx, cy) = xy(g.get("center").unwrap_or(&Value::Null)); + let (cx, cy) = xy(field(g, "center").unwrap_or(&Value::Null)); let (dx, dy) = (x - cx, y - cy); let lx = dx * c + dy * s; let ly = -dx * s + dy * c; - let rx = if index == 0.0 { calc(jsnum::max(1e-3, lx.abs())) } else { pass(g.get("rx")) }; - let ry = if index == 0.0 { pass(g.get("ry")) } else { calc(jsnum::max(1e-3, ly.abs())) }; + let rx = if index == 0.0 { calc(jsnum::max(1e-3, lx.abs())) } else { pass(field(g, "rx")) }; + let ry = if index == 0.0 { pass(field(g, "ry")) } else { calc(jsnum::max(1e-3, ly.abs())) }; // Nur ungedreht (`rotation === 0`) kann eine (fast) gleichseitige Ellipse wieder zum Kreis werden. - if g.get("rotation").and_then(Value::as_f64) == Some(0.0) { - return Some(with_geom(d, ellipse_or_circle(g.get("center"), rx, ry))); + if field(g, "rotation").and_then(Value::as_f64) == Some(0.0) { + return Some(with_geom(d, ellipse_or_circle(field(g, "center"), rx, ry))); } Some(with_geom(d, with_opt(g, vec![("rx", rx.v), ("ry", ry.v)]))) } @@ -620,18 +717,18 @@ fn or1(l: f64) -> f64 { /// Ecken eines Rechtecks/Bilds in Griff-Reihenfolge: min, (max.x, min.y), max, (min.x, max.y). fn rect_corners(g: &Value) -> [(f64, f64); 4] { - let mn = xy(g.get("min").unwrap_or(&Value::Null)); - let mx = xy(g.get("max").unwrap_or(&Value::Null)); + let mn = xy(field(g, "min").unwrap_or(&Value::Null)); + let mx = xy(field(g, "max").unwrap_or(&Value::Null)); [mn, (mx.0, mn.1), mx, (mn.0, mx.1)] } /// Ganze 2D-Zeichnung verschieben (`moveElementBy`); `None` = Form ohne Verschiebung. fn drawing_moved(d: &Value, dx: f64, dy: f64) -> Option { - let g = d.get("geom")?; + let g = field(d, "geom")?; let mv = |k: &str| moved(g.get(k).unwrap_or(&Value::Null), dx, dy); let ng = match shape(g) { "line" => with_all(g, vec![("a", mv("a")), ("b", mv("b"))]), - "polyline" | "bezier" | "spline" | "dimension" => with(g, "pts", moved_all(arr(g.get("pts")), dx, dy)), + "polyline" | "bezier" | "spline" | "dimension" => with(g, "pts", moved_all(arr(field(g, "pts")), dx, dy)), "rect" | "image" => with_all(g, vec![("min", mv("min")), ("max", mv("max"))]), "circle" | "arc" | "ellipse" => with(g, "center", mv("center")), "kote" | "detailref" | "scalebar" | "pointmarker" | "text" => with(g, "at", mv("at")), @@ -642,10 +739,10 @@ fn drawing_moved(d: &Value, dx: f64, dy: f64) -> Option { /// Kante (a, b) einer 2D-Zeichnung verschieben (`moveEdge`); `None` = keine Änderung. fn drawing_edge(d: &Value, a: f64, b: f64, dx: f64, dy: f64) -> Option { - let g = d.get("geom")?; + let g = field(d, "geom")?; let ng = match shape(g) { - "line" => with_all(g, vec![("a", moved(g.get("a").unwrap_or(&Value::Null), dx, dy)), ("b", moved(g.get("b").unwrap_or(&Value::Null), dx, dy))]), - "polyline" | "spline" => with(g, "pts", move_polygon_edge(arr(g.get("pts")), a, b, dx, dy, truthy(g.get("closed")))?), + "line" => with_all(g, vec![("a", moved(field(g, "a").unwrap_or(&Value::Null), dx, dy)), ("b", moved(field(g, "b").unwrap_or(&Value::Null), dx, dy))]), + "polyline" | "spline" => with(g, "pts", move_polygon_edge(arr(field(g, "pts")), a, b, dx, dy, truthy(field(g, "closed")))?), "rect" | "image" => { // Die zwei Kanten-Ecken verschieben, dann die bbox neu bilden (achsparallel). let corners = rect_corners(g); @@ -786,18 +883,18 @@ fn resize_geom(g: &Value, w: f64, h: f64, fx: f64, fy: f64) -> Option { "circle" | "arc" => { // bbox eines Kreises ist 2r × 2r; Radius = grössere Zielhälfte, Mitte nicht-uniform um den Anker. let c = p("center"); - let r = num_of(g.get("r")); + let r = num_of(field(g, "r")); let ax = (c.0 - r) + fx * (2.0 * r); let ay = (c.1 - r) + fy * (2.0 * r); let half = jsnum::max(w, h) / 2.0; - let nr = if half > 0.0 { Some(js_num(half)) } else { g.get("r").cloned() }; + let nr = if half > 0.0 { Some(js_num(half)) } else { field(g, "r").cloned() }; let sx = if r > 1e-9 { (w / 2.0) / r } else { 1.0 }; let sy = if r > 1e-9 { (h / 2.0) / r } else { 1.0 }; with_opt(g, vec![("center", Some(pt(ax + (c.0 - ax) * sx, ay + (c.1 - ay) * sy))), ("r", nr)]) } "ellipse" => { let c = p("center"); - let (rx, ry) = (num_of(g.get("rx")), num_of(g.get("ry"))); + let (rx, ry) = (num_of(field(g, "rx")), num_of(field(g, "ry"))); let (ax, ay, sx, sy) = scale_around((c.0 - rx, c.1 - ry, c.0 + rx, c.1 + ry), w, h, fx, fy); with_all(g, vec![("center", pt(ax + (c.0 - ax) * sx, ay + (c.1 - ay) * sy)), ("rx", js_num(jsnum::max(1e-3, rx * sx))), ("ry", js_num(jsnum::max(1e-3, ry * sy)))]) } @@ -815,7 +912,7 @@ fn resize_geom(g: &Value, w: f64, h: f64, fx: f64, fy: f64) -> Option { /// Dach-Eckgriff: die gegenüberliegende Ecke bleibt fix, der Umriss bleibt ein achsparalleles Rechteck. fn roof_grip(r: &Value, index: f64, x: f64, y: f64) -> Option { - let outline = r.get("outline")?.as_array()?; + let outline = field(r, "outline")?.as_array()?; let n = outline.len(); if n < 4 { return None; @@ -831,20 +928,20 @@ fn roof_grip(r: &Value, index: f64, x: f64, y: f64) -> Option { /// Winkel-Mitte geteilt (wie `kernel2d` Bogen-Segmente zuschneidet); eine Näherung über tessellierte /// Punkte wäre zu ungenau. Die Bulge-Liste wird nur mitgeführt, wenn es eine gab. fn insert_point(d: &Value, seg: f64, x: f64, y: f64) -> Option { - let g = d.get("geom")?; + let g = field(d, "geom")?; if shape(g) != "polyline" { return None; } - let pts = arr(g.get("pts")); + let pts = arr(field(g, "pts")); let n = pts.len(); let k = index_in(seg, n)?; let last = k == n - 1; - if last && !truthy(g.get("closed")) { + if last && !truthy(field(g, "closed")) { return None; } let a = xy(&pts[k]); let b = xy(if last { &pts[0] } else { &pts[k + 1] }); - let bulge = num_or(arr(g.get("bulge")).get(k), 0.0); + let bulge = num_or(arr(field(g, "bulge")).get(k), 0.0); // `bulgeArc` der Fassade: gerade (|bulge| < 1e-9 oder NaN) ohne Bogen. let arc = if bulge.abs() >= 1e-9 { crate::bulge::arc(a.0, a.1, b.0, b.1, bulge) } else { vec![] }; let (insert, b1, b2) = if arc.len() >= 6 { @@ -863,8 +960,8 @@ fn insert_point(d: &Value, seg: f64, x: f64, y: f64) -> Option { np.push(insert); np.extend_from_slice(&pts[k + 1..]); let mut fields = vec![("pts", Value::Array(np))]; - if truthy(g.get("bulge")) { - let old = arr(g.get("bulge")); + if truthy(field(g, "bulge")) { + let old = arr(field(g, "bulge")); let mut nb: Vec = old.iter().take(k).cloned().collect(); nb.push(js_num(b1)); nb.push(js_num(b2)); @@ -899,17 +996,17 @@ fn wall_thickness(root: &Map, wall_id: &str, thickness: f64, new_ return vec![]; } let Some(wall) = find(root, "walls", wall_id) else { return vec![] }; - let wt_id = wall.get("wallTypeId"); - let Some(wt) = arr(root.get("wallTypes")).iter().find(|t| t.get("id") == wt_id) else { return vec![] }; - let layers = arr(wt.get("layers")); + let wt_id = field(wall, "wallTypeId"); + let Some(wt) = arr(root.get("wallTypes")).iter().find(|t| field(t, "id") == wt_id) else { return vec![] }; + let layers = arr(field(wt, "layers")); if layers.is_empty() { return vec![]; } - let wt_idv = wt.get("id"); - let used_by_others = arr(root.get("walls")).iter().any(|w| id_of(w) != Some(wall_id) && w.get("wallTypeId") == wt_idv); + let wt_idv = field(wt, "id"); + let used_by_others = arr(root.get("walls")).iter().any(|w| id_of(w) != Some(wall_id) && field(w, "wallTypeId") == wt_idv); if layers.len() == 1 && !used_by_others { let tid = id_of(wt).unwrap_or(""); - return find(root, "wallTypes", tid).map(|t| vec![replace("wallTypes", with(t, "layers", single_layer(arr(t.get("layers")), thickness)))]).unwrap_or_default(); + return find(root, "wallTypes", tid).map(|t| vec![replace("wallTypes", with(t, "layers", single_layer(arr(field(t, "layers")), thickness)))]).unwrap_or_default(); } vec![add("wallTypes", new_type(new_id, new_name, layers, thickness)), replace("walls", with(wall, "wallTypeId", new_id.into()))] } @@ -922,20 +1019,20 @@ fn ceiling_thickness(root: &Map, ceiling_id: &str, thickness: f64 } let Some(c) = find(root, "ceilings", ceiling_id) else { return vec![] }; let active = |c: &Value| -> Option { - let v = c.get("ceilingTypeId"); - if nullish(v) { c.get("wallTypeId").cloned() } else { v.cloned() } + let v = field(c, "ceilingTypeId"); + if nullish(v) { field(c, "wallTypeId").cloned() } else { v.cloned() } }; let active_id = active(c); - let by_id = |coll: &str, id: Option<&Value>| arr(root.get(coll)).iter().find(|t| t.get("id") == id).cloned(); - let Some(ct) = by_id("ceilingTypes", c.get("ceilingTypeId")).or_else(|| by_id("wallTypes", c.get("wallTypeId"))) else { return vec![] }; - let layers = arr(ct.get("layers")); + let by_id = |coll: &str, id: Option<&Value>| arr(root.get(coll)).iter().find(|t| field(t, "id") == id).cloned(); + let Some(ct) = by_id("ceilingTypes", field(c, "ceilingTypeId")).or_else(|| by_id("wallTypes", field(c, "wallTypeId"))) else { return vec![] }; + let layers = arr(field(&ct, "layers")); if layers.is_empty() { return vec![]; } let used_by_others = arr(root.get("ceilings")).iter().any(|o| id_of(o) != Some(ceiling_id) && active(o) == active_id); - if layers.len() == 1 && !used_by_others && truthy(c.get("ceilingTypeId")) { + if layers.len() == 1 && !used_by_others && truthy(field(c, "ceilingTypeId")) { let tid = id_of(&ct).unwrap_or(""); - return find(root, "ceilingTypes", tid).map(|t| vec![replace("ceilingTypes", with(t, "layers", single_layer(arr(t.get("layers")), thickness)))]).unwrap_or_default(); + return find(root, "ceilingTypes", tid).map(|t| vec![replace("ceilingTypes", with(t, "layers", single_layer(arr(field(t, "layers")), thickness)))]).unwrap_or_default(); } let mut nc = with(c, "ceilingTypeId", new_id.into()); if let Value::Object(m) = &mut nc { @@ -957,25 +1054,25 @@ pub fn drawing_vertices(g: &Value, scale: f64) -> Option> { Some(match shape(g) { "line" | "xline" | "ray" => vec![p("a"), p("b")], "polyline" => { - let bulge = arr(g.get("bulge")); - polyline_vertices(pts("pts"), truthy(g.get("closed")), |i| num_or(bulge.get(i), 0.0)) + let bulge = arr(field(g, "bulge")); + polyline_vertices(pts("pts"), truthy(field(g, "closed")), |i| num_or(bulge.get(i), 0.0)) } "rect" | "image" => rect_corners(g).to_vec(), "circle" => { - let (c, r) = (p("center"), num_of(g.get("r"))); + let (c, r) = (p("center"), num_of(field(g, "r"))); vec![(c.0 + r, c.1), (c.0, c.1 + r)] } "arc" => { - let (c, r) = (p("center"), num_of(g.get("r"))); - let (a0, a1) = (num_of(g.get("a0")), num_of(g.get("a1"))); + let (c, r) = (p("center"), num_of(field(g, "r"))); + let (a0, a1) = (num_of(field(g, "a0")), num_of(field(g, "a1"))); let mid = (a0 + a1) / 2.0; [a0, a1, mid].iter().map(|a| (c.0 + r * jsnum::cos(*a), c.1 + r * jsnum::sin(*a))).collect() } "ellipse" => { - let rot = num_of(g.get("rotation")); + let rot = num_of(field(g, "rotation")); let (c, s) = (jsnum::cos(rot), jsnum::sin(rot)); let ctr = p("center"); - let (rx, ry) = (num_of(g.get("rx")), num_of(g.get("ry"))); + let (rx, ry) = (num_of(field(g, "rx")), num_of(field(g, "ry"))); vec![(ctr.0 + rx * c, ctr.1 + rx * s), (ctr.0 - ry * s, ctr.1 + ry * c)] } "bezier" | "spline" => pts("pts"), @@ -986,14 +1083,14 @@ pub fn drawing_vertices(g: &Value, scale: f64) -> Option> { let (a, b) = (out.first().copied().unwrap_or(nan), out.last().copied().unwrap_or(nan)); let (dx, dy) = (b.0 - a.0, b.1 - a.1); let len = or1(hypot2(dx, dy)); - let offset = num_of(g.get("offset")); + let offset = num_of(field(g, "offset")); let (nx, ny) = ((-dy / len) * offset, (dx / len) * offset); out.push(((a.0 + b.0) / 2.0 + nx, (a.1 + b.1) / 2.0 + ny)); let h = dim_height(g, scale); - let offs = arr(g.get("textOffsetsMm")); + let offs = arr(field(g, "textOffsetsMm")); for i in 0..n.saturating_sub(1) { let (along, perp) = match offs.get(i) { - Some(o) if truthy(Some(o)) => (mm_to_model(num_of(o.get("along")), scale), mm_to_model(num_of(o.get("perp")), scale)), + Some(o) if truthy(Some(o)) => (mm_to_model(num_of(field(o, "along")), scale), mm_to_model(num_of(field(o, "perp")), scale)), _ => (0.0, 0.0), }; out.push(dim_text_pos(out[i], out[i + 1], offset, h, along, perp)); @@ -1002,14 +1099,14 @@ pub fn drawing_vertices(g: &Value, scale: f64) -> Option> { } "kote" | "detailref" | "scalebar" | "pointmarker" | "block" => vec![p("at")], "text" => { - if truthy(g.get("pathPts")) { + if truthy(field(g, "pathPts")) { pts("pathPts") - } else if truthy(g.get("leaderTarget")) { + } else if truthy(field(g, "leaderTarget")) { let mut out = vec![p("at")]; out.extend(pts("leaderBendPoints")); out.push(p("leaderTarget")); out - } else if truthy(g.get("width")) && num_of(g.get("width")) > 0.0 { + } else if truthy(field(g, "width")) && num_of(field(g, "width")) > 0.0 { return None; } else { vec![p("at")] @@ -1080,6 +1177,10 @@ mod tests { v.as_object().unwrap().clone() } + fn rq(v: Value) -> Request { + serde_json::from_value(v).unwrap() + } + fn entity(r: &GripResult) -> &Value { match &r.ops[0] { Op::Replace { entity, .. } => entity, @@ -1103,18 +1204,18 @@ mod tests { #[test] fn wand_griff_und_sperre() { let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}, "extra": 1}]})); - let res = run(&r, &json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]})).unwrap(); + let res = run(&r, &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]}))).unwrap(); assert_eq!(entity(&res).to_string(), r#"{"id":"w","start":{"x":0,"y":0},"end":{"x":2,"y":3},"extra":1}"#); let locked = root(json!({"walls": [{"id": "w", "locked": true, "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}}]})); - assert!(run(&locked, &json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]})).unwrap().ops.is_empty()); + assert!(run(&locked, &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]}))).unwrap().ops.is_empty()); // Fehlendes Element: keine Op. - assert!(run(&r, &json!({"op": "moveGrip", "wallId": "x", "index": 1, "pt": [2, 3]})).unwrap().ops.is_empty()); + assert!(run(&r, &rq(json!({"op": "moveGrip", "wallId": "x", "index": 1, "pt": [2, 3]}))).unwrap().ops.is_empty()); } #[test] fn kreis_wird_ellipse() { let r = root(json!({"drawings2d": [{"id": "d", "geom": {"shape": "circle", "center": {"x": 0, "y": 0}, "r": 1}}]})); - let res = run(&r, &json!({"op": "moveGrip", "drawingId": "d", "index": 0, "pt": [2, 0]})).unwrap(); + let res = run(&r, &rq(json!({"op": "moveGrip", "drawingId": "d", "index": 0, "pt": [2, 0]}))).unwrap(); assert_eq!(entity(&res)["geom"].to_string(), r#"{"shape":"ellipse","center":{"x":0,"y":0},"rx":2,"ry":1,"rotation":0}"#); } @@ -1130,14 +1231,14 @@ mod tests { #[test] fn nan_als_marke() { let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}}]})); - let res = run(&r, &json!({"op": "moveBy", "wallId": "w", "delta": ["\u{1}NaN", 0]})).unwrap(); + let res = run(&r, &rq(json!({"op": "moveBy", "wallId": "w", "delta": ["\u{1}NaN", 0]}))).unwrap(); assert_eq!(entity(&res)["start"]["x"], json!("\u{1}NaN")); } #[test] fn punkt_loeschen_mindestzahl() { let r = root(json!({"drawings2d": [{"id": "d", "geom": {"shape": "polyline", "closed": false, "pts": [{"x": 0, "y": 0}, {"x": 1, "y": 0}]}}]})); - let res = run(&r, &json!({"op": "deletePoint", "id": "d", "index": 0})).unwrap(); + let res = run(&r, &rq(json!({"op": "deletePoint", "id": "d", "index": 0}))).unwrap(); assert_eq!(res.notice, Some("alert.polylineMinPoints")); assert!(res.ops.is_empty()); } @@ -1148,7 +1249,7 @@ mod tests { "wallTypes": [{"id": "wt", "name": "W", "layers": [{"componentId": "c", "thickness": 0.2}]}], "ceilings": [{"id": "c1", "wallTypeId": "wt", "thickness": 0.3}, {"id": "c2", "wallTypeId": "wt"}], })); - let ops = run(&r, &json!({"op": "ceilingThickness", "id": "c1", "thickness": 0.25, "newId": "ct-1", "newName": "Decke"})).unwrap().ops; + let ops = run(&r, &rq(json!({"op": "ceilingThickness", "id": "c1", "thickness": 0.25, "newId": "ct-1", "newName": "Decke"}))).unwrap().ops; assert_eq!(crate::ops::ops_to_json(&ops), r#"[{"kind":"add","collection":"ceilingTypes","items":[{"id":"ct-1","name":"Decke","layers":[{"componentId":"c","thickness":0.25}]}]},{"kind":"replace","collection":"ceilings","entity":{"id":"c1","wallTypeId":"wt","ceilingTypeId":"ct-1"}}]"#); } diff --git a/src-tauri/core/src/js_fmt.rs b/src-tauri/core/src/js_fmt.rs index 26ab7eff..4a5eae8d 100644 --- a/src-tauri/core/src/js_fmt.rs +++ b/src-tauri/core/src/js_fmt.rs @@ -15,6 +15,30 @@ pub fn to_fixed(x: f64, d: usize) -> String { if ax >= 1e21 { return format!("{}{}", if neg { "-" } else { "" }, ax); } + // Schnellweg: Rust rundet `{:.N}` korrekt (zum geraden Nachbarn nur bei exakten Halbwerten); ohne + // exakten Halbwert ist das Ergebnis dasselbe wie in JS, nur ohne die teure lange Formatierung. + if !exact_half(ax, d) { + let s = format!("{:.*}", d, ax); + return if neg { format!("-{s}") } else { s }; + } + to_fixed_wide(ax, d, neg) +} + +/// Ob `ax` (endlich, ≥ 0) bei `d` Nachkommastellen genau auf der Mitte zwischen zwei Ergebnissen liegt: +/// `ax · 10^d · 2` ist eine ungerade ganze Zahl, d. h. das niedrigste gesetzte Bit von `ax` ist 2^-(d+1). +fn exact_half(ax: f64, d: usize) -> bool { + if ax == 0.0 { + return false; + } + let bits = ax.to_bits(); + let exp = ((bits >> 52) & 0x7ff) as i64; + let frac = bits & ((1u64 << 52) - 1); + let (m, e) = if exp == 0 { (frac, -1074) } else { (frac | (1u64 << 52), exp - 1075) }; + e + m.trailing_zeros() as i64 + d as i64 + 1 == 0 +} + +/// Langsamer, exakter Weg (für exakte Halbwerte): Ziffern mit 25 Stellen Reserve, dann aufrunden. +fn to_fixed_wide(ax: f64, d: usize, neg: bool) -> String { // 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"); @@ -119,5 +143,30 @@ mod tests { 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"); + assert_eq!(to_fixed(0.25, 1), "0.3"); + assert_eq!(to_fixed(-0.25, 1), "-0.3"); + assert_eq!(to_fixed(-0.0, 2), "0.00"); + } + + #[test] + fn schnellweg_gleich_dem_genauen_weg() { + let mut x: u64 = 0x2545_f491_4f6c_dd1d; + for i in 0..200_000 { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + let v = match i % 4 { + 0 => (x % 1_000_000) as f64 / 1000.0, + 1 => f64::from_bits(x) % 1e6, + 2 => (x % 4096) as f64 / 64.0, + _ => (x as f64 / u64::MAX as f64 - 0.5) * 100.0, + }; + if !v.is_finite() { + continue; + } + for d in 0..8 { + assert_eq!(to_fixed(v, d), to_fixed_wide(v.abs(), d, v < 0.0), "{v} {d}"); + } + } } } diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 4b6d1529..1241c361 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -82,6 +82,7 @@ pub mod geo_translate; pub mod selection_filter; pub mod reorder; pub mod grips; +pub mod selection_info; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs index 5c7d6ee4..d956ec1f 100644 --- a/src-tauri/core/src/queries.rs +++ b/src-tauri/core/src/queries.rs @@ -100,9 +100,20 @@ pub fn run_root(root: &serde_json::Map, name: &str, t } // Griff-Änderungen ([K4] S3, `grips.rs`): `text` = JSON der Anfrage; Antwort `{ops, notice}` (ohne Commit). "gripOps" => { - let req: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("gripOps: {e}"))?; + let req: crate::grips::Request = serde_json::from_str(text).map_err(|e| format!("gripOps: {e}"))?; Ok(crate::grips::result_json(&crate::grips::run(root, &req)?)) } + // Objekt-Info der Auswahl ([K4] S3, `selection_info.rs`): `text` = JSON der gewählten ids je Art; Antwort + // `Selection` (TS) oder null, Zahlen mit Nicht-endlich-Marken. + "selectionInfo" => { + let a: crate::selection_info::SelArgs = serde_json::from_str(text).map_err(|e| format!("selectionInfo: {e}"))?; + crate::selection_info::derive(root, &a).map(crate::selection_info::J::into_string) + } + // Bounding-Boxen von Zeichnungen (Ausrichten/Verteilen): `text` = JSON der ids. + "drawingBBoxes" => { + let ids: Vec = serde_json::from_str(text).map_err(|e| format!("drawingBBoxes: {e}"))?; + Ok(crate::selection_info::drawing_bboxes(root, &ids).into_string()) + } _ => Err(format!("Unbekannte Wurzel-Abfrage: {name}")), } } diff --git a/src-tauri/core/src/selection_info.rs b/src-tauri/core/src/selection_info.rs new file mode 100644 index 00000000..170e07ae --- /dev/null +++ b/src-tauri/core/src/selection_info.rs @@ -0,0 +1,1242 @@ +//! Objekt-Info der Auswahl ([K4] S3, vorher `deriveSelection` in `src/state/selectionInfo.ts`): die +//! anzeigefertigen, effektiv aufgelösten Attribute des ERSTEN gewählten Elements für die Paletten +//! (Attribute, Objekt-Info) — Farbe/Strichstärke/Schraffur nach derselben Kette wie der Plan, Masse, +//! Flächen, Volumen, UK/OK, die Listen der Dropdowns (Wand-/Deckentypen, Geschosse, Layouts) und je +//! Bauteilart die eigenen Felder. Ausgabe: JSON in der Form `Selection` (TS), Schlüssel in der +//! Reihenfolge der früheren Objekt-Literale, fehlende (`undefined`) Felder weggelassen. +//! +//! Rechnung auf der rohen Projekt-Wurzel (verlustfrei, keine typisierte Sicht des ganzen Projekts — +//! nach einem Mausschritt an einer grossen Liste wäre deren Neueinlesen teurer als die Abfrage). Nur das +//! gewählte Dach, die Treppe und die Stütze werden typisiert gelesen, wo die Geometrie schon typisiert im +//! Kern steht (`roof.rs`, `stair.rs`, `model3d::column_footprint`). Zahlen wie in JS: `null` rechnet wie +//! 0 (`grips::num_of`), nicht endliche Ergebnisse reisen als Marken (`grips::js_num`). +//! +//! Wo TS warf (unbekannter Wandtyp, Deckentyp oder Bauteil), kommt dieselbe Meldung als Fehler. +//! Der B-Rep-Körper einer Extrusion (`spec`) bleibt in TS (truck-Pipeline, `plan/extrudedSolidSpec.ts`). + +use crate::grips::{field, js_num, num_of, truthy, xy}; +use crate::jsmath::hypot2; +use crate::jsnum; +use crate::ops::id_of; +use serde_json::{Map, Value}; + +const WALL_FALLBACK_MM: f64 = 0.18; +const DRAW_FALLBACK_COLOR: &str = "#d0d0d0"; +const WALL_FALLBACK_COLOR: &str = "#2b3039"; +const EXTRUSION_COLOR: &str = "#d98c40"; +const COLUMN_COLOR: &str = "#3a3f47"; + +/// Gewählte ids je Art (wie die Parameter von `deriveSelection`). +#[derive(serde::Deserialize, Default)] +#[serde(default, rename_all = "camelCase")] +pub struct SelArgs { + pub wall_ids: Vec, + pub drawing_id: Option, + pub ceiling_id: Option, + pub opening_id: Option, + pub stair_id: Option, + pub room_id: Option, + pub extruded_solid_id: Option, + pub column_id: Option, + pub roof_id: Option, + pub context_object_id: Option, + /// Lage der Elemente in ihren Listen (Liste → Index), von der Leseansicht; der Kern prüft die id an + /// dieser Stelle und sucht sonst linear (die Suche über grosse Listen kostet je Element). + pub at: std::collections::HashMap, +} + +// ── Hilfen ─────────────────────────────────────────────────────────────────── + +/// JSON-Text eines Werts. Die Antwort wird direkt als Text geschrieben (kein `Value`-Baum mit je +/// Schlüssel einer Zuteilung), durchgereichte Felder werden nur gelesen, nicht kopiert. +pub struct J(Vec); + +impl J { + fn null() -> J { + J(b"null".to_vec()) + } + fn arr(items: impl IntoIterator) -> J { + let mut out = vec![b'[']; + for (i, it) in items.into_iter().enumerate() { + if i > 0 { + out.push(b','); + } + out.extend(it.0); + } + out.push(b']'); + J(out) + } + pub fn into_string(self) -> String { + String::from_utf8(self.0).unwrap_or_default() + } +} + +/// Etwas, das sich als JSON schreiben lässt (Wert, Text-Stück). +trait Emit { + fn emit(&self, out: &mut Vec); +} +impl Emit for Value { + fn emit(&self, out: &mut Vec) { + let _ = serde_json::to_writer(out, self); + } +} +impl Emit for J { + fn emit(&self, out: &mut Vec) { + out.extend_from_slice(&self.0); + } +} +impl Emit for &T { + fn emit(&self, out: &mut Vec) { + (*self).emit(out) + } +} + +/// Objekt in Schlüssel-Reihenfolge; `undefined` (None/fehlend) entfällt. +struct O(Vec); + +impl Default for O { + fn default() -> Self { + O(vec![b'{']) + } +} + +impl O { + fn key(&mut self, k: &str) { + if self.0.len() > 1 { + self.0.push(b','); + } + self.0.push(b'"'); + self.0.extend_from_slice(k.as_bytes()); + self.0.extend_from_slice(b"\":"); + } + fn v(mut self, k: &str, v: impl Emit) -> Self { + self.key(k); + v.emit(&mut self.0); + self + } + fn o(self, k: &str, v: Option) -> Self { + match v { + Some(v) => self.v(k, v), + None => self, + } + } + fn n(self, k: &str, x: f64) -> Self { + self.v(k, js_num(x)) + } + fn s(self, k: &str, s: &str) -> Self { + self.v(k, Value::from(s)) + } + /// Feld `key` von `src` unverändert durchreichen (fehlend = `undefined`). + fn raw(self, k: &str, src: &Value, key: &str) -> Self { + self.o(k, field(src, key)) + } + fn done(mut self) -> J { + self.0.push(b'}'); + J(self.0) + } +} + +fn arr(v: Option<&Value>) -> &[Value] { + v.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]) +} + +/// Erstes Element mit `id` in einer Liste der Wurzel (`hint`: vermutete Lage, wird geprüft). +fn find<'a>(root: &'a Map, list: &str, id: &str, hint: Option) -> Option<&'a Value> { + let l = arr(root.get(list)); + if let Some(e) = hint.filter(|h| h.fract() == 0.0 && *h >= 0.0).and_then(|h| l.get(h as usize)) { + if id_of(e) == Some(id) { + return Some(e); + } + } + l.iter().find(|e| id_of(e) == Some(id)) +} + +/// Erstes Element, dessen Feld `key` gleich `val` ist (`===`; fehlend gleich fehlend). +fn find_by<'a>(list: &'a [Value], key: &str, val: Option<&Value>) -> Option<&'a Value> { + list.iter().find(|e| field(e, key) == val) +} + +/// `a ?? b`: Wert, ausser fehlend/`null`. +fn nn(v: Option<&Value>) -> Option<&Value> { + v.filter(|x| !x.is_null()) +} + +fn str_of(v: Option<&Value>) -> Option<&str> { + v.and_then(Value::as_str) +} + +/// `String(v)` für die Anzeige (Name eines Geschosses). +fn js_string(v: &Value) -> Value { + match v { + Value::String(_) => v.clone(), + Value::Number(n) => Value::from(crate::js_fmt::js_number(n.as_f64().unwrap_or(f64::NAN))), + Value::Null => Value::from("null"), + Value::Bool(b) => Value::from(if *b { "true" } else { "false" }), + _ => Value::from("[object Object]"), + } +} + +/// Kategorie (Ebene) per Code: erster Treffer der Tiefensuche (`findCategory`). +fn category<'a>(root: &'a Map, code: Option<&Value>) -> Option<&'a Value> { + fn walk<'a>(list: &'a [Value], code: Option<&Value>) -> Option<&'a Value> { + for c in list { + if field(c, "code") == code { + return Some(c); + } + if let Some(hit) = walk(arr(field(c, "children")), code) { + return Some(hit); + } + } + None + } + walk(arr(root.get("layers")), code) +} + +/// `getComponent`: Bauteil per id oder Fehler (Meldung wie TS). +fn component<'a>(root: &'a Map, id: Option<&Value>) -> Result<&'a Value, String> { + find_by(arr(root.get("components")), "id", id).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {}", id.map_or("undefined".into(), |v| js_text(v)))) +} + +/// Wert in einer Template-Zeichenkette (`${v}`). +fn js_text(v: &Value) -> String { + match js_string(v) { + Value::String(s) => s, + _ => String::new(), + } +} + +/// `x.color ?? cat?.color ?? fallback`. +fn color_of(el: &Value, cat: Option<&Value>, fallback: &str) -> Value { + nn(field(el, "color")).or_else(|| cat.and_then(|c| nn(field(c, "color")))).cloned().unwrap_or_else(|| fallback.into()) +} + +/// Strichstärke `x ?? cat?.lw ?? fallback` (nur die Kategorie-Kette). +fn lw_or(over: Option<&Value>, cat: Option<&Value>, fallback: f64) -> Value { + nn(over).or_else(|| cat.and_then(|c| nn(field(c, "lw")))).cloned().unwrap_or_else(|| js_num(fallback)) +} + +fn is_layer(src: Option<&Value>) -> bool { + str_of(src) == Some("layer") +} + +/// `resolveForeground`/`resolveBackground`: Override ?? (Quelle „layer" ⇒ Kategorie-Farbe) ?? Bauteil-Feld. +fn resolve_color(comp_field: Option<&Value>, over: Option<&Value>, cat: Option<&Value>, source: Option<&Value>) -> Option { + if let Some(o) = nn(over) { + return Some(o.clone()); + } + if is_layer(source) { + if let Some(c) = cat { + return nn(field(c, "color")).cloned().or_else(|| comp_field.cloned()); + } + } + comp_field.cloned() +} + +/// `resolveHatchId`: Override ?? (Quelle „layer" ⇒ Kategorie-Schraffur) ?? Rückfall. +fn resolve_hatch(over: Option<&Value>, source: Option<&Value>, cat: Option<&Value>, fallback: Option<&Value>) -> Option { + if let Some(o) = nn(over) { + return Some(o.clone()); + } + if is_layer(source) { + return cat.and_then(|c| nn(field(c, "hatch"))).or(fallback).cloned(); + } + fallback.cloned() +} + +/// Bauteil-Feld (`comp.foreground` …) als Rückfall, unverändert (auch `null`). +fn cf<'a>(comp: Option<&'a Value>, key: &str) -> Option<&'a Value> { + comp.and_then(|c| c.get(key)) +} + +/// Achsparallele bbox mit `Math.min/max`; nicht endlich → Null-Box. +fn bbox_of(pts: impl IntoIterator) -> [f64; 4] { + let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for (x, y) in pts { + x0 = jsnum::min(x0, x); + y0 = jsnum::min(y0, y); + x1 = jsnum::max(x1, x); + y1 = jsnum::max(y1, y); + } + if !x0.is_finite() { + return [0.0; 4]; + } + [x0, y0, x1, y1] +} + +fn bbox_value(b: [f64; 4]) -> J { + O::default().n("minX", b[0]).n("minY", b[1]).n("maxX", b[2]).n("maxY", b[3]).done() +} + +fn pts_of(v: Option<&Value>) -> Vec<(f64, f64)> { + arr(v).iter().map(xy).collect() +} + +fn ring(v: Option<&Value>) -> Vec<[f64; 2]> { + arr(v).iter().map(|p| xy(p).into()).collect() +} + +/// Polygonfläche (immer positiv, `polygonArea` = Raum-Bewertung im Kern). +fn polygon_area(v: Option<&Value>) -> f64 { + crate::room_area::evaluate(&ring(v), 0.0).gross +} + +/// Deckenfläche `|signedArea|` (kernel2d). +fn ceiling_area(v: Option<&Value>) -> f64 { + let p: Vec = pts_of(v).into_iter().map(|(x, y)| kernel2d::Vec2::new(x, y)).collect(); + kernel2d::signed_area(&p).abs() +} + +/// Summe der Schichtdicken (`wallTypeThickness`, `reduce` ab 0). +fn type_thickness(t: &Value) -> f64 { + arr(field(t, "layers")).iter().fold(0.0, |s, l| s + num_of(field(l, "thickness"))) +} + +/// Geschosse (`kind === "floor"`) als `{id, name}`. +fn floors(root: &Map) -> J { + J::arr( + arr(root.get("drawingLevels")) + .iter() + .filter(|z| str_of(field(z, "kind")) == Some("floor")) + .map(|z| O::default().raw("id", z, "id").raw("name", z, "name").done()), + ) +} + +fn level<'a>(root: &'a Map, id: Option<&Value>) -> Option<&'a Value> { + find_by(arr(root.get("drawingLevels")), "id", id) +} + +/// `floor?.name ?? fallback`. +fn floor_name(floor: Option<&Value>, fallback: Option<&Value>) -> Option { + floor.and_then(|f| nn(field(f, "name"))).or(fallback).cloned() +} + +/// UK/OK-Bindung (`resolveAnchor`): absolutes Z oder `None` (Rückfall des Aufrufers). +fn anchor(root: &Map, a: Option<&Value>) -> Option { + let a = a.filter(|a| truthy(Some(a)))?; + if str_of(field(a, "mode")) == Some("custom") { + // `return anchor.z` — fehlend/null fällt beim `??` des Aufrufers zurück. + return nn(field(a, "z")).map(|z| num_of(Some(z))); + } + let f = level(root, field(a, "floorId"))?; + Some(num_or(field(f, "baseElevation"), 0.0) + num_or(field(a, "offset"), 0.0)) +} + +fn num_or(v: Option<&Value>, d: f64) -> f64 { + if nn(v).is_some() { + num_of(v) + } else { + d + } +} + +/// (UK, OK) einer Wand oder Stütze: UK aus `bottom` sonst Geschoss-Basis, OK aus `top` sonst UK + Höhe. +fn vertical_extent(root: &Map, el: &Value) -> (f64, f64) { + let floor_base = level(root, field(el, "floorId")).map_or(0.0, |f| num_or(field(f, "baseElevation"), 0.0)); + let zb = anchor(root, field(el, "bottom")).unwrap_or(floor_base); + let zt = anchor(root, field(el, "top")).unwrap_or(zb + num_of(field(el, "height"))); + (zb, zt) +} + +/// Aufbau-Typ einer Decke (`getCeilingType`): eigener Deckentyp, sonst Alt-Wandtyp, sonst Fehler. +fn ceiling_type<'a>(root: &'a Map, c: &Value) -> Result<&'a Value, String> { + if truthy(field(c, "ceilingTypeId")) { + if let Some(t) = find_by(arr(root.get("ceilingTypes")), "id", field(c, "ceilingTypeId")) { + return Ok(t); + } + } + find_by(arr(root.get("wallTypes")), "id", field(c, "wallTypeId")) + .ok_or_else(|| format!("Unbekannter Deckentyp: {}", nn(field(c, "ceilingTypeId")).or(field(c, "wallTypeId")).map_or("undefined".into(), js_text))) +} + +/// Deckendicke (`ceilingThickness`): `thickness` > 0, sonst Typ-Dicke, sonst 0.2. +fn ceiling_thickness(root: &Map, c: &Value) -> f64 { + if nn(field(c, "thickness")).is_some() && num_of(field(c, "thickness")) > 0.0 { + return num_of(field(c, "thickness")); + } + ceiling_type(root, c).map_or(0.2, type_thickness) +} + +/// `wallTypeLabel`: Kürzel + Dicke in cm (einschichtig „BET 24", mehrschichtig „GKB·BET (25.5)"), sonst der Name. +fn wall_type_label(root: &Map, t: &Value) -> Value { + let comps = arr(root.get("components")); + let total_cm: f64 = crate::js_fmt::to_fixed(type_thickness(t) * 100.0, 1).parse().unwrap_or(f64::NAN); + let cm = if total_cm % 1.0 == 0.0 { jsnum::to_int32(total_cm).to_string() } else { crate::js_fmt::js_number(total_cm) }; + let layers = arr(field(t, "layers")); + let abbrevs: Vec = layers + .iter() + .map(|l| find_by(comps, "id", field(l, "componentId")).and_then(|c| nn(field(c, "abbrev"))).map_or(String::new(), js_text)) + .collect(); + if abbrevs.iter().all(|a| !a.is_empty()) { + if layers.len() == 1 { + return Value::from(format!("{} {cm}", abbrevs[0])); + } + return Value::from(format!("{} ({cm})", abbrevs.join("·"))); + } + field(t, "name").cloned().unwrap_or(Value::Null) +} + +/// Einträge der Typ-Auswahl (`WallTypeChoice`). +fn type_choices(root: &Map, list: &str) -> J { + J::arr( + arr(root.get(list)) + .iter() + .map(|t| { + O::default() + .raw("id", t, "id") + .raw("name", t, "name") + .v("label", wall_type_label(root, t)) + .n("thickness", type_thickness(t)) + .v("layerCount", Value::from(arr(field(t, "layers")).len())) + .done() + }), + ) +} + +/// Effektive Vordergrund-/Hintergrund-/Schraffur-Vorschau eines Bauteils (äusserste Schicht bzw. das +/// zugewiesene Bauteil als Repräsentant). +fn effective(el: &Value, comp: Option<&Value>, cat: Option<&Value>) -> (Option, Option, Option) { + let fg = if comp.is_some() { resolve_color(cf(comp, "foreground"), field(el, "foreground"), cat, field(el, "foregroundSource")) } else { field(el, "foreground").cloned() }; + let bg = if comp.is_some() { resolve_color(cf(comp, "background"), field(el, "background"), cat, field(el, "backgroundSource")) } else { field(el, "background").cloned() }; + let hatch = resolve_hatch(field(el, "hatchId"), field(el, "hatchSource"), cat, cf(comp, "hatchId")); + (fg, bg, hatch) +} + +// ── Abfrage ────────────────────────────────────────────────────────────────── + +/// Objekt-Info des ersten gewählten Elements (Vorrang wie `deriveSelection`); `Value::Null` = nichts. +pub fn derive(root: &Map, a: &SelArgs) -> Result { + fn id(o: &Option) -> Option<&str> { + o.as_deref().filter(|s| !s.is_empty()) + } + if let Some(i) = id(&a.context_object_id) { + if let Some(o) = find(root, "context", i, a.at.get("context").copied()) { + return Ok(context_selection(root, o)); + } + } + if let Some(i) = id(&a.drawing_id) { + return Ok(find(root, "drawings2d", i, a.at.get("drawings2d").copied()).map_or(J::null(), |d| drawing_selection(root, d))); + } + if let Some(i) = id(&a.extruded_solid_id) { + return Ok(find(root, "extrudedSolids", i, a.at.get("extrudedSolids").copied()).map_or(J::null(), |s| solid_selection(root, s))); + } + if let Some(i) = id(&a.column_id) { + return find(root, "columns", i, a.at.get("columns").copied()).map_or(Ok(J::null()), |c| column_selection(root, c)); + } + if let Some(i) = id(&a.opening_id) { + if let Some(o) = find(root, "openings", i, a.at.get("openings").copied()) { + return opening_selection(root, o); + } + } + if let Some(i) = a.wall_ids.first().filter(|s| !s.is_empty()) { + return find(root, "walls", i, a.at.get("walls").copied()).map_or(Ok(J::null()), |w| wall_selection(root, w)); + } + if let Some(i) = id(&a.ceiling_id) { + return find(root, "ceilings", i, a.at.get("ceilings").copied()).map_or(Ok(J::null()), |c| ceiling_selection(root, c)); + } + if let Some(i) = id(&a.roof_id) { + return find(root, "roofs", i, a.at.get("roofs").copied()).map_or(Ok(J::null()), |r| roof_selection(root, r)); + } + if let Some(i) = id(&a.stair_id) { + return find(root, "stairs", i, a.at.get("stairs").copied()).map_or(Ok(J::null()), |s| stair_selection(root, s)); + } + if let Some(i) = id(&a.room_id) { + return Ok(find(root, "rooms", i, a.at.get("rooms").copied()).map_or(J::null(), |r| room_selection(root, r))); + } + Ok(J::null()) +} + +fn wall_selection(root: &Map, w: &Value) -> Result { + let cat = category(root, field(w, "categoryCode")); + let color = color_of(w, cat, WALL_FALLBACK_COLOR); + let weight = lw_or(field(w, "strokeWeight"), cat, WALL_FALLBACK_MM); + let (s, e) = (xy(field(w, "start").unwrap_or(&Value::Null)), xy(field(w, "end").unwrap_or(&Value::Null))); + let bb = [jsnum::min(s.0, e.0), jsnum::min(s.1, e.1), jsnum::max(s.0, e.0), jsnum::max(s.1, e.1)]; + let wt = find_by(arr(root.get("wallTypes")), "id", field(w, "wallTypeId")) + .ok_or_else(|| format!("Unbekannter Wandtyp: {}", field(w, "wallTypeId").map_or("undefined".into(), js_text)))?; + let thickness = type_thickness(wt); + let layers = arr(field(wt, "layers")); + let outer = component(root, layers.first().and_then(|l| field(l, "componentId")))?; + let (fg, bg, hatch) = effective(w, Some(outer), cat); + let floor = level(root, field(w, "floorId")); + let (zb, zt) = vertical_extent(root, w); + let above = next_floor_above(root, field(w, "floorId")); + let length = hypot2(e.0 - s.0, e.1 - s.1); + let height = jsnum::max(0.0, zt - zb); + let gross = length * thickness * height; + let opening_volume = arr(root.get("openings")) + .iter() + .filter(|o| field(o, "hostWallId") == field(w, "id")) + .fold(0.0, |sum, o| sum + num_of(field(o, "width")) * num_of(field(o, "height")) * thickness); + let net = jsnum::max(0.0, gross - opening_volume); + // Interne Schichttrennlinien als wählbare Referenz: Achsversatz +n = halbe Dicke − Fugenlage. + let half = thickness / 2.0; + let mut cum = 0.0; + let mut boundaries = Vec::new(); + let abbrev = |l: &Value| -> Result { + let c = component(root, field(l, "componentId"))?; + Ok(nn(field(c, "abbrev")).or_else(|| field(c, "name")).map_or("undefined".into(), js_text)) + }; + for i in 0..layers.len().saturating_sub(1) { + cum += num_of(field(&layers[i], "thickness")); + let label = format!("{}|{}", abbrev(&layers[i])?, abbrev(&layers[i + 1])?); + boundaries.push(O::default().n("offset", half - cum).s("label", &label).done()); + } + let info = O::default() + .v("referenceLine", nn(field(w, "referenceLine")).cloned().unwrap_or_else(|| "center".into())) + .raw("referenceOffset", w, "referenceOffset") + .v("layerBoundaries", J::arr(boundaries)) + .v("sliceTermination", nn(field(w, "sliceTermination")).cloned().unwrap_or_else(|| "both".into())) + .raw("wallTypeId", w, "wallTypeId") + .n("thickness", thickness) + .v("singleLayer", Value::Bool(layers.len() <= 1)) + .v("wallTypes", type_choices(root, "wallTypes")) + .raw("floorId", w, "floorId") + .o("floorName", floor_name(floor, field(w, "floorId"))) + .v("floors", floors(root)) + .o("floorAbove", above) + .raw("bottom", w, "bottom") + .raw("top", w, "top") + .n("zBottom", zb) + .n("zTop", zt) + .n("length", length) + .n("grossVolume", gross) + .n("openingVolume", opening_volume) + .n("netVolume", net) + .done(); + Ok(O::default() + .s("kind", "wall") + .raw("id", w, "id") + .raw("categoryCode", w, "categoryCode") + .raw("floorId", w, "floorId") + .v("color", color) + .raw("colorPenId", w, "colorPenId") + .v("weightMm", weight) + .raw("fillHatchId", w, "hatchId") + .raw("foreground", w, "foreground") + .raw("foregroundPenId", w, "foregroundPenId") + .raw("background", w, "background") + .raw("backgroundPenId", w, "backgroundPenId") + .raw("foregroundSource", w, "foregroundSource") + .raw("backgroundSource", w, "backgroundSource") + .o("effectiveForeground", fg) + .o("effectiveBackground", bg) + .o("effectiveHatchId", hatch) + .raw("strokeWeightOverride", w, "strokeWeight") + .raw("strokeWeightSource", w, "strokeWeightSource") + .raw("hatchSource", w, "hatchSource") + .v("bbox", bbox_value(bb)) + .v("wall", info) + .done()) +} + +/// Geschoss direkt über `floor_id` (Reihenfolge der „floor"-Ebenen), `{id, name}`. +fn next_floor_above(root: &Map, floor_id: Option<&Value>) -> Option { + let fl: Vec<&Value> = arr(root.get("drawingLevels")).iter().filter(|z| str_of(field(z, "kind")) == Some("floor")).collect(); + let idx = fl.iter().position(|z| field(z, "id") == floor_id)?; + fl.get(idx + 1).map(|a| O::default().raw("id", a, "id").raw("name", a, "name").done()) +} + +fn ceiling_selection(root: &Map, c: &Value) -> Result { + let cat = category(root, field(c, "categoryCode")); + let color = color_of(c, cat, WALL_FALLBACK_COLOR); + let weight = lw_or(field(c, "strokeWeight"), cat, WALL_FALLBACK_MM); + let bb = bbox_of(pts_of(field(c, "outline"))); + let wt = ceiling_type(root, c)?; + let thickness = ceiling_thickness(root, c); + let outer = component(root, arr(field(wt, "layers")).first().and_then(|l| field(l, "componentId")))?; + let (fg, bg, hatch) = effective(c, Some(outer), cat); + let floor = level(root, field(c, "floorId")); + let floor_top = floor.map_or(0.0, |f| num_or(field(f, "baseElevation"), 0.0) + num_or(field(f, "floorHeight"), 0.0)); + let zt = anchor(root, field(c, "top")).unwrap_or(floor_top); + let zb = anchor(root, field(c, "bottom")).unwrap_or(zt - thickness); + let area = ceiling_area(field(c, "outline")); + let openings: Vec = arr(field(c, "openings")) + .iter() + .map(|hole| { + let b = bbox_of(pts_of(Some(hole))); + O::default().n("width", b[2] - b[0]).n("depth", b[3] - b[1]).done() + }) + .collect(); + let info = O::default() + .o("typeId", nn(field(c, "ceilingTypeId")).or(field(c, "wallTypeId")).cloned()) + .n("thickness", thickness) + .v("singleLayer", Value::Bool(arr(field(wt, "layers")).len() <= 1)) + .n("area", area) + .n("volume", area * thickness) + .v("ceilingTypes", type_choices(root, "ceilingTypes")) + .raw("floorId", c, "floorId") + .o("floorName", floor_name(floor, field(c, "floorId"))) + .v("floors", floors(root)) + .raw("top", c, "top") + .raw("bottom", c, "bottom") + .n("zBottom", zb) + .n("zTop", zt) + .v("openings", J::arr(openings)) + .done(); + Ok(O::default() + .s("kind", "ceiling") + .raw("id", c, "id") + .raw("categoryCode", c, "categoryCode") + .raw("floorId", c, "floorId") + .v("color", color) + .raw("colorPenId", c, "colorPenId") + .v("weightMm", weight) + .raw("fillHatchId", c, "hatchId") + .raw("foreground", c, "foreground") + .raw("foregroundPenId", c, "foregroundPenId") + .raw("background", c, "background") + .raw("backgroundPenId", c, "backgroundPenId") + .raw("foregroundSource", c, "foregroundSource") + .raw("backgroundSource", c, "backgroundSource") + .o("effectiveForeground", fg) + .o("effectiveBackground", bg) + .o("effectiveHatchId", hatch) + .raw("strokeWeightOverride", c, "strokeWeight") + .raw("strokeWeightSource", c, "strokeWeightSource") + .raw("hatchSource", c, "hatchSource") + .v("closed", Value::Bool(true)) + .v("bbox", bbox_value(bb)) + .v("ceiling", info) + .done()) +} + +fn roof_selection(root: &Map, r: &Value) -> Result { + let cat = category(root, field(r, "categoryCode")); + let color = color_of(r, cat, WALL_FALLBACK_COLOR); + let weight = lw_or(None, cat, WALL_FALLBACK_MM); + // `roofBBox`: Vergleiche ohne Math.min (NaN wird übergangen), leer = ±∞. + let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for (x, y) in pts_of(field(r, "outline")) { + if x < x0 { + x0 = x; + } + if y < y0 { + y0 = y; + } + if x > x1 { + x1 = x; + } + if y > y1 { + y1 = y; + } + } + // `roof.baseElevation !== undefined` (auch `null` gilt als gesetzt, rechnet wie 0 und bleibt in der Ausgabe null). + let (eaves, eaves_out) = match field(r, "baseElevation") { + Some(b) => (num_of(Some(b)), b.clone()), + None => { + let z = level(root, field(r, "floorId")).map_or(0.0, |f| num_or(field(f, "baseElevation"), 0.0) + num_or(field(f, "floorHeight"), 0.0)); + (z, js_num(z)) + } + }; + let ridge_height = roof_ridge_height(r, eaves)?; + let (w, d) = ((x1 - x0).abs(), (y1 - y0).abs()); + let holes: Vec = arr(field(r, "holes")) + .iter() + .map(|h| O::default().n("area", polygon_area(Some(h)).abs()).v("points", Value::from(arr(Some(h)).len())).done()) + .collect(); + let info = O::default() + .raw("shape", r, "shape") + .raw("pitchDeg", r, "pitchDeg") + .raw("pitchUpperDeg", r, "pitchUpperDeg") + .raw("roofTypeId", r, "roofTypeId") + .raw("mansardType", r, "mansardType") + .raw("mansardKneeRatio", r, "mansardKneeRatio") + .raw("halfHipRatio", r, "halfHipRatio") + .raw("overhang", r, "overhang") + .raw("overhangGable", r, "overhangGable") + .raw("ridgeAxis", r, "ridgeAxis") + .raw("thickness", r, "thickness") + .v("baseElevation", eaves_out) + .n("ridgeHeight", ridge_height) + .n("footprintArea", w * d) + .n("width", w) + .n("depth", d) + .n("minX", x0) + .n("minY", y0) + .v("edges", roof_edges(r)) + .v("holes", J::arr(holes)) + .v("hasEdgePitch", Value::Bool(field(r, "edgePitchDeg").is_some())) + .done(); + Ok(O::default() + .s("kind", "roof") + .raw("id", r, "id") + .raw("categoryCode", r, "categoryCode") + .raw("floorId", r, "floorId") + .v("color", color) + .raw("colorPenId", r, "colorPenId") + .v("weightMm", weight) + .v("closed", Value::Bool(true)) + .v("bbox", bbox_value([x0, y0, x1, y1])) + .v("roof", info) + .done()) +} + +thread_local! { + /// Zuletzt gerechnete Firsthöhen (Dach, Traufhöhe, Firsthöhe): die Objekt-Info fragt je Darstellung + /// neu, das Skelett eines Dachs kostet aber ein Vielfaches der übrigen Abfrage (TS merkte sich die + /// Geometrie je Dach-Objekt). + static RIDGE_CACHE: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Firsthöhe über der Traufe (Dach-Geometrie des Kerns, `roof.rs`), gemerkt für die letzten Dächer. +fn roof_ridge_height(r: &Value, eaves: f64) -> Result { + let hit = RIDGE_CACHE.with(|c| c.borrow().iter().find(|(v, z, _)| z.to_bits() == eaves.to_bits() && v == r).map(|e| e.2)); + if let Some(h) = hit { + return Ok(h); + } + let typed: crate::model::Roof = serde_json::from_value(r.clone()).map_err(|e| format!("Dach passt nicht zum Kern-Modell: {e}"))?; + let h = crate::roof::roof_geometry(&typed.params(), eaves).ridge_height; + RIDGE_CACHE.with(|c| { + let mut c = c.borrow_mut(); + if c.len() >= 16 { + c.remove(0); + } + c.push((r.clone(), eaves, h)); + }); + Ok(h) +} + +/// Kantenliste eines Dachs (`roofEdgeList`): Umriss, dann Höfe; Vorgabe je Kante aus `edgePitchDeg`. +fn roof_edges(r: &Value) -> J { + let shape = str_of(field(r, "shape")); + let gabled = shape == Some("sattel") || (shape == Some("mansarde") && nn(field(r, "mansardType")).map_or(Some("giebel"), |m| m.as_str()) == Some("giebel")); + let axis_y = str_of(field(r, "ridgeAxis")) == Some("y"); + let pitches = field(r, "edgePitchDeg").and_then(Value::as_array); + let mut rings: Vec<&[Value]> = vec![arr(field(r, "outline"))]; + rings.extend(arr(field(r, "holes")).iter().map(|h| arr(Some(h)))); + let mut out = Vec::new(); + let mut index = 0usize; + for (ri, ring) in rings.iter().enumerate() { + for (edge, a) in ring.iter().enumerate() { + let b = &ring[(edge + 1) % ring.len()]; + let (pa, pb) = (xy(a), xy(b)); + let spec = match pitches.and_then(|p| p.get(index)) { + Some(Value::Null) => O::default().s("kind", "gable").done(), + Some(v) if v.as_f64().is_some_and(|d| d.is_finite() && d >= 0.0) => O::default().s("kind", "pitch").v("deg", v).done(), + _ => O::default().s("kind", "default").done(), + }; + let default_gable = gabled && { + let (dx, dy) = ((pb.0 - pa.0).abs(), (pb.1 - pa.1).abs()); + if axis_y { + dy < dx + } else { + dx < dy + } + }; + out.push( + O::default() + .v("index", Value::from(index)) + .v("ring", Value::from(ri)) + .v("edge", Value::from(edge)) + .v("a", a) + .v("b", b) + .n("length", hypot2(pb.0 - pa.0, pb.1 - pa.1)) + .v("spec", spec) + .v("defaultGable", Value::Bool(default_gable)) + .done(), + ); + index += 1; + } + } + J::arr(out) +} + +fn opening_selection(root: &Map, o: &Value) -> Result { + use crate::opening_geom::{opening_gap_quad, v, WallRef}; + let cat = category(root, field(o, "categoryCode")); + let color = color_of(o, cat, WALL_FALLBACK_COLOR); + let weight = lw_or(None, cat, WALL_FALLBACK_MM); + let wall = find_by(arr(root.get("walls")), "id", field(o, "hostWallId")); + let floor = wall.and_then(|w| level(root, field(w, "floorId"))); + let mut quad = None; + if let Some(w) = wall { + let (s, e) = (xy(field(w, "start").unwrap_or(&Value::Null)), xy(field(w, "end").unwrap_or(&Value::Null))); + let wr = |total: f64, ref_off: f64| WallRef { start: v(s.0, s.1), end: v(e.0, e.1), total, ref_off }; + let (pos, width) = (num_of(field(o, "position")), num_of(field(o, "width"))); + // Der Wandtyp wird erst gebraucht (und kann werfen), wenn die Lücke nicht entartet ist. + if crate::opening_geom::opening_interval(&wr(0.0, 0.0), pos, width).is_some() { + let wt = find_by(arr(root.get("wallTypes")), "id", field(w, "wallTypeId")) + .ok_or_else(|| format!("Unbekannter Wandtyp: {}", field(w, "wallTypeId").map_or("undefined".into(), js_text)))?; + let total = type_thickness(wt); + quad = opening_gap_quad(&wr(total, reference_offset(w, total)), pos, width); + } + } + let bb = bbox_of(quad.unwrap_or_default().into_iter().map(|p| (p.x, p.y))); + let (zb, zt) = match wall { + Some(w) => { + let (wb, wt) = vertical_extent(root, w); + let bottom = wb + jsnum::max(0.0, num_of(field(o, "sillHeight"))); + (js_num(bottom), Some(js_num(jsnum::min(wt, bottom + num_of(field(o, "height")))))) + } + None => (js_num(0.0), field(o, "height").cloned()), + }; + let info = O::default() + .raw("id", o, "id") + .raw("kind", o, "kind") + .raw("hostWallId", o, "hostWallId") + .o("hostWallName", floor.map_or_else(|| field(o, "hostWallId").cloned(), |f| Some(Value::from(field(f, "name").map_or("undefined".into(), js_text))))) + .raw("position", o, "position") + .raw("width", o, "width") + .raw("height", o, "height") + .raw("sillHeight", o, "sillHeight") + .raw("hinge", o, "hinge") + .raw("swing", o, "swing") + .raw("swingAngle", o, "swingAngle") + .raw("openingDir", o, "openingDir") + .raw("wingCount", o, "wingCount") + .raw("doorType", o, "doorType") + .raw("lintelLines", o, "lintelLines") + .raw("typeId", o, "typeId") + .raw("detailLevel", o, "detailLevel") + .v("zBottom", zb) + .o("zTop", zt) + .raw("frameLine", o, "frameLine") + .raw("frameViewLine", o, "frameViewLine") + .raw("sashLine", o, "sashLine") + .raw("sillLineStyle", o, "sillLineStyle") + .done(); + Ok(O::default() + .s("kind", "opening") + .raw("id", o, "id") + .raw("categoryCode", o, "categoryCode") + .v("color", color) + .raw("colorPenId", o, "colorPenId") + .v("weightMm", weight) + .v("bbox", bbox_value(bb)) + .v("opening", info) + .done()) +} + +/// Achsversatz der Schichtstapelung (`wallReferenceOffset`): freier Versatz (auf die Dicke geklemmt), +/// sonst die benannte Referenzlinie. +fn reference_offset(w: &Value, total: f64) -> f64 { + let half = total / 2.0; + if nn(field(w, "referenceOffset")).is_some() { + return jsnum::max(-half, jsnum::min(half, num_of(field(w, "referenceOffset")))); + } + match nn(field(w, "referenceLine")).map_or(Some("center"), Value::as_str) { + Some("left") => half, + Some("right") => -half, + _ => 0.0, + } +} + +fn stair_selection(root: &Map, s: &Value) -> Result { + let cat = category(root, field(s, "categoryCode")); + let color = color_of(s, cat, WALL_FALLBACK_COLOR); + let weight = lw_or(None, cat, WALL_FALLBACK_MM); + let floor = level(root, field(s, "floorId")); + let (base, floor_height) = floor.map_or((0.0, 0.0), |f| (num_or(field(f, "baseElevation"), 0.0), num_or(field(f, "floorHeight"), 0.0))); + let tr = field(s, "totalRise"); + let rise = if nn(tr).is_some() && num_of(tr) > 0.0 { + num_of(tr) + } else if floor_height > 0.0 { + floor_height + } else { + 2.6 + }; + let (zb, zt) = (base, base + rise); + let total_rise = zt - zb; + let typed: crate::model::Stair = serde_json::from_value(s.clone()).map_err(|e| format!("Treppe passt nicht zum Kern-Modell: {e}"))?; + // Wie die TS-Fassade: Geometrie flach, leer (Unsinn-Eingabe) = leere Geometrie, daraus die bbox. + let mut geo = crate::stair::geometry(&typed.encode(), total_rise); + if geo.len() < 4 { + geo = vec![0.0, 0.0, 0.0, 0.0, -1.0, 0.0]; + geo.extend([0.0; 10]); + } + let b = crate::stair::bbox(&geo); + let bb = if b.len() < 4 { [0.0; 4] } else { [b[0], b[1], b[2], b[3]] }; + let info = O::default() + .raw("shape", s, "shape") + .raw("width", s, "width") + .raw("stepCount", s, "stepCount") + .n("totalRise", total_rise) + .n("riserHeight", geo[0]) + .n("treadDepth", geo[1]) + .v("up", Value::Bool(field(s, "up") != Some(&Value::Bool(false)))) + .raw("arrowStyle", s, "arrowStyle") + .raw("referenz", s, "referenz") + .raw("typeId", s, "typeId") + .raw("floorId", s, "floorId") + .o("floorName", floor_name(floor, field(s, "floorId"))) + .n("zBottom", zb) + .n("zTop", zt) + .done(); + Ok(O::default() + .s("kind", "stair") + .raw("id", s, "id") + .raw("categoryCode", s, "categoryCode") + .raw("floorId", s, "floorId") + .v("color", color) + .raw("colorPenId", s, "colorPenId") + .v("weightMm", weight) + .v("bbox", bbox_value(bb)) + .v("stair", info) + .done()) +} + +fn room_selection(root: &Map, r: &Value) -> J { + let cat = category(root, field(r, "categoryCode")); + let color = color_of(r, cat, WALL_FALLBACK_COLOR); + let weight = lw_or(None, cat, WALL_FALLBACK_MM); + let ev = crate::room_area::evaluate(&ring(field(r, "boundary")), 0.0); + let floor = level(root, field(r, "floorId")); + let bb = bbox_of(pts_of(field(r, "boundary"))); + let info = O::default() + .raw("name", r, "name") + .raw("siaCategory", r, "siaCategory") + .n("area", ev.net) + .n("perimeter", ev.perimeter) + .raw("floorId", r, "floorId") + .o("floorName", floor_name(floor, field(r, "floorId"))) + .done(); + O::default() + .s("kind", "room") + .raw("id", r, "id") + .raw("categoryCode", r, "categoryCode") + .raw("floorId", r, "floorId") + .v("color", color) + .raw("colorPenId", r, "colorPenId") + .v("weightMm", weight) + .v("closed", Value::Bool(true)) + .v("bbox", bbox_value(bb)) + .v("room", info) + .done() +} + +fn solid_selection(root: &Map, s: &Value) -> J { + let floor = level(root, field(s, "levelId")); + let bb = bbox_of(pts_of(field(s, "points"))); + let brep = field(s, "brep").filter(|b| truthy(Some(b))); + let taper = num_or(field(s, "taper"), 0.0); + let subtract = str_of(field(s, "operation")) == Some("subtract"); + let info = O::default() + .raw("height", s, "height") + .n("taper", taper) + .n("cornerRadius", num_or(field(s, "cornerRadius"), 0.0)) + .n("chamfer", num_or(field(s, "chamfer"), 0.0)) + .o("brepLabel", brep.map(|b| nn(field(b, "label")).cloned().unwrap_or_else(|| "B-Rep".into()))) + .n("area", polygon_area(field(s, "points"))) + // Platzhalter: `spec` (B-Rep für truck) setzt die TS-Fassade ein. + .v("spec", Value::Null) + .v("subtract", Value::Bool(subtract)) + .v("canSubtract", Value::Bool(brep.is_none() && taper < 1e-6)) + .n("baseOffset", num_or(field(s, "baseOffset"), 0.0)) + .raw("floorId", s, "levelId") + .o("floorName", floor_name(floor, field(s, "levelId"))) + .done(); + O::default() + .s("kind", "extrudedSolid") + .raw("id", s, "id") + .s("categoryCode", "") + .raw("floorId", s, "levelId") + .s("color", EXTRUSION_COLOR) + .n("weightMm", WALL_FALLBACK_MM) + .v("fillHatchId", Value::Null) + .v("fillColor", Value::Null) + .v("closed", Value::Bool(true)) + .v("bbox", bbox_value(bb)) + .v("extrudedSolid", info) + .done() +} + +fn column_selection(root: &Map, c: &Value) -> Result { + let floor = level(root, field(c, "floorId")); + let cat = category(root, field(c, "categoryCode")); + let typed: crate::model::Column = serde_json::from_value(c.clone()).map_err(|e| format!("Stütze passt nicht zum Kern-Modell: {e}"))?; + let bb = bbox_of(crate::model3d::column_footprint(&typed).into_iter().map(|p| (p.x, p.y))); + let (zb, zt) = vertical_extent(root, c); + let rotation = num_or(field(c, "rotation"), 0.0); + let info = O::default() + .raw("profile", c, "profile") + .raw("height", c, "height") + .n("rotationDeg", (rotation * 180.0) / std::f64::consts::PI) + .raw("floorId", c, "floorId") + .o("floorName", floor_name(floor, field(c, "floorId"))) + .n("zBottom", zb) + .n("zTop", zt) + .done(); + // Ein gelöschtes Bauteil wirft hier nicht (die Vorschau fällt auf „kein Bauteil" zurück). + let comp = if truthy(field(c, "componentId")) { find_by(arr(root.get("components")), "id", field(c, "componentId")) } else { None }; + let (fg, bg, hatch) = effective(c, comp, cat); + let weight = match nn(field(c, "strokeWeight")) { + Some(w) => w.clone(), + None if is_layer(field(c, "strokeWeightSource")) => cat.and_then(|k| nn(field(k, "lw"))).cloned().unwrap_or_else(|| js_num(WALL_FALLBACK_MM)), + None => js_num(WALL_FALLBACK_MM), + }; + Ok(O::default() + .s("kind", "column") + .raw("id", c, "id") + .raw("categoryCode", c, "categoryCode") + .raw("floorId", c, "floorId") + .v("color", color_of(c, cat, COLUMN_COLOR)) + .raw("colorPenId", c, "colorPenId") + .v("weightMm", weight) + .raw("fillHatchId", c, "hatchId") + .raw("foreground", c, "foreground") + .raw("foregroundPenId", c, "foregroundPenId") + .raw("background", c, "background") + .raw("backgroundPenId", c, "backgroundPenId") + .raw("foregroundSource", c, "foregroundSource") + .raw("backgroundSource", c, "backgroundSource") + .o("effectiveForeground", fg) + .o("effectiveBackground", bg) + .o("effectiveHatchId", hatch) + .raw("strokeWeightOverride", c, "strokeWeight") + .raw("strokeWeightSource", c, "strokeWeightSource") + .raw("hatchSource", c, "hatchSource") + .v("bbox", bbox_value(bb)) + .v("column", info) + .done()) +} + +fn context_selection(root: &Map, o: &Value) -> J { + let kind = str_of(field(o, "type")); + let mut pts: Vec<(f64, f64)> = Vec::new(); + match kind { + Some("contourSet") => { + for c in arr(field(o, "contours")) { + pts.extend(pts_of(field(c, "pts"))); + } + } + Some("image") => { + pts.push(xy(field(o, "min").unwrap_or(&Value::Null))); + pts.push(xy(field(o, "max").unwrap_or(&Value::Null))); + } + _ => { + let pos = arr(field(o, "positions")); + let mut i = 0; + while i + 2 < pos.len() { + pts.push((num_of(Some(&pos[i])), num_of(Some(&pos[i + 1])))); + i += 3; + } + } + } + let bb = bbox_of(pts); + let lv95 = root.get("geoAnchor").filter(|a| truthy(Some(a))).map(|a| { + let (lv, m) = (field(a, "lv95").unwrap_or(&Value::Null), field(a, "model").unwrap_or(&Value::Null)); + let (oe, on) = (num_of(field(lv, "e")) - num_of(field(m, "x")), num_of(field(lv, "n")) - num_of(field(m, "y"))); + O::default().n("e", (bb[0] + bb[2]) / 2.0 + oe).n("n", (bb[1] + bb[3]) / 2.0 + on).done() + }); + let image = kind == Some("image"); + O::default() + .s("kind", "contextObject") + .raw("id", o, "id") + .s("categoryCode", "") + .s("color", "#888888") + .n("weightMm", WALL_FALLBACK_MM) + .v("bbox", bbox_value(bb)) + .v("contextObject", O::default().raw("objType", o, "type").o("lv95Center", lv95).done()) + .v("isImage", Value::Bool(image)) + .o("opacity", image.then(|| nn(field(o, "opacity")).cloned().unwrap_or_else(|| Value::from(1u64)))) + .o("imageFilters", if image { field(o, "filters").cloned() } else { None }) + .done() +} + +/// Ob eine 2D-Form geschlossen ist (Füllung/Schraffur sinnvoll). +fn is_closed_geom(g: &Value) -> bool { + match str_of(field(g, "shape")) { + Some("rect" | "circle" | "ellipse") => true, + Some("polyline" | "spline") => truthy(field(g, "closed")), + _ => false, + } +} + +/// Bounding-Box einer 2D-Form (`geomBBox`, auch für Ausrichten/Verteilen). +pub fn geom_bbox(g: &Value) -> [f64; 4] { + let p = |k: &str| xy(g.get(k).unwrap_or(&Value::Null)); + let mut pts: Vec<(f64, f64)> = Vec::new(); + match str_of(field(g, "shape")) { + Some("line" | "xline" | "ray") => pts.extend([p("a"), p("b")]), + Some("polyline" | "bezier" | "spline") => pts = pts_of(field(g, "pts")), + Some("rect" | "image") => pts.extend([p("min"), p("max")]), + Some("circle" | "arc") => { + let (c, r) = (p("center"), num_of(field(g, "r"))); + pts.extend([(c.0 - r, c.1 - r), (c.0 + r, c.1 + r)]); + } + Some("ellipse") => { + // Genau mit Drehung (rotation 0 beim heutigen Werkzeug). + let rot = num_of(field(g, "rotation")); + let (c, s) = (jsnum::cos(rot), jsnum::sin(rot)); + let (rx, ry) = (num_of(field(g, "rx")), num_of(field(g, "ry"))); + let (hw, hh) = (hypot2(rx * c, ry * s), hypot2(rx * s, ry * c)); + let ctr = p("center"); + pts.extend([(ctr.0 - hw, ctr.1 - hh), (ctr.0 + hw, ctr.1 + hh)]); + } + Some("dimension") => { + let chain = pts_of(field(g, "pts")); + pts.extend(chain.iter().copied()); + if chain.len() >= 2 { + let (a, b) = (chain[0], chain[chain.len() - 1]); + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let l = hypot2(dx, dy); + let len = if l == 0.0 || l.is_nan() { 1.0 } else { l }; + let off = num_of(field(g, "offset")); + let (nx, ny) = ((-dy / len) * off, (dx / len) * off); + pts.extend(chain.iter().map(|q| (q.0 + nx, q.1 + ny))); + } + } + Some("kote" | "text" | "block" | "detailref" | "pointmarker") => pts.push(p("at")), + Some("scalebar") => { + let at = p("at"); + pts.extend([at, (at.0 + num_of(field(g, "segmentLength")) * num_of(field(g, "segments")), at.1)]); + } + _ => {} + } + bbox_of(pts) +} + +fn drawing_selection(root: &Map, d: &Value) -> J { + let g = field(d, "geom").unwrap_or(&Value::Null); + let ls = if truthy(field(d, "lineStyleId")) { find_by(arr(root.get("lineStyles")), "id", field(d, "lineStyleId")) } else { None }; + let cat = category(root, field(d, "categoryCode")); + let color = nn(field(d, "color")) + .or_else(|| ls.and_then(|l| nn(field(l, "color")))) + .or_else(|| cat.and_then(|c| nn(field(c, "color")))) + .cloned() + .unwrap_or_else(|| DRAW_FALLBACK_COLOR.into()); + // Wie der Plan: Override, „layer" (Standard) erzwingt die Kategorie, sonst Linienstil → Kategorie. + let cat_lw = cat.and_then(|c| nn(field(c, "lw"))); + let weight = nn(field(d, "weightMm")) + .or_else(|| if str_of(field(d, "strokeWeightSource")) != Some("object") { cat_lw } else { None }) + .or_else(|| ls.and_then(|l| nn(field(l, "weight")))) + .or(cat_lw) + .cloned() + .unwrap_or_else(|| js_num(WALL_FALLBACK_MM)); + let closed = is_closed_geom(g); + // Ein Drawing2D hat kein Bauteil; fehlende Quelle = „Nach Ebene". + let layer = Value::from("layer"); + let src = |k: &str| nn(d.get(k)).or(Some(&layer)).cloned(); + let pick = |k: &str| if closed { d.get(k).cloned() } else { None }; + let (fg, bg, hatch) = if closed { + let fs = src("foregroundSource"); + let bs = src("backgroundSource"); + let hs = src("hatchSource"); + ( + resolve_color(None, field(d, "foreground"), cat, fs.as_ref()), + resolve_color(None, field(d, "background"), cat, bs.as_ref()), + resolve_hatch(field(d, "hatchId"), hs.as_ref(), cat, None), + ) + } else { + (None, None, Some(Value::Null)) + }; + let is_image = str_of(field(g, "shape")) == Some("image"); + let detail = (str_of(field(g, "shape")) == Some("detailref")).then(|| { + let layouts = J::arr(arr(root.get("layouts")).iter().map(|l| O::default().raw("id", l, "id").raw("name", l, "name").done())); + O::default().raw("label", g, "label").raw("sheetLayoutId", g, "sheetLayoutId").raw("sheetLabel", g, "sheetLabel").v("availableLayouts", layouts).done() + }); + O::default() + .s("kind", "drawing2d") + .raw("id", d, "id") + .raw("categoryCode", d, "categoryCode") + .raw("floorId", d, "levelId") + .v("color", color) + .raw("colorPenId", d, "colorPenId") + .v("weightMm", weight) + .v("fillHatchId", if closed { nn(field(d, "hatchId")).cloned().unwrap_or(Value::Null) } else { Value::Null }) + .v("fillColor", if closed { nn(field(d, "fillColor")).cloned().unwrap_or(Value::Null) } else { Value::Null }) + .o("foreground", pick("foreground")) + .o("foregroundPenId", pick("foregroundPenId")) + .o("background", pick("background")) + .o("backgroundPenId", pick("backgroundPenId")) + .o("foregroundSource", pick("foregroundSource")) + .o("backgroundSource", pick("backgroundSource")) + .o("effectiveForeground", fg) + .o("effectiveBackground", bg) + .o("effectiveHatchId", hatch) + .raw("strokeWeightOverride", d, "weightMm") + .raw("strokeWeightSource", d, "strokeWeightSource") + .o("hatchSource", pick("hatchSource")) + .v("closed", Value::Bool(closed)) + .v("isImage", Value::Bool(is_image)) + .o("opacity", if is_image { Some(nn(field(g, "opacity")).cloned().unwrap_or_else(|| Value::from(1u64))) } else { field(d, "opacity").cloned() }) + .v("bbox", bbox_value(geom_bbox(g))) + .o("detailRef", detail) + .done() +} + +/// Bounding-Boxen der Zeichnungen `ids` in Listen-Reihenfolge: `[[id, minX, minY, maxX, maxY], …]`. +pub fn drawing_bboxes(root: &Map, ids: &[String]) -> J { + let wanted: std::collections::HashSet<&str> = ids.iter().map(String::as_str).collect(); + J::arr( + arr(root.get("drawings2d")) + .iter() + .filter(|d| id_of(d).is_some_and(|i| wanted.contains(i))) + .map(|d| { + let b = geom_bbox(field(d, "geom").unwrap_or(&Value::Null)); + let mut out = vec![b'[']; + field(d, "id").unwrap_or(&Value::Null).emit(&mut out); + for x in b { + out.push(b','); + js_num(x).emit(&mut out); + } + out.push(b']'); + J(out) + }), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn root(v: Value) -> Map { + v.as_object().unwrap().clone() + } + + fn sel(r: &Map, a: Value) -> Result { + derive(r, &serde_json::from_value(a).unwrap()).map(|j| serde_json::from_str(&j.into_string()).unwrap()) + } + + #[test] + fn wand_mit_typ_volumen_und_fuge() { + let r = root(json!({ + "layers": [{"code": "1", "name": "W", "color": "#111111", "lw": 0.35, "children": [{"code": "2", "color": "#222222", "lw": 0.5}]}], + "components": [{"id": "a", "name": "Beton", "abbrev": "BET", "foreground": "#f00"}, {"id": "b", "name": "Daemmung"}], + "wallTypes": [{"id": "t", "name": "Aussenwand", "layers": [{"componentId": "a", "thickness": 0.2}, {"componentId": "b", "thickness": 0.1}]}], + "drawingLevels": [{"id": "eg", "name": "EG", "kind": "floor", "baseElevation": 0}, {"id": "og", "name": "OG", "kind": "floor", "baseElevation": 3}], + "walls": [{"id": "w", "floorId": "eg", "categoryCode": "2", "start": {"x": 0, "y": 0}, "end": {"x": 4, "y": 3}, "wallTypeId": "t", "height": 2.5}], + "openings": [{"id": "o", "hostWallId": "w", "width": 1, "height": 2}], + })); + let s = sel(&r, json!({"wallIds": ["w"]})).unwrap(); + assert_eq!(s["color"], json!("#222222")); + assert_eq!(s["weightMm"], json!(0.5)); + assert_eq!(s["effectiveForeground"], json!("#f00")); + assert_eq!(s["wall"]["length"], json!(5)); + assert_eq!(s["wall"]["layerBoundaries"], json!([{"offset": 0.15000000000000002 - 0.2, "label": "BET|Daemmung"}])); + assert_eq!(s["wall"]["floorAbove"], json!({"id": "og", "name": "OG"})); + assert_eq!(s["wall"]["wallTypes"][0]["label"], json!("Aussenwand")); + let gross = 5.0 * 0.30000000000000004 * 2.5; + assert_eq!(s["wall"]["netVolume"].as_f64().unwrap(), gross - 2.0 * 0.30000000000000004); + // Unbekannter Wandtyp: dieselbe Meldung wie TS. + let mut bad = r.clone(); + bad["walls"][0]["wallTypeId"] = json!("x"); + assert_eq!(sel(&bad, json!({"wallIds": ["w"]})).unwrap_err(), "Unbekannter Wandtyp: x"); + } + + #[test] + fn typ_beschriftung_wie_ts() { + let r = root(json!({"components": [{"id": "a", "abbrev": "BET"}, {"id": "b", "abbrev": "GKB"}]})); + let one = json!({"name": "N", "layers": [{"componentId": "a", "thickness": 0.24}]}); + assert_eq!(wall_type_label(&r, &one), json!("BET 24")); + let two = json!({"name": "N", "layers": [{"componentId": "b", "thickness": 0.0125}, {"componentId": "a", "thickness": 0.24}]}); + assert_eq!(wall_type_label(&r, &two), json!("GKB·BET (25.3)")); + } + + #[test] + fn zeichnung_offen_und_geschlossen() { + let r = root(json!({"layers": [{"code": "1", "color": "#123", "lw": 0.25, "hatch": "h"}], + "drawings2d": [ + {"id": "l", "categoryCode": "1", "levelId": "f", "geom": {"shape": "line", "a": {"x": 0, "y": 0}, "b": {"x": 2, "y": -1}}}, + {"id": "r", "categoryCode": "1", "levelId": "f", "geom": {"shape": "rect", "min": {"x": 0, "y": 0}, "max": {"x": 1, "y": 1}}} + ]})); + let l = sel(&r, json!({"drawingId": "l"})).unwrap(); + assert_eq!(l["effectiveHatchId"], Value::Null); + assert_eq!(l["bbox"], json!({"minX": 0, "minY": -1, "maxX": 2, "maxY": 0})); + let rr = sel(&r, json!({"drawingId": "r"})).unwrap(); + assert_eq!(rr["effectiveHatchId"], json!("h")); + assert_eq!(rr["effectiveForeground"], json!("#123")); + assert!(sel(&r, json!({"drawingId": "x"})).unwrap().is_null()); + } +} diff --git a/src-tauri/core/src/web/grips.rs b/src-tauri/core/src/web/grips.rs index f9fe1e60..00bee250 100644 --- a/src-tauri/core/src/web/grips.rs +++ b/src-tauri/core/src/web/grips.rs @@ -12,7 +12,7 @@ use wasm_bindgen::prelude::wasm_bindgen; /// (zurückgewiesen, Dokument unverändert); Fehler als Text mit vorangestelltem `\u{1}`. #[wasm_bindgen] pub fn doc_grip_commit(h: u32, req_json: &str, key: &str, now_ms: f64) -> String { - let req: Value = match serde_json::from_str(req_json) { + let req: crate::grips::Request = match serde_json::from_str(req_json) { Ok(v) => v, Err(e) => return format!("\u{1}Griff-Anfrage: {e}"), }; diff --git a/src/core/document.ts b/src/core/document.ts index 754d6131..23f5eaec 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -245,7 +245,7 @@ export class ProjectDocument { commitGrip(base: Project, req: object, coalesceKey: string | undefined, now: number): { project: Project; ops: CoreOp[]; notice?: string } | { problems: string[] } { this.ensure(base); if (!this.handle) return { problems: ["Projekt-Dokument im Kern nicht offen."] }; - const out = core().doc_grip_commit(this.handle, toMarkedJson(req), coalesceKey ?? "", now); + const out = core().doc_grip_commit(this.handle, gripJson(req), coalesceKey ?? "", now); if (out.startsWith("\u0001")) throw new Error(out.slice(1)); const r = fromMarkedJson<{ ops: CoreOp[]; notice?: string } | { problems: string[] }>(out); if ("problems" in r) return r; @@ -255,10 +255,21 @@ export class ProjectDocument { return { project, ops: r.ops, notice: r.notice }; } + /** + * Wie {@link queryRoot} für Abfragen, deren Antwort nicht endliche Zahlen als Marken trägt + * (`selectionInfo`, `drawingBBoxes`); die Marken werden wieder Zahlen. + */ + queryRootMarked(name: "selectionInfo" | "drawingBBoxes", text = ""): T { + if (!this.handle) throw new Error(`Kern-Abfrage „${name}": Dokument nicht offen`); + const out = core().doc_query_root(this.handle, name, text); + if (out.startsWith("\u0001")) throw new Error(out.slice(1)); + return fromMarkedJson(out); + } + /** Wie {@link commitGrip}, aber nur rechnen (ohne Anwenden): die Ops und ggf. der Hinweis. */ gripOps(req: object): { ops: CoreOp[]; notice?: string } { if (!this.handle) throw new Error("Kern-Abfrage „gripOps“: Dokument nicht offen"); - const out = core().doc_query_root(this.handle, "gripOps", toMarkedJson(req)); + const out = core().doc_query_root(this.handle, "gripOps", gripJson(req)); if (out.startsWith("\u0001")) throw new Error(out.slice(1)); return fromMarkedJson(out); } @@ -320,6 +331,15 @@ export class ProjectDocument { } } +/** Griff-Anfrage als JSON; Marken nur bei nicht endlichen Zahlen (der Ersetzer kostet je Wert einen Aufruf). */ +function gripJson(req: object): string { + for (const v of Object.values(req)) { + const bad = typeof v === "number" ? !Number.isFinite(v) : Array.isArray(v) && v.some((x) => typeof x === "number" && !Number.isFinite(x)); + if (bad) return toMarkedJson(req); + } + return JSON.stringify(req); +} + let shared: ProjectDocument | null = null; /** diff --git a/src/editors/align.ts b/src/editors/align.ts index 92724a76..554d7111 100644 --- a/src/editors/align.ts +++ b/src/editors/align.ts @@ -2,12 +2,12 @@ // `editors/explode.ts`), damit sie ohne UI testbar bleiben. // // Beides arbeitet auf den BOUNDING-BOXEN der Elemente (dieselbe Herleitung wie -// im Attribut-Panel, s. `geomBBox`) und verschiebt sie anschliessend als +// im Attribut-Panel: Kern `selection_info.rs::geom_bbox`, Abfrage `drawingBBoxes`) und verschiebt sie anschliessend als // Ganzes. Die Form selbst bleibt unangetastet — es wird nur verschoben, nie // skaliert oder verzerrt. import type { Drawing2D, Project, Vec2 } from "../model/types"; -import { geomBBox } from "../state/selectionInfo"; +import { documentFor } from "../core/document"; import { mvGeom, patchItems } from "../core"; import type { CoreOp } from "../core"; @@ -27,9 +27,11 @@ interface Boxed { function boxesOf(project: Project, ids: string[]): Boxed[] { const wanted = new Set(ids); - return project.drawings2d - .filter((d) => wanted.has(d.id)) - .map((d) => ({ d, ...geomBBox(d.geom) })); + const list = project.drawings2d.filter((d) => wanted.has(d.id)); + if (list.length === 0) return []; + // Je Element `[id, minX, minY, maxX, maxY]`, in Listen-Reihenfolge wie `list`. + const b = documentFor(project).queryRootMarked<[string, number, number, number, number][]>("drawingBBoxes", JSON.stringify(ids)); + return list.map((d, i) => ({ d, minX: b[i][1], minY: b[i][2], maxX: b[i][3], maxY: b[i][4] })); } /** Ops: verschiebt die genannten Elemente um je einen eigenen Vektor. */ diff --git a/src/state/selectionInfo.test.ts b/src/state/selectionInfo.test.ts new file mode 100644 index 00000000..46b11e9c --- /dev/null +++ b/src/state/selectionInfo.test.ts @@ -0,0 +1,63 @@ +// Objekt-Info der Auswahl ([K4] S3: gerechnet im Kern, `selection_info.rs`) — Wand, Decke, +// Zeichnung, Extrusion (B-Rep-Beschreibung aus TS) und die Meldung bei unbekanntem Wandtyp. +import { describe, expect, it } from "vitest"; +import { deriveSelection } from "./selectionInfo"; +import { sampleProject } from "../model/sampleProject"; +import type { Project } from "../model/types"; + +const base = (): Project => structuredClone(sampleProject); + +describe("deriveSelection (Kern)", () => { + it("Wand: Typ-Liste, Geschosse, Länge, Volumen und UK/OK", () => { + const p = base(); + const w = p.walls[0]; + const sel = deriveSelection(p, [w.id], null)!; + expect(sel.kind).toBe("wall"); + expect(sel.id).toBe(w.id); + expect(sel.wall!.wallTypes.length).toBe(p.wallTypes.length); + expect(sel.wall!.floors.every((f) => p.drawingLevels.some((z) => z.id === f.id && z.kind === "floor"))).toBe(true); + expect(sel.wall!.length).toBeCloseTo(Math.hypot(w.end.x - w.start.x, w.end.y - w.start.y), 12); + expect(sel.wall!.netVolume).toBeLessThanOrEqual(sel.wall!.grossVolume); + expect(sel.wall!.zTop).toBeGreaterThan(sel.wall!.zBottom); + expect(sel.bbox.minX).toBe(Math.min(w.start.x, w.end.x)); + }); + + it("unbekannter Wandtyp bricht mit derselben Meldung ab wie bisher", () => { + const p = base(); + p.walls[0] = { ...p.walls[0], wallTypeId: "fehlt" }; + expect(() => deriveSelection(p, [p.walls[0].id], null)).toThrow("Unbekannter Wandtyp: fehlt"); + }); + + it("Zeichnung: offene Linie ohne Füllung, Rechteck mit Ebenen-Vorgaben", () => { + const p = base(); + const lvl = p.drawingLevels[0].id; + const code = p.layers[0].code; + p.drawings2d = [ + { id: "l", type: "drawing2d", levelId: lvl, categoryCode: code, geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 3, y: -2 } } }, + { id: "r", type: "drawing2d", levelId: lvl, categoryCode: code, hatchId: "h", geom: { shape: "rect", min: { x: 1, y: 1 }, max: { x: 2, y: 4 } } }, + ]; + const l = deriveSelection(p, [], "l")!; + expect(l.closed).toBe(false); + expect(l.effectiveHatchId).toBeNull(); + expect(l.bbox).toEqual({ minX: 0, minY: -2, maxX: 3, maxY: 0 }); + const r = deriveSelection(p, [], "r")!; + expect(r.closed).toBe(true); + expect(r.fillHatchId).toBe("h"); + expect(r.effectiveHatchId).toBe("h"); + expect(deriveSelection(p, [], "nix")).toBeNull(); + }); + + it("Extrusion: Fläche im Kern, B-Rep-Beschreibung (truck) aus TS", () => { + const p = base(); + const lvl = p.drawingLevels[0].id; + p.extrudedSolids = [ + { id: "x", type: "extrudedSolid", levelId: lvl, points: [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 3 }], height: 2 }, + ]; + const sel = deriveSelection(p, [], null, null, null, null, null, "x")!; + expect(sel.extrudedSolid!.area).toBeCloseTo(3, 12); + expect(sel.extrudedSolid!.spec).toMatchObject({ kind: "extrude", height: 2 }); + expect(Object.keys(sel.extrudedSolid!)).toEqual([ + "height", "taper", "cornerRadius", "chamfer", "area", "spec", "subtract", "canSubtract", "baseOffset", "floorId", "floorName", + ]); + }); +}); diff --git a/src/state/selectionInfo.ts b/src/state/selectionInfo.ts index 11cdc85f..ae4d4a51 100644 --- a/src/state/selectionInfo.ts +++ b/src/state/selectionInfo.ts @@ -8,59 +8,30 @@ // Übersteuerung am Element → LineStyle → Kategorie-Default. So zeigt die Palette // den TATSÄCHLICH gezeichneten Wert, nicht nur das (oft leere) Override-Feld. // +// [K4] S3: gerechnet wird im Rust-Kern (`src-tauri/core/src/selection_info.rs`, Wurzel-Abfrage +// `selectionInfo` auf dem Projekt-Dokument); hier stehen der Kontrakt (Typen) und die Fassade. Der +// B-Rep-Körper einer Extrusion (`spec`) kommt aus TS (`extrudedSolidSpec`, truck-Pipeline). +// // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import { extrudedSolidSpec } from "../core"; import type { SolidSpec } from "../engine/truckSolid"; -import { - ceilingThickness, - getCeilingType, - getComponent, - getWallType, - wallTypeLabel, - wallTypeThickness, -} from "../model/types"; +import { documentFor } from "../core/document"; import type { AttributeSource, - Ceiling, - Column, ColumnProfile, ContextImage, ContextObject, - Drawing2D, - Drawing2DGeom, - ExtrudedSolid, - Opening, Project, - Roof, RoofShape, - Room, SiaCategory, SliceTermination, - Stair, StairShape, VerticalAnchor, - Wall, WallReferenceLine, } from "../model/types"; -import { findCategory } from "../model/layers"; import type { DetailLevel } from "../model/viewTypes"; -import { localToLv95 } from "../io/lv95"; -import { resolveForeground, resolveBackground, resolveHatchId, resolveStrokeWeight } from "../core"; -import { columnVerticalExtent } from "../model/wall"; -import { columnFootprint } from "../core"; -import { evaluateRoom, polygonArea } from "../core"; -import { - ceilingVerticalExtent, - nextFloorAbove, - stairVerticalExtent, - wallVerticalExtent, -} from "../model/wall"; -import { ceilingArea, outlineBBox } from "../core"; -import { roofBBox, roofBaseElevation, roofEdgeList, roofGeometry } from "../core"; import type { RoofEdge } from "../core"; -import { openingGapQuad, openingVerticalExtent } from "../core"; -import { stairGeometry, stairBBox } from "../core"; /** Eintrag für die WallType-Auswahl (Preset-Dropdown) im Object-Info-Panel. */ export interface WallTypeChoice { @@ -541,754 +512,16 @@ export interface ContextObjectInfo { lv95Center?: { e: number; n: number }; } -const WALL_FALLBACK_MM = 0.18; -const DRAW_FALLBACK_COLOR = "#d0d0d0"; -const WALL_FALLBACK_COLOR = "#2b3039"; - -/** Ob eine 2D-Form geschlossen ist (Füllung/Schraffur sinnvoll). */ -function isClosedGeom(g: Drawing2DGeom): boolean { - return ( - g.shape === "rect" || - g.shape === "circle" || - g.shape === "ellipse" || - (g.shape === "polyline" && g.closed) || - (g.shape === "spline" && g.closed) - ); -} - -/** - * Bounding-Box einer 2D-Form. Exportiert, weil auch die Editier-Werkzeuge sie - * brauchen (Ausrichten/Verteilen, `editors/align.ts`) — dieselbe Herleitung - * wie fürs Attribut-Panel, damit beide Seiten nie auseinanderlaufen. - */ -export function geomBBox(g: Drawing2DGeom): SelectionBBox { - let minX = Infinity, - minY = Infinity, - maxX = -Infinity, - maxY = -Infinity; - const acc = (x: number, y: number) => { - minX = Math.min(minX, x); - minY = Math.min(minY, y); - maxX = Math.max(maxX, x); - maxY = Math.max(maxY, y); - }; - switch (g.shape) { - case "line": - case "xline": - case "ray": - acc(g.a.x, g.a.y); - acc(g.b.x, g.b.y); - break; - case "polyline": - for (const p of g.pts) acc(p.x, p.y); - break; - case "rect": - case "image": - acc(g.min.x, g.min.y); - acc(g.max.x, g.max.y); - break; - case "circle": - case "arc": - acc(g.center.x - g.r, g.center.y - g.r); - acc(g.center.x + g.r, g.center.y + g.r); - break; - case "ellipse": { - // Präzise Bounding-Box unter Berücksichtigung der Drehung (rotation=0 - // beim heutigen Werkzeug, Feld existiert für spätere Quellen). - const c = Math.cos(g.rotation), s = Math.sin(g.rotation); - const hw = Math.hypot(g.rx * c, g.ry * s); - const hh = Math.hypot(g.rx * s, g.ry * c); - acc(g.center.x - hw, g.center.y - hh); - acc(g.center.x + hw, g.center.y + hh); - break; - } - case "bezier": - case "spline": - for (const p of g.pts) acc(p.x, p.y); - break; - case "dimension": { - for (const p of g.pts) acc(p.x, p.y); - if (g.pts.length >= 2) { - const a = g.pts[0], b = g.pts[g.pts.length - 1]; - const dx = b.x - a.x, dy = b.y - a.y; - const len = Math.hypot(dx, dy) || 1; - const nx = (-dy / len) * g.offset, ny = (dx / len) * g.offset; - for (const p of g.pts) acc(p.x + nx, p.y + ny); - } - break; - } - case "kote": - case "text": - case "block": - case "detailref": - case "pointmarker": - acc(g.at.x, g.at.y); - break; - case "scalebar": - acc(g.at.x, g.at.y); - acc(g.at.x + g.segmentLength * g.segments, g.at.y); - break; - } - if (!isFinite(minX)) return { minX: 0, minY: 0, maxX: 0, maxY: 0 }; - return { minX, minY, maxX, maxY }; -} - -/** Selektion für eine Wand ableiten (Farbe übersteuerbar, Strichstärke = Kategorie). */ -function wallSelection(project: Project, wall: Wall): Selection { - const cat = findCategory(project.layers, wall.categoryCode); - const color = wall.color ?? cat?.color ?? WALL_FALLBACK_COLOR; - // Effektive Strichstärke: expliziter Override zuerst, sonst die Kategorie - // (die Quelle "layer"/"object" macht heute keinen Unterschied, da Component - // keine eigene Strichstärke trägt — siehe resolveStrokeWeight). - const weightMm = wall.strokeWeight ?? cat?.lw ?? WALL_FALLBACK_MM; - const minX = Math.min(wall.start.x, wall.end.x); - const minY = Math.min(wall.start.y, wall.end.y); - const maxX = Math.max(wall.start.x, wall.end.x); - const maxY = Math.max(wall.start.y, wall.end.y); - // Wand-Attribute auflösen (Referenzlinie, Aufbau, Referenzgeschoss, UK/OK). - const wt = getWallType(project, wall); - const thickness = wallTypeThickness(wt); - // Effektive Vordergrund-/Hintergrund-/Schraffur-Vorschau fürs Attribut-Panel - // (Nutzer-Wunsch: immer den TATSÄCHLICHEN Wert sehen, nicht nur ein leeres - // Override-Feld) — dieselbe Resolve-Kette wie beim Rendern (resolveForeground - // & Co.), als Bauteil-Repräsentant die ÄUSSERSTE Schicht (wie `abbrevOf` - // unten). Bei mehrschichtigem Aufbau nur eine Annäherung (jede Schicht kann - // im Schnitt ihre EIGENE Bauteilfarbe zeigen) — für die Panel-Vorschau - // ausreichend, der Override selbst wirkt ohnehin einheitlich auf alle Schichten. - const outerComponent = getComponent(project, wt.layers[0]?.componentId); - const effectiveForeground = outerComponent - ? resolveForeground(outerComponent, wall.foreground, cat, wall.foregroundSource) - : wall.foreground; - const effectiveBackground = outerComponent - ? resolveBackground(outerComponent, wall.background, cat, wall.backgroundSource) - : wall.background; - const effectiveHatchId = resolveHatchId( - wall.hatchId, - wall.hatchSource, - cat, - outerComponent?.hatchId, - ); - const floor = project.drawingLevels.find((z) => z.id === wall.floorId); - const { zBottom, zTop } = wallVerticalExtent(project, wall); - const above = nextFloorAbove(project, wall); - // Volumen aus Achslänge × Gesamtdicke × Höhe, abzüglich der Öffnungen (jede - // Öffnung durchbricht die volle Wanddicke: Breite × Höhe × Dicke). - const length = Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y); - const wallHeight = Math.max(0, zTop - zBottom); - const grossVolume = length * thickness * wallHeight; - const openingVolume = (project.openings ?? []) - .filter((o) => o.hostWallId === wall.id) - .reduce((sum, o) => sum + o.width * o.height * thickness, 0); - const netVolume = Math.max(0, grossVolume - openingVolume); - // Interne Schichttrennlinien als wählbare Referenz: von aussen (Schicht 0) - // nach innen aufsummiert; der Achsversatz +n = halbe Dicke − Fugenlage. - const half = thickness / 2; - const layerBoundaries: WallInfo["layerBoundaries"] = []; - let cum = 0; - const abbrevOf = (componentId: string): string => { - const c = getComponent(project, componentId); - return c ? c.abbrev ?? c.name : "?"; - }; - for (let i = 0; i < wt.layers.length - 1; i++) { - cum += wt.layers[i].thickness; - layerBoundaries.push({ - offset: half - cum, - label: `${abbrevOf(wt.layers[i].componentId)}|${abbrevOf(wt.layers[i + 1].componentId)}`, - }); - } - const wallInfo: WallInfo = { - referenceLine: wall.referenceLine ?? "center", - referenceOffset: wall.referenceOffset, - layerBoundaries, - sliceTermination: wall.sliceTermination ?? "both", - wallTypeId: wall.wallTypeId, - thickness, - singleLayer: wt.layers.length <= 1, - wallTypes: project.wallTypes.map((t) => ({ - id: t.id, - name: t.name, - label: wallTypeLabel(t, project.components), - thickness: wallTypeThickness(t), - layerCount: t.layers.length, - })), - floorId: wall.floorId, - floorName: floor?.name ?? wall.floorId, - floors: project.drawingLevels - .filter((z) => z.kind === "floor") - .map((z) => ({ id: z.id, name: z.name })), - floorAbove: above, - bottom: wall.bottom, - top: wall.top, - zBottom, - zTop, - length, - grossVolume, - openingVolume, - netVolume, - }; - // bbox aus der Wandachse (start/end); die Schichtdicke bleibt unberücksichtigt, - // damit die Box der Achs-Geometrie folgt (genügt für die Paletten). - return { - kind: "wall", - id: wall.id, - categoryCode: wall.categoryCode, - floorId: wall.floorId, - color, - colorPenId: wall.colorPenId, - weightMm, - fillHatchId: wall.hatchId, - fillColor: undefined, - foreground: wall.foreground, - foregroundPenId: wall.foregroundPenId, - background: wall.background, - backgroundPenId: wall.backgroundPenId, - foregroundSource: wall.foregroundSource, - backgroundSource: wall.backgroundSource, - effectiveForeground, - effectiveBackground, - effectiveHatchId, - strokeWeightOverride: wall.strokeWeight, - strokeWeightSource: wall.strokeWeightSource, - hatchSource: wall.hatchSource, - closed: undefined, - bbox: { minX, minY, maxX, maxY }, - wall: wallInfo, - }; -} - -/** Selektion für eine Decke ableiten (Farbe übersteuerbar, Strichstärke = Kategorie). */ -function ceilingSelection(project: Project, ceiling: Ceiling): Selection { - const cat = findCategory(project.layers, ceiling.categoryCode); - const color = ceiling.color ?? cat?.color ?? WALL_FALLBACK_COLOR; - const weightMm = ceiling.strokeWeight ?? cat?.lw ?? WALL_FALLBACK_MM; - const box = outlineBBox(ceiling.outline); - const wt = getCeilingType(project, ceiling); - const thickness = ceilingThickness(project, ceiling); - // Effektive Vordergrund-/Hintergrund-/Schraffur-Vorschau — s. Kommentar in - // wallSelection (dieselbe Kette, äusserste Schicht als Bauteil-Repräsentant). - const outerComponent = getComponent(project, wt.layers[0]?.componentId); - const effectiveForeground = outerComponent - ? resolveForeground(outerComponent, ceiling.foreground, cat, ceiling.foregroundSource) - : ceiling.foreground; - const effectiveBackground = outerComponent - ? resolveBackground(outerComponent, ceiling.background, cat, ceiling.backgroundSource) - : ceiling.background; - const effectiveHatchId = resolveHatchId( - ceiling.hatchId, - ceiling.hatchSource, - cat, - outerComponent?.hatchId, - ); - const floor = project.drawingLevels.find((z) => z.id === ceiling.floorId); - const { zBottom, zTop } = ceilingVerticalExtent(project, ceiling); - const ceilingInfo: CeilingInfo = { - typeId: ceiling.ceilingTypeId ?? ceiling.wallTypeId, - thickness, - singleLayer: wt.layers.length <= 1, - area: ceilingArea(ceiling.outline), - volume: ceilingArea(ceiling.outline) * thickness, - ceilingTypes: (project.ceilingTypes ?? []).map((t) => ({ - id: t.id, - name: t.name, - label: wallTypeLabel(t, project.components), - thickness: wallTypeThickness(t), - layerCount: t.layers.length, - })), - floorId: ceiling.floorId, - floorName: floor?.name ?? ceiling.floorId, - floors: project.drawingLevels - .filter((z) => z.kind === "floor") - .map((z) => ({ id: z.id, name: z.name })), - top: ceiling.top, - bottom: ceiling.bottom, - zBottom, - zTop, - // Aussparungen als anzeigefertige BBox-Masse (Breite × Tiefe je Loch). - openings: (ceiling.openings ?? []).map((hole) => { - const bb = outlineBBox(hole); - return { width: bb.maxX - bb.minX, depth: bb.maxY - bb.minY }; - }), - }; - return { - kind: "ceiling", - id: ceiling.id, - categoryCode: ceiling.categoryCode, - floorId: ceiling.floorId, - color, - colorPenId: ceiling.colorPenId, - weightMm, - fillHatchId: ceiling.hatchId, - fillColor: undefined, - foreground: ceiling.foreground, - foregroundPenId: ceiling.foregroundPenId, - background: ceiling.background, - backgroundPenId: ceiling.backgroundPenId, - foregroundSource: ceiling.foregroundSource, - backgroundSource: ceiling.backgroundSource, - effectiveForeground, - effectiveBackground, - effectiveHatchId, - strokeWeightOverride: ceiling.strokeWeight, - strokeWeightSource: ceiling.strokeWeightSource, - hatchSource: ceiling.hatchSource, - closed: true, - bbox: { minX: box.minX, minY: box.minY, maxX: box.maxX, maxY: box.maxY }, - ceiling: ceilingInfo, - }; -} - -/** Selektion für ein Dach ableiten (Farbe übersteuerbar, Strichstärke = Kategorie). */ -function roofSelection(project: Project, roof: Roof): Selection { - const cat = findCategory(project.layers, roof.categoryCode); - const color = roof.color ?? cat?.color ?? WALL_FALLBACK_COLOR; - const weightMm = cat?.lw ?? WALL_FALLBACK_MM; - const bb = roofBBox(roof.outline); - const eavesZ = roofBaseElevation(project, roof); - const g = roofGeometry(roof, eavesZ); - const footprintArea = Math.abs(bb.x1 - bb.x0) * Math.abs(bb.y1 - bb.y0); - const roofInfo: RoofInfo = { - shape: roof.shape, - pitchDeg: roof.pitchDeg, - pitchUpperDeg: roof.pitchUpperDeg, - roofTypeId: roof.roofTypeId, - mansardType: roof.mansardType, - mansardKneeRatio: roof.mansardKneeRatio, - halfHipRatio: roof.halfHipRatio, - overhang: roof.overhang, - overhangGable: roof.overhangGable, - ridgeAxis: roof.ridgeAxis, - thickness: roof.thickness, - baseElevation: eavesZ, - ridgeHeight: g.ridgeHeight, - footprintArea, - width: Math.abs(bb.x1 - bb.x0), - depth: Math.abs(bb.y1 - bb.y0), - minX: bb.x0, - minY: bb.y0, - edges: roofEdgeList(roof), - holes: (roof.holes ?? []).map((h) => ({ area: Math.abs(polygonArea(h)), points: h.length })), - hasEdgePitch: roof.edgePitchDeg !== undefined, - }; - return { - kind: "roof", - id: roof.id, - categoryCode: roof.categoryCode, - floorId: roof.floorId, - color, - colorPenId: roof.colorPenId, - weightMm, - closed: true, - bbox: { minX: bb.x0, minY: bb.y0, maxX: bb.x1, maxY: bb.y1 }, - roof: roofInfo, - }; -} - -/** Selektion für eine Öffnung ableiten (Farbe übersteuerbar, Strichstärke = Kategorie). */ -function openingSelection(project: Project, o: Opening): Selection { - const cat = findCategory(project.layers, o.categoryCode); - const color = o.color ?? cat?.color ?? WALL_FALLBACK_COLOR; - const weightMm = cat?.lw ?? WALL_FALLBACK_MM; - const wall = project.walls.find((w) => w.id === o.hostWallId); - const floor = wall - ? project.drawingLevels.find((z) => z.id === wall.floorId) - : undefined; - // Bounding-Box aus dem Lücken-Quad (volle Wanddicke); Fallback: leere Box. - const quad = wall ? openingGapQuad(project, wall, o) : null; - let minX = Infinity, - minY = Infinity, - maxX = -Infinity, - maxY = -Infinity; - for (const p of quad ?? []) { - minX = Math.min(minX, p.x); - minY = Math.min(minY, p.y); - maxX = Math.max(maxX, p.x); - maxY = Math.max(maxY, p.y); - } - if (!isFinite(minX)) { - minX = minY = maxX = maxY = 0; - } - const ext = wall - ? openingVerticalExtent(project, wall, o) - : { zBottom: 0, zTop: o.height }; - const openingInfo: OpeningInfo = { - id: o.id, - kind: o.kind, - hostWallId: o.hostWallId, - hostWallName: floor ? `${floor.name}` : o.hostWallId, - position: o.position, - width: o.width, - height: o.height, - sillHeight: o.sillHeight, - hinge: o.hinge, - swing: o.swing, - swingAngle: o.swingAngle, - openingDir: o.openingDir, - wingCount: o.wingCount, - doorType: o.doorType, - lintelLines: o.lintelLines, - typeId: o.typeId, - detailLevel: o.detailLevel, - zBottom: ext.zBottom, - zTop: ext.zTop, - frameLine: o.frameLine, - frameViewLine: o.frameViewLine, - sashLine: o.sashLine, - sillLineStyle: o.sillLineStyle, - }; - return { - kind: "opening", - id: o.id, - categoryCode: o.categoryCode, - color, - colorPenId: o.colorPenId, - weightMm, - fillHatchId: undefined, - fillColor: undefined, - closed: undefined, - bbox: { minX, minY, maxX, maxY }, - opening: openingInfo, - }; -} - -/** Selektion für eine Treppe ableiten (Farbe übersteuerbar, Strichstärke = Kategorie). */ -function stairSelection(project: Project, s: Stair): Selection { - const cat = findCategory(project.layers, s.categoryCode); - const color = s.color ?? cat?.color ?? WALL_FALLBACK_COLOR; - const weightMm = cat?.lw ?? WALL_FALLBACK_MM; - const { zBottom, zTop } = stairVerticalExtent(project, s); - const totalRise = zTop - zBottom; - const geo = stairGeometry(s, totalRise); - const box = stairBBox(geo); - const floor = project.drawingLevels.find((z) => z.id === s.floorId); - const stairInfo: StairInfo = { - shape: s.shape, - width: s.width, - stepCount: s.stepCount, - totalRise, - riserHeight: geo.riserHeight, - treadDepth: geo.treadDepth, - up: s.up !== false, - arrowStyle: s.arrowStyle, - referenz: s.referenz, - typeId: s.typeId, - floorId: s.floorId, - floorName: floor?.name ?? s.floorId, - zBottom, - zTop, - }; - return { - kind: "stair", - id: s.id, - categoryCode: s.categoryCode, - floorId: s.floorId, - color, - colorPenId: s.colorPenId, - weightMm, - fillHatchId: undefined, - fillColor: undefined, - closed: undefined, - bbox: { minX: box.minX, minY: box.minY, maxX: box.maxX, maxY: box.maxY }, - stair: stairInfo, - }; -} - -/** Selektion für einen Raum ableiten (Fläche/Umfang aus dem Umriss abgeleitet). */ -function roomSelection(project: Project, r: Room): Selection { - const cat = findCategory(project.layers, r.categoryCode); - const color = r.color ?? cat?.color ?? WALL_FALLBACK_COLOR; - const weightMm = cat?.lw ?? WALL_FALLBACK_MM; - const res = evaluateRoom(r.boundary, r.siaCategory); - const floor = project.drawingLevels.find((z) => z.id === r.floorId); - let minX = Infinity, - minY = Infinity, - maxX = -Infinity, - maxY = -Infinity; - for (const p of r.boundary) { - minX = Math.min(minX, p.x); - minY = Math.min(minY, p.y); - maxX = Math.max(maxX, p.x); - maxY = Math.max(maxY, p.y); - } - if (!isFinite(minX)) minX = minY = maxX = maxY = 0; - const roomInfo: RoomInfo = { - name: r.name, - siaCategory: r.siaCategory, - area: res.netArea, - perimeter: res.perimeter, - floorId: r.floorId, - floorName: floor?.name ?? r.floorId, - }; - return { - kind: "room", - id: r.id, - categoryCode: r.categoryCode, - floorId: r.floorId, - color, - colorPenId: r.colorPenId, - weightMm, - fillHatchId: undefined, - fillColor: undefined, - closed: true, - bbox: { minX, minY, maxX, maxY }, - room: roomInfo, - }; -} - -/** Auswahl-Farbe der Extrusions-Footprints (identisch zum Grundriss-Umriss/3D-Orange). */ -const EXTRUSION_COLOR = "#d98c40"; - -/** Selektion für einen extrudierten Körper ableiten (truck-Integration). */ -function extrudedSolidSelection(project: Project, s: ExtrudedSolid): Selection { - const floor = project.drawingLevels.find((z) => z.id === s.levelId); - let minX = Infinity, - minY = Infinity, - maxX = -Infinity, - maxY = -Infinity; - for (const p of s.points) { - minX = Math.min(minX, p.x); - minY = Math.min(minY, p.y); - maxX = Math.max(maxX, p.x); - maxY = Math.max(maxY, p.y); - } - if (!isFinite(minX)) minX = minY = maxX = maxY = 0; - const info: ExtrudedSolidInfo = { - height: s.height, - taper: s.taper ?? 0, - cornerRadius: s.cornerRadius ?? 0, - chamfer: s.chamfer ?? 0, - ...(s.brep ? { brepLabel: s.brep.label ?? "B-Rep" } : {}), - area: polygonArea(s.points), - spec: s.operation === "subtract" ? null : extrudedSolidSpec(s, floor?.baseElevation ?? 0), - subtract: s.operation === "subtract", - canSubtract: !s.brep && (s.taper ?? 0) < 1e-6, - baseOffset: s.baseOffset ?? 0, - floorId: s.levelId, - floorName: floor?.name ?? s.levelId, - }; - return { - kind: "extrudedSolid", - id: s.id, - categoryCode: "", - floorId: s.levelId, - color: EXTRUSION_COLOR, - weightMm: WALL_FALLBACK_MM, - fillHatchId: null, - fillColor: null, - closed: true, - bbox: { minX, minY, maxX, maxY }, - extrudedSolid: info, - }; -} - -/** Umriss-/Auswahlfarbe der Stützen-Poché (neutrales Tragwerks-Grau). */ -const COLUMN_COLOR = "#3a3f47"; - -/** Selektion für eine Stütze (Column) ableiten. */ -function columnSelection(project: Project, col: Column): Selection { - const floor = project.drawingLevels.find((z) => z.id === col.floorId); - const category = findCategory(project.layers, col.categoryCode); - const pts = columnFootprint(col); - let minX = Infinity, - minY = Infinity, - maxX = -Infinity, - 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); - } - if (!isFinite(minX)) minX = minY = maxX = maxY = 0; - const { zBottom, zTop } = columnVerticalExtent(project, col); - const info: ColumnInfo = { - profile: col.profile, - height: col.height, - rotationDeg: ((col.rotation ?? 0) * 180) / Math.PI, - floorId: col.floorId, - floorName: floor?.name ?? col.floorId, - zBottom, - zTop, - }; - // Effektive Vordergrund-/Hintergrund-/Schraffur-/Strichstärke-Vorschau — s. - // Kommentar in wallSelection (dieselbe Kette, das zugewiesene Bauteil als - // Repräsentant statt der äussersten Schicht, da Column nur EIN componentId - // trägt statt eines geschichteten Aufbaus). - // `getComponent` wirft bei unbekannter ID (z. B. gelöschtes Bauteil) — die - // Panel-Vorschau soll dabei nicht abstürzen (analog dem try/catch in - // structures.ts addColumnPoche), einfach auf "kein Bauteil" zurückfallen. - const comp = col.componentId - ? project.components.find((c) => c.id === col.componentId) - : undefined; - const effectiveForeground = comp - ? resolveForeground(comp, col.foreground, category, col.foregroundSource) - : col.foreground; - const effectiveBackground = comp - ? resolveBackground(comp, col.background, category, col.backgroundSource) - : col.background; - const effectiveHatchId = resolveHatchId(col.hatchId, col.hatchSource, category, comp?.hatchId); - const weightMm = resolveStrokeWeight(col.strokeWeight, col.strokeWeightSource, category, WALL_FALLBACK_MM); - return { - kind: "column", - id: col.id, - categoryCode: col.categoryCode, - floorId: col.floorId, - color: col.color ?? category?.color ?? COLUMN_COLOR, - colorPenId: col.colorPenId, - weightMm, - fillHatchId: col.hatchId, - foreground: col.foreground, - foregroundPenId: col.foregroundPenId, - background: col.background, - backgroundPenId: col.backgroundPenId, - foregroundSource: col.foregroundSource, - backgroundSource: col.backgroundSource, - effectiveForeground, - effectiveBackground, - effectiveHatchId, - strokeWeightOverride: col.strokeWeight, - strokeWeightSource: col.strokeWeightSource, - hatchSource: col.hatchSource, - bbox: { minX, minY, maxX, maxY }, - column: info, - }; -} - -/** - * Selektion für ein Kontext-Objekt (importiertes Mesh/Terrain/Konturen-Satz) - * ableiten. Bbox aus den rohen x/y-Koordinaten (Meshes: flaches [x,y,z…]- - * Array, nur x/y je Vertex; Konturen: `pts` je Kontur) — die Höhe (z) bleibt - * unberücksichtigt (2D-Bbox wie bei allen anderen Elementarten). `lv95Center` - * nur, wenn `project.geoAnchor` gesetzt ist (sonst kein Rückrechnungs-Bezug). - */ -function contextObjectSelection(project: Project, obj: ContextObject): Selection { - let minX = Infinity, - minY = Infinity, - maxX = -Infinity, - maxY = -Infinity; - const consider = (x: number, y: number) => { - minX = Math.min(minX, x); - minY = Math.min(minY, y); - maxX = Math.max(maxX, x); - maxY = Math.max(maxY, y); - }; - if (obj.type === "contourSet") { - for (const c of obj.contours) for (const p of c.pts) consider(p.x, p.y); - } else if (obj.type === "image") { - consider(obj.min.x, obj.min.y); - consider(obj.max.x, obj.max.y); - } else { - const pos = obj.positions; - for (let i = 0; i + 2 < pos.length; i += 3) consider(pos[i], pos[i + 1]); - } - if (!isFinite(minX)) minX = minY = maxX = maxY = 0; - const anchor = project.geoAnchor; - const lv95Center = anchor - ? localToLv95( - (minX + maxX) / 2, - (minY + maxY) / 2, - { e: anchor.lv95.e - anchor.model.x, n: anchor.lv95.n - anchor.model.y }, - ) - : undefined; - const isImage = obj.type === "image"; - return { - kind: "contextObject", - id: obj.id, - categoryCode: "", - color: "#888888", - weightMm: WALL_FALLBACK_MM, - bbox: { minX, minY, maxX, maxY }, - contextObject: { objType: obj.type, lv95Center }, - // Deckkraft + Bildkorrektur nur bei Luftbildern (`ContextImage`) — steuert - // die (wiederverwendete) Deckkraft-Zeile + die neue Bildkorrektur-Sektion - // im Attribute-Panel, s. `AttributesPanel.tsx`. - isImage, - opacity: isImage ? ((obj as ContextImage).opacity ?? 1) : undefined, - imageFilters: isImage ? (obj as ContextImage).filters : undefined, - }; -} - -/** Selektion für ein 2D-Zeichenelement ableiten (gleiche Auflösung wie generatePlan). */ -function drawingSelection(project: Project, d: Drawing2D): Selection { - const ls = d.lineStyleId - ? project.lineStyles.find((l) => l.id === d.lineStyleId) - : undefined; - const cat = findCategory(project.layers, d.categoryCode); - const color = d.color ?? ls?.color ?? cat?.color ?? DRAW_FALLBACK_COLOR; - // Effektive Strichstärke, dieselbe Kette wie der Plan (`plan/drawings.rs`) - // (resolveStrokeWeight): Override zuerst, Source ≠ "object" (also "layer" - // ODER fehlend, s. AttributeSource-Default) erzwingt die Kategorie (umgeht - // das LineStyle-Gewicht), sonst die LineStyle-/Kategorie-Kette. - const weightMm = - d.weightMm ?? - (d.strokeWeightSource !== "object" ? cat?.lw : undefined) ?? - ls?.weight ?? - cat?.lw ?? - WALL_FALLBACK_MM; - const closed = isClosedGeom(d.geom); - // Effektive Vordergrund-/Hintergrund-/Schraffur-Vorschau — s. Kommentar in - // wallSelection. Ein Drawing2D hat KEIN eigenes Bauteil (daher auch keine - // „Nach Bauteil"-Option im Panel, s. AttributesPanel.tsx) — als Platzhalter - // ein leeres Bauteil, dessen foreground/background/hatchId immer fehlen, - // sodass die Kette bei einem (aus Alt-Daten) expliziten `source:"object"` - // korrekt auf „kein Wert" statt einer erfundenen Bauteilfarbe fällt. Anders - // als bei Wand/Decke (Default „Nach Bauteil") gilt bei Drawing2D „Nach - // Ebene" als Default — daher hier explizit `?? "layer"` VOR dem Resolver - // (der selbst weiterhin generisch „Nach Bauteil" als Default kennt). - const noComponent = { id: "", name: "", color, hatchId: "", joinPriority: 0 }; - const effectiveForeground = closed - ? resolveForeground(noComponent, d.foreground, cat, d.foregroundSource ?? "layer") - : undefined; - const effectiveBackground = closed - ? resolveBackground(noComponent, d.background, cat, d.backgroundSource ?? "layer") - : undefined; - const effectiveHatchId = closed - ? resolveHatchId(d.hatchId, d.hatchSource ?? "layer", cat, undefined) - : null; - return { - kind: "drawing2d", - id: d.id, - categoryCode: d.categoryCode, - floorId: d.levelId, - color, - colorPenId: d.colorPenId, - weightMm, - fillHatchId: closed ? d.hatchId ?? null : null, - fillColor: closed ? d.fillColor ?? null : null, - foreground: closed ? d.foreground : undefined, - foregroundPenId: closed ? d.foregroundPenId : undefined, - background: closed ? d.background : undefined, - backgroundPenId: closed ? d.backgroundPenId : undefined, - foregroundSource: closed ? d.foregroundSource : undefined, - backgroundSource: closed ? d.backgroundSource : undefined, - effectiveForeground, - effectiveBackground, - effectiveHatchId, - strokeWeightOverride: d.weightMm, - strokeWeightSource: d.strokeWeightSource, - hatchSource: closed ? d.hatchSource : undefined, - closed, - isImage: d.geom.shape === "image", - // Deckkraft: beim BILD die eigene Bild-Deckkraft, sonst die - // Objekt-Transparenz des Elements (`Drawing2D.opacity`). - opacity: d.geom.shape === "image" ? (d.geom.opacity ?? 1) : d.opacity, - bbox: geomBBox(d.geom), - detailRef: - d.geom.shape === "detailref" - ? { - label: d.geom.label, - sheetLayoutId: d.geom.sheetLayoutId, - sheetLabel: d.geom.sheetLabel, - availableLayouts: (project.layouts ?? []).map((l) => ({ id: l.id, name: l.name })), - } - : undefined, - }; -} +/** Meldungen, mit denen die Objekt-Info wie bisher abbricht (unbekannter Typ/Bauteil). */ +const THROWN = /^Unbekannte[rs]? /; /** * Leitet den Selektions-Kontrakt für das ERSTE selektierte Element ab. * Drawing-Auswahl und Wand-Auswahl schließen sich aus; bei Drawing-Auswahl * hat diese Vorrang. Liefert `null`, wenn nichts (oder kein auffindbares - * Element) selektiert ist. + * Element) selektiert ist. Ein unbekannter Wand-/Deckentyp oder ein fehlendes + * Bauteil wirft wie bisher; ein Element, das das Kern-Modell nicht lesen kann, + * ergibt `null` (mit Warnung). */ export function deriveSelection( project: Project, @@ -1303,46 +536,49 @@ export function deriveSelection( selectedRoofId: string | null = null, selectedContextObjectId: string | null = null, ): Selection | null { - if (selectedContextObjectId) { - const o = (project.context ?? []).find((x) => x.id === selectedContextObjectId); - if (o) return contextObjectSelection(project, o); + const args = { + wallIds: selectedWallIds, + drawingId: selectedDrawingId, + ceilingId: selectedCeilingId, + openingId: selectedOpeningId, + stairId: selectedStairId, + roomId: selectedRoomId, + extrudedSolidId: selectedExtrudedSolidId, + columnId: selectedColumnId, + roofId: selectedRoofId, + contextObjectId: selectedContextObjectId, + // Lage in der Leseansicht (= Reihenfolge im Dokument): erspart dem Kern die lineare Suche. + at: {} as Record, + }; + const P = project as unknown as Record; + const hint = (list: string, id: string | null | undefined) => { + if (!id) return; + const i = (P[list] ?? []).findIndex((x) => x.id === id); + if (i >= 0) args.at[list] = i; + }; + hint("context", selectedContextObjectId); + hint("drawings2d", selectedDrawingId); + hint("extrudedSolids", selectedExtrudedSolidId); + hint("columns", selectedColumnId); + hint("openings", selectedOpeningId); + hint("walls", selectedWallIds[0]); + hint("ceilings", selectedCeilingId); + hint("roofs", selectedRoofId); + hint("stairs", selectedStairId); + hint("rooms", selectedRoomId); + let sel: Selection | null; + try { + sel = documentFor(project).queryRootMarked("selectionInfo", JSON.stringify(args)); + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + if (THROWN.test(msg)) throw new Error(msg); + console.warn("Objekt-Info:", msg); + return null; } - if (selectedDrawingId) { - const d = project.drawings2d.find((x) => x.id === selectedDrawingId); - return d ? drawingSelection(project, d) : null; + if (sel?.extrudedSolid) { + const s = (project.extrudedSolids ?? []).find((x) => x.id === sel!.id); + const floor = s && project.drawingLevels.find((z) => z.id === s.levelId); + sel.extrudedSolid.spec = s && s.operation !== "subtract" ? extrudedSolidSpec(s, floor?.baseElevation ?? 0) : null; } - if (selectedExtrudedSolidId) { - const s = (project.extrudedSolids ?? []).find((x) => x.id === selectedExtrudedSolidId); - return s ? extrudedSolidSelection(project, s) : null; - } - if (selectedColumnId) { - const c = (project.columns ?? []).find((x) => x.id === selectedColumnId); - return c ? columnSelection(project, c) : null; - } - if (selectedOpeningId) { - const o = (project.openings ?? []).find((x) => x.id === selectedOpeningId); - if (o) return openingSelection(project, o); - } - const wallId = selectedWallIds[0]; - if (wallId) { - const w = project.walls.find((x) => x.id === wallId); - return w ? wallSelection(project, w) : null; - } - if (selectedCeilingId) { - const c = (project.ceilings ?? []).find((x) => x.id === selectedCeilingId); - return c ? ceilingSelection(project, c) : null; - } - if (selectedRoofId) { - const r = (project.roofs ?? []).find((x) => x.id === selectedRoofId); - return r ? roofSelection(project, r) : null; - } - if (selectedStairId) { - const s = (project.stairs ?? []).find((x) => x.id === selectedStairId); - return s ? stairSelection(project, s) : null; - } - if (selectedRoomId) { - const r = (project.rooms ?? []).find((x) => x.id === selectedRoomId); - return r ? roomSelection(project, r) : null; - } - return null; + return sel; }