diff --git a/TODO.md b/TODO.md index 0273f656..62c0aca8 100644 --- a/TODO.md +++ b/TODO.md @@ -704,6 +704,25 @@ Frage: WebGPU weiterführen oder wie BIMCraft CPU + native GPU? - ◐ **[14] „Never crash".** TS-Wächter `guarded()` um das truck-WASM (Trap → neu instanziieren, einmal wiederholen). Rust-Kern: Bindungen verwerfen Unsinn statt zu paniken. Offen: Wächter für render3d/render2d/Kern, Rust-Lints `unwrap_used`/`expect_used`/`panic` auf `deny`, Obergrenzen. · M + - ✅ (29.10.) Kaputte Projekte (Datei/Import) bringen keine Abfrage mehr zum Werfen. Fuzz-Test + `src/core/robustness.test.ts`: Beispiel, „alle Element-Arten", 7 Zufallsprojekte, gekacheltes Projekt × 21 + Verderbnisse (hängende Wand-/Decken-/Dach-/Tür-/Treppentypen, Bauteile, Geschosse, Öffnungs-Wand, Schraffur/ + Linienstil/Stift/Stiftsatz, Block, Layout-Master/-Ausschnitt; Gruppen/Ordner, die sich selbst enthalten; leere und + Ein-Punkt-Polygone; NaN/±∞/negativ; fehlende Felder; doppelte ids; falsche Typen; kaputte Schnittlinien/Baurecht/ + Sonne) gegen jede Fassade (Plan aller Ebenen + sichtbare Geschosse, Schnitt, Ansicht, Szene/SVG/DXF je Plan, 3D, + Pick, IFC, OBJ/STL/GLB, Liste, Kennzahlen, Raumprogramm, Flächen/IVHB, Baurecht, Sonne, Layouts, Prüfung, + Speichern/Laden). Vorher u. a. 158 Würfe allein am Beispiel. Ursachen behoben: (1) Kern-Ableitungen fallen bei + hängenden Verweisen auf Vorgaben zurück statt `Err` (`wall_type_or_fallback`/`component_or_fallback`: eine Schicht + 0,2 m, neutrales Grau; fehlende Schraffur → ohne Muster; hängender Linienstil einer Schraffur → 0,13 durchgezogen; + Deckentyp → Rückfall-Schicht; Verschneidung mit Rückfall-Werten; Plan, Schnitt, Ansicht, 3D, IFC, Mesh). (2) Typisierte + Sicht tolerant (`model/lenient.rs`): EIN Wert, der nicht passt (`null` statt Zahl — NaN überlebt JSON nicht —, + Zeichenkette statt Punkt), legte das ganze Dokument lahm; jetzt fällt nur er auf die Vorgabe zurück (Pflichtfelder wie + `Vec2` → 0), nicht lesbare Listenelemente entfallen, die JSON-Wurzel bleibt unverändert. (3) Mesh-Export: gebrochene + Indizes/NaN-Ecken aus Importen sprengten den `fileio`-Leser. (4) TS `visibleCodesFromSnapshot`/`resolveTitleBlock` + ohne `layerVisibility`/`viewports`. `projectWarnings` (Kern `project_refs.rs`) listet hängende Verweise, Zyklen und + ersetzte Werte; `dossier-cli validate` (und MCP `validate`) gibt sie als „Warnung: …" aus (Exit 0, solange keine + Fehler). Kein Panic gefunden. Offen: Hülle (Panels/Editoren) nicht geprüft; Kategorie-Codes ohne Kategorie werden + nicht gewarnt (bewusst, häufig bei Importen). - ✅ **[16] Befehle mit Unsinn füttern.** 27.10.: `commands/hostile.test.ts` füttert alle Befehle; fand 1 Speicher-Explosion (revisionCloud), behoben. · S - ✅ **[22] Fester Check vor Abschluss.** `npm run check` (tsc, vitest, cargo test aller 6 Crates, diff --git a/src-tauri/core/src/document.rs b/src-tauri/core/src/document.rs index b3f71c18..8924e353 100644 --- a/src-tauri/core/src/document.rs +++ b/src-tauri/core/src/document.rs @@ -230,21 +230,23 @@ impl Document { } /// Typisierte Sicht des Projekts (gecacht; nach Ops werden nur die berührten Felder neu gelesen). - /// Fehler = Feld, das dem Modell widerspricht (Meldung von serde). + /// Werte, die dem Modell widersprechen, fallen auf die Vorgabe zurück (`model::lenient`) — das + /// `Result` bleibt für die Aufrufer, ist aber stets `Ok`. pub fn project(&mut self) -> Result<&Project, String> { if self.typed.is_none() { // Die Map wird nur ausgeliehen: `Value::Object` braucht Besitz, daher temporär herausnehmen. let value = Value::Object(std::mem::take(&mut self.root)); - let parsed = Project::deserialize(&value).map_err(|e| e.to_string()); + let parsed = Project::deserialize(&value); if let Value::Object(m) = value { self.root = m; } - self.typed = Some(parsed?); + // Passt ein Wert nicht zum Modell (Datei/Import: `null` statt Zahl, falscher Typ), fällt nur + // er auf die Vorgabe zurück statt das ganze Projekt (`model::lenient`). + self.typed = Some(parsed.unwrap_or_else(|_| crate::model::lenient::project_lenient(&self.root).0)); self.dirty.clear(); self.dirty_items.clear(); } else if !self.dirty.is_empty() || !self.dirty_items.is_empty() { let mut dirty: Vec = self.dirty.drain().collect(); - let mut failed = None; if let Some(t) = self.typed.as_mut() { // Einzelne Elemente (nach `replace`), ausser ihre Liste wird ohnehin ganz gelesen; // geht es nicht (Liste ohne Element-Weg, Element passt nicht), die ganze Liste. @@ -258,16 +260,9 @@ impl Document { } } for key in &dirty { - if let Err(e) = t.set_field(key, self.root.get(key).filter(|v| !v.is_null())) { - failed = Some(e); - break; - } + crate::model::lenient::set_field_lenient(t, key, self.root.get(key).filter(|v| !v.is_null())); } } - if let Some(e) = failed { - self.typed = None; - return Err(e); - } } Ok(self.typed.as_ref().expect("gerade gesetzt")) } diff --git a/src-tauri/core/src/ifc_data.rs b/src-tauri/core/src/ifc_data.rs index 6e3ffce7..f82e2ad3 100644 --- a/src-tauri/core/src/ifc_data.rs +++ b/src-tauri/core/src/ifc_data.rs @@ -487,24 +487,6 @@ fn sia_label(key: &str) -> &'static str { const SIA_CATEGORIES: [SiaCategory; 6] = [SiaCategory::HNF, SiaCategory::NNF, SiaCategory::VF, SiaCategory::FF, SiaCategory::KGF, SiaCategory::AGF]; -/// Gleiche Fehlermeldung wie die Pick-Geometrie des 3D (`pickGeometry`): eine Öffnung in einer Wand -/// mit unbekanntem Wandtyp bricht ab, bevor die Wände gerechnet werden. -pub(crate) fn pick_opening_check(p: &Project) -> Result<(), String> { - for o in p.openings.as_deref().unwrap_or(&[]) { - let Some(wall) = p.walls.iter().find(|w| w.id == o.host_wall_id) else { continue }; - let axis = hypot2(wall.end.x - wall.start.x, wall.end.y - wall.start.y); - let from = max(0.0, min(o.position, axis)); - let to = max(from, min(o.position + o.width, axis)); - if to - from < 1e-4 { - continue; - } - if p.wall_type(wall).is_none() { - return Err(format!("Unbekannter Wandtyp: {}", wall.wall_type_id)); - } - } - Ok(()) -} - /// Der flache IFC-Puffer aus dem Projekt (s. Modulkopf). pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result { // Georeferenziert: die ganze Geometrie auf die echten LV95-Koordinaten (ohne Bezug unverändert). @@ -550,7 +532,6 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result let component_name = |p: &Project, id: &str| -> String { p.component(id).map_or_else(|| id.to_string(), |c| c.name.clone()) }; // ── Wände ────────────────────────────────────────────────────────────── - pick_opening_check(&p)?; let all_bands = model3d::emit_walls(&p, true)?; let mut bands_by_wall: HashMap<&str, Vec<&RWall>> = HashMap::new(); for b in &all_bands { @@ -1053,9 +1034,11 @@ mod tests { let mut p = Project { id: "leer".into(), ..Default::default() }; let f = ifc_export_data(&p, &IfcOptions::default()).unwrap(); assert_eq!(f.nums.last(), Some(&REC_END_COLUMNS)); + // Hängender Wandtyp (Datei/Import): Export mit dem Rückfall-Typ statt Abbruch. p = sample(); p.walls[0].wall_type_id = "fehlt".into(); - assert_eq!(ifc_export_data(&p, &IfcOptions::default()).unwrap_err(), "Unbekannter Wandtyp: fehlt"); + let f = ifc_export_data(&p, &IfcOptions::default()).unwrap(); + assert_eq!(f.nums.last(), Some(&REC_END_COLUMNS)); } #[test] diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 44f1539a..0035ad47 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -85,6 +85,7 @@ pub mod ugrid; pub mod wasm_alloc; pub mod text_layout; pub mod plan_text; +pub mod project_refs; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/mesh_data.rs b/src-tauri/core/src/mesh_data.rs index 229d1354..d16dcee3 100644 --- a/src-tauri/core/src/mesh_data.rs +++ b/src-tauri/core/src/mesh_data.rs @@ -217,7 +217,13 @@ fn append_model_mesh(prim: &mut Prim, positions: &[f64], indices: &[f64], closed i += 3; } let nv = (pos.len() / 3) as f64; - let ok = |v: f64| v >= 0.0 && v < nv; + // Nur ganzzahlige Indizes auf endliche Ecken (Importe/Dateien können Unsinn tragen); die + // übrigen Ecken bleiben endlich (0), damit der Puffer lesbar bleibt. + let bad: Vec = pos.chunks_exact(3).map(|c| !c.iter().all(|v| v.is_finite())).collect(); + for v in pos.iter_mut().filter(|v| !v.is_finite()) { + *v = 0.0; + } + let ok = |v: f64| v >= 0.0 && v < nv && v.fract() == 0.0 && !bad[v as usize]; let mut tri: Vec = Vec::new(); let mut i = 0; while i + 2 < indices.len() { @@ -265,7 +271,6 @@ pub fn mesh_export_data(src: &Project, opt: &MeshOptions) -> Result = Vec::new(); let mut mats = Materials::default(); - crate::ifc_data::pick_opening_check(&p)?; let walls = model3d::emit_walls(&p, true)?; let slabs = model3d::emit_slabs(&p); let levels: Vec<(String, String)> = p.drawing_levels.iter().filter(|l| l.kind == DrawingLevelKind::Floor).map(|l| (l.id.clone(), l.name.clone())).collect(); @@ -518,8 +523,20 @@ mod tests { #[test] fn kaputtes_kontext_netz_ohne_panik() { let mut p = Project { id: "k".into(), ..Default::default() }; - p.context = Some(vec![ContextObject::ImportedMesh(ImportedMesh { id: "m".into(), positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, f64::NAN], indices: vec![0.0, 1.0, 9.0, 0.0, 1.0, 2.0, f64::NAN, 0.0, 1.0], ..Default::default() })]); + p.context = Some(vec![ContextObject::ImportedMesh(ImportedMesh { id: "m".into(), positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, f64::NAN], indices: vec![0.0, 1.0, 9.0, 0.0, 1.0, 2.0, f64::NAN, 0.0, 1.0], ..Default::default() })]); let f = mesh_export_data(&p, &MeshOptions::default()).unwrap(); assert!(f.strings.iter().any(|s| s == "Kontext_m")); } + + /// Gebrochene Indizes und nicht endliche Ecken (Datei/Import) dürfen nicht in den Puffer: der + /// Leser (`fileio`) verlangt ganzzahlige Indizes und endliche Zahlen. + #[test] + fn nur_ganzzahlige_indizes_und_endliche_ecken() { + let mut g = Prim { material: 0.0, positions: Vec::new(), indices: Vec::new() }; + let pos = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, f64::NAN]; + append_model_mesh(&mut g, &pos, &[0.0, 1.0, 2.0, 0.0, 1.5, 2.0, 1.0, 2.0, 3.0], false); + assert_eq!(g.indices, vec![0.0, 2.0, 1.0], "nur das ganzzahlige Dreieck ohne NaN-Ecke"); + assert!(g.positions.iter().all(|v| v.is_finite())); + assert_eq!(g.positions.len(), 12); + } } diff --git a/src-tauri/core/src/model/helpers.rs b/src-tauri/core/src/model/helpers.rs index 6df7c114..65c91583 100644 --- a/src-tauri/core/src/model/helpers.rs +++ b/src-tauri/core/src/model/helpers.rs @@ -9,7 +9,36 @@ use std::collections::HashMap; use crate::roof::{MansardType, RoofParams, Shape}; use crate::roof_skeleton::Axis; +/// Rückfall-Bauteil für hängende Verweise (Datei/Import nennt ein Bauteil, das fehlt): neutrales +/// Grau, keine Schraffur, Verschneidungs-Priorität 0. +static FALLBACK_COMPONENT: std::sync::LazyLock = + std::sync::LazyLock::new(|| Component { name: "?".into(), color: "#bfbfbf".into(), ..Default::default() }); + +/// Rückfall-Wandtyp für hängende Verweise: eine Schicht 0.2 m (wie der Dicken-Rückfall in TS) aus +/// dem [`FALLBACK_COMPONENT`]. +static FALLBACK_WALL_TYPE: std::sync::LazyLock = std::sync::LazyLock::new(|| WallType { + name: "?".into(), + layers: vec![Layer { thickness: 0.2, ..Default::default() }], + ..Default::default() +}); + impl Project { + /// Wandtyp oder — bei hängendem Verweis — der Rückfall-Typ (eine Schicht 0.2 m). Für alle + /// Ableitungen, die nicht an fehlenden Daten scheitern dürfen (Plan, Schnitt, 3D, Exporte). + pub fn wall_type_or_fallback(&self, w: &Wall) -> &WallType { + self.wall_type(w).unwrap_or(&FALLBACK_WALL_TYPE) + } + + /// Bauteil oder — bei hängendem Verweis — das neutrale Rückfall-Bauteil. + pub fn component_or_fallback(&self, id: &str) -> &Component { + self.component(id).unwrap_or(&FALLBACK_COMPONENT) + } + + /// Schichten des Rückfall-Wandtyps (auch für Decken mit hängendem Typ). + pub fn fallback_layers() -> &'static [Layer] { + &FALLBACK_WALL_TYPE.layers + } + pub fn floor(&self, id: &str) -> Option<&DrawingLevel> { self.drawing_levels.iter().find(|l| l.id == id) } diff --git a/src-tauri/core/src/model/lenient.rs b/src-tauri/core/src/model/lenient.rs new file mode 100644 index 00000000..a0b08d94 --- /dev/null +++ b/src-tauri/core/src/model/lenient.rs @@ -0,0 +1,336 @@ +//! Tolerantes Einlesen der typisierten Sicht: Dateien von der Platte und Importe können Werte tragen, +//! die nicht zum Modell passen — `null` statt einer Zahl (NaN überlebt JSON nicht), eine Zeichenkette +//! statt eines Punkts, eine kaputte Form. Ohne Toleranz scheitert das ganze Projekt an EINEM Wert und +//! jede Abfrage wirft. Hier wird nur das Nötige verworfen: der Wert, an dem es scheitert, fällt auf die +//! Vorgabe des Modells zurück (`#[serde(default)]`); lässt sich ein Listenelement gar nicht lesen, +//! entfällt es. Die JSON-Wurzel des Dokuments bleibt unverändert (Speichern verliert nichts). +//! +//! Vorgehen (typunabhängig, nur über Probe-Lesen): erst das ganze Feld, dann je Listenelement; ein +//! Element, das nicht passt, wird von leer aus wieder aufgebaut — Schlüssel (bzw. Listeneinträge) +//! werden in Hälften zugefügt, solange das Probe-Lesen gelingt; ein einzelner Schlüssel, der es +//! scheitern lässt, wird rekursiv repariert oder weggelassen. Aufwand nur im Fehlerfall. + +use super::Project; +use serde_json::{Map, Value}; + +/// Ein Pfadschritt im JSON-Baum. +#[derive(Clone, Debug)] +enum Seg { + Key(String), + Index(usize), +} + +fn get_mut<'a>(v: &'a mut Value, path: &[Seg]) -> Option<&'a mut Value> { + let mut cur = v; + for s in path { + cur = match (s, cur) { + (Seg::Key(k), Value::Object(m)) => m.get_mut(k)?, + (Seg::Index(i), Value::Array(a)) => a.get_mut(*i)?, + _ => return None, + }; + } + Some(cur) +} + +fn path_text(path: &[Seg]) -> String { + let mut s = String::new(); + for p in path { + match p { + Seg::Key(k) => { + if !s.is_empty() { + s.push('.'); + } + s.push_str(k); + } + Seg::Index(i) => s.push_str(&format!("[{i}]")), + } + } + s +} + +/// Repariert `cur` (ganzer Wert, den `ok` prüft) so, dass `ok(cur)` gelingt; verworfene Pfade +/// landen in `dropped`. `false`: auch die Wurzel lässt sich nicht lesen. +fn repair(cur: &mut Value, ok: &dyn Fn(&Value) -> bool, dropped: &mut Vec) -> bool { + if ok(cur) { + return true; + } + let mut path = Vec::new(); + rebuild(cur, &mut path, ok, dropped) +} + +/// Baut den Knoten an `path` von leer aus neu auf (Vorbedingung: das Ganze scheitert mit ihm). +/// `false`: der Knoten lässt sich auch leer nicht lesen — der Aufrufer entfernt ihn. +fn rebuild(cur: &mut Value, path: &mut Vec, ok: &dyn Fn(&Value) -> bool, dropped: &mut Vec) -> bool { + let Some(node) = get_mut(cur, path) else { return false }; + match std::mem::take(node) { + Value::Object(orig) => { + // 1. Leer anfangen (Strukturen mit Vorgaben) und die Schlüssel wieder zufügen. + *get_mut(cur, path).expect("eben gelesen") = Value::Object(Map::new()); + if ok(cur) { + add_keys(cur, path, orig.into_iter().collect(), ok, dropped); + return true; + } + // 2. Pflichtfelder (z. B. `Vec2 {x, y}`): `null` bzw. jeder Nicht-Zahl-Wert als 0. + for zero_all in [false, true] { + let mut subst = Vec::new(); + let candidate: Map = orig + .iter() + .map(|(k, v)| { + let replace = if zero_all { !(v.is_number() || v.is_object() || v.is_array()) } else { v.is_null() }; + if replace { + subst.push(k.clone()); + (k.clone(), Value::from(0.0)) + } else { + (k.clone(), v.clone()) + } + }) + .collect(); + if subst.is_empty() { + continue; + } + *get_mut(cur, path).expect("eben gelesen") = Value::Object(candidate); + if ok(cur) { + for k in subst { + path.push(Seg::Key(k)); + dropped.push(path_text(path)); + path.pop(); + } + return true; + } + } + // 3. Nur die Zeichenketten (Kennungen wie `shape`/`kind`/`type` innerer Enums), dann der Rest. + let (tags, rest): (Vec<(String, Value)>, Vec<(String, Value)>) = orig.into_iter().partition(|(_, v)| v.is_string()); + *get_mut(cur, path).expect("eben gelesen") = Value::Object(tags.into_iter().collect()); + if !ok(cur) { + return false; + } + add_keys(cur, path, rest, ok, dropped); + true + } + Value::Array(orig) => { + *get_mut(cur, path).expect("eben gelesen") = Value::Array(Vec::new()); + if !ok(cur) { + return false; + } + add_items(cur, path, orig, ok, dropped); + true + } + other => { + *get_mut(cur, path).expect("eben gelesen") = other; + false + } + } +} + +/// Fügt `items` (in Hälften) zum Objekt an `path` hinzu, solange `ok` gilt. +fn add_keys(cur: &mut Value, path: &mut Vec, items: Vec<(String, Value)>, ok: &dyn Fn(&Value) -> bool, dropped: &mut Vec) { + if items.is_empty() { + return; + } + let keys: Vec = items.iter().map(|(k, _)| k.clone()).collect(); + let insert_all = |cur: &mut Value, path: &[Seg], items: &[(String, Value)]| { + if let Some(Value::Object(m)) = get_mut(cur, path) { + for (k, v) in items { + m.insert(k.clone(), v.clone()); + } + } + }; + let remove_all = |cur: &mut Value, path: &[Seg], keys: &[String]| { + if let Some(Value::Object(m)) = get_mut(cur, path) { + for k in keys { + m.remove(k); + } + } + }; + insert_all(cur, path, &items); + if ok(cur) { + return; + } + remove_all(cur, path, &keys); + if items.len() == 1 { + let (k, v) = items.into_iter().next().expect("ein Eintrag"); + let container = v.is_object() || v.is_array(); + if let Some(Value::Object(m)) = get_mut(cur, path) { + m.insert(k.clone(), v); + } + path.push(Seg::Key(k.clone())); + let fixed = container && rebuild(cur, path, ok, dropped); + if !fixed { + dropped.push(path_text(path)); + } + path.pop(); + if !fixed { + if let Some(Value::Object(m)) = get_mut(cur, path) { + m.remove(&k); + } + } + return; + } + let mut items = items; + let second = items.split_off(items.len() / 2); + add_keys(cur, path, items, ok, dropped); + add_keys(cur, path, second, ok, dropped); +} + +/// Hängt `items` (in Hälften, Reihenfolge bleibt) an die Liste an `path`, solange `ok` gilt. +fn add_items(cur: &mut Value, path: &mut Vec, items: Vec, ok: &dyn Fn(&Value) -> bool, dropped: &mut Vec) { + if items.is_empty() { + return; + } + let len = |cur: &mut Value, path: &[Seg]| match get_mut(cur, path) { + Some(Value::Array(a)) => a.len(), + _ => 0, + }; + let base = len(cur, path); + if let Some(Value::Array(a)) = get_mut(cur, path) { + a.extend(items.iter().cloned()); + } + if ok(cur) { + return; + } + if let Some(Value::Array(a)) = get_mut(cur, path) { + a.truncate(base); + } + if items.len() == 1 { + let v = items.into_iter().next().expect("ein Eintrag"); + let container = v.is_object() || v.is_array(); + if let Some(Value::Array(a)) = get_mut(cur, path) { + a.push(v); + } + path.push(Seg::Index(base)); + let fixed = container && rebuild(cur, path, ok, dropped); + if !fixed { + dropped.push(path_text(path)); + } + path.pop(); + if !fixed { + if let Some(Value::Array(a)) = get_mut(cur, path) { + a.truncate(base); + } + } + return; + } + let mut items = items; + let second = items.split_off(items.len() / 2); + add_items(cur, path, items, ok, dropped); + add_items(cur, path, second, ok, dropped); +} + +/// Setzt das Feld `key` der typisierten Sicht tolerant (s. Modulkopf). Liefert die verworfenen +/// Pfade (leer, wenn alles passte). Scheitert nie: notfalls gilt die Vorgabe des Felds. +pub fn set_field_lenient(p: &mut Project, key: &str, v: Option<&Value>) -> Vec { + if p.set_field(key, v).is_ok() { + return Vec::new(); + } + let mut dropped = Vec::new(); + let Some(v) = v else { return dropped }; + let probe = |val: &Value| Project::default().set_field(key, Some(val)).is_ok(); + let mut cur = v.clone(); + if let Value::Array(items) = &mut cur { + // Je Element prüfen (Probe mit einer Ein-Element-Liste), kaputte reparieren oder weglassen. + let mut out = Vec::with_capacity(items.len()); + for (i, item) in std::mem::take(items).into_iter().enumerate() { + let mut one = Value::Array(vec![item]); + let mut d = Vec::new(); + let fine = repair(&mut one, &probe, &mut d); + let kept = match one { + Value::Array(mut a) if fine && a.len() == 1 => a.pop(), + _ => None, + }; + dropped.extend(d.into_iter().map(|s| format!("{key}[{i}]{}", s.strip_prefix("[0]").unwrap_or(&s)))); + match kept { + Some(x) => out.push(x), + None => dropped.push(format!("{key}[{i}]")), + } + } + cur = Value::Array(out); + } else { + let mut d = Vec::new(); + if !repair(&mut cur, &probe, &mut d) { + dropped.push(key.to_string()); + let _ = p.set_field(key, None); + return dropped; + } + dropped.extend(d.into_iter().map(|s| if s.is_empty() { key.to_string() } else { format!("{key}.{s}") })); + } + if p.set_field(key, Some(&cur)).is_err() { + dropped.push(key.to_string()); + let _ = p.set_field(key, None); + } + dropped +} + +/// Typisierte Sicht der ganzen JSON-Wurzel, tolerant (s. Modulkopf): erst am Stück, im Fehlerfall +/// Feld für Feld. Liefert die verworfenen Pfade. +pub fn project_lenient(root: &Map) -> (Project, Vec) { + let mut p = Project::default(); + let mut dropped = Vec::new(); + for (k, v) in root { + dropped.extend(set_field_lenient(&mut p, k, Some(v).filter(|v| !v.is_null()))); + } + (p, dropped) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde::Deserialize; + use serde_json::json; + + fn root(v: Value) -> Map { + match v { + Value::Object(m) => m, + _ => unreachable!(), + } + } + + #[test] + fn null_statt_zahl_faellt_auf_vorgabe() { + let r = root(json!({ + "id": "p", "name": "x", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "drawingLevels": [], "layers": [], "drawings2d": [], + "walls": [ + {"id": "w1", "type": "wall", "floorId": "eg", "categoryCode": "20", "start": {"x": null, "y": 2}, "end": {"x": 3, "y": 2}, "wallTypeId": "t", "height": null}, + {"id": "w2", "type": "wall", "floorId": "eg", "categoryCode": "20", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}, "wallTypeId": "t", "height": 2.5} + ] + })); + assert!(Project::deserialize(&Value::Object(r.clone())).is_err(), "Vorbedingung: streng scheitert es"); + let (p, dropped) = project_lenient(&r); + assert_eq!(p.walls.len(), 2); + assert_eq!(p.walls[0].start.y, 2.0, "der Rest des Punkts bleibt"); + assert_eq!(p.walls[0].start.x, 0.0); + assert_eq!(p.walls[0].height, 0.0); + assert_eq!(p.walls[0].end.x, 3.0); + assert_eq!(p.walls[1].height, 2.5); + assert!(dropped.contains(&"walls[0].start.x".to_string()) && dropped.contains(&"walls[0].height".to_string()), "{dropped:?}"); + } + + #[test] + fn falsche_typen_und_kaputte_listen() { + let r = root(json!({ + "id": "p", "lineStyles": "keine Liste", "walls": [ + {"id": "w1", "start": "hier", "height": "hoch"}, + 7, + {"id": "w3", "end": {"x": 1, "y": 1}} + ], + "ceilings": [{"id": "c1", "outline": [{"x": 0, "y": 0}, null, {"x": 1, "y": "a"}, {"x": 1, "y": 1}]}], + "siteRules": {"parcel": [{"x": 0, "y": 0}], "maxHeight": null} + })); + let (p, dropped) = project_lenient(&r); + assert!(p.line_styles.is_empty()); + assert_eq!(p.walls.iter().map(|w| w.id.as_str()).collect::>(), ["w1", "w3"], "nicht lesbares Element entfällt"); + assert_eq!(p.walls[1].end.x, 1.0); + let c = &p.ceilings.as_ref().unwrap()[0]; + assert_eq!(c.outline.len(), 3, "kaputter Punkt entfällt, halber Punkt mit Vorgabe: {:?}", c.outline); + assert_eq!((c.outline[1].x, c.outline[1].y), (1.0, 0.0)); + assert!(p.site_rules.is_some()); + assert!(dropped.iter().any(|d| d == "walls[1]"), "{dropped:?}"); + } + + #[test] + fn passendes_projekt_unveraendert() { + let r = root(json!({"id": "p", "walls": [{"id": "w", "height": 3}]})); + let (p, dropped) = project_lenient(&r); + assert!(dropped.is_empty()); + assert_eq!(p, Project::deserialize(&Value::Object(r)).unwrap()); + } +} diff --git a/src-tauri/core/src/model/mod.rs b/src-tauri/core/src/model/mod.rs index 946b4745..3c97be6f 100644 --- a/src-tauri/core/src/model/mod.rs +++ b/src-tauri/core/src/model/mod.rs @@ -7,6 +7,7 @@ pub mod generated; pub mod helpers; pub mod items; +pub mod lenient; pub mod manual; #[cfg(test)] pub(crate) mod ts_export; diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index 2cb44b13..ec235a4d 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -433,19 +433,19 @@ fn compute_joins_by_floor(p: &Project) -> Result, Stri let mut jw: Vec = Vec::with_capacity(walls.len()); let mut finite = true; for w in walls { - let layers = p.wall_type(w).map(|wt| { - wt.layers + // Hängende Wandtypen/Bauteile (Datei/Import) verschneiden mit den Rückfall-Werten. + let layers = Some( + p.wall_type_or_fallback(w) + .layers .iter() .map(|l| { - let comp = p.component(&l.component_id); - let idx = comp.map(|c| { - let n = comp_index.len() as u32; - *comp_index.entry(c.id.as_str()).or_insert(n) - }); - JoinLayer { thickness: l.thickness, component: idx, priority: comp.map_or(f64::NAN, |c| c.join_priority) } + let comp = p.component_or_fallback(&l.component_id); + let n = comp_index.len() as u32; + let idx = *comp_index.entry(comp.id.as_str()).or_insert(n); + JoinLayer { thickness: l.thickness, component: Some(idx), priority: comp.join_priority } }) - .collect::>() - }); + .collect::>(), + ); let reference = wall_reference(w); finite &= [w.start.x, w.start.y, w.end.x, w.end.y].iter().all(|v| v.is_finite()) && !matches!(reference, Reference::Offset(v) if !v.is_finite()) @@ -464,11 +464,11 @@ fn compute_joins_by_floor(p: &Project) -> Result, Stri merged.insert(w.id.clone(), c); } } - Err(joins::JoinError::UnknownWallType(i)) => return Err(format!("Unbekannter Wandtyp: {}", walls[i].wall_type_id)), - Err(joins::JoinError::UnknownComponent(i)) => { - let bad = walls[i]; - let missing = p.wall_type(bad).and_then(|t| t.layers.iter().find(|l| p.component(&l.component_id).is_none())).map(|l| l.component_id.clone()).unwrap_or_default(); - return Err(format!("Unbekanntes Bauteil-Material: {missing}")); + // Mit den Rückfällen oben nicht mehr erwartet: dann eben ohne Verschneidung. + Err(_) => { + for w in walls { + merged.insert(w.id.clone(), WallCuts::default()); + } } } } @@ -1145,7 +1145,8 @@ fn roof_color(p: &Project, override_color: Option, component_id: &str) -> R if component_id.is_empty() { return Ok(ROOF_RGB); } - p.component(component_id).map(|c| hex_to_rgb(&c.color, ROOF_RGB)).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {component_id}")) + // Hängendes Bauteil (Datei/Import): Dach-Vorgabefarbe. + Ok(p.component(component_id).map_or(ROOF_RGB, |c| hex_to_rgb(&c.color, ROOF_RGB))) } /// Dächer als geschlossene, geschichtete Dreiecks-Meshes (`emitRoofs`). @@ -1444,7 +1445,7 @@ pub fn pick_geometry(p: &Project) -> Result { let Some(wall) = p.walls.iter().find(|w| w.id == o.host_wall_id) else { continue }; let wr = wall_ref(p, wall); let Some((jamb_start, jamb_end)) = opening_geom::opening_jambs(&wr, o.position, o.width) else { continue }; - let thickness = p.wall_type(wall).map(|t| Project::type_thickness(&t.layers)).ok_or_else(|| format!("Unbekannter Wandtyp: {}", wall.wall_type_id))?; + let thickness = Project::type_thickness(&p.wall_type_or_fallback(wall).layers); let (zb, zt) = p.wall_vertical_extent(wall); let o_bottom = zb + o.sill_height.max(0.0); let o_top = zt.min(o_bottom + o.height); diff --git a/src-tauri/core/src/plan/domains.rs b/src-tauri/core/src/plan/domains.rs index e762416b..737b6e58 100644 --- a/src-tauri/core/src/plan/domains.rs +++ b/src-tauri/core/src/plan/domains.rs @@ -215,18 +215,15 @@ fn pv(p: [f64; 2]) -> Vec2 { Vec2 { x: p[0], y: p[1] } } -/// `getComponent` (wirft in TS). +/// `getComponent`; hängender Verweis (Datei/Import) → neutrales Rückfall-Bauteil statt Abbruch. fn component<'a>(p: &'a Project, id: &str) -> Result<&'a Component, String> { - p.component(id).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {id}")) + Ok(p.component_or_fallback(id)) } -/// `resolveHatch` mit der Fehlermeldung von TS (`getHatch`/`getLineStyle` werfen). -pub(super) fn resolve_hatch_or_err(p: &Project, hatch_id: &str, wall_angle_deg: Option, fg: Option<&str>) -> Result { - let h = p.hatch(hatch_id).ok_or_else(|| format!("Unbekannte Schraffur: {hatch_id}"))?; - if let Some(ls) = h.line_style_id.as_deref().filter(|s| !s.is_empty()) { - p.line_style(ls).ok_or_else(|| format!("Unbekannter Linienstil: {ls}"))?; - } - resolve_hatch(p, hatch_id, wall_angle_deg, fg, None).ok_or_else(|| format!("Unbekannte Schraffur: {hatch_id}")) +/// `resolveHatch`; hängende Schraffur (Datei/Import) → ohne Muster statt Abbruch (ein hängender +/// Linienstil der Schraffur fällt in `resolve_hatch` auf die Vorgabe-Strichstärke zurück). +pub(super) fn resolve_hatch_or_none(p: &Project, hatch_id: &str, wall_angle_deg: Option, fg: Option<&str>) -> HatchRender { + resolve_hatch(p, hatch_id, wall_angle_deg, fg, None).unwrap_or_else(no_hatch) } /// Footprints der gezeichneten Wände dieses Geschosses (`buildWallFootprints`). @@ -251,7 +248,8 @@ fn ceiling_layers<'a>(p: &'a Project, c: &Ceiling) -> Result<&'a [Layer], String return Ok(&ct.layers); } } - p.wall_types.iter().find(|t| t.id == c.wall_type_id).map(|t| t.layers.as_slice()).ok_or_else(|| format!("Unbekannter Deckentyp: {}", c.ceiling_type_id.as_deref().unwrap_or(&c.wall_type_id))) + // Hängender Typ (Datei/Import): Rückfall-Schicht statt Abbruch. + Ok(p.wall_types.iter().find(|t| t.id == c.wall_type_id).map_or(Project::fallback_layers(), |t| t.layers.as_slice())) } /// Typname einer Decke für `object_name` (Maps in TS: letzter Eintrag je id gewinnt). @@ -290,7 +288,7 @@ fn ceilings(c: &Ctx, out: &mut Vec, bounds: &mut Bounds) -> Result<() let stroke = color.unwrap_or(POCHE_STROKE); let view_hatch_id = resolve_hatch_id(ce.hatch_id.as_deref(), ce.hatch_source, category, comp.and_then(|k| k.view_hatch_id.as_deref())); let hatch = match (c.a.detail != Detail::Grob, comp, view_hatch_id.filter(|s| !s.is_empty())) { - (true, Some(k), Some(id)) => resolve_hatch_or_err(p, id, None, resolve_foreground(k, ce.foreground.as_deref(), category, ce.foreground_source))?, + (true, Some(k), Some(id)) => resolve_hatch_or_none(p, id, None, resolve_foreground(k, ce.foreground.as_deref(), category, ce.foreground_source)), _ => no_hatch(), }; let fill = match comp { diff --git a/src-tauri/core/src/plan/drawings.rs b/src-tauri/core/src/plan/drawings.rs index b20a8b23..6c227339 100644 --- a/src-tauri/core/src/plan/drawings.rs +++ b/src-tauri/core/src/plan/drawings.rs @@ -8,7 +8,7 @@ //! Ein Block wird über `scale_geom` (Skalierung, Drehung, Verschiebung) rekursiv ausgegeben. //! Texte bleiben Daten (`drawingText`); das Text-Layout macht der Verbraucher. -use super::domains::{resolve_hatch_or_err, Bounds, Ctx}; +use super::domains::{Bounds, Ctx}; use super::overrides::Actions; use super::prim::{HatchRender, Primitive}; use super::style::*; @@ -585,10 +585,8 @@ fn emit_inner(c: &Ctx, d: &Drawing2D, attrs: Attrs, geom: &Drawing2DGeom, greyed // Gefüllte Fläche einer geschlossenen Form (Vollton-Füllung und/oder Schraffur), vor den Strichen. let fill_poly = |em: &mut Em, pts: Vec| -> Result<(), String> { let hatch = match hatch_id.filter(|s| !s.is_empty()) { - Some(h) => { - resolve_hatch_or_err(p, h, None, foreground)?; - resolve_hatch(p, h, None, foreground, Some((d.hatch_angle_deg, d.hatch_scale, d.hatch_origin))).ok_or_else(|| format!("Unbekannte Schraffur: {h}"))? - } + // Hängende Schraffur (Datei/Import): Fläche ohne Muster statt Abbruch. + Some(h) => resolve_hatch(p, h, None, foreground, Some((d.hatch_angle_deg, d.hatch_scale, d.hatch_origin))).unwrap_or_else(no_hatch), None => no_hatch(), }; let pr = polygon(pts, fill_color, "none", 0.0, hatch, em.greyed, Some(em.id)); diff --git a/src-tauri/core/src/plan/elevation.rs b/src-tauri/core/src/plan/elevation.rs index 705fe07a..526274d6 100644 --- a/src-tauri/core/src/plan/elevation.rs +++ b/src-tauri/core/src/plan/elevation.rs @@ -150,7 +150,8 @@ fn collect_roof_faces(p: &Project, frame: &[f64; 9]) -> Result, String let fill = match roof.color.as_deref().filter(|c| !c.is_empty()) { Some(c) => hex_to_rgb(c, ROOF_RGB_FALLBACK), None => match outer.filter(|l| !l.component_id.is_empty()) { - Some(l) => hex_to_rgb(&p.component(&l.component_id).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {}", l.component_id))?.color, ROOF_RGB_FALLBACK), + // Hängendes Bauteil (Datei/Import): Dach-Vorgabefarbe. + Some(l) => p.component(&l.component_id).map_or(ROOF_RGB_FALLBACK, |c| hex_to_rgb(&c.color, ROOF_RGB_FALLBACK)), None => ROOF_RGB_FALLBACK, }, }; diff --git a/src-tauri/core/src/plan/section.rs b/src-tauri/core/src/plan/section.rs index c47a819e..4d702e5c 100644 --- a/src-tauri/core/src/plan/section.rs +++ b/src-tauri/core/src/plan/section.rs @@ -496,10 +496,6 @@ fn rect_of_band(c: &Cut) -> Option<[f64; 4]> { (c.pts.len() >= 3).then(|| bbox(&c.pts)) } -fn missing(what: &str, id: &str) -> String { - format!("{what}: {id}") -} - /// Bauteil-Stil einer Schicht (Füllung, Schraffur) mit dem Override des Elements (`split*Layers`). #[allow(clippy::too_many_arguments)] fn layer_style( @@ -515,7 +511,8 @@ fn layer_style( angle: f64, ) -> Result<(String, HatchRender), String> { let hid = resolve_hatch_id(hatch_id, hatch_source, category, Some(&comp.hatch_id)).unwrap_or(&comp.hatch_id); - let hatch = resolve_hatch(p, hid, Some(angle), resolve_foreground(comp, fg, category, fg_source), None).ok_or_else(|| missing("Unbekannte Schraffur", hid))?; + // Hängende Schraffur (Datei/Import): ohne Muster statt Abbruch. + let hatch = resolve_hatch(p, hid, Some(angle), resolve_foreground(comp, fg, category, fg_source), None).unwrap_or_else(no_hatch); let bg = resolve_background(comp, bg, category, bg_source); let fill = bg.map(String::from).unwrap_or_else(|| poche_fill(hatch.pattern).to_string()); Ok((fill, hatch)) @@ -525,7 +522,7 @@ fn layer_style( /// Jede Schicht ist im Schnitt-Modell eine eigene Platte; ihr Band trägt so genau ihr Bauteil. fn style_slab_layer(cp: &mut Cut, p: &Project, layer: &Layer, owner: &Ceiling) -> Result<(), String> { let category = p.layer_category(&owner.category_code); - let comp = p.component(&layer.component_id).ok_or_else(|| missing("Unbekanntes Bauteil-Material", &layer.component_id))?; + let comp = p.component_or_fallback(&layer.component_id); let (fill, hatch) = layer_style(p, comp, owner.hatch_id.as_deref(), owner.hatch_source, owner.foreground.as_deref(), owner.foreground_source, owner.background.as_deref(), owner.background_source, category, SECTION_SLAB_AXIS_ANGLE_DEG)?; cp.fill = Some(fill); cp.hatch = Some(hatch); @@ -561,7 +558,7 @@ fn split_wall_layers(cp: &Cut, p: &Project, layers: &[Layer], owner: &Wall, u_wo let mut out = Vec::with_capacity(layers.len()); let mut acc = 0.0; for layer in ordered { - let comp = p.component(&layer.component_id).ok_or_else(|| missing("Unbekanntes Bauteil-Material", &layer.component_id))?; + let comp = p.component_or_fallback(&layer.component_id); let (fill, hatch) = layer_style(p, comp, owner.hatch_id.as_deref(), owner.hatch_source, owner.foreground.as_deref(), owner.foreground_source, owner.background.as_deref(), owner.background_source, category, SECTION_WALL_AXIS_ANGLE_DEG)?; let u_left = u_min + acc * scale; acc += layer.thickness; @@ -599,7 +596,7 @@ fn attach_cut_styles(cuts: Vec, p: &Project, plane: &Plane, walls: &[Option cp.source_id = owner.map(|o| o.id.clone()); cp.category = owner.map(|o| o.category_code.clone()); if let Some(o) = owner { - let wt = p.wall_type(o).ok_or_else(|| missing("Unbekannter Wandtyp", &o.wall_type_id))?; + let wt = p.wall_type_or_fallback(o); if wt.layers.len() > 1 { bands.extend(split_wall_layers(&cp, p, &wt.layers, o, u_world)?); continue; @@ -618,7 +615,7 @@ fn attach_cut_styles(cuts: Vec, p: &Project, plane: &Plane, walls: &[Option SlabOwner::Ceiling(o, layer) => { cp.source_id = Some(o.id.clone()); cp.category = Some(o.category_code.clone()); - let layers = ceiling_layers(p, o).ok_or_else(|| missing("Unbekannter Deckentyp", o.ceiling_type_id.as_deref().unwrap_or(&o.wall_type_id)))?; + let layers = ceiling_layers(p, o).unwrap_or(Project::fallback_layers()); if layers.len() > 1 { // Schicht-Platte: Stil genau dieser Schicht; ohne Schicht (Dicke 0) ohne Stil. if let Some(l) = layer.and_then(|i| layers.get(i)) { @@ -1371,8 +1368,7 @@ fn cross_section(p: &Project, wall: &Wall, o: &Opening, p0: (f64, f64), u: (f64, let n0 = rel.0 * n.0 + rel.1 * n.1; let a0 = rel.0 * a.0 + rel.1 * a.1; let ua = u.0 * a.0 + u.1 * a.1; - let wt = p.wall_type(wall).ok_or_else(|| missing("Unbekannter Wandtyp", &wall.wall_type_id))?; - let total = sum_thickness(&wt.layers); + let total = sum_thickness(&p.wall_type_or_fallback(wall).layers); let ref_off = crate::joins::reference_offset(model3d::wall_reference(wall), total); let along = a0 + ((ref_off - n0) / un) * ua; if along < from + 1e-4 || along > to - 1e-4 { @@ -1414,7 +1410,7 @@ fn window_cut(p: &Project, wall: &Wall, o: &Opening, c: &CrossSection) -> Result let mut f_max = f_min + DEFAULT_FRAME_DEPTH; let mut glass: Vec = vec![(f_min + f_max) / 2.0]; // `windowSymbol(project, wall, o, 1, spec, "mittel")`. - let total = sum_thickness(&p.wall_type(wall).ok_or_else(|| missing("Unbekannter Wandtyp", &wall.wall_type_id))?.layers); + let total = sum_thickness(&p.wall_type_or_fallback(wall).layers); let ref_off = crate::joins::reference_offset(model3d::wall_reference(wall), total); let spec = wt.map(|t| crate::opening_geom::WindowSpec { sashes: sashes_of_window_type(t), diff --git a/src-tauri/core/src/plan/style.rs b/src-tauri/core/src/plan/style.rs index 80176473..03b9481d 100644 --- a/src-tauri/core/src/plan/style.rs +++ b/src-tauri/core/src/plan/style.rs @@ -84,13 +84,11 @@ pub fn poche_fill(p: HatchPattern) -> &'static str { } } -/// `resolveHatch`: `None`, wenn Schraffur oder ihr Linienstil fehlen (TS wirft dort — Aufrufer fängt). +/// `resolveHatch`: `None`, wenn die Schraffur fehlt. Ein hängender Linienstil der Schraffur +/// (Datei/Import) zählt wie keiner (Vorgabe-Strichstärke 0.13, durchgezogen). pub fn resolve_hatch(p: &Project, hatch_id: &str, wall_angle_deg: Option, foreground: Option<&str>, placement: Option<(Option, Option, Option)>) -> Option { let h = p.hatch(hatch_id)?; - let ls = match h.line_style_id.as_deref().filter(|s| !s.is_empty()) { - Some(id) => Some(p.line_style(id)?), - None => None, - }; + let ls = h.line_style_id.as_deref().filter(|s| !s.is_empty()).and_then(|id| p.line_style(id)); let (p_angle, p_scale, p_origin) = placement.unwrap_or((None, None, None)); let base_angle = p_angle.unwrap_or(h.angle); let angle = match wall_angle_deg { diff --git a/src-tauri/core/src/plan/walls.rs b/src-tauri/core/src/plan/walls.rs index 87c7d07f..19652f3b 100644 --- a/src-tauri/core/src/plan/walls.rs +++ b/src-tauri/core/src/plan/walls.rs @@ -34,8 +34,9 @@ pub fn opening_label(o: &Opening) -> String { format!("{} {}×{}", if o.kind == ElementKind::Door { "Tür" } else { "Fenster" }, to_fixed(o.width * 100.0, 0), to_fixed(o.height * 100.0, 0)) } +/// Wandtyp; hängender Verweis (Datei/Import) → Rückfall-Typ, nie ein Fehler. fn wall_type<'a>(p: &'a Project, w: &Wall) -> Result<&'a WallType, String> { - p.wall_type(w).ok_or_else(|| format!("Unbekannter Wandtyp: {}", w.wall_type_id)) + Ok(p.wall_type_or_fallback(w)) } /// Verschneidung der gezeichneten Wände (`computeJoins` in TS, gleicher Puffer). Fehler wie die @@ -52,33 +53,18 @@ fn plan_joins(p: &Project, walls: &[EffWall]) -> Result, String> { (None, Some(WallReferenceLine::Right)) => buf.extend([2.0, 0.0]), _ => buf.extend([0.0, 0.0]), } - let Some(wt) = p.wall_type(w) else { - buf.extend([0.0, 0.0]); - continue; - }; + // Hängende Wandtypen/Bauteile (Datei/Import) verschneiden mit den Rückfall-Werten. + let wt = p.wall_type_or_fallback(w); buf.extend([1.0, wt.layers.len() as f64]); for l in &wt.layers { - let comp = p.component(&l.component_id); - let idx = match comp { - Some(c) => { - let n = comp_index.len(); - *comp_index.entry(c.id.as_str()).or_insert(n) as f64 - } - None => -1.0, - }; - buf.extend([l.thickness, idx, comp.map_or(f64::NAN, |c| c.join_priority)]); + let comp = p.component_or_fallback(&l.component_id); + let n = comp_index.len(); + let idx = *comp_index.entry(comp.id.as_str()).or_insert(n) as f64; + buf.extend([l.thickness, idx, comp.join_priority]); } } let out = joins::compute_joins_flat(&buf); - if out.first() == Some(&1.0) { - let bad = out.get(1).and_then(|i| walls.get(*i as usize)); - if let Some(e) = bad { - for l in &wall_type(p, e.w)?.layers { - p.component(&l.component_id).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {}", l.component_id))?; - } - } - return Err("computeJoins: unbekannter Wandtyp oder Bauteil".into()); - } + // Fehler der Verschneidung (mit den Rückfällen oben nicht mehr erwartet): Wände ohne Verschneidung. if out.first() != Some(&0.0) { return Ok(vec![WallCuts::default(); walls.len()]); } @@ -199,9 +185,9 @@ fn wall_poche(c: &Ctx, out: &mut Vec, e: &EffWall, gaps: &[(f64, f64) return Ok(s.clone()); } let layer = wt.layers.get(li).ok_or("Schicht fehlt")?; - let comp = p.component(&layer.component_id).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {}", layer.component_id))?; + let comp = p.component_or_fallback(&layer.component_id); let hid = resolve_hatch_id(w.hatch_id.as_deref(), w.hatch_source, category, Some(&comp.hatch_id)).unwrap_or(&comp.hatch_id); - let hatch = super::domains::resolve_hatch_or_err(p, hid, Some(angle), resolve_foreground(comp, w.foreground.as_deref(), category, w.foreground_source))?; + let hatch = super::domains::resolve_hatch_or_none(p, hid, Some(angle), resolve_foreground(comp, w.foreground.as_deref(), category, w.foreground_source)); let bg = resolve_background(comp, w.background.as_deref(), category, w.background_source); let fill = bg.unwrap_or(if hatch.pattern == HatchPattern::Solid { HATCH_INK } else { HATCH_PAPER }).to_string(); styles.insert(li, (hatch.clone(), fill.clone())); diff --git a/src-tauri/core/src/project_refs.rs b/src-tauri/core/src/project_refs.rs new file mode 100644 index 00000000..8737a216 --- /dev/null +++ b/src-tauri/core/src/project_refs.rs @@ -0,0 +1,272 @@ +//! Warnungen zu einem Projekt, das trotzdem geladen und gerechnet werden kann (`dossier-cli validate`, +//! TS `projectWarnings`): hängende Verweise (Wandtyp, Bauteil, Geschoss, Schraffur, Linienstil, Stift, +//! Gruppe, Layout …), Gruppen/Ordner, die sich selbst enthalten, und Werte, die nicht zum Modell passen +//! (`model::lenient` setzt dort die Vorgabe ein). Die Ableitungen fallen in all diesen Fällen auf +//! Vorgaben zurück — die Warnung sagt, wo. + +use crate::model::{lenient, Drawing2DGeom, Project}; +use serde_json::{Map, Value}; +use std::collections::{HashMap, HashSet}; + +/// Warnungen (deutsch, je eine Zeile) für die JSON-Wurzel eines Projekts. +pub fn project_warnings(root: &Map) -> Vec { + let (p, dropped) = lenient::project_lenient(root); + let mut out: Vec = dropped.into_iter().map(|d| format!("Wert passt nicht zum Modell, Vorgabe verwendet: {d}")).collect(); + out.extend(dangling_refs(&p)); + out +} + +fn ids<'a, T: 'a>(items: impl IntoIterator, id: impl Fn(&'a T) -> &'a str) -> HashSet<&'a str> { + items.into_iter().map(id).collect() +} + +/// Hängende Verweise und Zyklen im typisierten Projekt. +pub fn dangling_refs(p: &Project) -> Vec { + let mut out = Vec::new(); + let levels = ids(&p.drawing_levels, |l| l.id.as_str()); + let wall_types = ids(&p.wall_types, |t| t.id.as_str()); + let ceiling_types = ids(p.ceiling_types.as_deref().unwrap_or(&[]), |t| t.id.as_str()); + let roof_types = ids(p.roof_types.as_deref().unwrap_or(&[]), |t| t.id.as_str()); + let door_types = ids(p.door_types.as_deref().unwrap_or(&[]), |t| t.id.as_str()); + let window_types = ids(p.window_types.as_deref().unwrap_or(&[]), |t| t.id.as_str()); + let stair_types = ids(p.stair_types.as_deref().unwrap_or(&[]), |t| t.id.as_str()); + let components = ids(&p.components, |c| c.id.as_str()); + let hatches = ids(&p.hatches, |h| h.id.as_str()); + let line_styles = ids(&p.line_styles, |l| l.id.as_str()); + let pens = ids(p.pens.as_deref().unwrap_or(&[]), |x| x.id.as_str()); + let block_defs = ids(p.block_defs.as_deref().unwrap_or(&[]), |b| b.id.as_str()); + let walls = ids(&p.walls, |w| w.id.as_str()); + let snapshots = ids(p.view_snapshots.as_deref().unwrap_or(&[]), |s| s.id.as_str()); + let masters = ids(p.master_layouts.as_deref().unwrap_or(&[]), |m| m.id.as_str()); + let layout_folders = ids(p.layout_folders.as_deref().unwrap_or(&[]), |f| f.id.as_str()); + let snapshot_folders = ids(p.view_snapshot_folders.as_deref().unwrap_or(&[]), |f| f.id.as_str()); + + fn miss(out: &mut Vec, what: &str, owner: &str, kind: &str, id: &str, known: &HashSet<&str>) { + if !id.is_empty() && !known.contains(id) { + out.push(format!("{what} „{owner}\": {kind} „{id}\" fehlt.")); + } + } + fn check_pens(out: &mut Vec, pens: &HashSet<&str>, what: &str, owner: &str, ps: [&Option; 3]) { + for x in ps { + miss(out, what, owner, "Stift", x.as_deref().unwrap_or(""), pens); + } + } + let none: Option = None; + + for w in &p.walls { + miss(&mut out, "Wand", &w.id, "Geschoss", &w.floor_id, &levels); + miss(&mut out, "Wand", &w.id, "Wandtyp", &w.wall_type_id, &wall_types); + miss(&mut out, "Wand", &w.id, "Schraffur", w.hatch_id.as_deref().unwrap_or(""), &hatches); + check_pens(&mut out, &pens, "Wand", &w.id, [&w.color_pen_id, &w.foreground_pen_id, &w.background_pen_id]); + } + for o in p.openings.as_deref().unwrap_or(&[]) { + miss(&mut out, "Öffnung", &o.id, "Wand", &o.host_wall_id, &walls); + let types = if door_types.contains(o.type_id.as_deref().unwrap_or("")) { &door_types } else { &window_types }; + miss(&mut out, "Öffnung", &o.id, "Typ", o.type_id.as_deref().unwrap_or(""), types); + check_pens(&mut out, &pens, "Öffnung", &o.id, [&o.color_pen_id, &none, &none]); + } + for c in p.ceilings.as_deref().unwrap_or(&[]) { + miss(&mut out, "Decke", &c.id, "Geschoss", &c.floor_id, &levels); + match c.ceiling_type_id.as_deref().filter(|s| !s.is_empty()) { + Some(t) if ceiling_types.contains(t) => {} + Some(t) if !c.wall_type_id.is_empty() && wall_types.contains(c.wall_type_id.as_str()) => { + out.push(format!("Decke „{}\": Deckentyp „{t}\" fehlt (Wandtyp „{}\" verwendet).", c.id, c.wall_type_id)) + } + Some(t) => out.push(format!("Decke „{}\": Deckentyp „{t}\" fehlt.", c.id)), + None => miss(&mut out, "Decke", &c.id, "Wandtyp", &c.wall_type_id, &wall_types), + } + miss(&mut out, "Decke", &c.id, "Schraffur", c.hatch_id.as_deref().unwrap_or(""), &hatches); + check_pens(&mut out, &pens, "Decke", &c.id, [&c.color_pen_id, &c.foreground_pen_id, &c.background_pen_id]); + } + for r in p.roofs.as_deref().unwrap_or(&[]) { + miss(&mut out, "Dach", &r.id, "Geschoss", &r.floor_id, &levels); + miss(&mut out, "Dach", &r.id, "Dachtyp", r.roof_type_id.as_deref().unwrap_or(""), &roof_types); + } + for s in p.stairs.as_deref().unwrap_or(&[]) { + miss(&mut out, "Treppe", &s.id, "Geschoss", &s.floor_id, &levels); + miss(&mut out, "Treppe", &s.id, "Treppentyp", s.type_id.as_deref().unwrap_or(""), &stair_types); + } + for c in p.columns.as_deref().unwrap_or(&[]) { + miss(&mut out, "Stütze", &c.id, "Geschoss", &c.floor_id, &levels); + miss(&mut out, "Stütze", &c.id, "Bauteil", c.component_id.as_deref().unwrap_or(""), &components); + miss(&mut out, "Stütze", &c.id, "Schraffur", c.hatch_id.as_deref().unwrap_or(""), &hatches); + } + for r in p.rooms.as_deref().unwrap_or(&[]) { + miss(&mut out, "Raum", &r.id, "Geschoss", &r.floor_id, &levels); + } + for d in &p.drawings2d { + miss(&mut out, "Zeichnung", &d.id, "Ebene", &d.level_id, &levels); + miss(&mut out, "Zeichnung", &d.id, "Linienstil", d.line_style_id.as_deref().unwrap_or(""), &line_styles); + miss(&mut out, "Zeichnung", &d.id, "Schraffur", d.hatch_id.as_deref().unwrap_or(""), &hatches); + check_pens(&mut out, &pens, "Zeichnung", &d.id, [&d.color_pen_id, &d.foreground_pen_id, &d.background_pen_id]); + if let Drawing2DGeom::Block { block_def_id, .. } = &d.geom { + miss(&mut out, "Zeichnung", &d.id, "Block", block_def_id, &block_defs); + } + } + for x in p.extruded_solids.as_deref().unwrap_or(&[]) { + miss(&mut out, "Körper", &x.id, "Ebene", &x.level_id, &levels); + } + let type_layers = p + .wall_types + .iter() + .map(|t| ("Wandtyp", &t.id, &t.layers)) + .chain(p.ceiling_types.as_deref().unwrap_or(&[]).iter().map(|t| ("Deckentyp", &t.id, &t.layers))) + .chain(p.roof_types.as_deref().unwrap_or(&[]).iter().map(|t| ("Dachtyp", &t.id, &t.layers))); + for (what, id, layers) in type_layers { + for l in layers { + miss(&mut out, what, id, "Bauteil", &l.component_id, &components); + miss(&mut out, what, id, "Linienstil", l.joint_line_style_id.as_deref().unwrap_or(""), &line_styles); + } + } + for c in &p.components { + miss(&mut out, "Bauteil", &c.id, "Schraffur", &c.hatch_id, &hatches); + miss(&mut out, "Bauteil", &c.id, "Schraffur", c.view_hatch_id.as_deref().unwrap_or(""), &hatches); + check_pens(&mut out, &pens, "Bauteil", &c.id, [&c.color_pen_id, &c.foreground_pen_id, &c.background_pen_id]); + } + for h in &p.hatches { + miss(&mut out, "Schraffur", &h.id, "Linienstil", h.line_style_id.as_deref().unwrap_or(""), &line_styles); + } + for c in p.flat_categories() { + check_pens(&mut out, &pens, "Kategorie", &c.code, [&c.color_pen_id, &none, &none]); + } + let pen_sets = ids(p.pen_sets.as_deref().unwrap_or(&[]), |s| s.id.as_str()); + miss(&mut out, "Projekt", &p.id, "Stiftsatz", p.active_pen_set_id.as_deref().unwrap_or(""), &pen_sets); + for l in p.layouts.as_deref().unwrap_or(&[]) { + miss(&mut out, "Layout", &l.id, "Master", l.master_id.as_deref().unwrap_or(""), &masters); + miss(&mut out, "Layout", &l.id, "Ordner", l.folder_id.as_deref().unwrap_or(""), &layout_folders); + for v in &l.viewports { + miss(&mut out, "Layout", &l.id, "Ausschnitt", &v.snapshot_id, &snapshots); + } + } + for m in p.master_layouts.as_deref().unwrap_or(&[]) { + miss(&mut out, "Master-Layout", &m.id, "Ordner", m.folder_id.as_deref().unwrap_or(""), &layout_folders); + } + for s in p.view_snapshots.as_deref().unwrap_or(&[]) { + miss(&mut out, "Ausschnitt", &s.id, "Geschoss", &s.active_level_id, &levels); + miss(&mut out, "Ausschnitt", &s.id, "Ordner", s.folder_id.as_deref().unwrap_or(""), &snapshot_folders); + } + + // Gruppen: Mitglieder und Zyklen. + let groups = p.groups.as_deref().unwrap_or(&[]); + let group_ids = ids(groups, |g| g.id.as_str()); + let members: [(&str, HashSet<&str>); 7] = [ + ("Zeichnung", ids(&p.drawings2d, |d| d.id.as_str())), + ("Decke", ids(p.ceilings.as_deref().unwrap_or(&[]), |x| x.id.as_str())), + ("Raum", ids(p.rooms.as_deref().unwrap_or(&[]), |x| x.id.as_str())), + ("Treppe", ids(p.stairs.as_deref().unwrap_or(&[]), |x| x.id.as_str())), + ("Stütze", ids(p.columns.as_deref().unwrap_or(&[]), |x| x.id.as_str())), + ("Dach", ids(p.roofs.as_deref().unwrap_or(&[]), |x| x.id.as_str())), + ("Öffnung", ids(p.openings.as_deref().unwrap_or(&[]), |x| x.id.as_str())), + ]; + for g in groups { + for w in &g.wall_ids { + miss(&mut out, "Gruppe", &g.id, "Wand", w, &walls); + } + let lists = [&g.drawing_ids, &g.ceiling_ids, &g.room_ids, &g.stair_ids, &g.column_ids, &g.roof_ids, &g.opening_ids]; + for (list, (kind, known)) in lists.into_iter().zip(&members) { + for id in list { + miss(&mut out, "Gruppe", &g.id, kind, id, known); + } + } + for id in &g.group_ids { + miss(&mut out, "Gruppe", &g.id, "Gruppe", id, &group_ids); + } + } + let children: HashMap<&str, Vec<&str>> = groups.iter().map(|g| (g.id.as_str(), g.group_ids.iter().map(String::as_str).collect())).collect(); + for g in groups { + if reaches(&children, &g.id, &g.id) { + out.push(format!("Gruppe „{}\" enthält sich selbst (über verschachtelte Gruppen).", g.id)); + } + } + // Ordner: Eltern-Ketten ohne Zyklus. + let folder_cycles = |what: &str, parents: HashMap<&str, &str>, out: &mut Vec| { + for &start in parents.keys() { + let mut seen = HashSet::new(); + let mut cur = start; + while let Some(&next) = parents.get(cur) { + if next == start { + out.push(format!("{what} „{start}\" ist sein eigener Vorfahre.")); + break; + } + if !seen.insert(next) { + break; + } + cur = next; + } + } + }; + let lf = p.layout_folders.as_deref().unwrap_or(&[]); + folder_cycles("Layout-Ordner", lf.iter().filter_map(|f| Some((f.id.as_str(), f.parent_id.as_deref()?))).collect(), &mut out); + let sf = p.view_snapshot_folders.as_deref().unwrap_or(&[]); + folder_cycles("Ausschnitt-Ordner", sf.iter().filter_map(|f| Some((f.id.as_str(), f.parent_id.as_deref()?))).collect(), &mut out); + out.sort(); + out.dedup(); + out +} + +/// Erreicht `from` über `children` (ohne sich selbst als Start zu zählen) den Knoten `target`? +fn reaches(children: &HashMap<&str, Vec<&str>>, from: &str, target: &str) -> bool { + let mut stack: Vec<&str> = children.get(from).cloned().unwrap_or_default(); + let mut seen: HashSet<&str> = HashSet::new(); + while let Some(n) = stack.pop() { + if n == target { + return true; + } + if seen.insert(n) { + stack.extend(children.get(n).into_iter().flatten().copied()); + } + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn root(v: Value) -> Map { + match v { + Value::Object(m) => m, + _ => unreachable!(), + } + } + + #[test] + fn haengende_verweise_und_zyklen() { + let r = root(json!({ + "id": "p", + "drawingLevels": [{"id": "eg", "kind": "floor"}], + "wallTypes": [{"id": "aw", "layers": [{"componentId": "beton", "thickness": 0.2}]}], + "components": [], + "walls": [{"id": "w1", "floorId": "eg", "wallTypeId": "nope"}, {"id": "w2", "floorId": "og", "wallTypeId": "aw", "height": null}], + "openings": [{"id": "o1", "hostWallId": "w9"}], + "groups": [ + {"id": "g1", "groupIds": ["g2"], "wallIds": ["w1"]}, + {"id": "g2", "groupIds": ["g1", "g3"]} + ], + "layoutFolders": [{"id": "a", "parentId": "b"}, {"id": "b", "parentId": "a"}, {"id": "c", "parentId": "c"}] + })); + let w = project_warnings(&r); + let has = |s: &str| w.iter().any(|x| x.contains(s)); + assert!(has("Wand „w1\": Wandtyp „nope\" fehlt."), "{w:#?}"); + assert!(has("Wand „w2\": Geschoss „og\" fehlt.")); + assert!(has("Wandtyp „aw\": Bauteil „beton\" fehlt.")); + assert!(has("Öffnung „o1\": Wand „w9\" fehlt.")); + assert!(has("Gruppe „g2\": Gruppe „g3\" fehlt.")); + assert!(has("Gruppe „g1\" enthält sich selbst")); + assert!(has("Layout-Ordner „a\" ist sein eigener Vorfahre.") && has("Layout-Ordner „c\"")); + assert!(has("Vorgabe verwendet: walls[1].height")); + } + + #[test] + fn stimmiges_projekt_ohne_warnung() { + let r = root(json!({ + "id": "p", + "drawingLevels": [{"id": "eg"}], + "wallTypes": [{"id": "aw", "layers": [{"componentId": "beton", "thickness": 0.2}]}], + "components": [{"id": "beton", "hatchId": ""}], + "walls": [{"id": "w1", "floorId": "eg", "wallTypeId": "aw"}] + })); + assert_eq!(project_warnings(&r), Vec::::new()); + } +} diff --git a/src-tauri/core/src/style.rs b/src-tauri/core/src/style.rs index 2a60c14c..ab574047 100644 --- a/src-tauri/core/src/style.rs +++ b/src-tauri/core/src/style.rs @@ -48,7 +48,7 @@ fn pattern_id(p: HatchPattern) -> f64 { } /// Aufgelöste Schraffur (Kern von `resolveHatch`): Muster, Massstab, Endwinkel, Musterlinien-Stärke. -/// `None`, wenn Schraffur oder ihr Linienstil fehlen (TS wirft dort). +/// `None`, wenn die Schraffur fehlt; ein hängender Linienstil zählt wie keiner (0.13). pub struct HatchCore { pub pattern: HatchPattern, pub scale: f64, @@ -58,10 +58,7 @@ pub struct HatchCore { pub fn resolve_hatch_core(p: &Project, hatch_id: &str, wall_angle_deg: Option) -> Option { let h = p.hatch(hatch_id)?; - let ls = match h.line_style_id.as_deref().filter(|s| !s.is_empty()) { - Some(id) => Some(p.line_style(id)?), - None => None, - }; + let ls = h.line_style_id.as_deref().filter(|s| !s.is_empty()).and_then(|id| p.line_style(id)); let base = h.angle; let angle = match wall_angle_deg { Some(w) if h.relative_to_wall == Some(true) => base - w, diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 45e7e646..3db3d61c 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -39,6 +39,7 @@ mod layout_model; mod parametric_walls; mod reorder; mod text_layout; +mod project_refs; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/project_refs.rs b/src-tauri/core/src/web/project_refs.rs new file mode 100644 index 00000000..3d19635e --- /dev/null +++ b/src-tauri/core/src/web/project_refs.rs @@ -0,0 +1,17 @@ +//! Bindung der Projekt-Warnungen (`crate::project_refs`) für die TS-Fassade `projectWarnings` +//! (`src/core/ops.ts`) und `dossier-cli validate`. Eingabe das Projekt als JSON, Ausgabe ein +//! JSON-Array der Warnungen; kaputte Eingaben ergeben eine Warnung, nie einen Panic. + +use serde_json::Value; +use wasm_bindgen::prelude::wasm_bindgen; + +/// Warnungen (hängende Verweise, Zyklen, nicht lesbare Werte) eines Projekts. +#[wasm_bindgen] +pub fn project_warnings(project_json: &str) -> String { + let out = match serde_json::from_str::(project_json) { + Ok(Value::Object(m)) => crate::project_refs::project_warnings(&m), + Ok(_) => vec!["kein JSON-Objekt".to_string()], + Err(e) => vec![e.to_string()], + }; + Value::from(out).to_string() +} diff --git a/src/cli/cli.test.ts b/src/cli/cli.test.ts index 2f525eb2..a4c69a0f 100644 --- a/src/cli/cli.test.ts +++ b/src/cli/cli.test.ts @@ -38,6 +38,20 @@ describe("dossier-cli", () => { expect(JSON.parse(readFileSync(out, "utf8")).formatVersion).toBeGreaterThanOrEqual(1); }); + it("validate meldet hängende Verweise als Warnung, Plan rechnet trotzdem", async () => { + const broken = join(dir, "haengend.obp"); + const p = { ...sampleProject, walls: sampleProject.walls.map((w, i) => (i === 0 ? { ...w, wallTypeId: "nope" } : w)) }; + writeFileSync(broken, serializeProject(p)); + const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + try { + expect(await run([broken, "validate"])).toBe(0); + expect(err.mock.calls.map((c) => String(c[0])).join("")).toContain(`Warnung: Wand „${sampleProject.walls[0].id}": Wandtyp „nope" fehlt.`); + } finally { + err.mockRestore(); + } + expect(await run([broken, "plan", "--out", join(dir, "haengend.svg")])).toBe(0); + }); + it("Plan als SVG", async () => { const out = join(dir, "eg.svg"); expect(await call("plan", "--out", out)).toBe(0); diff --git a/src/cli/main.ts b/src/cli/main.ts index ed5b6578..04337e41 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -110,6 +110,7 @@ import { setWasmBytesProvider, initCore, validateProject, + projectWarnings, sampleProject, } from "../core"; import type { CoreOp, Project } from "../core"; @@ -556,11 +557,14 @@ async function execute(project: Project, file: string, command: string, rest: st } case "validate": { const problems = validateProject(project); + // Hängende Verweise u. Ä.: das Projekt lässt sich rechnen (Vorgaben), aber es soll auffallen. + const warnings = projectWarnings(project); + if (warnings.length) process.stderr.write(warnings.map((w) => `Warnung: ${w}`).join("\n") + "\n"); if (problems.length) { process.stderr.write(problems.join("\n") + "\n"); return 1; } - process.stdout.write("ok\n"); + process.stdout.write(warnings.length ? `ok (${warnings.length} Warnung${warnings.length === 1 ? "" : "en"})\n` : "ok\n"); return 0; } case "migrate": diff --git a/src/cli/mcp.ts b/src/cli/mcp.ts index 12bc8b09..c3699643 100644 --- a/src/cli/mcp.ts +++ b/src/cli/mcp.ts @@ -16,6 +16,7 @@ import { serializeProject, validateOps, validateProject, + projectWarnings, } from "../core"; import type { CoreOp, Project } from "../core"; @@ -124,7 +125,8 @@ export async function callTool(file: string, name: string, args: Record 0); + const warnings = projectWarnings(project).map((w) => `Warnung: ${w}`); + return text([...problems, ...warnings].join("\n") || "ok", problems.length > 0); } default: return text(`unbekanntes Werkzeug: ${name}`, true); diff --git a/src/core/extra.ts b/src/core/extra.ts index 60c8a878..2a6ca181 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -20,6 +20,7 @@ export { planToSvgString } from "../export/planToSvgString"; export { setWasmBytesProvider } from "../engine/wasmSource"; export { initCore, coreReady } from "../engine/coreWasm"; export { applyOps, validateProject, validateOps } from "./ops"; +export { projectWarnings } from "./ops"; export type { CoreOp } from "./ops"; export type { Project, DrawingLevel } from "../model/types"; export { computeKennzahlen, checkRoomProgram, solidVolume } from "../analysis/kennzahlen"; diff --git a/src/core/ops.ts b/src/core/ops.ts index 90b4aad3..e3466b31 100644 --- a/src/core/ops.ts +++ b/src/core/ops.ts @@ -174,6 +174,16 @@ export function validateProject(p: Project): string[] { return problemsOf(core().project_validate(JSON.stringify(p, markNonFinite))); } +/** + * Warnungen zu einem Projekt, das trotzdem geladen und gerechnet wird (Kern `project_refs.rs`): + * hängende Verweise (Wandtyp, Bauteil, Geschoss, Schraffur, Linienstil, Stift, Gruppe, Layout …), + * Gruppen/Ordner, die sich selbst enthalten, und Werte, die nicht zum Modell passen. Die + * Ableitungen setzen dort Vorgaben ein; `dossier-cli validate` meldet die Liste. + */ +export function projectWarnings(p: Project): string[] { + return problemsOf(core().project_warnings(JSON.stringify(p))); +} + /** * Prüft angewendete Ops (nur was sie anfassen, billig genug für jeden Drag-Schritt): nicht * endliche Zahlen in neuen/ersetzten Elementen und `setField`-Zahlen, NEUE doppelte ids in den diff --git a/src/core/robustness.test.ts b/src/core/robustness.test.ts new file mode 100644 index 00000000..5733eba2 --- /dev/null +++ b/src/core/robustness.test.ts @@ -0,0 +1,365 @@ +// Robustheit des Kerns gegen kaputte Projekte: Dateien von der Platte und Importe können hängende +// Verweise (Wandtyp, Bauteil, Geschoss, Gruppe, Schraffur, Linienstil, Stift …), fehlende Felder, +// NaN, leere Polygone, doppelte ids und Zyklen (Gruppen/Ordner, die sich selbst enthalten) tragen. +// Keine Abfrage und keine Fassade darf daran werfen oder (in Rust) in Panik geraten — sie fallen auf +// Vorgaben zurück, wie der übrige tolerante Modell-Code. `validate` meldet die Verweise als Warnung. + +import { beforeAll, describe, expect, it } from "vitest"; +import type { Layout, Project } from "../model/types"; +import { sampleProject } from "../model/sampleProject"; +import { bigSampleProject } from "../plan/bigSampleProject.testing"; +import { randomProject, richProject, rng } from "../model/richProject.testing"; +import { + computeSection, + generateElevationPlan, + generatePlan, + generateSectionPlan, + generateVisibleLevelsPlan, + pickGeometry, + planSceneBin, + planToRenderScene, + projectToModel3d, + wallMaterialColorMaps, +} from "./index"; +import { + buildPlanDxf, + checkRoomProgram, + checkSiteRules, + compareRoomProgram, + computeAreaTable, + computeIvhb, + computeKennzahlen, + exportGlb, + exportIfcSpf, + exportObj, + exportScheduleCsv, + exportStl, + layoutRoomProgram, + parseProjectFile, + planToSvgString, + projectLatLon, + serializeProject, + shadowPolygons, + sunPosition, + validateProject, + buildingFootprint, + modelTop, + projectWarnings, +} from "./extra"; +import { loadFileioForTests } from "../engine/fileioWasm.testing"; +import { buildLayoutTree, buildMasterTree, folderPdfPages, resolveTitleBlock, visibleCodesFromSnapshot } from "../model/layoutModel"; + +type Mut = Record; // eslint-disable-line @typescript-eslint/no-explicit-any + +const clone = (p: Project): Mut => JSON.parse(JSON.stringify(p)) as Mut; +const list = (p: Mut, k: string): Mut[] => (Array.isArray(p[k]) ? (p[k] as Mut[]) : []); + +/** Alle Kategorie-Codes (verschachtelt), wie die CLI. */ +function allCodes(p: Project): Set { + const out = new Set(); + const walk = (ls: unknown): void => { + if (!Array.isArray(ls)) return; + for (const l of ls as Mut[]) { + if (l && typeof l.code === "string") out.add(l.code); + walk(l?.children); + } + }; + walk(p.layers); + return out; +} + +/** Verdorbene Fassungen eines Projekts: Name → Projekt. */ +function corruptions(base: Project, seed: number): [string, Project][] { + const r = rng(seed); + const out: [string, Project][] = []; + const add = (name: string, f: (p: Mut) => void) => { + const p = clone(base); + f(p); + out.push([name, p as unknown as Project]); + }; + const some = (a: T[]): T[] => a.filter((_, i) => i === 0 || r() < 0.5); + + add("Wandtyp hängt", (p) => some(list(p, "walls")).forEach((w) => (w.wallTypeId = "nope"))); + add("alle Wandtypen weg", (p) => (p.wallTypes = [])); + add("Bauteil hängt", (p) => { + for (const k of ["wallTypes", "ceilingTypes", "roofTypes"]) for (const t of list(p, k)) for (const l of t.layers ?? []) l.componentId = "nope"; + }); + add("Bauteile weg", (p) => (p.components = [])); + add("Schraffur/Linienstil hängt", (p) => { + for (const c of list(p, "components")) { + c.hatchId = "nope"; + c.cutHatchId = "nope"; + c.lineStyleId = "nope"; + } + const walk = (ls: Mut[]) => { + for (const l of ls) { + l.hatchId = "nope"; + l.lineStyleId = "nope"; + l.penId = "nope"; + walk(l.children ?? []); + } + }; + walk(list(p, "layers")); + for (const d of list(p, "drawings2d")) { + d.hatchId = "nope"; + d.lineStyleId = "nope"; + d.penId = "nope"; + d.fillPenId = "nope"; + } + p.hatches = []; + p.lineStyles = []; + }); + add("Stifte hängen", (p) => { + p.activePenSetId = "nope"; + p.penSets = [{ id: "ps", name: "x", pens: { nope: { color: "not-a-color", weight: NaN } } }]; + for (const w of list(p, "walls")) w.penId = "nope"; + }); + add("Geschoss hängt", (p) => { + for (const k of ["walls", "stairs", "columns", "ceilings", "rooms"]) for (const e of list(p, k)) e.floorId = "nope"; + for (const k of ["drawings2d", "extrudedSolids"]) for (const e of list(p, k)) e.levelId = "nope"; + for (const e of list(p, "roofs")) e.floorId = "nope"; + for (const w of list(p, "walls")) { + w.bottom = { mode: "floor", floorId: "nope", offset: 0 }; + w.top = { mode: "floor", floorId: "nope2" }; + } + }); + add("Öffnung ohne Wand", (p) => list(p, "openings").forEach((o) => (o.hostWallId = "nope"))); + add("Typen hängen", (p) => { + for (const o of list(p, "openings")) o.typeId = "nope"; + for (const s of list(p, "stairs")) s.typeId = "nope"; + for (const c of list(p, "ceilings")) { + c.ceilingTypeId = "nope"; + c.wallTypeId = "nope"; + } + for (const rf of list(p, "roofs")) rf.roofTypeId = "nope"; + for (const d of list(p, "drawings2d")) if (d.geom?.shape === "block") d.geom.blockDefId = "nope"; + for (const pw of list(p, "parametricWalls")) pw.defaultWallTypeId = "nope"; + }); + add("Gruppen hängen und enthalten sich", (p) => { + p.groups = [ + { id: "g1", name: "A", wallIds: ["nope"], drawingIds: ["nope"], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: ["g1", "g2", "nope"] }, + { id: "g2", name: "B", wallIds: [list(p, "walls")[0]?.id ?? "x"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: ["g1"] }, + ]; + }); + add("Ordner zyklisch", (p) => { + p.viewSnapshotFolders = [ + { id: "f1", name: "A", parentId: "f2" }, + { id: "f2", name: "B", parentId: "f1" }, + { id: "f3", name: "C", parentId: "f3" }, + ]; + p.layoutFolders = [ + { id: "lf1", name: "A", kind: "layout", parentId: "lf2" }, + { id: "lf2", name: "B", kind: "layout", parentId: "lf1" }, + { id: "lf3", name: "C", kind: "master", parentId: "lf3" }, + ]; + for (const l of list(p, "layouts")) l.folderId = "lf1"; + for (const m of list(p, "masterLayouts")) m.folderId = "lf3"; + for (const s of list(p, "viewSnapshots")) s.folderId = "f1"; + }); + add("Layouts hängen", (p) => { + for (const l of list(p, "layouts")) { + l.masterId = "nope"; + l.folderId = "nope"; + for (const v of l.viewports ?? []) v.snapshotId = "nope"; + } + for (const s of list(p, "viewSnapshots")) { + s.activeLevelId = "nope"; + s.enabledOverrideRuleIds = ["nope"]; + } + }); + add("leere Polygone", (p) => { + for (const c of list(p, "ceilings")) c.outline = []; + for (const rm of list(p, "rooms")) rm.boundary = []; + for (const rf of list(p, "roofs")) rf.outline = []; + for (const x of list(p, "extrudedSolids")) x.points = []; + if (p.siteRules) p.siteRules.parcel = []; + for (const d of list(p, "drawings2d")) if (Array.isArray(d.geom?.pts)) d.geom.pts = []; + }); + add("Ein-Punkt-Polygone", (p) => { + for (const c of list(p, "ceilings")) c.outline = c.outline?.slice(0, 1) ?? []; + for (const rm of list(p, "rooms")) rm.boundary = rm.boundary?.slice(0, 2) ?? []; + for (const rf of list(p, "roofs")) rf.outline = rf.outline?.slice(0, 2) ?? []; + for (const w of list(p, "walls")) w.end = { ...w.start }; + }); + add("NaN", (p) => { + const ws = list(p, "walls"); + if (ws[0]) ws[0].start = { x: NaN, y: 0 }; + if (ws[1]) ws[1].height = NaN; + for (const c of list(p, "ceilings").slice(0, 1)) c.outline = [{ x: NaN, y: NaN }, { x: 1, y: 0 }, { x: 1, y: 1 }]; + for (const t of list(p, "wallTypes").slice(0, 1)) for (const l of t.layers ?? []) l.thickness = NaN; + for (const lv of list(p, "drawingLevels")) lv.baseElevation = NaN; + for (const o of list(p, "openings").slice(0, 2)) o.width = NaN; + for (const s of list(p, "stairs").slice(0, 1)) s.width = NaN; + }); + add("Unendlich und negativ", (p) => { + for (const w of list(p, "walls").slice(0, 2)) w.height = -3; + for (const t of list(p, "wallTypes")) for (const l of t.layers ?? []) l.thickness = -0.1; + for (const o of list(p, "openings").slice(0, 2)) { + o.width = 1e300; + o.offset = -1e300; + } + for (const s of list(p, "stairs")) { + s.steps = 1e9; + s.width = 0; + } + for (const c of list(p, "columns")) c.height = -1; + }); + add("fehlende Felder", (p) => { + for (const k of ["walls", "openings", "ceilings", "roofs", "stairs", "rooms", "columns", "drawings2d", "extrudedSolids", "wallTypes", "components", "drawingLevels", "hatches", "lineStyles", "layouts", "viewSnapshots"]) { + for (const e of some(list(p, k))) { + const keys = Object.keys(e).filter((x) => x !== "id"); + for (const x of keys) if (r() < 0.4) delete e[x]; + } + } + }); + add("doppelte ids", (p) => { + for (const k of ["walls", "openings", "ceilings", "roofs", "stairs", "rooms", "drawings2d", "wallTypes", "components", "drawingLevels", "hatches", "lineStyles", "layers"]) { + const a = list(p, k); + if (a.length) p[k] = [...a, ...a.map((e) => ({ ...e }))]; + } + }); + add("falsche Typen", (p) => { + for (const w of list(p, "walls").slice(0, 1)) { + w.height = "hoch"; + w.start = null; + } + for (const c of list(p, "ceilings").slice(0, 1)) c.outline = "keine Liste"; + for (const d of list(p, "drawings2d").slice(0, 2)) d.geom = { shape: "unbekannt" }; + for (const lv of list(p, "drawingLevels").slice(0, 1)) lv.kind = "unbekannt"; + }); + add("Schnitt-/Ansichtslinien kaputt", (p) => { + for (const lv of list(p, "drawingLevels")) { + if (lv.kind === "section" || lv.kind === "elevation") { + lv.line = { a: { x: 0, y: 0 }, b: { x: 0, y: 0 } }; + lv.depth = NaN; + } + } + }); + add("Baurecht/Sonne kaputt", (p) => { + p.siteRules = { parcel: [{ x: 0, y: 0 }, { x: NaN, y: 1 }, { x: 1, y: 1 }], setbacks: [NaN, -1], defaultSetback: NaN, buildingLines: [{ a: { x: 0, y: 0 }, b: { x: 0, y: 0 } }], maxHeight: NaN, show: true }; + p.sunStudy = { when: "kein Datum", show: true }; + p.geoAnchor = { lv95: { e: NaN, n: 1e12 }, height: NaN, model: { x: 0, y: 0 } }; + }); + return out; +} + +/** Ruft alle Kern-Abfragen/Fassaden auf ein Projekt auf; liefert die Fehler (Name: Meldung). */ +async function runAll(project: Project): Promise { + const errors: string[] = []; + const run = async (name: string, f: () => unknown): Promise => { + try { + return await f(); + } catch (e) { + errors.push(`${name}: ${e instanceof Error ? e.message : String(e)}`); + return undefined; + } + }; + const codes = allCodes(project); + const levels = Array.isArray(project.drawingLevels) ? project.drawingLevels.filter((l) => l && typeof l === "object") : []; + const plans: unknown[] = []; + for (const l of levels) { + if (l.kind === "section") { + const o = (await run(`computeSection ${l.id}`, () => computeSection(project, l))) as Awaited> | undefined; + if (o) plans.push(await run(`generateSectionPlan ${l.id}`, () => generateSectionPlan(o, false, { visibleCodes: codes, hiddenLines: true, openings: true }))); + } else if (l.kind === "elevation") { + plans.push(await run(`generateElevationPlan ${l.id}`, () => generateElevationPlan(project, l))); + } else { + plans.push(await run(`generatePlan ${l.id}`, () => generatePlan(project, l.id, codes, undefined, "fein", true, false, true, 50))); + await run(`generateVisibleLevelsPlan ${l.id}`, () => generateVisibleLevelsPlan(project, l.id, codes)); + } + } + await run("generatePlan unbekanntes Geschoss", () => generatePlan(project, "nope", codes)); + for (const [i, plan] of plans.entries()) { + if (!plan) continue; + const pl = plan as Parameters[0]; + await run(`planToRenderScene #${i}`, () => planToRenderScene(pl, 100)); + await run(`planSceneBin #${i}`, () => planSceneBin(pl, 100)); + await run(`planToSvgString #${i}`, () => planToSvgString(pl, { scaleDenominator: 100 })); + await run(`buildPlanDxf #${i}`, () => buildPlanDxf(pl, project)); + } + await run("projectToModel3d", () => projectToModel3d(project)); + await run("pickGeometry", () => pickGeometry(project)); + await run("wallMaterialColorMaps", () => wallMaterialColorMaps(project)); + await run("exportIfcSpf", () => exportIfcSpf(project)); + await run("exportObj", () => exportObj(project)); + await run("exportStl", () => exportStl(project)); + await run("exportGlb", () => exportGlb(project)); + await run("exportScheduleCsv", () => exportScheduleCsv(project)); + await run("computeKennzahlen", () => computeKennzahlen(project)); + await run("checkRoomProgram", () => checkRoomProgram(project)); + await run("compareRoomProgram", () => compareRoomProgram(project)); + await run("layoutRoomProgram", () => layoutRoomProgram(project)); + await run("computeAreaTable", () => computeAreaTable(project)); + await run("computeIvhb", () => computeIvhb(project)); + await run("checkSiteRules", () => checkSiteRules(project)); + await run("buildingFootprint", () => buildingFootprint(project)); + await run("modelTop", () => modelTop(project)); + await run("sun", () => { + const { lat, lon } = projectLatLon(project); + return shadowPolygons(project, sunPosition(lat, lon, new Date(Date.UTC(2026, 5, 21, 10)))); + }); + await run("Layouts", () => { + const layouts = Array.isArray(project.layouts) ? project.layouts : []; + const masters = Array.isArray(project.masterLayouts) ? project.masterLayouts : []; + const folders = Array.isArray(project.layoutFolders) ? project.layoutFolders : []; + buildLayoutTree(folders, layouts); + buildMasterTree(folders, masters); + for (const f of folders) folderPdfPages(project, f.id); + for (const l of layouts as Layout[]) { + resolveTitleBlock(project, l, masters.find((m) => m.id === l.masterId), "2026-10-29"); + for (const v of l.viewports ?? []) { + const snap = (project.viewSnapshots ?? []).find((s) => s.id === v.snapshotId); + if (snap) generatePlan(project, snap.activeLevelId ?? "", visibleCodesFromSnapshot(snap)); + } + } + }); + await run("validateProject", () => validateProject(project)); + await run("projectWarnings", () => projectWarnings(project)); + await run("serialize/parse", () => { + const r = parseProjectFile(serializeProject(project)); + if (!r.ok) throw new Error(r.error); + }); + return errors; +} + +describe("Kern robust gegen kaputte Projekte", () => { + beforeAll(async () => { + await loadFileioForTests(); + }); + + const bases: [string, () => Project][] = [ + ["Beispiel", () => sampleProject], + ["alle Element-Arten", () => richProject()], + ...[1, 3, 5, 8, 11, 13, 21].map((seed): [string, () => Project] => [`Zufall ${seed}`, () => randomProject(seed)]), + ["Kacheln 2×2", () => bigSampleProject(2)], + ]; + + for (const [baseName, make] of bases) { + it(`${baseName}: keine Abfrage wirft`, async () => { + const base = make(); + const failures: string[] = []; + for (const [i, [name, p]] of corruptions(base, 7 + baseName.length).entries()) { + for (const e of await runAll(p)) failures.push(`[${name} #${i}] ${e}`); + } + expect(failures).toEqual([]); + }, 240_000); + } + + it("hängender Wandtyp: Plan wie mit dem Rückfall-Typ (kein Werfen, Wand bleibt sichtbar)", () => { + const p = clone(sampleProject); + p.walls[0].wallTypeId = "nope"; + const floor = sampleProject.drawingLevels.find((l) => l.kind === "floor")!; + const plan = generatePlan(p as Project, floor.id, allCodes(sampleProject)); + expect(plan.primitives.some((x) => x.kind === "polygon" && (x as { wallId?: string }).wallId === p.walls[0].id)).toBe(true); + }); + + it("validate meldet hängende Verweise als Warnung", () => { + const p = clone(sampleProject); + p.walls[0].wallTypeId = "nope"; + p.openings[0].hostWallId = "wand-fehlt"; + const w = projectWarnings(p as Project); + expect(w.some((x) => x.includes("nope"))).toBe(true); + expect(w.some((x) => x.includes("wand-fehlt"))).toBe(true); + expect(projectWarnings(sampleProject)).toEqual([]); + }); +}); diff --git a/src/export/exportIfc.test.ts b/src/export/exportIfc.test.ts index f09dd7ef..5a1ae6c4 100644 --- a/src/export/exportIfc.test.ts +++ b/src/export/exportIfc.test.ts @@ -703,10 +703,12 @@ describe("[B5] Pset_*Common mit den Werten aus dem Modell", () => { }); describe("Sammler im Kern ([K4], 29.10.)", () => { - it("Fehler des Kerns kommen mit dessen Meldung (unbekannter Wandtyp)", () => { + it("hängender Wandtyp (Datei/Import): Export mit dem Rückfall-Typ statt Abbruch", () => { const p = fixtureProject(); const broken: Project = { ...p, walls: p.walls.map((w, i) => (i === 0 ? { ...w, wallTypeId: "fehlt" } : w)) }; - expect(() => exportIfcSpf(broken)).toThrow("Unbekannter Wandtyp: fehlt"); + const spf = exportIfcSpf(broken); + expect(spf).toContain("IFCWALL"); + expect(spf).toContain(p.walls[0].id); }); it("zweimal exportieren gibt dieselbe Datei (bis auf den Zeitstempel)", () => { diff --git a/src/model/layoutModel.ts b/src/model/layoutModel.ts index 9e83b58c..3cfce168 100644 --- a/src/model/layoutModel.ts +++ b/src/model/layoutModel.ts @@ -568,7 +568,7 @@ export function resolveTitleBlock( today: string = new Date().toISOString().slice(0, 10), ): ResolvedTitleBlock { const arg = { - layout: { id: layout.id, name: layout.name, planNumber: layout.planNumber, viewports: layout.viewports.slice(0, 1) }, + layout: { id: layout.id, name: layout.name, planNumber: layout.planNumber, viewports: (layout.viewports ?? []).slice(0, 1) }, master: master ? { titleBlock: master.titleBlock } : null, today, }; @@ -581,7 +581,8 @@ export function resolveTitleBlock( */ export function visibleCodesFromSnapshot(snap: ViewSnapshot): Set { const out = new Set(); - for (const [code, visible] of Object.entries(snap.layerVisibility)) { + // Fehlt die Map (Datei/Import), ist nichts sichtbar — kein Absturz. + for (const [code, visible] of Object.entries(snap.layerVisibility ?? {})) { if (visible) out.add(code); } return out; diff --git a/src/model/richProject.testing.ts b/src/model/richProject.testing.ts new file mode 100644 index 00000000..222d7196 --- /dev/null +++ b/src/model/richProject.testing.ts @@ -0,0 +1,154 @@ +// Testhilfe: Beispielprojekt mit allen Element-Arten (`richProject`) und daraus abgeleitete +// Zufallsprojekte (`randomProject`, Listen gemischt/gekürzt, Zahlen verrauscht, optionale Felder weg). +// Genutzt von der Modell-Rundreise und dem Robustheitstest des Kerns. + +import { sampleProject } from "./sampleProject"; +import type { Drawing2DGeom, LayoutAnnotation, ParametricRule, Project, RichTextDoc } from "./types"; + +export const plain = (p: unknown): unknown => JSON.parse(JSON.stringify(p)); + +const doc: RichTextDoc = { + version: 1, + paragraphs: [{ runs: [{ text: "Hallo", marks: { bold: true, sizePt: 9, color: "#112233", super: true } }], align: "center", lineHeight: 1.2 }], +}; + +const geoms: Drawing2DGeom[] = [ + { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } }, + { shape: "xline", a: { x: 0, y: 0 }, b: { x: 1, y: 1 } }, + { shape: "ray", a: { x: 0, y: 0 }, b: { x: 0, y: 1 } }, + { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], closed: true, bulge: [0, 0.5, 0] }, + { shape: "rect", min: { x: 0, y: 0 }, max: { x: 2, y: 1 } }, + { shape: "circle", center: { x: 1, y: 1 }, r: 0.5 }, + { shape: "arc", center: { x: 1, y: 1 }, r: 0.5, a0: 0, a1: 1.5 }, + { shape: "ellipse", center: { x: 1, y: 1 }, rx: 2, ry: 1, rotation: 0.3 }, + { shape: "bezier", pts: [{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 1 }, { x: 3, y: 0 }] }, + { shape: "spline", pts: [{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 0 }], closed: false, mode: "control" }, + { + shape: "dimension", pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }], offset: 0.5, gapMm: 1, overshootMm: 2, tickLenMm: 3, + textHeightMm: 2.5, lineWeightMm: 0.18, extWeightMm: 0.13, tickWeightMm: 0.35, textOffsetsMm: [{ along: 1, perp: -1 }], + }, + { shape: "kote", at: { x: 1, y: 2 }, value: 3.05, kind: "ukRoh", rotation: 0 }, + { shape: "detailref", at: { x: 1, y: 2 }, label: "3", sheetLayoutId: "lay1", sheetLabel: "A-12" }, + { shape: "scalebar", at: { x: 0, y: -2 }, segmentLength: 1, segments: 5 }, + { shape: "pointmarker", at: { x: 2, y: 2 } }, + { + shape: "text", at: { x: 0, y: 3 }, text: "Notiz", height: 0.25, angle: 0.1, width: 2, marks: { italic: true }, doc, + leaderTarget: { x: 1, y: 1 }, leaderBendPoints: [{ x: 0.5, y: 2 }], pathPts: [{ x: 0, y: 3 }, { x: 2, y: 3 }], + }, + { shape: "block", blockDefId: "blk1", at: { x: 5, y: 5 }, rotation: 1.57, scale: 2 }, + { shape: "image", min: { x: 0, y: 0 }, max: { x: 1, y: 1 }, src: "data:image/png;base64,AAAA", opacity: 0.5 }, +]; + +const rules: ParametricRule[] = [ + { type: "grid", spacing: 3, directions: "both", wallTypeId: "wt1", referenceLine: "center", height: 2.8 }, + { type: "module", moduleSize: 1.2, direction: "x", referenceWallId: "w1" }, + { type: "conditional-thickness", condition: "exterior", wallTypeId: "wt1", logic: "or" }, + { type: "reference-line", referenceLine: "left", target: "all" }, + { type: "sequence", rules: [{ type: "reference-line", referenceLine: "right", target: "exterior" }], stopOnMatch: true }, +]; + +const annotations: LayoutAnnotation[] = [ + { kind: "line", id: "a1", x1Mm: 0, y1Mm: 0, x2Mm: 10, y2Mm: 10, color: "#000000", weightMm: 0.25 }, + { kind: "rect", id: "a2", xMm: 1, yMm: 2, widthMm: 30, heightMm: 20 }, + { kind: "text", id: "a3", xMm: 1, yMm: 2, text: "Titel", heightMm: 5, doc, widthMm: 40 }, + { kind: "image", id: "a4", xMm: 1, yMm: 2, widthMm: 30, heightMm: 20, src: "data:image/png;base64,AAAA", opacity: 1 }, +]; + +/** Beispielprojekt, ergänzt um alle Element-Arten, die es selbst nicht enthält. */ +export function richProject(): Project { + const lvl = sampleProject.drawingLevels[0].id; + return { + ...sampleProject, + formatVersion: 2, + textStyles: [{ id: "ts1", label: "Titel", marks: { bold: true, font: "Helvetica", sizePt: 14 } }], + blockDefs: [{ id: "blk1", name: "Nordpfeil", geom2d: geoms.slice(0, 4) }], + pens: [{ id: "pen1", name: "Kontur" }], + penSets: [{ id: "ps1", name: "Standard", pens: { pen1: { color: "#000000", weight: 0.35 } } }], + activePenSetId: "ps1", + customPalettes: [{ id: "pal1", name: "Projekt", colors: ["#ff0000", "#00ff00"], visible: true }], + builtinPaletteBanks: { ral: false, tango: true }, + roomProgram: [{ name: "Wohnen", siaCategory: "HNF", area: 30, count: 2, group: "Wohnung", note: "Süd" }], + roomProgramTolerance: 0.1, + parcelArea: 812, + sunStudy: { when: "2026-06-21T12:00", show: true }, + siteRules: { + parcel: [{ x: -5, y: -5 }, { x: 30, y: -5 }, { x: 30, y: 30 }], + setbacks: [3, 4, 5], defaultSetback: 4, buildingLines: [{ a: { x: 0, y: 0 }, b: { x: 10, y: 0 } }], maxHeight: 15, show: true, + }, + scaleLineWeights: true, + drawings2d: geoms.map((geom, i) => ({ + id: `d${i}`, type: "drawing2d" as const, levelId: lvl, categoryCode: "90", geom, + ...(i % 2 ? { noPrint: true, endMarks: { start: "arrow" as const, end: "dot" as const, sizeMm: 2 }, opacity: 0.8 } : {}), + ...(i % 3 === 0 ? { hatchOrigin: { x: 1, y: 1 }, hatchSource: "layer" as const, weightMm: 0.5, fillColor: "#eeeeee" } : {}), + })), + context: [ + { type: "importedMesh", id: "c1", name: "Nachbar", layer: "L", categoryCode: "95", color: "#aabbcc", ifcGlobalId: "2O2Fr$t4X7Zf8NOew3FLOH", positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [0, 1, 2] }, + { + type: "contourSet", id: "c2", name: "Höhenlinien", contours: [ + { z: 400, pts: [{ x: 0, y: 0 }, { x: 5, y: 1 }], closed: false, layer: "HL", filled: true }, + { z: 401, pts: [], closed: false, curve: { kind: "arc", cx: 0, cy: 0, r: 2, a0: 0, a1: 1 } }, + ], + }, + { type: "terrainMesh", id: "c3", name: "Gelände", positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [0, 1, 2], vertexColors: [1, 0, 0, 0, 1, 0, 0, 0, 1] }, + { type: "image", id: "c4", name: "Luftbild", src: "data:image/png;base64,AAAA", min: { x: 0, y: 0 }, max: { x: 10, y: 10 }, opacity: 0.7, drape: true, filters: { saturation: 0.5, grayscale: 1 } }, + ], + extrudedSolids: [ + { id: "x1", type: "extrudedSolid", levelId: lvl, points: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], height: 2, baseOffset: 0.1, operation: "subtract", taper: 0.1, cornerRadius: 0.05, chamfer: 0.02 }, + { id: "x2", type: "extrudedSolid", levelId: lvl, points: [], height: 1, circle: { center: { x: 3, y: 3 }, r: 0.4 }, brep: { spec: { kind: "box", w: 1, nested: { a: [1, 2] } }, origin: { x: 0, y: 0 }, label: "Quader" } }, + ], + columns: [ + { + id: "col1", type: "column", floorId: lvl, categoryCode: "50", position: { x: 2, y: 2 }, profile: { kind: "round", radius: 0.15 }, + rotation: 0, height: 2.6, bottom: { mode: "floor", floorId: lvl, offset: -0.1 }, top: { mode: "custom", z: 3 }, strokeWeightSource: "object", + }, + { id: "col2", type: "column", floorId: lvl, categoryCode: "50", position: { x: 4, y: 2 }, profile: { kind: "rect", width: 0.3, depth: 0.2 }, rotation: 0.5, height: 2.6 }, + ], + groups: [{ id: "g1", name: "Gruppe", wallIds: [sampleProject.walls[0].id], drawingIds: ["d1"], ceilingIds: [], roomIds: [], stairIds: [], columnIds: ["col1"], roofIds: [], openingIds: [], groupIds: [] }], + parametricWalls: [{ id: "pw1", name: "Raster", description: "Test", rules, defaultWallTypeId: sampleProject.wallTypes[0].id }], + overrideRules: [{ id: "or1", name: "Rot", enabled: true, condition: { type: "layer_name", operator: "contains", value: "Wand" }, actions: { color: "#ff0000", lineweight: 0.5 } }], + viewSnapshots: [{ + id: "vs1", name: "EG", folderId: "vf1", viewType: "grundriss", view3d: "isoBackLeft", fov: 50, scaleDenominator: 100, detail: "fein", activeLevelId: lvl, + layerVisibility: { "10": true, "20": false }, drawingVisibility: { [lvl]: true }, enabledOverrideRuleIds: ["or1"], cameraCenter: { x: 1, y: 2 }, cameraPxPerMeter: 40, + }], + viewSnapshotFolders: [{ id: "vf1", name: "Pläne" }, { id: "vf2", name: "Unter", parentId: "vf1" }], + layouts: [{ id: "lay1", name: "Blatt 1", paper: "a3", orientation: "landscape", planNumber: "A-12", masterId: "m1", folderId: "lf1", viewports: [{ id: "vp1", snapshotId: "vs1", xMm: 10, yMm: 10, widthMm: 200, heightMm: 150, scaleDenominator: 50 }], annotations }], + masterLayouts: [{ id: "m1", name: "Master", paper: "a3", orientation: "landscape", titleBlock: { projectName: "P", sheetName: "S", scale: "1:100", date: "28.10.", author: "K" }, border: true }], + layoutFolders: [{ id: "lf1", name: "Pläne", kind: "layout" }], + referenceElevationMasl: 432.1, + geoAnchor: { lv95: { e: 2600000, n: 1200000 }, height: 432, model: { x: 0, y: 0 }, label: "Bern" }, + }; +} + +/** Zufallsgenerator mit Saat (LCG, reproduzierbar). */ +export function rng(seed: number): () => number { + let x = seed >>> 0; + return () => (x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296; +} + +// Optionale Projekt-Felder (laut Typ) — dürfen in Zufallsprojekten fehlen. +const OPTIONAL_KEYS = [ + "formatVersion", "textStyles", "ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens", "penSets", + "activePenSetId", "customPalettes", "builtinPaletteBanks", "roomProgram", "roomProgramTolerance", "parcelArea", "sunStudy", "siteRules", + "scaleLineWeights", "ceilings", "roofs", "openings", "stairs", "rooms", "context", "extrudedSolids", "columns", "groups", + "parametricWalls", "overrideRules", "viewSnapshots", "viewSnapshotFolders", "layouts", "masterLayouts", "layoutFolders", + "referenceElevationMasl", "geoAnchor", +] as const satisfies readonly (keyof Project)[]; + +/** Zufallsprojekt: Listen gemischt/gekürzt/verdoppelt, Zahlen verrauscht, optionale Felder weggelassen. */ +export function randomProject(seed: number): Project { + const r = rng(seed); + const jitter = (v: unknown, depth = 0): unknown => { + if (typeof v === "number") return r() < 0.5 ? v : Math.round((v + (r() - 0.5) * 10) * 1e6) / 1e6; + if (Array.isArray(v)) { + let a = v.map((x) => jitter(x, depth + 1)); + if (depth === 1 && a.length > 1 && r() < 0.3) a = a.filter(() => r() < 0.7); + if (depth === 1 && r() < 0.2) a = [...a].reverse(); + return a; + } + if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, jitter(x, depth + 1)])); + return v; + }; + const p = jitter(plain(richProject()), 0) as Record; + for (const k of OPTIONAL_KEYS) if (r() < 0.25) delete p[k]; + return p as unknown as Project; +} diff --git a/src/model/types.roundtrip.test.ts b/src/model/types.roundtrip.test.ts index d7d60fba..4d3dfd07 100644 --- a/src/model/types.roundtrip.test.ts +++ b/src/model/types.roundtrip.test.ts @@ -6,9 +6,8 @@ import { describe, expect, it } from "vitest"; import { ProjectDocument } from "../core/document"; import { sampleProject } from "./sampleProject"; -import type { Drawing2DGeom, LayoutAnnotation, ParametricRule, Project, RichTextDoc } from "./types"; - -const plain = (p: unknown): unknown => JSON.parse(JSON.stringify(p)); +import type { Project } from "./types"; +import { plain, randomProject, richProject } from "./richProject.testing"; function viaRust(p: Project): unknown { const d = new ProjectDocument(p); @@ -35,152 +34,6 @@ function diffPaths(a: unknown, b: unknown, path = "", out: string[] = []): strin return out; } -const doc: RichTextDoc = { - version: 1, - paragraphs: [{ runs: [{ text: "Hallo", marks: { bold: true, sizePt: 9, color: "#112233", super: true } }], align: "center", lineHeight: 1.2 }], -}; - -const geoms: Drawing2DGeom[] = [ - { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } }, - { shape: "xline", a: { x: 0, y: 0 }, b: { x: 1, y: 1 } }, - { shape: "ray", a: { x: 0, y: 0 }, b: { x: 0, y: 1 } }, - { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], closed: true, bulge: [0, 0.5, 0] }, - { shape: "rect", min: { x: 0, y: 0 }, max: { x: 2, y: 1 } }, - { shape: "circle", center: { x: 1, y: 1 }, r: 0.5 }, - { shape: "arc", center: { x: 1, y: 1 }, r: 0.5, a0: 0, a1: 1.5 }, - { shape: "ellipse", center: { x: 1, y: 1 }, rx: 2, ry: 1, rotation: 0.3 }, - { shape: "bezier", pts: [{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 1 }, { x: 3, y: 0 }] }, - { shape: "spline", pts: [{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 0 }], closed: false, mode: "control" }, - { - shape: "dimension", pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }], offset: 0.5, gapMm: 1, overshootMm: 2, tickLenMm: 3, - textHeightMm: 2.5, lineWeightMm: 0.18, extWeightMm: 0.13, tickWeightMm: 0.35, textOffsetsMm: [{ along: 1, perp: -1 }], - }, - { shape: "kote", at: { x: 1, y: 2 }, value: 3.05, kind: "ukRoh", rotation: 0 }, - { shape: "detailref", at: { x: 1, y: 2 }, label: "3", sheetLayoutId: "lay1", sheetLabel: "A-12" }, - { shape: "scalebar", at: { x: 0, y: -2 }, segmentLength: 1, segments: 5 }, - { shape: "pointmarker", at: { x: 2, y: 2 } }, - { - shape: "text", at: { x: 0, y: 3 }, text: "Notiz", height: 0.25, angle: 0.1, width: 2, marks: { italic: true }, doc, - leaderTarget: { x: 1, y: 1 }, leaderBendPoints: [{ x: 0.5, y: 2 }], pathPts: [{ x: 0, y: 3 }, { x: 2, y: 3 }], - }, - { shape: "block", blockDefId: "blk1", at: { x: 5, y: 5 }, rotation: 1.57, scale: 2 }, - { shape: "image", min: { x: 0, y: 0 }, max: { x: 1, y: 1 }, src: "data:image/png;base64,AAAA", opacity: 0.5 }, -]; - -const rules: ParametricRule[] = [ - { type: "grid", spacing: 3, directions: "both", wallTypeId: "wt1", referenceLine: "center", height: 2.8 }, - { type: "module", moduleSize: 1.2, direction: "x", referenceWallId: "w1" }, - { type: "conditional-thickness", condition: "exterior", wallTypeId: "wt1", logic: "or" }, - { type: "reference-line", referenceLine: "left", target: "all" }, - { type: "sequence", rules: [{ type: "reference-line", referenceLine: "right", target: "exterior" }], stopOnMatch: true }, -]; - -const annotations: LayoutAnnotation[] = [ - { kind: "line", id: "a1", x1Mm: 0, y1Mm: 0, x2Mm: 10, y2Mm: 10, color: "#000000", weightMm: 0.25 }, - { kind: "rect", id: "a2", xMm: 1, yMm: 2, widthMm: 30, heightMm: 20 }, - { kind: "text", id: "a3", xMm: 1, yMm: 2, text: "Titel", heightMm: 5, doc, widthMm: 40 }, - { kind: "image", id: "a4", xMm: 1, yMm: 2, widthMm: 30, heightMm: 20, src: "data:image/png;base64,AAAA", opacity: 1 }, -]; - -/** Beispielprojekt, ergänzt um alle Element-Arten, die es selbst nicht enthält. */ -function richProject(): Project { - const lvl = sampleProject.drawingLevels[0].id; - return { - ...sampleProject, - formatVersion: 2, - textStyles: [{ id: "ts1", label: "Titel", marks: { bold: true, font: "Helvetica", sizePt: 14 } }], - blockDefs: [{ id: "blk1", name: "Nordpfeil", geom2d: geoms.slice(0, 4) }], - pens: [{ id: "pen1", name: "Kontur" }], - penSets: [{ id: "ps1", name: "Standard", pens: { pen1: { color: "#000000", weight: 0.35 } } }], - activePenSetId: "ps1", - customPalettes: [{ id: "pal1", name: "Projekt", colors: ["#ff0000", "#00ff00"], visible: true }], - builtinPaletteBanks: { ral: false, tango: true }, - roomProgram: [{ name: "Wohnen", siaCategory: "HNF", area: 30, count: 2, group: "Wohnung", note: "Süd" }], - roomProgramTolerance: 0.1, - parcelArea: 812, - sunStudy: { when: "2026-06-21T12:00", show: true }, - siteRules: { - parcel: [{ x: -5, y: -5 }, { x: 30, y: -5 }, { x: 30, y: 30 }], - setbacks: [3, 4, 5], defaultSetback: 4, buildingLines: [{ a: { x: 0, y: 0 }, b: { x: 10, y: 0 } }], maxHeight: 15, show: true, - }, - scaleLineWeights: true, - drawings2d: geoms.map((geom, i) => ({ - id: `d${i}`, type: "drawing2d" as const, levelId: lvl, categoryCode: "90", geom, - ...(i % 2 ? { noPrint: true, endMarks: { start: "arrow" as const, end: "dot" as const, sizeMm: 2 }, opacity: 0.8 } : {}), - ...(i % 3 === 0 ? { hatchOrigin: { x: 1, y: 1 }, hatchSource: "layer" as const, weightMm: 0.5, fillColor: "#eeeeee" } : {}), - })), - context: [ - { type: "importedMesh", id: "c1", name: "Nachbar", layer: "L", categoryCode: "95", color: "#aabbcc", ifcGlobalId: "2O2Fr$t4X7Zf8NOew3FLOH", positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [0, 1, 2] }, - { - type: "contourSet", id: "c2", name: "Höhenlinien", contours: [ - { z: 400, pts: [{ x: 0, y: 0 }, { x: 5, y: 1 }], closed: false, layer: "HL", filled: true }, - { z: 401, pts: [], closed: false, curve: { kind: "arc", cx: 0, cy: 0, r: 2, a0: 0, a1: 1 } }, - ], - }, - { type: "terrainMesh", id: "c3", name: "Gelände", positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [0, 1, 2], vertexColors: [1, 0, 0, 0, 1, 0, 0, 0, 1] }, - { type: "image", id: "c4", name: "Luftbild", src: "data:image/png;base64,AAAA", min: { x: 0, y: 0 }, max: { x: 10, y: 10 }, opacity: 0.7, drape: true, filters: { saturation: 0.5, grayscale: 1 } }, - ], - extrudedSolids: [ - { id: "x1", type: "extrudedSolid", levelId: lvl, points: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], height: 2, baseOffset: 0.1, operation: "subtract", taper: 0.1, cornerRadius: 0.05, chamfer: 0.02 }, - { id: "x2", type: "extrudedSolid", levelId: lvl, points: [], height: 1, circle: { center: { x: 3, y: 3 }, r: 0.4 }, brep: { spec: { kind: "box", w: 1, nested: { a: [1, 2] } }, origin: { x: 0, y: 0 }, label: "Quader" } }, - ], - columns: [ - { - id: "col1", type: "column", floorId: lvl, categoryCode: "50", position: { x: 2, y: 2 }, profile: { kind: "round", radius: 0.15 }, - rotation: 0, height: 2.6, bottom: { mode: "floor", floorId: lvl, offset: -0.1 }, top: { mode: "custom", z: 3 }, strokeWeightSource: "object", - }, - { id: "col2", type: "column", floorId: lvl, categoryCode: "50", position: { x: 4, y: 2 }, profile: { kind: "rect", width: 0.3, depth: 0.2 }, rotation: 0.5, height: 2.6 }, - ], - groups: [{ id: "g1", name: "Gruppe", wallIds: [sampleProject.walls[0].id], drawingIds: ["d1"], ceilingIds: [], roomIds: [], stairIds: [], columnIds: ["col1"], roofIds: [], openingIds: [], groupIds: [] }], - parametricWalls: [{ id: "pw1", name: "Raster", description: "Test", rules, defaultWallTypeId: sampleProject.wallTypes[0].id }], - overrideRules: [{ id: "or1", name: "Rot", enabled: true, condition: { type: "layer_name", operator: "contains", value: "Wand" }, actions: { color: "#ff0000", lineweight: 0.5 } }], - viewSnapshots: [{ - id: "vs1", name: "EG", folderId: "vf1", viewType: "grundriss", view3d: "isoBackLeft", fov: 50, scaleDenominator: 100, detail: "fein", activeLevelId: lvl, - layerVisibility: { "10": true, "20": false }, drawingVisibility: { [lvl]: true }, enabledOverrideRuleIds: ["or1"], cameraCenter: { x: 1, y: 2 }, cameraPxPerMeter: 40, - }], - viewSnapshotFolders: [{ id: "vf1", name: "Pläne" }, { id: "vf2", name: "Unter", parentId: "vf1" }], - layouts: [{ id: "lay1", name: "Blatt 1", paper: "a3", orientation: "landscape", planNumber: "A-12", masterId: "m1", folderId: "lf1", viewports: [{ id: "vp1", snapshotId: "vs1", xMm: 10, yMm: 10, widthMm: 200, heightMm: 150, scaleDenominator: 50 }], annotations }], - masterLayouts: [{ id: "m1", name: "Master", paper: "a3", orientation: "landscape", titleBlock: { projectName: "P", sheetName: "S", scale: "1:100", date: "28.10.", author: "K" }, border: true }], - layoutFolders: [{ id: "lf1", name: "Pläne", kind: "layout" }], - referenceElevationMasl: 432.1, - geoAnchor: { lv95: { e: 2600000, n: 1200000 }, height: 432, model: { x: 0, y: 0 }, label: "Bern" }, - }; -} - -/** Zufallsgenerator mit Saat (LCG, reproduzierbar). */ -function rng(seed: number): () => number { - let x = seed >>> 0; - return () => (x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296; -} - -// Optionale Projekt-Felder (laut Typ) — dürfen in Zufallsprojekten fehlen. -const OPTIONAL_KEYS = [ - "formatVersion", "textStyles", "ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens", "penSets", - "activePenSetId", "customPalettes", "builtinPaletteBanks", "roomProgram", "roomProgramTolerance", "parcelArea", "sunStudy", "siteRules", - "scaleLineWeights", "ceilings", "roofs", "openings", "stairs", "rooms", "context", "extrudedSolids", "columns", "groups", - "parametricWalls", "overrideRules", "viewSnapshots", "viewSnapshotFolders", "layouts", "masterLayouts", "layoutFolders", - "referenceElevationMasl", "geoAnchor", -] as const satisfies readonly (keyof Project)[]; - -/** Zufallsprojekt: Listen gemischt/gekürzt/verdoppelt, Zahlen verrauscht, optionale Felder weggelassen. */ -function randomProject(seed: number): Project { - const r = rng(seed); - const jitter = (v: unknown, depth = 0): unknown => { - if (typeof v === "number") return r() < 0.5 ? v : Math.round((v + (r() - 0.5) * 10) * 1e6) / 1e6; - if (Array.isArray(v)) { - let a = v.map((x) => jitter(x, depth + 1)); - if (depth === 1 && a.length > 1 && r() < 0.3) a = a.filter(() => r() < 0.7); - if (depth === 1 && r() < 0.2) a = [...a].reverse(); - return a; - } - if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, jitter(x, depth + 1)])); - return v; - }; - const p = jitter(plain(richProject()), 0) as Record; - for (const k of OPTIONAL_KEYS) if (r() < 0.25) delete p[k]; - return p as unknown as Project; -} - describe("Modell-Rundreise TS → Rust → TS ([K4] S4)", () => { it("Beispielprojekt bleibt gleich", () => { const back = viaRust(sampleProject);