From 040366bf75aaa99bd241ece38a5c5057e590fde0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 14:49:53 +0000 Subject: [PATCH] =?UTF-8?q?[154]=20Bauteile=20aus=20Zeichnung=20erkennen:?= =?UTF-8?q?=20W=C3=A4nde=20(Linienpaare,=20B=C3=B6gen,=20St=C3=B6sse),=20T?= =?UTF-8?q?=C3=BCren/Fenster/Durchbr=C3=BCche,=20R=C3=A4ume=20aus=20DXF-Li?= =?UTF-8?q?nien?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Kern drawing_recognize.rs (Befehl recognize über cmd_create: Ops, Vorschau, Bericht), Befehl erkennen mit Vorschau/Zählern/Bericht, CLI erkennen, Rundreise-Test DXF-Export → Import → erkennen (Musterhaus 100 %, komplex Wände 79 %/Achsen 96 %, Öffnungen 76 %). --- TODO.md | 37 + src-tauri/core/src/cmd_create.rs | 6 +- src-tauri/core/src/drawing_recognize.rs | 1750 +++++++++++++++++ src-tauri/core/src/drawing_recognize_tests.rs | 486 +++++ src-tauri/core/src/lib.rs | 1 + src/cli/main.ts | 26 +- src/commands/cmds/recognize.test.ts | 100 + src/commands/cmds/recognize.ts | 146 ++ src/commands/registry.ts | 4 + src/core/extra.ts | 2 + src/i18n/de.ts | 24 + src/i18n/en.ts | 24 + src/io/recognizeDrawing.roundtrip.test.ts | 194 ++ src/io/recognizeDrawing.ts | 82 + 14 files changed, 2880 insertions(+), 2 deletions(-) create mode 100644 src-tauri/core/src/drawing_recognize.rs create mode 100644 src-tauri/core/src/drawing_recognize_tests.rs create mode 100644 src/commands/cmds/recognize.test.ts create mode 100644 src/commands/cmds/recognize.ts create mode 100644 src/io/recognizeDrawing.roundtrip.test.ts create mode 100644 src/io/recognizeDrawing.ts diff --git a/TODO.md b/TODO.md index ba4a948f..7af40cb6 100644 --- a/TODO.md +++ b/TODO.md @@ -3461,6 +3461,43 @@ Format · [90] Versionsvergleich · [91] Assistent · [92] Speckle. Dreiecksflächen (Schependomlaan-SVG 20–27 MB); Schnitt-Projektion ohne Zellen-Cache je Netz (Topologie gemerkt, Sichtbarkeit je Aufruf); Gelände-Netze aus IFC („Gelaende") erscheinen als Körper statt als Geländelinie; nicht in der Tauri-App/Metal geprüft. · M +- ◐ **[154] Bauteile aus Zeichnung erkennen.** (7.11.) Befehl `erkennen` (Kürzel `bauteileerkennen`, `recognize`; nur + Geschosse): aus den 2D-Linien eines Bestandsplans (DXF/DWG-Import aus ArchiCAD/Vectorworks/AutoCAD) werden Wände, Öffnungen + und Räume. Quelle: gewählte 2D-Elemente, sonst die Zeichnung des aktiven Geschosses, sonst die erste Ebene mit Zeichnung + (Option E schaltet durch). Beim Start Vorschau (Wandbänder, Türbögen/Fensterlinien/Durchbruch-Kreuze, Raumumrisse, unklare + Stellen als Kreuz) mit Zählern als Meldung und am Cursor; B = Bericht (Wanddicken, mit Füllung bestätigt, Bogenwände, + Räume ohne Namen, unklar je Grund); Enter übernimmt als EIN Undo-Schritt ins aktive Geschoss (Wandhöhe = Geschosshöhe, + Tür 2.10, Fenster 1.20 auf 0.90). Kern `drawing_recognize.rs` (über `cmd_create`: `cmd: "recognize"` Ops/Vorschau, + Abfrage `q: "recognize"` Bericht), TS dünn: `io/recognizeDrawing.ts` (Fassade, auch CLI), `commands/cmds/recognize.ts`. + Erkennung: Linien/Polylinien/Rechtecke/Bögen (Bulges; in Sehnen zerlegte Bögen ≥ 3 Kanten mit gleichsinniger Drehung + ≤ 25° und Ecken ± 3 mm auf einem Kreis werden Bögen) nach Richtung gebündelt, deckungsgleiche verschmolzen; parallele + Paare 5–60 cm mit Überlappung ≥ 50 % gierig nach Abstand (Füllung/Schraffur dazwischen zuerst, je Linienseite einmal), + Schicht-/Achslinie dazwischen → eine Wand; Layer mit Wand-Namen (Wand, Wände, Mauer, WALL …) → nur deren Linien für Paare; + Stücke gleicher Achse/Dicke → eine Wand (Lücke ≤ 1.5 m immer, ≤ 4 m mit Tür-/Fensterhinweis); was ganz im Band einer + grösseren Wand liegt (Fensterrahmen, Abschlusslinien anstossender Wände) entfällt; Enden auf Achsen anderer Wände (L/T/Kreuz, + Tür in der Ecke bis 4 m mit Hinweis) und auf Bogenwand-Achsen; Umlauf um den Schwerpunkt (rechts = aussen, wie [B4]). + Öffnungen = ungedeckte Achsstrecken ≥ 30 cm: Türbogen 50–130° am Pfosten (Radius = Breite, zwei halbe = zweiflüglig) → + Tür mit Anschlag (`hinge`) und Aufschlagseite (`swing`), Linien parallel im Band (nicht länger als Lücke + 40 cm) → Fenster, + sonst Wanddurchbruch (`doorType: wandoeffnung`); Bogenwände aus konzentrischen Bögen, Stücke einer Achse mit Lücken → + eine Bogenwand mit Fenster (Bogen im Band)/Durchbruch (Lage als Bogenlänge). Wandtyp nach Gesamtdicke (± 5 mm, gleicher + Baustoff bevorzugt) wiederverwendet, sonst einschichtig neu („Wand {cm} cm (erkannt)“; Baustoff aus Layer-/Schraffurname + Beton/Mauerwerk/KS/Holz/Dämmung/Leichtbau, sonst tragender Projekt-Baustoff). Räume: Zellen der Achsen minus Wandbänder + (lichte Fläche), Name = grösster Text darin (sonst Raumnummer, sonst „Raum n“), SIA-Kategorie aus „HNF/NNF/VF …“, + Flächenangabe („17.01 m²“) > 5 % daneben → unklar. Unklar mit Grund: Flächenangabe abweichend/ausserhalb, Wandlinie ohne + Gegenlinie, Türbogen ohne Lücke, halber Türbogen, Lücke > 1.5 m ohne Hinweis, > 60 000 Linien. CLI + `dossier-cli erkennen [--level] [--source] [--out]` (z. B. `convert plan.dxf p.obp --cmd "erkennen --out e.obp"`). + Tests: Rust 16 (L-Haus mit T- und Kreuzstoss + Raumtexte, Flächenangabe, Tür mit Bogen/Fenster/Durchbruch, zweiflüglig, + breite Lücke, Tür in der Ecke, Bogenwand aus Bögen und aus Bulges, tessellierter Erker mit Fenster im Bogen, Layer-Filter, + Schicht-/Achslinie, Schraffur → Material, Ops/Typen/Auswahl/Vorschau/Bericht, Unsinn ohne Panic); vitest Befehl (6) und + Rundreise (`io/recognizeDrawing.roundtrip.test.ts`): eigener DXF-Export → Import → erkennen → Vergleich. Quote: Musterhaus + EG 5/5 Wände, 3/3 Öffnungen, Tür mit Anschlag/Aufschlag; OG 4/4; Musterhaus komplex (UG/EG/OG/DG) Wände 45/57 exakt (79 %), + Achsen-Abdeckung 96 % (Rest v. a. kollineare Wände über einen T-Stoss, die als eine Wand erkannt werden; Fundament-/ + Stützmauern), Öffnungen 35/46 (76 %). Geprüft: cargo test Kern, WASM (Linux, `--no-opt`), tsc, vitest (Goldens + unverändert), CLI + Chromium-Bilder (Musterhaus, komplex EG/OG). **Offen:** Schiebe-/Hebeschiebetüren werden Fenster + (Symbol ohne Bogen), Türen mit Futter/Zarge breiter als der Bogen bleiben Durchbruch + „Türbogen ohne Lücke“, Türen in + Bogenwänden, Stösse von Bogenwänden untereinander, schräg anstossende Enden in einer Wandfläche, Stützen/Treppen/Decken, + Blöcke (INSERT) werden schon beim Import aufgelöst (Tür-Blöcke als Linien), Brüstungs-/Sturzhöhen nicht aus 2D ableitbar; + nur Linux-Container, nicht in der Tauri-App geklickt (kein Knopf in der Werkzeugleiste, nur Befehlszeile). - ◐ **[68] Baugrube / Geländebearbeitung.** (30.10.) Kontext-Objekt `excavation` (Rust-Modell, `ContextObject`): Sohle (`outline`, `bottom` m ±0.00), Böschung `slope` (Standard 45°, je Kante `edgeSlopes`), Schüttung `fillSlope` (33.7°), Bermen `bermWidth`/`bermHeight`. Neues Gelände = clamp(t, b − d·tan β, b + H(d)) mit d = Abstand zum diff --git a/src-tauri/core/src/cmd_create.rs b/src-tauri/core/src/cmd_create.rs index 051b11f5..2818e03c 100644 --- a/src-tauri/core/src/cmd_create.rs +++ b/src-tauri/core/src/cmd_create.rs @@ -255,7 +255,7 @@ pub(crate) fn category_or(p: &Project, code: &str, ctx: &Ctx) -> Value { /// Farbe der Kategorie `code` (erste im Baum), sonst `def` (auch bei leerer Farbe: fehlt sie in der /// Datei, liest die typisierte Sicht ""). -fn category_color(p: &Project, code: &str, def: &str) -> Value { +pub(crate) fn category_color(p: &Project, code: &str, def: &str) -> Value { match find_category(&p.layers, code) { Some(c) if !c.color.is_empty() => s(&c.color), _ => s(def), @@ -1093,6 +1093,8 @@ pub fn ops(root: &Map, p: &Project, v: &Value) -> Option> "ceiling" => ceiling_ops(p, v, &ctx, ids), "room" => room_ops(p, v, &ctx, ids), "wand" => wand_ops(p, v, &ctx, ids), + // [154] Bauteile aus Zeichnung erkennen. + "recognize" => crate::drawing_recognize::ops(p, v, &ctx, ids), "stair" => stair_ops(p, v, &ctx, ids), "opening" => opening_ops(root, p, v, &ctx, ids), "roof" => roof_ops(p, v, &ctx, ids), @@ -1173,6 +1175,7 @@ pub fn preview_req(root: &Map, project: &Project, req: &Req, pts: } None => p.ok = false, }, + "recognize" => p.ok = crate::drawing_recognize::preview(project, v, &ctx, out, &mut p.info), "column" => { if let Some(at) = pts.first() { out.poly(&column_footprint(*at, v)); @@ -1217,6 +1220,7 @@ pub fn query(root: &Map, p: &Project, v: &Value) -> Option json!({ "hit": null }), }, + "recognize" => crate::drawing_recognize::report(p, v), "pickProfile" => json!({ "hit": pick_profile(root, level, at).map_or(Value::Null, profile_json) }), "profile" => json!({ "hit": find(root, "drawings2d", s_of(v, "id")).map_or(Value::Null, profile_json) }), _ => return crate::cmd_draw::query(root, p, v).or_else(|| crate::cmd_solid::query(root, p, v)).map(Ok), diff --git a/src-tauri/core/src/drawing_recognize.rs b/src-tauri/core/src/drawing_recognize.rs new file mode 100644 index 00000000..5f1d6ce7 --- /dev/null +++ b/src-tauri/core/src/drawing_recognize.rs @@ -0,0 +1,1750 @@ +//! Bauteile aus Zeichnung erkennen ([154]): aus den 2D-Linien eines Grundrisses (meist ein DXF/DWG-Import +//! aus ArchiCAD, Vectorworks, AutoCAD) werden editierbare Wände, Öffnungen und Räume. +//! +//! Ablauf ([`analyze`], rein geometrisch, ohne Projekt): +//! 1. **Linien** (Linien, Polylinien-Kanten, Rechtecke; Bögen aus `arc` und Polylinien-Bulges) nach Richtung +//! gebündelt (±0.3°, Bündel höchstens 1° breit) und je Bündel auf Lage `c` (Abstand quer) + Intervall `t` +//! projiziert; deckungsgleiche Stücke verschmelzen (gleicher Layer: auch Stoss an Stoss). +//! 2. **Wandpaare**: parallele Linien im Abstand 5–60 cm, Überlappung ≥ 50 % der kürzeren. Gierig nach +//! Abstand (mit Füllung/Schraffur dazwischen zuerst), je Linienseite belegt jedes Stück höchstens einmal. +//! Drei Linien übereinander (Schichtlinie, Achslinie) verschmelzen zu einer dicken Wand. Gibt es Layer +//! mit Wand-Namen („Wand“, „Mauer“, „A-WALL“ …), zählen für die Paare nur deren Linien. +//! 3. **Läufe**: Stücke derselben Achse und Dicke werden eine Wand; Lücken bis 1.5 m immer, bis 4 m nur mit +//! Tür-/Fenster-Hinweis darin. Dünne „Wände“ im Band einer dickeren (Fensterrahmen) entfallen. +//! 4. **Stösse**: Wandenden auf die Achse einer anderen Wand gezogen (L/T, Ende im Band ± 5 cm; mit +//! Tür-/Fenster-Hinweis bis 4 m, Tür in der Ecke). Wände laufen um den Schwerpunkt herum (erste Schicht +//! = rechts = aussen, wie [B4]). +//! 5. **Öffnungen**: was auf der Achse weder von Wandstücken noch vom Band einer kreuzenden Wand gedeckt +//! ist (≥ 30 cm): Türbogen (50–130°, Zentrum an einem Pfosten, Radius = Breite bzw. halbe Breite bei zwei +//! Bögen) → Tür mit Anschlag und Aufschlagseite; Linien parallel zur Wand im Band → Fenster; sonst +//! Wanddurchbruch. +//! 6. **Räume**: Zellen der Wandachsen (`kernel2d::detect_rooms`, lichter Umriss), Name aus dem grössten Text +//! darin, SIA-Kategorie (HNF …) und Flächenangabe („17.01 m²“, Abweichung > 5 % → unklar). +//! +//! Konzentrische Bögen im Abstand 5–60 cm werden Bogenwände (ohne Öffnungen und Stösse). Ergebnis als Ops +//! (ein Undo-Schritt, [`ops`]), Vorschau ([`preview`]) und Bericht ([`report`], erkannt / unklar mit Grund). + +use crate::cmd_create::{add_op, category_color, has_category, obj, pv, pvs, s, s_of, Ctx, V}; +use crate::cmd_transform::{IdGen, Shapes}; +use crate::json_util::js_num; +use crate::jsmath::hypot2; +use crate::jsnum::{atan2, cos, sin, tan}; +use crate::model::{Drawing2DGeom, LayerCategory, Project}; +use crate::ops::Op; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::f64::consts::PI; + +/// Wanddicke (m): kleinste und grösste. +pub const MIN_THICK: f64 = 0.05; +pub const MAX_THICK: f64 = 0.60; +/// Richtungs-Toleranz paralleler Linien (1°). +const PAR_TOL: f64 = 0.017_453_292_519_943_295; +/// Kette der Richtungs-Bündel (0.3°). +const ANG_CHAIN: f64 = 0.005_235_987_755_982_988; +/// Gleiche Lage quer (deckungsgleiche Linien). +const COL_TOL: f64 = 0.002; +/// Kürzestes Wandstück. +const MIN_PIECE: f64 = 0.05; +/// Lücken bis hier gehören immer zur Wand (Öffnung), bis [`GAP_MAX`] nur mit Hinweis. +const GAP_FREE: f64 = 1.5; +const GAP_MAX: f64 = 4.0; +/// Kleinste Öffnung. +const MIN_OPENING: f64 = 0.3; +/// Schutz vor quadratischem Aufwand. +const MAX_SEGS: usize = 60_000; +const MAX_ARCS: usize = 6_000; +/// Höchstzahl der Einträge „unklar“ im Bericht. +const MAX_UNCLEAR: usize = 200; + +// ── Eingabe ────────────────────────────────────────────────────────────────── + +#[derive(Clone, Debug)] +pub struct Seg { + pub a: V, + pub b: V, + pub layer: usize, +} + +/// Kreisbogen gegen den Uhrzeigersinn von `a0` über `sweep` (> 0). +#[derive(Clone, Debug)] +pub struct ArcIn { + pub c: V, + pub r: f64, + pub a0: f64, + pub sweep: f64, + pub layer: usize, +} + +#[derive(Clone, Debug)] +pub struct TextIn { + pub at: V, + pub text: String, + pub h: f64, + pub angle: f64, +} + +/// Gefüllte/schraffierte geschlossene Fläche (Bestätigung + Material-Hinweis). +#[derive(Clone, Debug)] +pub struct FillIn { + pub ring: Vec, + pub layer: usize, + /// Name der Schraffur (Material-Hinweis), falls bekannt. + pub hatch: Option, +} + +#[derive(Clone, Debug, Default)] +pub struct Input { + /// Layer-Namen (Kategorie-Namen; beim DXF-Import = DXF-Layer). + pub layers: Vec, + pub segs: Vec, + pub arcs: Vec, + pub texts: Vec, + pub fills: Vec, +} + +impl Input { + pub fn layer(&mut self, name: &str) -> usize { + if let Some(i) = self.layers.iter().position(|l| l == name) { + return i; + } + self.layers.push(name.to_string()); + self.layers.len() - 1 + } +} + +// ── Ergebnis ───────────────────────────────────────────────────────────────── + +#[derive(Clone, Debug, PartialEq)] +pub struct RWall { + pub a: V, + pub b: V, + /// Bogenwand: Modell-Bulge (positiv = Uhrzeigersinn, s. `wall_arc`). + pub bulge: Option, + pub t: f64, + /// Material-Hinweis (Gruppe, s. [`MATERIALS`]). + pub material: Option<&'static str>, + /// Füllung/Schraffur zwischen den Linien gefunden. + pub filled: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum RKind { + /// Tür: Scharnier am Ende (sonst am Anfang), Blatt rechts der Wandrichtung, Flügelzahl. + Door { hinge_end: bool, swing_right: bool, leaves: u8 }, + Window, + Void, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct ROpening { + pub wall: usize, + /// Abstand des ersten Pfostens vom Wandanfang. + pub pos: f64, + pub width: f64, + pub kind: RKind, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct RRoom { + pub ring: Vec, + pub name: Option, + pub sia: Option<&'static str>, + pub area_text: Option, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Unclear { + pub code: &'static str, + pub at: V, +} + +#[derive(Clone, Debug, Default)] +pub struct Recognition { + pub walls: Vec, + pub openings: Vec, + pub rooms: Vec, + pub unclear: Vec, + /// Nur Linien auf Wand-Layern verwendet. + pub layer_filter: bool, +} + +impl Recognition { + fn flag(&mut self, code: &'static str, at: V) { + if self.unclear.len() < MAX_UNCLEAR && at.0.is_finite() && at.1.is_finite() { + self.unclear.push(Unclear { code, at }); + } + } + pub fn count(&self, f: impl Fn(&RKind) -> bool) -> usize { + self.openings.iter().filter(|o| f(&o.kind)).count() + } +} + +// ── Vektoren ───────────────────────────────────────────────────────────────── + +fn add(a: V, b: V) -> V { + (a.0 + b.0, a.1 + b.1) +} +fn sub(a: V, b: V) -> V { + (a.0 - b.0, a.1 - b.1) +} +fn mul(a: V, k: f64) -> V { + (a.0 * k, a.1 * k) +} +fn dot(a: V, b: V) -> f64 { + a.0 * b.0 + a.1 * b.1 +} +fn cross(a: V, b: V) -> f64 { + a.0 * b.1 - a.1 * b.0 +} +fn len(a: V) -> f64 { + hypot2(a.0, a.1) +} +fn fin(p: V) -> bool { + p.0.is_finite() && p.1.is_finite() +} + +fn polygon_area(r: &[V]) -> f64 { + let n = r.len(); + let mut s = 0.0; + for i in 0..n { + s += cross(r[i], r[(i + 1) % n]); + } + s / 2.0 +} + +fn point_in(r: &[V], p: V) -> bool { + let n = r.len(); + let mut inside = false; + let mut j = n.wrapping_sub(1); + for i in 0..n { + let (a, b) = (r[i], r[j]); + if (a.1 > p.1) != (b.1 > p.1) && p.0 < (b.0 - a.0) * (p.1 - a.1) / (b.1 - a.1) + a.0 { + inside = !inside; + } + j = i; + } + inside +} + +/// Winkel in [0, 2π). +fn wrap2pi(a: f64) -> f64 { + let mut x = a % (2.0 * PI); + if x < 0.0 { + x += 2.0 * PI; + } + if x >= 2.0 * PI - 1e-12 { + x = 0.0; + } + x +} + +// ── Layer- und Material-Hinweise ───────────────────────────────────────────── + +/// Layer-Namen, die Wände tragen (Teilwort, klein). +const WALL_WORDS: [&str; 6] = ["wand", "wände", "waende", "mauer", "wall", "murs"]; + +pub fn wallish_layer(name: &str) -> bool { + let l = name.to_lowercase(); + WALL_WORDS.iter().any(|w| l.contains(w)) +} + +/// Material-Gruppen: (Gruppe, Teilwörter, kurze Wörter nur als ganzes Wort). +const MATERIALS: [(&str, &[&str], &[&str]); 6] = [ + ("beton", &["beton", "concrete"], &["stb", "sb"]), + ("mauerwerk", &["mauerwerk", "backstein", "ziegel", "brick", "masonry"], &["mw", "bks"]), + ("kalksandstein", &["kalksand"], &["ks"]), + ("holz", &["holz", "wood", "timber"], &[]), + ("daemmung", &["dämm", "daemm", "insul"], &[]), + ("leichtbau", &["gips", "drywall", "leichtbau", "trockenbau"], &["gk", "gkb"]), +]; + +pub fn material_of(text: &str) -> Option<&'static str> { + let l = text.to_lowercase(); + let words: Vec<&str> = l.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).collect(); + MATERIALS.iter().find(|(_, long, short)| long.iter().any(|w| l.contains(w)) || words.iter().any(|w| short.contains(w))).map(|m| m.0) +} + +// ── Tessellierte Bögen ─────────────────────────────────────────────────────── + +/// Kreis durch drei Punkte (relativ zum ersten gerechnet: Landeskoordinaten bleiben genau). +fn circle3(a: V, b: V, c: V) -> Option<(V, f64)> { + let (b, c) = (sub(b, a), sub(c, a)); + let d = 2.0 * cross(b, c); + if d.abs() < 1e-12 { + return None; + } + let (b2, c2) = (dot(b, b), dot(c, c)); + let u = ((c.1 * b2 - b.1 * c2) / d, (b.0 * c2 - c.0 * b2) / d); + let r = len(u); + (r.is_finite() && fin(u)).then_some((add(a, u), r)) +} + +/// Grösste Kantenlänge und Drehung je Ecke eines tessellierten Bogens; Abstand der Ecken vom Kreis. +const TESS_MAX_EDGE: f64 = 2.0; +const TESS_MAX_TURN: f64 = 0.436_332_312_998_582_4; // 25° +const TESS_MIN_TURN: f64 = 0.003_490_658_503_988_659; // 0.2° +const TESS_TOL: f64 = 0.003; + +/// Linienzug (offen; geschlossen mit wiederholtem Anfang) in Strecken und Bögen: ≥ 3 kurze Kanten mit +/// gleichsinniger Drehung (0.2–25° je Ecke), deren Ecken auf einem Kreis liegen (± 3 mm, r ≤ 100 m), +/// werden ein Bogen (DXF-Exporte zerlegen Bögen oft in Sehnen). +fn fit_arcs(pts: &[V], layer: usize, segs: &mut Vec, arcs: &mut Vec) { + if pts.len() < 2 { + return; + } + let nseg = pts.len() - 1; + let short = |k: usize| len(sub(pts[k + 1], pts[k])) <= TESS_MAX_EDGE; + let turn = |k: usize| { + let (d1, d2) = (sub(pts[k + 1], pts[k]), sub(pts[k + 2], pts[k + 1])); + atan2(cross(d1, d2), dot(d1, d2)) + }; + let mut i = 0; + while i < nseg { + let mut j = i; + if short(i) && i + 1 < nseg { + let t0 = turn(i); + if (TESS_MIN_TURN..=TESS_MAX_TURN).contains(&t0.abs()) { + while j + 1 < nseg && short(j + 1) { + let t = turn(j); + if t * t0 <= 0.0 || !(TESS_MIN_TURN..=TESS_MAX_TURN).contains(&t.abs()) { + break; + } + j += 1; + } + } + if j - i + 1 >= 3 { + if let Some(arc) = fit_run(&pts[i..=j + 1], t0, layer) { + arcs.push(arc); + i = j + 1; + continue; + } + } + } + segs.push(Seg { a: pts[i], b: pts[i + 1], layer }); + i += 1; + } +} + +fn fit_run(p: &[V], turn: f64, layer: usize) -> Option { + let (s, e) = (p[0], p[p.len() - 1]); + let (c, r) = circle3(s, p[p.len() / 2], e)?; + if r > 100.0 || p.iter().any(|q| (len(sub(*q, c)) - r).abs() > TESS_TOL) { + return None; + } + let ang = |q: V| wrap2pi(atan2(q.1 - c.1, q.0 - c.0)); + let (from, to) = if turn > 0.0 { (s, e) } else { (e, s) }; + let a0 = ang(from); + let mut sweep = wrap2pi(ang(to) - a0); + if sweep < 1e-9 { + sweep = 2.0 * PI; + } + Some(ArcIn { c, r, a0, sweep, layer }) +} + +// ── Einlesen aus dem Projekt ───────────────────────────────────────────────── + +fn flatten_names(list: &[LayerCategory], out: &mut HashMap) { + for c in list { + out.insert(c.code.clone(), c.name.clone()); + if let Some(ch) = &c.children { + flatten_names(ch, out); + } + } +} + +/// Bogen aus einer Polylinien-Kante mit Modell-Bulge (gegen den Uhrzeigersinn normalisiert). +fn bulge_arc(a: V, b: V, bulge: f64, layer: usize) -> Option { + let k = kernel2d::bulge_arc(kernel2d::Vec2::new(a.0, a.1), kernel2d::Vec2::new(b.0, b.1), bulge)?; + if !(k.r.is_finite() && k.r > 1e-6 && k.sweep.is_finite()) { + return None; + } + let (a0, sweep) = if k.sweep >= 0.0 { (k.a0, k.sweep) } else { (k.a0 + k.sweep, -k.sweep) }; + Some(ArcIn { c: (k.center.x, k.center.y), r: k.r, a0: wrap2pi(a0), sweep, layer }) +} + +/// Linien, Bögen, Texte und Füllungen der Zeichnungen: `ids` (Auswahl) oder alle der Ebene `level`. +pub fn collect(p: &Project, level: &str, ids: &[String]) -> Input { + let mut names = HashMap::new(); + flatten_names(&p.layers, &mut names); + let hatch_names: HashMap<&str, &str> = p.hatches.iter().map(|h| (h.id.as_str(), h.name.as_str())).collect(); + let mut inp = Input::default(); + let pick: std::collections::HashSet<&str> = ids.iter().map(String::as_str).collect(); + for d in &p.drawings2d { + if if pick.is_empty() { d.level_id != level } else { !pick.contains(d.id.as_str()) } { + continue; + } + let lname = names.get(&d.category_code).cloned().unwrap_or_else(|| d.category_code.clone()); + let layer = inp.layer(&lname); + let filled = d.fill_color.is_some() || d.hatch_id.is_some() || d.background.is_some(); + let hatch = d.hatch_id.as_deref().and_then(|h| hatch_names.get(h)).map(|s| s.to_string()); + let fill = |inp: &mut Input, ring: Vec| { + if filled && ring.len() >= 3 { + inp.fills.push(FillIn { ring, layer, hatch: hatch.clone() }); + } + }; + match &d.geom { + Drawing2DGeom::Line { a, b } => inp.segs.push(Seg { a: (a.x, a.y), b: (b.x, b.y), layer }), + Drawing2DGeom::Polyline { pts, closed, bulge, .. } if bulge.as_ref().is_none_or(|b| b.iter().all(|x| !(x.abs() > 1e-9))) => { + let mut v: Vec = pts.iter().map(|q| (q.x, q.y)).collect(); + if *closed && v.len() >= 3 { + v.push(v[0]); + } + fit_arcs(&v, layer, &mut inp.segs, &mut inp.arcs); + if *closed { + fill(&mut inp, pts.iter().map(|q| (q.x, q.y)).collect()); + } + } + Drawing2DGeom::Polyline { pts, closed, bulge, .. } => { + let n = pts.len(); + let m = if *closed { n } else { n.saturating_sub(1) }; + for i in 0..m { + let (a, b) = ((pts[i].x, pts[i].y), (pts[(i + 1) % n].x, pts[(i + 1) % n].y)); + let bl = bulge.as_ref().and_then(|v| v.get(i).copied()).filter(|b| b.is_finite() && b.abs() > 1e-9); + match bl.and_then(|bl| bulge_arc(a, b, bl, layer)) { + Some(arc) => inp.arcs.push(arc), + None => inp.segs.push(Seg { a, b, layer }), + } + } + if *closed { + fill(&mut inp, pts.iter().map(|q| (q.x, q.y)).collect()); + } + } + Drawing2DGeom::Rect { min, max } => { + let c = [(min.x, min.y), (max.x, min.y), (max.x, max.y), (min.x, max.y)]; + for i in 0..4 { + inp.segs.push(Seg { a: c[i], b: c[(i + 1) % 4], layer }); + } + fill(&mut inp, c.to_vec()); + } + Drawing2DGeom::Arc { center, r, a0, a1 } => { + let mut sweep = a1 - a0; + while sweep <= 0.0 && sweep.is_finite() { + sweep += 2.0 * PI; + } + if r.is_finite() && *r > 1e-6 && sweep.is_finite() && a0.is_finite() { + inp.arcs.push(ArcIn { c: (center.x, center.y), r: *r, a0: wrap2pi(*a0), sweep: sweep.min(2.0 * PI), layer }); + } + } + Drawing2DGeom::Circle { center, r } => { + if r.is_finite() && *r > 1e-6 { + inp.arcs.push(ArcIn { c: (center.x, center.y), r: *r, a0: 0.0, sweep: 2.0 * PI, layer }); + } + } + Drawing2DGeom::Text { at, text, height, angle, .. } => { + inp.texts.push(TextIn { at: (at.x, at.y), text: text.clone(), h: *height, angle: *angle }); + } + _ => {} + } + } + inp.segs.retain(|s| fin(s.a) && fin(s.b) && len(sub(s.b, s.a)) > 1e-4); + inp.arcs.retain(|a| fin(a.c) && a.r.is_finite() && a.a0.is_finite()); + inp.texts.retain(|t| fin(t.at) && !t.text.trim().is_empty()); + inp +} + +// ── 1. Linien bündeln ──────────────────────────────────────────────────────── + +/// Linie im Rahmen ihres Richtungs-Bündels. +#[derive(Clone, Debug)] +struct Line { + cl: usize, + c: f64, + t0: f64, + t1: f64, + layer: usize, + wallish: bool, +} + +#[derive(Clone, Copy, Debug)] +struct Frame { + u: V, + n: V, +} + +impl Frame { + fn of_angle(th: f64) -> Frame { + let u = (cos(th), sin(th)); + Frame { u, n: (-u.1, u.0) } + } + fn at(&self, c: f64, t: f64) -> V { + add(mul(self.n, c), mul(self.u, t)) + } +} + +/// Richtungs-Bündel: Rahmen je Bündel, Bündel je Strecke. +fn bundle(segs: &[(V, V)]) -> (Vec, Vec) { + let ang: Vec = segs + .iter() + .map(|(a, b)| { + let mut th = atan2(b.1 - a.1, b.0 - a.0); + if th < 0.0 { + th += PI; + } + if th >= PI - 1e-12 { + th -= PI; + } + th + }) + .collect(); + let mut idx: Vec = (0..segs.len()).collect(); + idx.sort_by(|&i, &j| ang[i].total_cmp(&ang[j])); + let mut cl_of = vec![0usize; segs.len()]; + let mut starts: Vec = Vec::new(); + let mut prev = f64::NEG_INFINITY; + for &i in &idx { + let th = ang[i]; + if starts.is_empty() || th - prev > ANG_CHAIN || th - starts[starts.len() - 1] > PAR_TOL { + starts.push(th); + } + cl_of[i] = starts.len() - 1; + prev = th; + } + // Rundum: Bündel knapp unter π gehört zum Bündel bei 0. + if starts.len() > 1 && starts[0] < ANG_CHAIN { + let last = starts.len() - 1; + let max_last = idx.iter().filter(|&&i| cl_of[i] == last).map(|&i| ang[i]).fold(0.0, f64::max); + if max_last > PI - ANG_CHAIN && max_last - starts[last] < PAR_TOL { + for c in cl_of.iter_mut() { + if *c == last { + *c = 0; + } + } + starts.pop(); + } + } + (starts.iter().map(|&th| Frame::of_angle(th)).collect(), cl_of) +} + +/// Strecken auf ihr Bündel projizieren und deckungsgleiche verschmelzen. +fn lines_of(segs: &[Seg], wallish: &[bool], frames: &[Frame], cl_of: &[usize]) -> Vec { + let mut raw: Vec = segs + .iter() + .enumerate() + .map(|(i, s)| { + let f = frames[cl_of[i]]; + let (ta, tb) = (dot(f.u, s.a), dot(f.u, s.b)); + Line { cl: cl_of[i], c: (dot(f.n, s.a) + dot(f.n, s.b)) / 2.0, t0: ta.min(tb), t1: ta.max(tb), layer: s.layer, wallish: wallish[s.layer] } + }) + .collect(); + raw.sort_by(|a, b| a.cl.cmp(&b.cl).then(a.c.total_cmp(&b.c))); + let mut out = Vec::new(); + let mut i = 0; + while i < raw.len() { + let mut j = i + 1; + while j < raw.len() && raw[j].cl == raw[i].cl && raw[j].c - raw[j - 1].c <= COL_TOL && raw[j].c - raw[i].c <= 2.0 * COL_TOL { + j += 1; + } + let mut g: Vec = raw[i..j].to_vec(); + g.sort_by(|a, b| a.t0.total_cmp(&b.t0)); + let mut cur = g[0].clone(); + for l in g.into_iter().skip(1) { + let joins = l.t0 <= cur.t1 - 1e-3 || (l.t0 <= cur.t1 + 1e-3 && l.layer == cur.layer); + if joins { + cur.t1 = cur.t1.max(l.t1); + if l.wallish && !cur.wallish { + cur.layer = l.layer; + cur.wallish = true; + } + } else { + out.push(std::mem::replace(&mut cur, l)); + } + } + out.push(cur); + i = j; + } + out +} + +// ── Intervalle ─────────────────────────────────────────────────────────────── + +/// Vereinigung (sortiert, verschmolzen). +fn union(mut iv: Vec<(f64, f64)>) -> Vec<(f64, f64)> { + iv.retain(|i| i.1 > i.0); + iv.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut out: Vec<(f64, f64)> = Vec::new(); + for i in iv { + match out.last_mut() { + Some(l) if i.0 <= l.1 + 1e-6 => l.1 = l.1.max(i.1), + _ => out.push(i), + } + } + out +} + +/// `[a, b]` ohne die Intervalle `used` (vereinigt). +fn subtract(a: f64, b: f64, used: &[(f64, f64)]) -> Vec<(f64, f64)> { + let mut out = Vec::new(); + let mut cur = a; + for &(u0, u1) in used { + if u1 <= cur { + continue; + } + if u0 >= b { + break; + } + if u0 > cur { + out.push((cur, u0.min(b))); + } + cur = cur.max(u1); + if cur >= b { + break; + } + } + if cur < b { + out.push((cur, b)); + } + out +} + +// ── 2. Wandpaare ───────────────────────────────────────────────────────────── + +#[derive(Clone, Debug)] +struct Piece { + cl: usize, + /// Untere / obere Linie (nach `c`). + lo: usize, + hi: usize, + c: f64, + t: f64, + s0: f64, + s1: f64, + filled: bool, + material: Option<&'static str>, +} + +struct Ctx2<'a> { + inp: &'a Input, + frames: Vec, + lines: Vec, + /// Alle Strecken (alle Layer) mit ihrem Bündel, für die Fenster-Hinweise. + all: Vec<(V, V)>, + /// Bögen, die eine Tür sein können (nicht als Wand verwendet). + door_arcs: Vec, +} + +fn fill_at(inp: &Input, p: V) -> Option<&FillIn> { + inp.fills.iter().find(|f| { + let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for q in &f.ring { + x0 = x0.min(q.0); + y0 = y0.min(q.1); + x1 = x1.max(q.0); + y1 = y1.max(q.1); + } + p.0 >= x0 && p.0 <= x1 && p.1 >= y0 && p.1 <= y1 && point_in(&f.ring, p) + }) +} + +fn pieces(cx: &Ctx2) -> Vec { + struct Cand { + i: usize, + j: usize, + d: f64, + t0: f64, + t1: f64, + filled: bool, + material: Option<&'static str>, + } + let lines = &cx.lines; + let mut by_cl: Vec> = vec![Vec::new(); cx.frames.len()]; + for (i, l) in lines.iter().enumerate() { + by_cl[l.cl].push(i); + } + let mut cands = Vec::new(); + for (cl, ids) in by_cl.iter_mut().enumerate() { + ids.sort_by(|&a, &b| lines[a].c.total_cmp(&lines[b].c)); + let f = cx.frames[cl]; + for (k, &i) in ids.iter().enumerate() { + let li = &lines[i]; + for &j in &ids[k + 1..] { + let lj = &lines[j]; + let d = lj.c - li.c; + if d > MAX_THICK + 1e-3 { + break; + } + if d < MIN_THICK - 1e-3 { + continue; + } + let (t0, t1) = (li.t0.max(lj.t0), li.t1.min(lj.t1)); + let ov = t1 - t0; + if ov < MIN_PIECE || ov < 0.5 * (li.t1 - li.t0).min(lj.t1 - lj.t0) - 1e-9 { + continue; + } + let mid = f.at(li.c + d / 2.0, (t0 + t1) / 2.0); + let fill = fill_at(cx.inp, mid); + let material = fill + .and_then(|f| f.hatch.as_deref().and_then(material_of).or_else(|| material_of(&cx.inp.layers[f.layer]))) + .or_else(|| material_of(&cx.inp.layers[li.layer])) + .or_else(|| material_of(&cx.inp.layers[lj.layer])); + cands.push(Cand { i, j, d, t0, t1, filled: fill.is_some(), material }); + } + } + } + cands.sort_by(|a, b| (!a.filled).cmp(&!b.filled).then(a.d.total_cmp(&b.d)).then((b.t1 - b.t0).total_cmp(&(a.t1 - a.t0)))); + // Belegung je Linie und Seite: 0 = oben (+n), 1 = unten (−n). + let mut used: Vec<[Vec<(f64, f64)>; 2]> = vec![[Vec::new(), Vec::new()]; lines.len()]; + let mut out = Vec::new(); + for c in cands { + let mut busy = used[c.i][0].clone(); + busy.extend(used[c.j][1].iter().copied()); + let busy = union(busy); + let free = subtract(c.t0, c.t1, &busy); + for (s0, s1) in free.into_iter().filter(|f| f.1 - f.0 >= MIN_PIECE) { + used[c.i][0].push((s0, s1)); + used[c.j][1].push((s0, s1)); + used[c.i][0] = union(std::mem::take(&mut used[c.i][0])); + used[c.j][1] = union(std::mem::take(&mut used[c.j][1])); + out.push(Piece { cl: lines[c.i].cl, lo: c.i, hi: c.j, c: lines[c.i].c + c.d / 2.0, t: c.d, s0, s1, filled: c.filled, material: c.material }); + } + } + stack(out, lines) +} + +/// Drei Linien übereinander (Schicht-/Achslinie): Paare unten–Mitte und Mitte–oben → eine Wand. +fn stack(mut ps: Vec, lines: &[Line]) -> Vec { + loop { + let mut found = None; + 'outer: for (a, p) in ps.iter().enumerate() { + for (b, q) in ps.iter().enumerate() { + if a == b || q.lo != p.hi || q.cl != p.cl || p.t + q.t > MAX_THICK + 1e-3 { + continue; + } + // Nur Schichten über (fast) dieselbe Strecke: der Abschluss einer anstossenden Wand (kurze + // Querlinie) ist keine Schichtlinie. + let (s0, s1) = (p.s0.max(q.s0), p.s1.min(q.s1)); + if s1 - s0 >= MIN_PIECE && s1 - s0 >= 0.5 * (p.s1 - p.s0).max(q.s1 - q.s0) { + found = Some((a, b, s0, s1)); + break 'outer; + } + } + } + let Some((a, b, s0, s1)) = found else { return ps }; + let (p, q) = (ps[a].clone(), ps[b].clone()); + let (clo, chi) = (lines[p.lo].c, lines[q.hi].c); + let mut add = vec![Piece { + cl: p.cl, + lo: p.lo, + hi: q.hi, + c: (clo + chi) / 2.0, + t: chi - clo, + s0, + s1, + filled: p.filled || q.filled, + material: p.material.or(q.material), + }]; + // Reste ausserhalb der gemeinsamen Strecke nur, wenn sie wie eigene Wände lang sind. + for r in [&p, &q] { + for (r0, r1) in [(r.s0, s0), (s1, r.s1)] { + if r1 - r0 >= 0.5 { + add.push(Piece { s0: r0, s1: r1, ..r.clone() }); + } + } + } + let (hi, lo) = (a.max(b), a.min(b)); + ps.remove(hi); + ps.remove(lo); + ps.extend(add); + } +} + +// ── Hinweise in einer Lücke ────────────────────────────────────────────────── + +/// Türbogen? (Öffnungswinkel 50–130°, Radius 0.3–2 m.) +fn door_like(a: &ArcIn) -> bool { + a.sweep >= 50f64.to_radians() && a.sweep <= 130f64.to_radians() && a.r >= 0.3 && a.r <= 2.0 +} + +fn arc_mid(a: &ArcIn) -> V { + let m = a.a0 + a.sweep / 2.0; + add(a.c, (a.r * cos(m), a.r * sin(m))) +} + +/// Wand-Rahmen einer Lücke: Ursprung `o`, Richtung `u`, Normale `n`, Achse bei n = 0. +#[derive(Clone, Copy)] +struct Band { + o: V, + u: V, + n: V, + t: f64, +} + +impl Band { + fn st(&self, p: V) -> (f64, f64) { + let d = sub(p, self.o); + (dot(d, self.u), dot(d, self.n)) + } +} + +/// Türbögen an der Lücke `[g0, g1]`: (Bogen, am Anfang?, ganze Breite?). +fn door_arcs_at(cx: &Ctx2, b: &Band, g0: f64, g1: f64) -> Vec<(usize, bool, bool)> { + let w = g1 - g0; + let mut out = Vec::new(); + for &k in &cx.door_arcs { + let a = &cx.inp.arcs[k]; + let (sc, nc) = b.st(a.c); + if nc.abs() > b.t / 2.0 + 0.15 { + continue; + } + let at_start = (sc - g0).abs() <= 0.15; + let at_end = (sc - g1).abs() <= 0.15; + if !(at_start || at_end) { + continue; + } + let full = (a.r - w).abs() <= 0.12 * w + 0.05; + let half = (a.r - w / 2.0).abs() <= 0.06 * w + 0.05; + if full || half { + out.push((k, at_start && (!at_end || (sc - g0).abs() <= (sc - g1).abs()), full)); + } + } + out +} + +/// Fensterlinien: parallel zur Wand, im Band (nicht auf den Wandflächen), über ≥ 50 % der Lücke. +fn window_lines_at(cx: &Ctx2, b: &Band, g0: f64, g1: f64) -> usize { + let w = g1 - g0; + let sin_tol = PAR_TOL.sin(); + cx.all + .iter() + .filter(|(p, q)| { + let d = sub(*q, *p); + let l = len(d); + if l < 1e-6 || cross(mul(d, 1.0 / l), b.u).abs() > sin_tol { + return false; + } + let ((s0, n0), (s1, n1)) = (b.st(*p), b.st(*q)); + let n = (n0 + n1) / 2.0; + let ov = s0.max(s1).min(g1) - s0.min(s1).max(g0); + // Nicht viel länger als die Lücke (keine durchlaufende Achs-/Deckenlinie). + n.abs() < b.t / 2.0 - 0.005 && ov >= 0.5 * w && l <= w + 0.4 + }) + .count() +} + +fn evidence(cx: &Ctx2, b: &Band, g0: f64, g1: f64) -> bool { + !door_arcs_at(cx, b, g0, g1).is_empty() || window_lines_at(cx, b, g0, g1) > 0 +} + +// ── 3. Läufe ───────────────────────────────────────────────────────────────── + +#[derive(Clone, Debug)] +struct Run { + cl: usize, + c: f64, + t: f64, + s0: f64, + s1: f64, + cover: Vec<(f64, f64)>, + filled: bool, + material: Option<&'static str>, +} + +fn runs(cx: &Ctx2, mut ps: Vec) -> Vec { + ps.sort_by(|a, b| a.cl.cmp(&b.cl).then(a.c.total_cmp(&b.c))); + // Gruppen gleicher Achse und Dicke. + let mut groups: Vec> = Vec::new(); + for p in ps { + match groups.iter_mut().rev().take_while(|g| g[0].cl == p.cl && p.c - g[0].c <= 0.01).find(|g| (g[0].t - p.t).abs() <= 0.006) { + Some(g) => g.push(p), + None => groups.push(vec![p]), + } + } + let mut out: Vec = Vec::new(); + for mut g in groups { + g.sort_by(|a, b| a.s0.total_cmp(&b.s0)); + let f = cx.frames[g[0].cl]; + let mk = |p: &Piece| Run { cl: p.cl, c: p.c, t: p.t, s0: p.s0, s1: p.s1, cover: vec![(p.s0, p.s1)], filled: p.filled, material: p.material }; + let mut cur = mk(&g[0]); + for p in g.iter().skip(1) { + let gap = p.s0 - cur.s1; + let band = Band { o: f.at(cur.c, 0.0), u: f.u, n: f.n, t: cur.t }; + let merge = gap <= GAP_FREE || (gap <= GAP_MAX && evidence(cx, &band, cur.s1, p.s0)); + if merge { + cur.s1 = cur.s1.max(p.s1); + cur.cover.push((p.s0, p.s1)); + cur.filled |= p.filled; + cur.material = cur.material.or(p.material); + } else { + out.push(std::mem::replace(&mut cur, mk(p))); + } + } + out.push(cur); + } + // Was ganz im Band einer grösseren Wand liegt, entfällt: Fensterrahmen/Brüstung (dünn, gleiche Richtung) + // und Scheinpaare aus Abschlusslinien anstossender oder durchlaufender Wände (quer). + let corners = |r: &Run| -> [V; 4] { + let f = cx.frames[r.cl]; + let h = r.t / 2.0; + [f.at(r.c - h, r.s0), f.at(r.c + h, r.s0), f.at(r.c + h, r.s1), f.at(r.c - h, r.s1)] + }; + let inside = |p: V, q: &Run| { + let f = cx.frames[q.cl]; + let (s, n) = (dot(p, f.u), dot(p, f.n) - q.c); + s >= q.s0 - 0.005 && s <= q.s1 + 0.005 && n.abs() <= q.t / 2.0 + 0.005 + }; + let area = |r: &Run| r.t * (r.s1 - r.s0); + let keep: Vec = out + .iter() + .enumerate() + .map(|(i, r)| !out.iter().enumerate().any(|(j, q)| j != i && area(q) > area(r) + 1e-9 && corners(r).iter().all(|p| inside(*p, q)))) + .collect(); + out.into_iter().zip(keep).filter(|(_, k)| *k).map(|(r, _)| r).collect() +} + +// ── 4. Stösse ──────────────────────────────────────────────────────────────── + +#[derive(Clone, Debug)] +struct W { + a: V, + b: V, + t: f64, + /// Gedeckte Strecken auf der Achse (Weltpunkte). + cover: Vec<(V, V)>, + filled: bool, + material: Option<&'static str>, +} + +impl W { + fn dir(&self) -> V { + let d = sub(self.b, self.a); + mul(d, 1.0 / len(d)) + } + fn length(&self) -> f64 { + len(sub(self.b, self.a)) + } + fn band(&self) -> Band { + let u = self.dir(); + Band { o: self.a, u, n: (-u.1, u.0), t: self.t } + } +} + +/// Schnitt der Achsen: (λ auf `w` ab `p` in Richtung `u`, μ auf `q` ab `q.a`). +fn intersect(p: V, u: V, q: &W) -> Option<(f64, f64)> { + let uq = q.dir(); + let den = cross(u, uq); + if !(den.abs() >= PAR_TOL.sin() * 10.0) { + return None; + } + let d = sub(q.a, p); + Some((cross(d, uq) / den, cross(d, u) / den)) +} + +fn join(cx: &Ctx2, ws: &mut [W]) { + let n = ws.len(); + let mut target: Vec<[Option; 2]> = vec![[None, None]; n]; + for i in 0..n { + if !(ws[i].length() > 1e-6) { + continue; + } + for e in 0..2 { + let w = &ws[i]; + let u = w.dir(); + let (p, out) = if e == 0 { (w.a, mul(u, -1.0)) } else { (w.b, u) }; + let mut best: Option<(f64, V)> = None; + for (j, q) in ws.iter().enumerate() { + if j == i || !(q.length() > 1e-6) { + continue; + } + let Some((lam, mu)) = intersect(p, out, q) else { continue }; + // Am Kreuz- oder T-Stoss enden auch die anderen Wände an Flächen: Spiel bis halbe Höchstdicke. + let ql = q.length(); + if mu < -(MAX_THICK / 2.0 + 0.05) || mu > ql + MAX_THICK / 2.0 + 0.05 { + continue; + } + let reach = q.t / 2.0 + 0.05; + let ok = if lam.abs() <= reach { + true + } else if lam > reach && lam <= q.t / 2.0 + GAP_MAX { + // Tür/Fenster in der Ecke: Lücke zwischen Wandende und Fläche der anderen Wand. + let b = w.band(); + let (g0, g1) = if e == 0 { (-(lam - q.t / 2.0), 0.0) } else { (w.length(), w.length() + lam - q.t / 2.0) }; + g1 - g0 >= MIN_OPENING && evidence(cx, &b, g0, g1) + } else { + false + }; + if ok && best.is_none_or(|(l, _)| lam.abs() < l) { + best = Some((lam.abs(), add(p, mul(out, lam)))); + } + } + target[i][e] = best.map(|b| b.1); + } + } + for (w, t) in ws.iter_mut().zip(target) { + if let Some(a) = t[0] { + w.a = a; + } + if let Some(b) = t[1] { + w.b = b; + } + } +} + +/// Kreuzende/anstossende Wände decken ihr Band auf der Achse der anderen. +fn cross_cover(ws: &mut [W]) { + let n = ws.len(); + let mut add_cov: Vec> = vec![Vec::new(); n]; + for i in 0..n { + for j in i + 1..n { + let (wi, wj) = (&ws[i], &ws[j]); + let ui = wi.dir(); + let Some((lam, mu)) = intersect(wi.a, ui, wj) else { continue }; + let tol = 1e-3; + if lam < -tol - wj.t / 2.0 || lam > wi.length() + tol + wj.t / 2.0 || mu < -tol - wi.t / 2.0 || mu > wj.length() + tol + wi.t / 2.0 { + continue; + } + let sin = cross(ui, wj.dir()).abs(); + let x = add(wi.a, mul(ui, lam)); + let hi = wj.t / 2.0 / sin; + add_cov[i].push((add(x, mul(ui, -hi)), add(x, mul(ui, hi)))); + let uj = wj.dir(); + let hj = wi.t / 2.0 / sin; + add_cov[j].push((add(x, mul(uj, -hj)), add(x, mul(uj, hj)))); + } + } + for (w, c) in ws.iter_mut().zip(add_cov) { + w.cover.extend(c); + } +} + +// ── Bogenwände ─────────────────────────────────────────────────────────────── + +/// Konzentrische Bogenpaare → Bogenwände; gibt die verwendeten Bögen zurück. +/// Bogenwand: Achse als Kreisbogen gegen den Uhrzeigersinn. +#[derive(Clone, Debug)] +struct ArcW { + c: V, + r: f64, + a0: f64, + sweep: f64, + t: f64, + material: Option<&'static str>, + filled: bool, +} + +impl ArcW { + fn at(&self, a: f64) -> V { + add(self.c, (self.r * cos(a), self.r * sin(a))) + } + fn wall(&self) -> RWall { + let snap = |p: V| ((p.0 * 1e6).round() / 1e6, (p.1 * 1e6).round() / 1e6); + // Gegen den Uhrzeigersinn = negativer Modell-Bulge. + RWall { + a: snap(self.at(self.a0)), + b: snap(self.at(self.a0 + self.sweep)), + bulge: Some(-tan(self.sweep / 4.0)), + t: (self.t * 1e6).round() / 1e6, + material: self.material, + filled: self.filled, + } + } +} + +/// Gerade Wandenden auf die Achse einer Bogenwand ziehen (Ende im Band ± 5 cm, nahe einem Bogenende); das +/// Bogenende rückt auf denselben Punkt. +fn join_arcs(ws: &mut [W], arcs: &mut [ArcW]) { + for w in ws.iter_mut() { + if !(w.length() > 1e-6) { + continue; + } + for e in 0..2 { + let u = w.dir(); + let (p, out) = if e == 0 { (w.a, mul(u, -1.0)) } else { (w.b, u) }; + let mut best: Option<(f64, usize, f64, V)> = None; + for (k, a) in arcs.iter().enumerate() { + // Gerade p + λ·out mit dem Kreis |x − c| = r. + let f = sub(p, a.c); + let (bq, cq) = (dot(f, out), dot(f, f) - a.r * a.r); + let disc = bq * bq - cq; + if disc < 0.0 { + continue; + } + for lam in [-bq - disc.sqrt(), -bq + disc.sqrt()] { + if !(lam.abs() <= a.t / 2.0 + 0.05) { + continue; + } + let x = add(p, mul(out, lam)); + let ang = wrap2pi(atan2(x.1 - a.c.1, x.0 - a.c.0)); + // Winkel-Abstand zum nächsten Bogenende (als Bogenlänge). + let d0 = wrap2pi(a.a0 - ang).min(wrap2pi(ang - a.a0)); + let e1 = a.a0 + a.sweep; + let d1 = wrap2pi(e1 - ang).min(wrap2pi(ang - e1)); + if d0.min(d1) * a.r > w.t / 2.0 + 0.3 { + continue; + } + if best.is_none_or(|b| lam.abs() < b.0) { + best = Some((lam.abs(), k, ang, x)); + } + } + } + let Some((_, k, ang, x)) = best else { continue }; + if e == 0 { + w.a = x; + } else { + w.b = x; + } + let a = &mut arcs[k]; + let e1 = a.a0 + a.sweep; + let d0 = wrap2pi(a.a0 - ang).min(wrap2pi(ang - a.a0)); + let d1 = wrap2pi(e1 - ang).min(wrap2pi(ang - e1)); + if d0 <= d1 { + // Anfang verschieben, Ende bleibt. + let delta = wrap2pi(ang - a.a0 + PI) - PI; + a.a0 = wrap2pi(ang); + a.sweep -= delta; + } else { + let delta = wrap2pi(ang - e1 + PI) - PI; + a.sweep += delta; + } + } + } +} + +/// Bogenstücke derselben Achse (Mittelpunkt ± 1 cm, Radius ± 5 mm, gleiche Dicke) mit Lücke bis 1.5 m (bis +/// 4 m mit Fensterbogen darin) werden eine Bogenwand; die Lücken Öffnungen (Lage und Breite als Bogenlänge auf +/// der Achse): konzentrische Bögen im Band → Fenster, sonst Wanddurchbruch. Rückgabe: Wände und Öffnungen +/// (Index der Wand, Lage, Breite, Art). +#[allow(clippy::type_complexity)] +fn merge_arc_walls(inp: &Input, arcs: Vec, used: &[bool]) -> (Vec, Vec<(usize, f64, f64, RKind)>) { + let mut groups: Vec> = Vec::new(); + for a in arcs { + match groups.iter_mut().find(|g| len(sub(g[0].c, a.c)) <= 0.01 && (g[0].r - a.r).abs() <= 0.005 && (g[0].t - a.t).abs() <= 0.006) { + Some(g) => g.push(a), + None => groups.push(vec![a]), + } + } + // Fensterbogen in der Lücke [g0, g1] (Winkel, gegen den Uhrzeigersinn) der Achse `w`? + let window_in = |w: &ArcW, g0: f64, g1: f64| { + inp.arcs.iter().enumerate().any(|(k, a)| { + if used.get(k).copied().unwrap_or(false) || len(sub(a.c, w.c)) > 0.01 || (a.r - w.r).abs() >= w.t / 2.0 - 0.005 { + return false; + } + let gap = g1 - g0; + let off = wrap2pi(a.a0 - g0); + let ov = [off, off - 2.0 * PI].iter().map(|o| (o + a.sweep).min(gap) - o.max(0.0)).fold(0.0, f64::max); + ov >= 0.5 * gap + }) + }; + let mut walls = Vec::new(); + let mut openings = Vec::new(); + for mut g in groups { + g.sort_by(|a, b| a.a0.total_cmp(&b.a0)); + // Beim grössten Zwischenraum beginnen (Kreis). + let n = g.len(); + let gap_after = |i: usize| wrap2pi(g[(i + 1) % n].a0 - (g[i].a0 + g[i].sweep)); + let start = if n > 1 { (0..n).max_by(|&i, &j| gap_after(i).total_cmp(&gap_after(j))).map_or(0, |i| (i + 1) % n) } else { 0 }; + g.rotate_left(start); + let mut cur = g[0].clone(); + let mut gaps: Vec<(f64, f64)> = Vec::new(); + let flush = |cur: &ArcW, gaps: &mut Vec<(f64, f64)>, walls: &mut Vec, openings: &mut Vec<(usize, f64, f64, RKind)>| { + let k = walls.len(); + for (g0, g1) in gaps.drain(..) { + let kind = if window_in(cur, g0, g1) { RKind::Window } else { RKind::Void }; + let r6 = |x: f64| (x * 1e6).round() / 1e6; + openings.push((k, r6((g0 - cur.a0) * cur.r), r6((g1 - g0) * cur.r), kind)); + } + walls.push(cur.clone()); + }; + for a in g.into_iter().skip(1) { + let end = cur.a0 + cur.sweep; + let gap = wrap2pi(a.a0 - end); + let total = cur.sweep + gap + a.sweep; + let len_gap = gap * cur.r; + let merge = total < 2.0 * PI - 1e-6 && (len_gap <= GAP_FREE || (len_gap <= GAP_MAX && window_in(&cur, end, end + gap))); + if merge { + if len_gap >= MIN_OPENING { + gaps.push((end, end + gap)); + } + cur.sweep = total; + cur.filled |= a.filled; + cur.material = cur.material.or(a.material); + } else { + flush(&cur, &mut gaps, &mut walls, &mut openings); + cur = a; + } + } + flush(&cur, &mut gaps, &mut walls, &mut openings); + } + (walls, openings) +} + +fn arc_walls(inp: &Input, use_arc: &[bool], out: &mut Vec) -> Vec { + let arcs = &inp.arcs; + let mut used = vec![false; arcs.len()]; + if arcs.len() > MAX_ARCS { + return used; + } + let mut cands = Vec::new(); + for i in 0..arcs.len() { + for j in 0..arcs.len() { + let (a, b) = (&arcs[i], &arcs[j]); + if !use_arc[i] || !use_arc[j] || b.r <= a.r || len(sub(a.c, b.c)) > 0.01 { + continue; + } + let d = b.r - a.r; + if !(MIN_THICK - 1e-3..=MAX_THICK + 1e-3).contains(&d) { + continue; + } + // Gemeinsamer Winkelbereich (Kreisintervalle). + let shift = wrap2pi(b.a0 - a.a0); + let mut best = (0.0, 0.0); + for off in [shift, shift - 2.0 * PI] { + let (s0, s1) = (off.max(0.0), (off + b.sweep).min(a.sweep)); + if s1 - s0 > best.1 - best.0 { + best = (s0, s1); + } + } + let ov = best.1 - best.0; + let rm = (a.r + b.r) / 2.0; + if ov * rm < MIN_PIECE || ov < 0.5 * a.sweep.min(b.sweep) - 1e-9 { + continue; + } + cands.push((d, i, j, a.a0 + best.0, ov)); + } + } + cands.sort_by(|x, y| x.0.total_cmp(&y.0)); + for (d, i, j, a0, sweep) in cands { + if used[i] || used[j] { + continue; + } + used[i] = true; + used[j] = true; + let (c, r) = (arcs[i].c, arcs[i].r + d / 2.0); + // Vollkreis: zwei Halbbögen (Anfang ≠ Ende). + let parts = if sweep > 2.0 * PI - 1e-3 { vec![(a0, PI), (a0 + PI, PI)] } else { vec![(a0, sweep)] }; + for (s, sw) in parts { + let material = material_of(&inp.layers[arcs[i].layer]).or_else(|| material_of(&inp.layers[arcs[j].layer])); + let mid = s + sw / 2.0; + let filled = fill_at(inp, add(c, (r * cos(mid), r * sin(mid)))).is_some(); + out.push(ArcW { c, r, a0: wrap2pi(s), sweep: sw, t: d, material, filled }); + } + } + used +} + +// ── Räume ──────────────────────────────────────────────────────────────────── + +const SIA: [&str; 6] = ["HNF", "NNF", "VF", "FF", "KGF", "AGF"]; + +/// Flächenangabe („17.01 m²“, „17,0 m2“, „17 qm“). +pub fn parse_area(text: &str) -> Option { + let t = text.trim(); + let l = t.to_lowercase(); + let k = ["m²", "m2", "qm"].iter().filter_map(|u| l.find(u)).min()?; + let num: String = l[..k].trim().chars().rev().take_while(|c| c.is_ascii_digit() || *c == '.' || *c == ',' || *c == '\'').collect::>().into_iter().rev().collect(); + let v: f64 = num.replace('\'', "").replace(',', ".").parse().ok()?; + (v > 0.0 && v.is_finite()).then_some(v) +} + +fn sia_of(text: &str) -> Option<&'static str> { + let first = text.split(|c: char| !c.is_alphanumeric()).find(|w| !w.is_empty())?; + SIA.iter().find(|s| **s == first).copied() +} + +/// Text als Raumname brauchbar (Buchstaben, keine Fläche, keine SIA-Angabe)? +fn name_like(text: &str) -> bool { + parse_area(text).is_none() && sia_of(text).is_none() && text.chars().any(char::is_alphabetic) +} + +fn text_points(t: &TextIn) -> [V; 2] { + let w = 0.3 * t.h * t.text.chars().count() as f64; + let (c, s) = (cos(t.angle), sin(t.angle)); + [t.at, add(t.at, (c * w - s * t.h / 2.0, s * w + c * t.h / 2.0))] +} + +fn rooms(inp: &Input, walls: &[RWall], rec: &mut Recognition) { + let mut segs = Vec::new(); + for w in walls { + let pts = crate::wall_arc::axis_polyline(w.a, w.b, w.bulge, 0.0, w.t); + for q in pts.windows(2) { + segs.push(kernel2d::WallSegment { a: kernel2d::Vec2::new(q[0].0, q[0].1), b: kernel2d::Vec2::new(q[1].0, q[1].1), thickness: w.t }); + } + } + // Zellen der Achsen, dann die Wandbänder abziehen: lichter Umriss an den echten Wandflächen (der + // Innen-Versatz von `detect_rooms` nähme die mittlere Dicke aller Wände). + let found = kernel2d::detect_rooms(&segs, 0.05, 0.5, false); + let bands: Vec<(Vec<[f64; 2]>, [f64; 4])> = walls + .iter() + .filter_map(|w| { + let band = match crate::wall_arc::band_preview(w.a, w.b, w.bulge, w.t) { + Some((b, _)) => b, + None => { + let d = sub(w.b, w.a); + let l = len(d); + if !(l > 1e-9) { + return None; + } + let n = mul((-d.1 / l, d.0 / l), w.t / 2.0); + vec![add(w.a, n), add(w.b, n), sub(w.b, n), sub(w.a, n)] + } + }; + let bb = band.iter().fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |b, p| [b[0].min(p.0), b[1].min(p.1), b[2].max(p.0), b[3].max(p.1)]); + Some((band.iter().map(|p| [p.0, p.1]).collect(), bb)) + }) + .collect(); + let mut used_text = vec![false; inp.texts.len()]; + for cell in found { + let cell: Vec<[f64; 2]> = cell.iter().map(|p| [p.x, p.y]).collect(); + let bb = cell.iter().fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]); + let cut: Vec>> = bands.iter().filter(|(_, b)| b[0] <= bb[2] && b[2] >= bb[0] && b[1] <= bb[3] && b[3] >= bb[1]).map(|(r, _)| vec![r.clone()]).collect(); + let rest = crate::polygon_bool::difference(&[vec![cell]], &cut); + let Some(best) = rest.iter().filter_map(|p| p.first()).max_by(|a, b| { + let ar = |r: &Vec<[f64; 2]>| polygon_area(&r.iter().map(|q| (q[0], q[1])).collect::>()).abs(); + ar(a).total_cmp(&ar(b)) + }) else { + continue; + }; + let ring: Vec = best.iter().map(|q| ((q[0] * 1e6).round() / 1e6, (q[1] * 1e6).round() / 1e6)).collect(); + if ring.len() < 3 || polygon_area(&ring).abs() < 0.5 { + continue; + } + let inside: Vec = (0..inp.texts.len()).filter(|&k| text_points(&inp.texts[k]).iter().any(|p| point_in(&ring, *p))).collect(); + let mut name: Option<&TextIn> = None; + let mut sia = None; + let mut area_text = None; + for &k in &inside { + let t = &inp.texts[k]; + used_text[k] = true; + if let Some(a) = parse_area(&t.text) { + area_text = area_text.or(Some((a, t.at))); + } else if let Some(s) = sia_of(&t.text) { + sia = sia.or(Some(s)); + } else if name_like(&t.text) && name.is_none_or(|n| t.h > n.h + 1e-9) { + name = Some(t); + } + } + // Raumnummer allein („1.07“) als Name. + let name = name.map(|t| t.text.trim().to_string()).or_else(|| { + inside.iter().map(|&k| inp.texts[k].text.trim()).find(|t| parse_area(t).is_none() && sia_of(t).is_none() && t.chars().any(|c| c.is_ascii_digit())).map(str::to_string) + }); + if let Some((a, at)) = area_text { + let real = polygon_area(&ring).abs(); + if (real - a).abs() > 0.05 * a { + rec.flag("areaMismatch", at); + } + } + rec.rooms.push(RRoom { ring, name, sia, area_text: area_text.map(|a| a.0) }); + } + for (k, t) in inp.texts.iter().enumerate() { + if !used_text[k] && parse_area(&t.text).is_some() { + rec.flag("areaOutside", t.at); + } + } +} + +// ── Gesamtablauf ───────────────────────────────────────────────────────────── + +pub fn analyze(inp: &Input) -> Recognition { + let mut rec = Recognition::default(); + if inp.segs.len() > MAX_SEGS { + rec.flag("tooMany", inp.segs.first().map_or((0.0, 0.0), |s| s.a)); + return rec; + } + let wallish: Vec = inp.layers.iter().map(|l| wallish_layer(l)).collect(); + let n_wallish = inp.segs.iter().filter(|s| wallish[s.layer]).count() + inp.arcs.iter().filter(|a| wallish[a.layer]).count(); + rec.layer_filter = n_wallish >= 4; + let use_layer = |l: usize| !rec.layer_filter || wallish[l]; + + // Bogenwände zuerst (ihre Bögen sind keine Türbögen). + let use_arc: Vec = inp.arcs.iter().map(|a| use_layer(a.layer)).collect(); + let mut arc_ws = Vec::new(); + let arc_used = arc_walls(inp, &use_arc, &mut arc_ws); + + let pair_segs: Vec = inp.segs.iter().filter(|s| use_layer(s.layer)).cloned().collect(); + let ends: Vec<(V, V)> = pair_segs.iter().map(|s| (s.a, s.b)).collect(); + let (frames, cl_of) = bundle(&ends); + let lines = lines_of(&pair_segs, &wallish, &frames, &cl_of); + let door_arcs: Vec = (0..inp.arcs.len()).filter(|&k| !arc_used[k] && door_like(&inp.arcs[k])).collect(); + let cx = Ctx2 { inp, frames, lines, all: inp.segs.iter().map(|s| (s.a, s.b)).collect(), door_arcs }; + + let ps = pieces(&cx); + // Unpaarige Wandlinien (nur mit Wand-Layern aussagekräftig). + if rec.layer_filter { + let mut paired = vec![false; cx.lines.len()]; + for p in &ps { + paired[p.lo] = true; + paired[p.hi] = true; + } + for (i, l) in cx.lines.iter().enumerate() { + if !paired[i] && l.t1 - l.t0 >= 0.5 && l.wallish { + rec.flag("lineUnpaired", cx.frames[l.cl].at(l.c, (l.t0 + l.t1) / 2.0)); + } + } + } + let rs = runs(&cx, ps); + let mut ws: Vec = rs + .iter() + .map(|r| { + let f = cx.frames[r.cl]; + W { + a: f.at(r.c, r.s0), + b: f.at(r.c, r.s1), + t: r.t, + cover: r.cover.iter().map(|&(s0, s1)| (f.at(r.c, s0), f.at(r.c, s1))).collect(), + filled: r.filled, + material: r.material, + } + }) + .collect(); + // Zweimal: ein in der Ecke verlängertes Ende (Tür) erreicht erst danach die Achse der anderen Wand. + join(&cx, &mut ws); + join(&cx, &mut ws); + join_arcs(&mut ws, &mut arc_ws); + let snap = |p: V| ((p.0 * 1e6).round() / 1e6, (p.1 * 1e6).round() / 1e6); + for w in ws.iter_mut() { + w.a = snap(w.a); + w.b = snap(w.b); + w.t = (w.t * 1e6).round() / 1e6; + } + ws.retain(|w| w.length() >= 0.1); + // Umlauf um den Schwerpunkt: rechts (erste Schicht) = aussen. + let (mut sx, mut sy, mut sl) = (0.0, 0.0, 0.0); + for w in &ws { + let m = mul(add(w.a, w.b), 0.5); + let l = w.length(); + sx += m.0 * l; + sy += m.1 * l; + sl += l; + } + if sl > 0.0 { + let g = (sx / sl, sy / sl); + for w in ws.iter_mut() { + let u = w.dir(); + let right = (u.1, -u.0); + if dot(sub(mul(add(w.a, w.b), 0.5), g), right) < -1e-9 { + std::mem::swap(&mut w.a, &mut w.b); + } + } + } + cross_cover(&mut ws); + + // Öffnungen. + let mut arc_taken = vec![false; inp.arcs.len()]; + for (wi, w) in ws.iter().enumerate() { + let b = w.band(); + let l = w.length(); + let cov = union( + w.cover + .iter() + .map(|(p, q)| { + let (s0, s1) = (b.st(*p).0, b.st(*q).0); + (s0.min(s1).max(0.0), s0.max(s1).min(l)) + }) + .collect(), + ); + for (g0, g1) in subtract(0.0, l, &cov) { + let wdt = g1 - g0; + if wdt < MIN_OPENING { + continue; + } + let mid = add(b.o, mul(b.u, (g0 + g1) / 2.0)); + let arcs: Vec<(usize, bool, bool)> = door_arcs_at(&cx, &b, g0, g1).into_iter().filter(|a| !arc_taken[a.0]).collect(); + let kind = if let Some(&(k, at_start, _)) = arcs.iter().find(|a| a.2) { + arc_taken[k] = true; + let (_, nm) = b.st(arc_mid(&inp.arcs[k])); + RKind::Door { hinge_end: !at_start, swing_right: nm < 0.0, leaves: 1 } + } else if !arcs.is_empty() { + // Zwei halbe Bögen: zweiflüglig (Anschlag am ersten Bogen). + let (k, at_start, _) = arcs[0]; + for a in &arcs { + arc_taken[a.0] = true; + } + let (_, nm) = b.st(arc_mid(&inp.arcs[k])); + let leaves = if arcs.iter().any(|a| a.1) && arcs.iter().any(|a| !a.1) { 2 } else { 1 }; + if leaves == 1 { + rec.flag("doorHalf", mid); + } + RKind::Door { hinge_end: !at_start, swing_right: nm < 0.0, leaves } + } else if window_lines_at(&cx, &b, g0, g1) > 0 { + RKind::Window + } else if wdt > GAP_FREE + 1e-6 { + rec.flag("gapWide", mid); + continue; + } else { + RKind::Void + }; + let r6 = |x: f64| (x * 1e6).round() / 1e6; + rec.openings.push(ROpening { wall: wi, pos: r6(g0), width: r6(wdt), kind }); + } + } + for &k in &cx.door_arcs { + if !arc_taken[k] { + rec.flag("doorArc", inp.arcs[k].c); + } + } + + rec.walls = ws.iter().map(|w| RWall { a: w.a, b: w.b, bulge: None, t: w.t, material: w.material, filled: w.filled }).collect(); + arc_ws.retain(|a| a.sweep > 1e-6 && a.sweep * a.r >= 0.1); + let (arc_ws, arc_openings) = merge_arc_walls(inp, arc_ws, &arc_used); + let base = rec.walls.len(); + rec.walls.extend(arc_ws.iter().map(ArcW::wall)); + rec.openings.extend(arc_openings.into_iter().map(|(k, pos, width, kind)| ROpening { wall: base + k, pos, width, kind })); + let walls = rec.walls.clone(); + rooms(inp, &walls, &mut rec); + rec +} + +// ── Anfrage → Ergebnis ─────────────────────────────────────────────────────── + +/// Quell-Ebene (`src`, sonst aktive Ebene) und Auswahl (`ids`) der Anfrage. +fn input_of(p: &Project, v: &Value, level: &str) -> Input { + let src = v.get("src").and_then(Value::as_str).filter(|s| !s.is_empty()).unwrap_or(level); + let ids: Vec = v.get("ids").and_then(|x| serde_json::from_value(x.clone()).ok()).unwrap_or_default(); + collect(p, src, &ids) +} + +pub fn recognize(p: &Project, v: &Value, level: &str) -> Recognition { + analyze(&input_of(p, v, level)) +} + +/// Gesamtdicke eines Wandtyps. +fn type_thickness(t: &crate::model::WallType) -> f64 { + t.layers.iter().fold(0.0, |s, l| s + l.thickness) +} + +/// Wandtyp für Dicke + Material: vorhanden (±5 mm, gleiches Material bevorzugt) oder neu. +fn wall_type_for(p: &Project, v: &Value, ctx: &Ctx, t: f64, material: Option<&'static str>, made: &mut Vec<(f64, Option<&'static str>, String, Value)>, ids: &mut IdGen) -> String { + let comp_matches = |cid: &str| -> bool { + material.is_some_and(|m| { + p.components.iter().any(|c| c.id == cid && (material_of(&c.id) == Some(m) || material_of(&c.name) == Some(m))) + }) + }; + let mut best: Option<(bool, f64, &str)> = None; + for wt in &p.wall_types { + let d = (type_thickness(wt) - t).abs(); + if d > 0.005 { + continue; + } + let m = wt.layers.iter().any(|l| comp_matches(&l.component_id)); + if best.is_none_or(|(bm, bd, _)| (m && !bm) || (m == bm && d < bd)) { + best = Some((m, d, &wt.id)); + } + } + if let Some((_, _, id)) = best { + return id.to_string(); + } + if let Some(m) = made.iter().find(|m| (m.0 - t).abs() <= 0.005 && m.1 == material) { + return m.2.clone(); + } + // Neu: einschichtig, Baustoff nach Hinweis, sonst ein tragender Baustoff des Projekts (Mauerwerk, + // Kalksandstein, Beton), sonst die dickste Schicht des aktiven Wandtyps, sonst der erste Baustoff. + let group_of = |c: &crate::model::Component| material_of(&c.id).or_else(|| material_of(&c.name)); + let comp = material + .and_then(|m| p.components.iter().find(|c| group_of(c) == Some(m))) + .or_else(|| ["mauerwerk", "kalksandstein", "beton"].iter().find_map(|m| p.components.iter().find(|c| group_of(c) == Some(*m)))) + .map(|c| c.id.clone()) + .or_else(|| { + p.wall_types.iter().find(|w| w.id == ctx.wall_type).and_then(|w| w.layers.iter().max_by(|a, b| a.thickness.total_cmp(&b.thickness))).map(|l| l.component_id.clone()) + }) + .or_else(|| p.components.first().map(|c| c.id.clone())) + .unwrap_or_default(); + let id = ids.next("WT"); + let cm = crate::js_fmt::to_fixed(t * 100.0, 1); + let cm = cm.strip_suffix(".0").unwrap_or(&cm).to_string(); + let tmpl = v.get("typeName").and_then(Value::as_str).filter(|s| !s.is_empty()).unwrap_or("Wand {cm} cm"); + let wt = json!({"id": id, "name": tmpl.replace("{cm}", &cm), "layers": [{"componentId": comp, "thickness": js_num((t * 1000.0).round() / 1000.0)}]}); + made.push((t, material, id.clone(), wt)); + id +} + +fn door_type(p: &Project, leaves: u8) -> Option { + let list = p.door_types.as_ref()?; + list.iter() + .find(|d| matches!(d.kind, crate::model::DoorTypeKind::Dreh) && (d.leaf_count - leaves as f64).abs() < 0.5) + .or_else(|| list.iter().find(|d| matches!(d.kind, crate::model::DoorTypeKind::Dreh))) + .map(|d| d.id.clone()) +} + +fn cat(p: &Project, code: &str, ctx: &Ctx) -> String { + if has_category(p, code) { code.to_string() } else { ctx.cat.to_string() } +} + +/// Ops: neue Wandtypen, Wände, Öffnungen, Räume (ein Undo-Schritt). +pub fn ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let rec = recognize(p, v, ctx.level); + if rec.walls.is_empty() { + return Vec::new(); + } + let height = ctx.floor_height.unwrap_or(2.6); + let (wcat, ocat, rcat) = (cat(p, "20", ctx), cat(p, "21", ctx), cat(p, "60", ctx)); + let mut made = Vec::new(); + let mut walls = Vec::new(); + let mut wall_ids = Vec::new(); + for w in &rec.walls { + let type_id = wall_type_for(p, v, ctx, w.t, w.material, &mut made, ids); + let id = ids.next("W"); + let mut f = vec![("id", s(&id)), ("type", s("wall")), ("floorId", s(ctx.level)), ("categoryCode", s(&wcat)), ("start", pv(w.a)), ("end", pv(w.b))]; + if let Some(b) = w.bulge { + f.push(("bulge", js_num(b))); + } + f.push(("wallTypeId", s(&type_id))); + f.push(("height", js_num(height))); + walls.push(obj(f)); + wall_ids.push(id); + } + let door_h = 2.1f64.min(height - 0.1).max(0.5); + let sill = 0.9f64.min((height - 0.6).max(0.0)); + let win_h = 1.2f64.min(height - sill - 0.1).max(0.3); + let window_type = p.window_types.as_ref().and_then(|l| l.first()).map(|w| w.id.clone()); + let mut openings = Vec::new(); + for o in &rec.openings { + let mut f = vec![("id", s(&ids.next("O"))), ("type", s("opening")), ("hostWallId", s(&wall_ids[o.wall])), ("categoryCode", s(&ocat))]; + match o.kind { + RKind::Door { hinge_end, swing_right, leaves } => { + f.push(("kind", s("door"))); + if let Some(t) = door_type(p, leaves) { + f.push(("typeId", s(&t))); + } + f.extend([("position", js_num(o.pos)), ("width", js_num(o.width)), ("height", js_num(door_h)), ("sillHeight", js_num(0.0))]); + f.push(("swing", s(if swing_right { "right" } else { "left" }))); + f.push(("hinge", s(if hinge_end { "end" } else { "start" }))); + } + RKind::Window => { + f.push(("kind", s("window"))); + if let Some(t) = &window_type { + f.push(("typeId", s(t))); + } + f.extend([("position", js_num(o.pos)), ("width", js_num(o.width)), ("height", js_num(win_h)), ("sillHeight", js_num(sill))]); + } + RKind::Void => { + f.push(("kind", s("door"))); + f.extend([("position", js_num(o.pos)), ("width", js_num(o.width)), ("height", js_num(door_h)), ("sillHeight", js_num(0.0))]); + f.push(("doorType", s("wandoeffnung"))); + } + } + openings.push(obj(f)); + } + let tmpl = v.get("roomName").and_then(Value::as_str).filter(|s| !s.is_empty()).unwrap_or("Raum {n}"); + let mut k = p.rooms.as_ref().map_or(0, Vec::len); + let mut rooms = Vec::new(); + for r in &rec.rooms { + k += 1; + let name = r.name.clone().unwrap_or_else(|| tmpl.replace("{n}", &k.to_string())); + let doc = json!({ "version": 1, "paragraphs": [{ "runs": [{ "text": name, "marks": {} }], "align": "center" }] }); + rooms.push(obj(vec![ + ("id", s(&ids.next("RM"))), + ("type", s("room")), + ("floorId", s(ctx.level)), + ("categoryCode", s(&rcat)), + ("siaCategory", s(r.sia.unwrap_or("HNF"))), + ("name", s(&name)), + ("boundary", pvs(&r.ring)), + ("color", category_color(p, &rcat, "#4a4a4a")), + ("stampDoc", doc), + ])); + } + let mut out = Vec::new(); + if !made.is_empty() { + out.extend(add_op("wallTypes", made.into_iter().map(|m| m.3).collect())); + } + out.extend(add_op("walls", walls)); + if !openings.is_empty() { + out.extend(add_op("openings", openings)); + } + if !rooms.is_empty() { + out.extend(add_op("rooms", rooms)); + } + out +} + +/// Zähler `[Wände, Türen, Fenster, Durchbrüche, Räume, unklar]`. +pub fn counts(r: &Recognition) -> [usize; 6] { + [ + r.walls.len(), + r.count(|k| matches!(k, RKind::Door { .. })), + r.count(|k| matches!(k, RKind::Window)), + r.count(|k| matches!(k, RKind::Void)), + r.rooms.len(), + r.unclear.len(), + ] +} + +/// Vorschau: Wandbänder, Öffnungen (Tür: Bogen + Blatt, Fenster: zwei Linien, Durchbruch: Kreuz), Räume, +/// unklare Stellen (kleines Kreuz). `info` = [`counts`]. `false` = nichts erkannt. +pub fn preview(p: &Project, v: &Value, ctx: &Ctx, out: &mut Shapes, info: &mut Vec) -> bool { + let r = recognize(p, v, ctx.level); + for w in &r.walls { + if let Some((band, axis)) = crate::wall_arc::band_preview(w.a, w.b, w.bulge, w.t) { + out.poly(&band); + out.poly_open(&axis); + continue; + } + let d = sub(w.b, w.a); + let u = mul(d, 1.0 / len(d)); + let n = mul((-u.1, u.0), w.t / 2.0); + out.poly(&[add(w.a, n), add(w.b, n), sub(w.b, n), sub(w.a, n)]); + } + for o in &r.openings { + let w = &r.walls[o.wall]; + let d = sub(w.b, w.a); + let u = mul(d, 1.0 / len(d)); + let n = (-u.1, u.0); + let at = |s: f64, k: f64| add(add(w.a, mul(u, s)), mul(n, k)); + let (s0, s1, h) = (o.pos, o.pos + o.width, w.t / 2.0); + match o.kind { + RKind::Door { hinge_end, swing_right, leaves } => { + let side = if swing_right { -1.0 } else { 1.0 }; + // Bogen von der Schliess- (auf der Achse) in die Offenstellung (quer, Aufschlagseite). + let leaf = |hinge: f64, toward: f64, r: f64, out: &mut Shapes| { + let pts: Vec = (0..=12) + .map(|i| { + let a = (i as f64 / 12.0) * PI / 2.0; + at(hinge + toward * r * cos(a), side * r * sin(a)) + }) + .collect(); + out.poly_open(&pts); + out.line(at(hinge, 0.0), at(hinge, side * r)); + }; + if leaves >= 2 { + leaf(s0, 1.0, o.width / 2.0, out); + leaf(s1, -1.0, o.width / 2.0, out); + } else if hinge_end { + leaf(s1, -1.0, o.width, out); + } else { + leaf(s0, 1.0, o.width, out); + } + } + RKind::Window => { + out.line(at(s0, h / 3.0), at(s1, h / 3.0)); + out.line(at(s0, -h / 3.0), at(s1, -h / 3.0)); + } + RKind::Void => { + out.line(at(s0, h), at(s1, -h)); + out.line(at(s0, -h), at(s1, h)); + } + } + } + for room in &r.rooms { + out.poly(&room.ring); + } + for u in &r.unclear { + let k = 0.15; + out.line((u.at.0 - k, u.at.1 - k), (u.at.0 + k, u.at.1 + k)); + out.line((u.at.0 - k, u.at.1 + k), (u.at.0 + k, u.at.1 - k)); + } + info.extend(counts(&r).iter().map(|&c| c as f64)); + !r.walls.is_empty() +} + +/// Bericht (Abfrage `recognize`): Zähler, Layer-Filter, unklare Stellen mit Grund (i18n-Schlüssel der Hülle). +pub fn report(p: &Project, v: &Value) -> Value { + let level = s_of(v, "level"); + let r = recognize(p, v, level); + let c = counts(&r); + let filled = r.walls.iter().filter(|w| w.filled).count(); + let arcs = r.walls.iter().filter(|w| w.bulge.is_some()).count(); + let unnamed = r.rooms.iter().filter(|x| x.name.is_none()).count(); + let mut thick: Vec = r.walls.iter().map(|w| (w.t * 1000.0).round() / 1000.0).collect(); + thick.sort_by(f64::total_cmp); + thick.dedup(); + json!({ + "walls": c[0], "doors": c[1], "windows": c[2], "voids": c[3], "rooms": c[4], + "arcWalls": arcs, "filledWalls": filled, "unnamedRooms": unnamed, + "thicknesses": thick.iter().map(|t| js_num(*t)).collect::>(), + "layerFilter": r.layer_filter, + "unclear": r.unclear.iter().map(|u| json!({"code": u.code, "x": js_num(u.at.0), "y": js_num(u.at.1)})).collect::>(), + }) +} + +#[cfg(test)] +#[path = "drawing_recognize_tests.rs"] +mod tests; diff --git a/src-tauri/core/src/drawing_recognize_tests.rs b/src-tauri/core/src/drawing_recognize_tests.rs new file mode 100644 index 00000000..a8621014 --- /dev/null +++ b/src-tauri/core/src/drawing_recognize_tests.rs @@ -0,0 +1,486 @@ +//! Tests zu [154] Bauteile aus Zeichnung erkennen: synthetische Grundrisse (L-Haus mit T- und Kreuzstoss, +//! Bogenwand, Tür mit Bogen, Fenster, Durchbruch, Raumtexte), Layer-Filter, Schichtlinie, Ops, Unsinn. + +use super::*; +use serde_json::json; + +const EPS: f64 = 1e-6; + +struct B { + inp: Input, +} + +impl B { + fn new() -> B { + B { inp: Input::default() } + } + fn line(&mut self, layer: &str, a: V, b: V) -> &mut B { + let l = self.inp.layer(layer); + self.inp.segs.push(Seg { a, b, layer: l }); + self + } + /// Geschlossener Linienzug (Polylinie als Kanten). + fn ring(&mut self, layer: &str, pts: &[V]) -> &mut B { + for i in 0..pts.len() { + self.line(layer, pts[i], pts[(i + 1) % pts.len()]); + } + self + } + fn rect(&mut self, layer: &str, x0: f64, y0: f64, x1: f64, y1: f64) -> &mut B { + self.ring(layer, &[(x0, y0), (x1, y0), (x1, y1), (x0, y1)]) + } + fn arc(&mut self, layer: &str, c: V, r: f64, a0_deg: f64, sweep_deg: f64) -> &mut B { + let l = self.inp.layer(layer); + self.inp.arcs.push(ArcIn { c, r, a0: a0_deg.to_radians(), sweep: sweep_deg.to_radians(), layer: l }); + self + } + fn text(&mut self, at: V, t: &str, h: f64) -> &mut B { + self.inp.texts.push(TextIn { at, text: t.into(), h, angle: 0.0 }); + self + } +} + +fn near(a: V, b: V, tol: f64) -> bool { + len(sub(a, b)) <= tol +} + +/// Wand mit Achse a–b (beide Richtungen). +fn has_wall(r: &Recognition, a: V, b: V, t: f64) -> bool { + r.walls.iter().any(|w| (w.t - t).abs() < 1e-6 && ((near(w.a, a, 1e-6) && near(w.b, b, 1e-6)) || (near(w.a, b, 1e-6) && near(w.b, a, 1e-6)))) +} + +/// L-Haus (Achsen 12×6 + 6×4, Aussenwände 30 cm) mit zwei Innenwänden 15 cm: T-Stösse bei (6,0) und (0,6), +/// Kreuz bei (6,6). Zeichnung wie aus CAD: Aussenumriss + Raumumrisse (lichte Masse). +fn l_house() -> B { + let mut b = B::new(); + b.ring("A-WALL", &[(-0.15, -0.15), (12.15, -0.15), (12.15, 6.15), (6.15, 6.15), (6.15, 10.15), (-0.15, 10.15)]); + b.rect("A-WALL", 0.15, 0.15, 5.925, 5.925); // A1 + b.rect("A-WALL", 0.15, 6.075, 5.85, 9.85); // A2 + b.rect("A-WALL", 6.075, 0.15, 11.85, 5.85); // B + b +} + +#[test] +fn l_haus_mit_t_und_kreuzstoss() { + let mut b = l_house(); + b.text((1.0, 3.0), "Wohnen", 0.35).text((1.0, 2.5), "33.35 m²", 0.25).text((1.0, 2.0), "HNF", 0.25); + b.text((7.0, 3.0), "Küche", 0.35).text((1.0, 8.0), "Zimmer", 0.35).text((1.0, 7.5), "1.07", 0.2); + let r = analyze(&b.inp); + assert!(r.layer_filter); + assert_eq!(r.walls.len(), 8, "{:#?}", r.walls); + for (a, bb, t) in [ + ((0.0, 0.0), (12.0, 0.0), 0.3), + ((12.0, 0.0), (12.0, 6.0), 0.3), + ((12.0, 6.0), (6.0, 6.0), 0.3), + ((6.0, 6.0), (6.0, 10.0), 0.3), + ((6.0, 10.0), (0.0, 10.0), 0.3), + ((0.0, 10.0), (0.0, 0.0), 0.3), + ((6.0, 0.0), (6.0, 6.0), 0.15), + ((0.0, 6.0), (6.0, 6.0), 0.15), + ] { + assert!(has_wall(&r, a, bb, t), "fehlt {a:?}–{bb:?} t={t}: {:#?}", r.walls); + } + // Aussenwände laufen gegen den Uhrzeigersinn (rechts = aussen). + let bottom = r.walls.iter().find(|w| w.a.1.abs() < EPS && w.b.1.abs() < EPS).unwrap(); + assert!(bottom.b.0 > bottom.a.0); + assert!(r.openings.is_empty(), "{:?}", r.openings); + assert_eq!(r.rooms.len(), 3); + let wohnen = r.rooms.iter().find(|x| x.name.as_deref() == Some("Wohnen")).expect("Wohnen"); + assert!((polygon_area(&wohnen.ring).abs() - 33.350625).abs() < 1e-6, "{:?}", wohnen.ring); + assert_eq!(wohnen.sia, Some("HNF")); + assert_eq!(wohnen.area_text, Some(33.35)); + assert!(r.rooms.iter().any(|x| x.name.as_deref() == Some("Küche"))); + // Grösster Text gewinnt vor der Raumnummer. + assert!(r.rooms.iter().any(|x| x.name.as_deref() == Some("Zimmer"))); + assert!(r.unclear.is_empty(), "{:?}", r.unclear); +} + +#[test] +fn flaechenangabe_falsch_ist_unklar() { + let mut b = l_house(); + b.text((7.0, 3.0), "Küche", 0.35).text((7.0, 2.0), "20.0 m2", 0.25).text((20.0, 2.0), "5 m²", 0.25); + let r = analyze(&b.inp); + let codes: Vec<&str> = r.unclear.iter().map(|u| u.code).collect(); + assert!(codes.contains(&"areaMismatch") && codes.contains(&"areaOutside"), "{codes:?}"); +} + +/// Gerade Wand 6 m (30 cm) mit Lücken; Hilfe für die Öffnungs-Tests. +fn wall_with_gaps(gaps: &[(f64, f64)]) -> B { + let mut b = B::new(); + let mut x = 0.0; + let mut spans = Vec::new(); + for &(g0, g1) in gaps { + spans.push((x, g0)); + x = g1; + } + spans.push((x, 6.0)); + for (x0, x1) in spans { + b.rect("Mauerwerk Wand", x0, -0.15, x1, 0.15); + } + b +} + +#[test] +fn tuer_mit_bogen_fenster_und_durchbruch() { + let mut b = wall_with_gaps(&[(1.0, 1.9), (3.0, 4.2), (4.6, 5.4)]); + // Tür: Scharnier am rechten Pfosten (x = 1.9), Blatt schlägt nach −y auf (Bogen 180°…270°). + b.arc("Türen", (1.9, -0.12), 0.9, 180.0, 90.0).line("Türen", (1.9, -0.12), (1.9, -1.02)); + // Fenster: Glaslinien im Band. + b.line("Fenster", (3.0, -0.03), (4.2, -0.03)).line("Fenster", (3.0, 0.03), (4.2, 0.03)); + let r = analyze(&b.inp); + assert_eq!(r.walls.len(), 1, "{:#?}", r.walls); + let w = &r.walls[0]; + assert!((w.t - 0.3).abs() < EPS); + assert_eq!(w.material, Some("mauerwerk")); + assert_eq!(r.openings.len(), 3, "{:#?}", r.openings); + // Lage unabhängig von der Wandrichtung: Anfang des Pfostens in Weltkoordinaten. + let u = mul(sub(w.b, w.a), 1.0 / len(sub(w.b, w.a))); + let x_of = |o: &ROpening| { + let p0 = add(w.a, mul(u, o.pos)); + let p1 = add(w.a, mul(u, o.pos + o.width)); + (p0.0.min(p1.0), p0.0.max(p1.0)) + }; + let door = r.openings.iter().find(|o| matches!(o.kind, RKind::Door { .. })).unwrap(); + let (x0, x1) = x_of(door); + assert!((x0 - 1.0).abs() < EPS && (x1 - 1.9).abs() < EPS); + let RKind::Door { hinge_end, swing_right, leaves } = door.kind else { unreachable!() }; + assert_eq!(leaves, 1); + // Scharnier bei x = 1.9, Blatt auf −y — in Wandrichtung ausgedrückt. + let hinge = add(w.a, mul(u, if hinge_end { door.pos + door.width } else { door.pos })); + assert!((hinge.0 - 1.9).abs() < EPS); + let n = (-u.1, u.0); + let side = if swing_right { -1.0 } else { 1.0 }; + assert!(mul(n, side).1 < 0.0, "Aufschlag nach −y"); + let win = r.openings.iter().find(|o| o.kind == RKind::Window).unwrap(); + let (x0, x1) = x_of(win); + assert!((x0 - 3.0).abs() < EPS && (x1 - 4.2).abs() < EPS); + let void = r.openings.iter().find(|o| o.kind == RKind::Void).unwrap(); + let (x0, x1) = x_of(void); + assert!((x0 - 4.6).abs() < EPS && (x1 - 5.4).abs() < EPS); + assert!(r.unclear.is_empty(), "{:?}", r.unclear); +} + +#[test] +fn zweifluegelige_tuer_aus_zwei_halben_boegen() { + let mut b = wall_with_gaps(&[(2.0, 3.6)]); + b.arc("Türen", (2.0, 0.15), 0.8, 0.0, 90.0).arc("Türen", (3.6, 0.15), 0.8, 90.0, 90.0); + let r = analyze(&b.inp); + assert_eq!(r.openings.len(), 1); + assert!(matches!(r.openings[0].kind, RKind::Door { leaves: 2, .. }), "{:?}", r.openings); + assert!((r.openings[0].width - 1.6).abs() < EPS); +} + +#[test] +fn breite_luecke_ohne_hinweis_trennt_waende() { + let r = analyze(&wall_with_gaps(&[(2.0, 4.5)]).inp); + assert_eq!(r.walls.len(), 2); + assert!(r.openings.is_empty()); + // Mit Fensterlinien wird es eine Wand mit Fenster. + let mut b = wall_with_gaps(&[(2.0, 4.5)]); + b.line("Fenster", (2.0, 0.0), (4.5, 0.0)); + let r = analyze(&b.inp); + assert_eq!(r.walls.len(), 1); + assert_eq!(r.openings.len(), 1); + assert_eq!(r.openings[0].kind, RKind::Window); +} + +#[test] +fn tuer_in_der_ecke() { + // Ecke bei (0,0): Wand 1 entlang x (Lücke 0.15–1.05 an der Ecke), Wand 2 entlang y. + let mut b = B::new(); + b.ring("Wand", &[(-0.15, -0.15), (6.0, -0.15), (6.0, 0.15), (1.05, 0.15), (1.05, -0.15)]); + b.line("Wand", (-0.15, -0.15), (-0.15, 5.0)).line("Wand", (0.15, 0.15), (0.15, 5.0)).line("Wand", (-0.15, 5.0), (0.15, 5.0)); + b.line("Wand", (-0.15, -0.15), (0.15, -0.15)).line("Wand", (0.15, -0.15), (0.15, 0.15)); + b.arc("Tür", (0.15, 0.15), 0.9, 0.0, 90.0); + let r = analyze(&b.inp); + assert_eq!(r.walls.len(), 2, "{:#?}", r.walls); + assert!(has_wall(&r, (0.0, 0.0), (6.0, 0.0), 0.3), "{:#?}", r.walls); + assert!(has_wall(&r, (0.0, 0.0), (0.0, 5.0), 0.3), "{:#?}", r.walls); + assert_eq!(r.openings.len(), 1, "{:?} {:?}", r.openings, r.unclear); + assert!(matches!(r.openings[0].kind, RKind::Door { leaves: 1, .. })); + assert!((r.openings[0].width - 0.9).abs() < EPS); +} + +#[test] +fn bogenwand_aus_konzentrischen_boegen() { + let mut b = B::new(); + b.arc("Wand", (0.0, 0.0), 4.85, 0.0, 90.0).arc("Wand", (0.0, 0.0), 5.15, 0.0, 90.0); + b.line("Wand", (4.85, 0.0), (5.15, 0.0)).line("Wand", (0.0, 4.85), (0.0, 5.15)); + let r = analyze(&b.inp); + assert_eq!(r.walls.len(), 1, "{:#?}", r.walls); + let w = &r.walls[0]; + assert!((w.t - 0.3).abs() < EPS); + assert!(near(w.a, (5.0, 0.0), 1e-9) && near(w.b, (0.0, 5.0), 1e-9), "{w:?}"); + let arc = crate::wall_arc::WallArc::of(kernel2d::Vec2::new(w.a.0, w.a.1), kernel2d::Vec2::new(w.b.0, w.b.1), w.bulge).unwrap(); + assert!((arc.r - 5.0).abs() < 1e-9 && (arc.sweep - PI / 2.0).abs() < 1e-9, "{arc:?}"); + assert!(len(sub((arc.center.x, arc.center.y), (0.0, 0.0))) < 1e-9); + // Kein Türbogen-Hinweis (die Bögen sind die Wand). + assert!(r.unclear.is_empty()); +} + +#[test] +fn bogenwand_aus_polylinien_bulge() { + // Polylinien-Bogen (Modell-Bulge, negativ = gegen den Uhrzeigersinn). + let bl = -tan(PI / 8.0); + let a1 = bulge_arc((4.85, 0.0), (0.0, 4.85), bl, 0).unwrap(); + let a2 = bulge_arc((5.15, 0.0), (0.0, 5.15), bl, 0).unwrap(); + assert!((a1.sweep - PI / 2.0).abs() < 1e-9 && a1.a0.abs() < 1e-9, "{a1:?}"); + let mut inp = Input::default(); + inp.layer("Wand"); + inp.arcs.extend([a1, a2]); + let r = analyze(&inp); + assert_eq!(r.walls.len(), 1); +} + +#[test] +fn layer_filter_ignoriert_moebel() { + let mut b = wall_with_gaps(&[]); + // Möbel parallel in 40 cm Abstand (wäre sonst eine Wand) und ein Tisch. + b.line("Möbel", (1.0, 0.55), (4.0, 0.55)).rect("Möbel", 1.0, 2.0, 3.0, 2.4); + b.line("Mauerwerk Wand", (8.0, 8.0), (12.0, 8.0)); + let r = analyze(&b.inp); + assert!(r.layer_filter); + assert_eq!(r.walls.len(), 1, "{:#?}", r.walls); + // Die einsame Linie auf dem Wand-Layer ist unklar. + assert_eq!(r.unclear.iter().filter(|u| u.code == "lineUnpaired").count(), 1, "{:?}", r.unclear); + // Ohne Wand-Layer zählt alles: der Tisch (40 cm) wird eine Wand. + let mut b = B::new(); + b.rect("0", 0.0, -0.15, 6.0, 0.15).rect("0", 1.0, 2.0, 3.0, 2.4); + let r = analyze(&b.inp); + assert!(!r.layer_filter); + assert_eq!(r.walls.len(), 2); +} + +#[test] +fn schichtlinie_und_achslinie_ergeben_eine_wand() { + let mut b = B::new(); + // Aussenwand 34.5 cm: Putz/Dämmung/Mauerwerk-Linien (Schichtgrenzen bei −0.1525 und 0.0075). + for y in [-0.1725, -0.1525, 0.0075, 0.1575, 0.1725] { + b.line("Wand", (0.0, y), (5.0, y)); + } + let r = analyze(&b.inp); + assert_eq!(r.walls.len(), 1, "{:#?}", r.walls); + assert!((r.walls[0].t - 0.345).abs() < 1e-9); + assert!(near(mul(add(r.walls[0].a, r.walls[0].b), 0.5), (2.5, 0.0), 1e-9)); +} + +#[test] +fn schraffur_bestaetigt_und_gibt_material() { + let mut b = wall_with_gaps(&[]); + let l = b.inp.layer("Schraffur"); + b.inp.fills.push(FillIn { ring: vec![(0.0, -0.15), (6.0, -0.15), (6.0, 0.15), (0.0, 0.15)], layer: l, hatch: Some("Beton".into()) }); + let r = analyze(&b.inp); + assert!(r.walls[0].filled); + assert_eq!(r.walls[0].material, Some("beton")); +} + +#[test] +fn material_und_flaechentexte() { + assert_eq!(material_of("A-WALL-CONC"), None); + assert_eq!(material_of("Wand Beton"), Some("beton")); + assert_eq!(material_of("MW 15"), Some("mauerwerk")); + assert_eq!(material_of("Wand_KS"), Some("kalksandstein")); + assert_eq!(material_of("Kasten"), None); + assert_eq!(parse_area("17.01 m²"), Some(17.01)); + assert_eq!(parse_area("F: 17,5 m2"), Some(17.5)); + assert_eq!(parse_area("1'017 qm"), Some(1017.0)); + assert_eq!(parse_area("Wohnen"), None); + assert!(wallish_layer("20_Wände") && wallish_layer("A-WALL") && wallish_layer("Mauerwerk") && !wallish_layer("Möbel")); +} + +#[test] +fn unsinn_ohne_panic() { + let mut b = B::new(); + b.line("Wand", (f64::NAN, 0.0), (1.0, 0.0)).line("Wand", (0.0, 0.0), (0.0, 0.0)).arc("Wand", (0.0, 0.0), f64::INFINITY, 0.0, 90.0); + b.line("Wand", (0.0, 0.0), (1e300, 1e300)).line("Wand", (0.0, 0.1), (1e300, 1e300)); + let _ = analyze(&b.inp); + let _ = analyze(&Input::default()); +} + +// ── Über das Projekt (Ops) ─────────────────────────────────────────────────── + +fn project(drawings: Vec) -> (Project, serde_json::Map) { + let v = json!({ + "id": "p", "name": "t", "lineStyles": [], "hatches": [], + "components": [{"id": "brick", "name": "Mauerwerk", "color": "#a0522d"}, {"id": "concrete", "name": "Beton", "color": "#999999"}], + "wallTypes": [{"id": "aw", "name": "Aussenwand 30", "layers": [{"componentId": "brick", "thickness": 0.3}]}], + "doorTypes": [{"id": "dt1", "name": "Tür", "kind": "dreh", "leafCount": 1, "leafStyle": "glatt", "frameThickness": 0.06}], + "layers": [ + {"code": "20", "name": "Wände", "color": "#000000", "lw": 0.5, "visible": true, "locked": false}, + {"code": "21", "name": "Türen/Fenster", "color": "#000000", "lw": 0.25, "visible": true, "locked": false}, + {"code": "60", "name": "Räume", "color": "#6b7280", "lw": 0.1, "visible": true, "locked": false}, + {"code": "101", "name": "A-WALL", "color": "#000000", "lw": 0.5, "visible": true, "locked": false}, + {"code": "102", "name": "A-DOOR", "color": "#000000", "lw": 0.25, "visible": true, "locked": false}, + {"code": "103", "name": "A-ANNO", "color": "#000000", "lw": 0.25, "visible": true, "locked": false} + ], + "openings": [], "walls": [], + "drawingLevels": [ + {"id": "eg", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 2.8}, + {"id": "imp", "name": "Import", "kind": "drawing", "visible": true, "locked": false} + ], + "drawings2d": drawings + }); + let p: Project = serde_json::from_value(v.clone()).unwrap(); + (p, v.as_object().unwrap().clone()) +} + +fn dl(id: &str, code: &str, geom: Value) -> Value { + json!({"id": id, "type": "drawing2d", "levelId": "imp", "categoryCode": code, "geom": geom}) +} + +fn poly(pts: &[V]) -> Value { + json!({"shape": "polyline", "closed": true, "pts": pts.iter().map(|p| json!({"x": p.0, "y": p.1})).collect::>()}) +} + +/// Raum 5 × 4 (Achsen) mit Aussenwänden 30 cm und Innenwand 15 cm, Tür mit Bogen, Raumtext. +fn small_house() -> Vec { + vec![ + dl("o", "101", poly(&[(-0.15, -0.15), (1.0, -0.15), (1.0, 0.15), (0.15, 0.15), (0.15, 3.85), (4.85, 3.85), (4.85, 0.15), (1.9, 0.15), (1.9, -0.15), (5.15, -0.15), (5.15, 4.15), (-0.15, 4.15)])), + dl("i", "101", poly(&[(2.425, 0.15), (2.575, 0.15), (2.575, 3.85), (2.425, 3.85)])), + dl("arc", "102", json!({"shape": "arc", "center": {"x": 1.0, "y": 0.0}, "r": 0.9, "a0": 0.0, "a1": PI / 2.0})), + dl("t1", "103", json!({"shape": "text", "at": {"x": 0.5, "y": 2.0}, "text": "Wohnen", "height": 0.35, "angle": 0.0})), + dl("t2", "103", json!({"shape": "text", "at": {"x": 0.5, "y": 1.5}, "text": "9.5 m²", "height": 0.25, "angle": 0.0})), + ] +} + +/// Neue Elemente einer Liste aus den Ops. +fn added(ops: &[Op], coll: &str) -> Vec { + ops.iter() + .filter_map(|o| match o { + Op::Add { collection, items, .. } if collection == coll => Some(items.clone()), + _ => None, + }) + .flatten() + .collect() +} + +fn req(extra: Value) -> Value { + let mut v = json!({"cmd": "recognize", "src": "imp", "stamp": "s", "typeName": "Wand {cm} cm (erkannt)", + "ctx": {"level": "eg", "floorHeight": 2.8, "cat": "20", "wallType": "aw"}}); + for (k, x) in extra.as_object().unwrap() { + v[k] = x.clone(); + } + v +} + +#[test] +fn ops_waende_typen_oeffnungen_raeume() { + let (p, root) = project(small_house()); + let ops = crate::cmd_create::ops(&root, &p, &req(json!({}))).expect("recognize"); + let items = |coll: &str| added(&ops, coll); + let walls = items("walls"); + assert_eq!(walls.len(), 5, "{walls:#?}"); + // 30 cm: vorhandener Typ; 15 cm: neuer Typ (Baustoff des aktiven Typs). + assert_eq!(walls.iter().filter(|w| w["wallTypeId"] == "aw").count(), 4); + let types = items("wallTypes"); + assert_eq!(types.len(), 1, "{types:?}"); + assert_eq!(types[0]["name"], "Wand 15 cm (erkannt)"); + assert_eq!(types[0]["layers"][0]["componentId"], "brick"); + assert!(walls.iter().all(|w| w["floorId"] == "eg" && w["height"] == 2.8 && w["categoryCode"] == "20")); + let openings = items("openings"); + assert_eq!(openings.len(), 1, "{openings:?}"); + let o = &openings[0]; + assert_eq!(o["kind"], "door"); + assert_eq!(o["typeId"], "dt1"); + assert_eq!(o["sillHeight"], 0.0); + assert!((o["width"].as_f64().unwrap() - 0.9).abs() < 1e-9); + let host = walls.iter().find(|w| w["id"] == o["hostWallId"]).unwrap(); + assert_eq!(host["wallTypeId"], "aw"); + let rooms = items("rooms"); + assert_eq!(rooms.len(), 2); + assert!(rooms.iter().any(|r| r["name"] == "Wohnen" && r["categoryCode"] == "60")); + // Alles typisiert lesbar. + for w in &walls { + let _: crate::model::Wall = serde_json::from_value(w.clone()).unwrap(); + } + let _: crate::model::Opening = serde_json::from_value(o.clone()).unwrap(); + for r in &rooms { + let _: crate::model::Room = serde_json::from_value(r.clone()).unwrap(); + } + for t in &types { + let _: crate::model::WallType = serde_json::from_value(t.clone()).unwrap(); + } +} + +#[test] +fn auswahl_vorschau_und_bericht() { + let (p, root) = project(small_house()); + // Nur die Innenwand gewählt: eine Wand. + let ops = crate::cmd_create::ops(&root, &p, &req(json!({"ids": ["i"]}))).unwrap(); + let n = added(&ops, "walls").len(); + // Ohne Gegen-Wände kein Stoss; ein Wand-Layer mit 4 Linien → Filter an. + assert_eq!(n, 1); + let pv = crate::cmd_create::preview(&root, &p, &req(json!({})), &[]); + assert!(pv.ok); + assert_eq!(pv.info, vec![5.0, 1.0, 0.0, 0.0, 2.0, 1.0]); + let rep = report(&p, &json!({"q": "recognize", "level": "eg", "src": "imp"})); + assert_eq!(rep["walls"], 5); + assert_eq!(rep["doors"], 1); + assert_eq!(rep["layerFilter"], true); + // „9.5 m²“ steht im westlichen Raum (2.275 × 3.7 = 8.4175 m²): Abweichung > 5 %. + assert_eq!(rep["unclear"][0]["code"], "areaMismatch"); + // Leere Ebene: nichts. + let pv = crate::cmd_create::preview(&root, &p, &req(json!({"src": "eg"})), &[]); + assert!(!pv.ok); + assert!(crate::cmd_create::ops(&root, &p, &req(json!({"src": "eg"}))).unwrap().is_empty()); +} + +/// Erker wie im Musterhaus komplex: gerade Wand – halbkreisförmige Bogenwand – gerade Wand, der Bogen im +/// DXF in Sehnen zerlegt (Polylinie ohne Bulge). → drei Wände, Bogenwand mit Mittelpunkt/Radius, Stösse auf +/// den Achsen. +#[test] +fn tessellierter_erker() { + let (c, t): (V, f64) = ((15.0, 5.0), 0.39); + let arc_pts = |r: f64, a0: f64, a1: f64, n: usize| -> Vec { + (0..=n) + .map(|i| { + let a = a0 + (a1 - a0) * i as f64 / n as f64; + (c.0 + r * a.cos(), c.1 + r * a.sin()) + }) + .collect() + }; + let ro = 2.0 + t / 2.0; + let ri = 2.0 - t / 2.0; + let ao = (t / 2.0 / ro).asin(); + let ai = (t / 2.0 / ri).asin(); + // Aussen: x = 15.195 und der äussere Bogen; innen: x = 14.805 und der innere Bogen. + let mut outer = vec![(15.195, 0.0)]; + outer.extend(arc_pts(ro, -PI / 2.0 + ao, PI / 2.0 - ao, 24)); + outer.push((15.195, 10.0)); + let mut inner = vec![(14.805, 0.0)]; + inner.extend(arc_pts(ri, -PI / 2.0 - ai, PI / 2.0 + ai, 24)); + inner.push((14.805, 10.0)); + let mut inp = Input::default(); + let l = inp.layer("Wand"); + fit_arcs(&outer, l, &mut inp.segs, &mut inp.arcs); + fit_arcs(&inner, l, &mut inp.segs, &mut inp.arcs); + assert_eq!(inp.arcs.len(), 2, "{:?}", inp.arcs); + assert!(inp.arcs.iter().all(|a| len(sub(a.c, c)) < 1e-9)); + let r = analyze(&inp); + assert_eq!(r.walls.len(), 3, "{:#?}", r.walls); + assert!(has_wall(&r, (15.0, 0.0), (15.0, 3.0), t) && has_wall(&r, (15.0, 7.0), (15.0, 10.0), t), "{:#?}", r.walls); + let w = r.walls.iter().find(|w| w.bulge.is_some()).unwrap(); + assert!(near(w.a, (15.0, 3.0), 1e-6) && near(w.b, (15.0, 7.0), 1e-6), "{w:?}"); + let arc = crate::wall_arc::WallArc::of(kernel2d::Vec2::new(w.a.0, w.a.1), kernel2d::Vec2::new(w.b.0, w.b.1), w.bulge).unwrap(); + assert!((arc.r - 2.0).abs() < 1e-6 && len(sub((arc.center.x, arc.center.y), c)) < 1e-6, "{arc:?}"); + // Fenster im Bogen: Bogenwand mit Lücke 60°–75° (Fensterbögen im Band) → eine Bogenwand mit Fenster. + let mut inp = Input::default(); + let l = inp.layer("Wand"); + let f = inp.layer("Fenster"); + for (r0, a0, sw) in [(ro, -60.0, 120.0), (ri, -60.0, 120.0), (ro, 75.0, 30.0), (ri, 75.0, 30.0)] { + inp.arcs.push(ArcIn { c, r: r0, a0: wrap2pi(f64::to_radians(a0)), sweep: f64::to_radians(sw), layer: l }); + } + inp.arcs.push(ArcIn { c, r: 2.0, a0: f64::to_radians(60.0), sweep: f64::to_radians(15.0), layer: f }); + let r = analyze(&inp); + assert_eq!(r.walls.len(), 1, "{:#?}", r.walls); + assert_eq!(r.openings.len(), 1, "{:?}", r.openings); + assert_eq!(r.openings[0].kind, RKind::Window); + assert!((r.openings[0].pos - 2.0 * f64::to_radians(120.0)).abs() < 1e-6 && (r.openings[0].width - 2.0 * f64::to_radians(15.0)).abs() < 1e-6, "{:?}", r.openings); + // Rechtecke und Zickzack bleiben gerade. + let mut segs = Vec::new(); + let mut arcs = Vec::new(); + fit_arcs(&[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)], 0, &mut segs, &mut arcs); + fit_arcs(&[(0.0, 0.0), (1.0, 0.1), (2.0, 0.0), (3.0, 0.1), (4.0, 0.0)], 0, &mut segs, &mut arcs); + assert!(arcs.is_empty()); + assert_eq!(segs.len(), 8); +} diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index aac6b3cf..3c4d33d6 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -128,5 +128,6 @@ pub mod opening_slide; #[cfg(feature = "web")] mod web; pub mod presentation_sheet; +pub mod drawing_recognize; #[cfg(test)] mod wall_join3d_tests; diff --git a/src/cli/main.ts b/src/cli/main.ts index a62e3f53..b2bea643 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -26,6 +26,9 @@ // Bauteile ([B4]); Bericht als JSON auf stdout // dossier-cli import-mesh [--out neu.obp] [--unit mm|cm|m|inch|foot] [--up z|y|auto] // [--placement center|original] 3D-Modell als Kontext-Meshes; Bericht als JSON +// dossier-cli erkennen [--level EG] [--source ebene] [--out neu.obp] +// [154] Bauteile aus 2D-Zeichnung erkennen (Wände, Öffnungen, Räume +// ins Geschoss); Bericht als JSON. Z. B. convert plan.dxf p.obp --cmd "erkennen --out e.obp" // dossier-cli model3d [--explode 3] [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png) // dossier-cli pointcloud-info [--voxel 0.05] [--max 2000000] // Punktwolke lesen ([B9]) und Bericht als JSON (ohne Projekt) @@ -119,6 +122,9 @@ import { withDocument, AI_BRIDGE_DEFAULT_PORT, standardOverrideRules, + recognizeMutation, + recognizeReport, + recognizeSourceLevels, } from "../core"; import type { Project } from "../core"; import { serveStdio } from "./mcp"; @@ -363,7 +369,7 @@ export async function run(argv: string[]): Promise { if (file === "mcp" && args.flags.has("app")) return runAppBridge(args); if (!file || (!command && args.cmds.length === 0)) { process.stderr.write( - "Aufruf: dossier-cli [Optionen]\n" + + "Aufruf: dossier-cli [Optionen]\n" + " dossier-cli convert [--cmd \"befehl …\"]…\n" + " dossier-cli --cmd \"befehl …\" [--cmd …] ({last} = zuletzt geschriebene Datei)\n" + " dossier-cli pointcloud-info [--voxel 0.05] [--max 2000000]\n" + @@ -872,6 +878,24 @@ async function execute(project: Project, file: string, command: string, rest: st if (target) out(args, serializeProject(r.next), target); return 0; } + case "erkennen": { + // [154] Quelle: --source (Ebene, id oder Name), sonst die Zeichnung des Geschosses, sonst die erste Ebene mit Zeichnung. + const lvl = findLevel(project, ["floor"], args.flags.get("level")); + if (!lvl) fail("Geschoss nicht gefunden"); + const sources = recognizeSourceLevels(project); + const want = args.flags.get("source")?.toLowerCase(); + const src = want + ? project.drawingLevels.find((l) => l.id.toLowerCase() === want || l.name.toLowerCase() === want)?.id + : sources.includes(lvl.id) + ? lvl.id + : sources[0]; + if (!src) fail("erkennen: keine 2D-Zeichnung (--source)"); + const opts = { levelId: lvl.id, floorHeight: lvl.floorHeight, sourceLevelId: src, wallTypeId: project.wallTypes[0]?.id, typeName: "Wand {cm} cm (erkannt)" }; + process.stdout.write(JSON.stringify(recognizeReport(project, opts), null, 2) + "\n"); + const target = args.flags.get("out"); + if (target) out(args, serializeProject(recognizeMutation(opts)(project)), target); + return 0; + } case "import-mesh": { const src = rest[0]; if (!src) fail("import-mesh: Modelldatei fehlt"); diff --git a/src/commands/cmds/recognize.test.ts b/src/commands/cmds/recognize.test.ts new file mode 100644 index 00000000..7f227f53 --- /dev/null +++ b/src/commands/cmds/recognize.test.ts @@ -0,0 +1,100 @@ +/** `recognizeCommand` ([154]): Vorschau + Zähler beim Start, Bericht (B), Quelle (E), Enter = ein Commit. */ +import { describe, expect, it } from "vitest"; +import { recognizeCommand, reportText } from "./recognize"; +import { resolveCommand } from "../registry"; +import type { CommandContext, Project } from "../types"; +import type { Drawing2D } from "../../model/types"; + +const poly = (id: string, code: string, pts: [number, number][], level = "imp"): Drawing2D => + ({ id, type: "drawing2d", levelId: level, categoryCode: code, geom: { shape: "polyline", closed: true, pts: pts.map(([x, y]) => ({ x, y })) } }) as Drawing2D; + +/** Raum 5 × 4 (Achsen), Aussenwände 30 cm, Innenwand 15 cm, Tür mit Bogen, Raumtext — auf einer Zeichnungsebene. */ +function project(): Project { + return { + id: "t", name: "T", lineStyles: [], hatches: [], + components: [{ id: "brick", name: "Mauerwerk", color: "#a0522d" }] as Project["components"], + wallTypes: [{ id: "aw", name: "Aussenwand 30", layers: [{ componentId: "brick", thickness: 0.3 }] }], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.8, cutHeight: 1.0, baseElevation: 0 }, + { id: "imp", name: "Import", kind: "drawing", visible: true, locked: false }, + ], + layers: [ + { code: "20", name: "Wände", color: "#000000", lw: 0.5, visible: true, locked: false }, + { code: "101", name: "A-WALL", color: "#000000", lw: 0.5, visible: true, locked: false }, + { code: "102", name: "A-DOOR", color: "#000000", lw: 0.25, visible: true, locked: false }, + ], + walls: [], openings: [], ceilings: [], stairs: [], rooms: [], context: [], + drawings2d: [ + poly("o", "101", [[-0.15, -0.15], [1, -0.15], [1, 0.15], [0.15, 0.15], [0.15, 3.85], [4.85, 3.85], [4.85, 0.15], [1.9, 0.15], [1.9, -0.15], [5.15, -0.15], [5.15, 4.15], [-0.15, 4.15]]), + poly("i", "101", [[2.425, 0.15], [2.575, 0.15], [2.575, 3.85], [2.425, 3.85]]), + { id: "arc", type: "drawing2d", levelId: "imp", categoryCode: "102", geom: { shape: "arc", center: { x: 1, y: 0 }, r: 0.9, a0: 0, a1: Math.PI / 2 } } as Drawing2D, + { id: "t1", type: "drawing2d", levelId: "imp", categoryCode: "102", geom: { shape: "text", at: { x: 0.5, y: 2 }, text: "Wohnen", height: 0.35, angle: 0 } } as Drawing2D, + ], + } as Project; +} + +const ctxOf = (p: Project, drawingIds: string[] = []): CommandContext => + ({ project: p, level: p.drawingLevels[0], defaultCategoryCode: "20", activeLineStyleId: "solid", activeWallTypeId: "aw", lastPoint: null, selection: { wallIds: [], drawingId: null, drawingIds } }) as CommandContext; + +describe("recognizeCommand", () => { + it("Name und Kürzel", () => { + expect(resolveCommand("erkennen")?.name).toBe("erkennen"); + expect(resolveCommand("bauteileerkennen")?.name).toBe("erkennen"); + }); + + it("Start: Vorschau und Zähler aus der Zeichnungsebene, Enter übernimmt als ein Commit", () => { + const p = project(); + const ctx = ctxOf(p); + const start = recognizeCommand.autoRun!(ctx); + expect(start.done).toBeFalsy(); + expect(start.draft?.preview.length).toBeGreaterThan(5); + expect(start.notice?.key).toBe("cmd.recognize.summary"); + expect(start.notice?.params).toMatchObject({ walls: 5, doors: 1, windows: 0, voids: 0, rooms: 2 }); + const [, mv] = recognizeCommand.onMove(recognizeCommand.init(), { x: 1, y: 1 }, null, ctx); + expect(mv.draft?.hud?.text).toContain("5"); + const [, r] = recognizeCommand.onConfirm(recognizeCommand.init(), ctx); + expect(r.done).toBe(true); + const next = r.commit!(p); + expect(next.walls.length).toBe(5); + expect(next.walls.every((w) => w.floorId === "eg" && w.height === 2.8)).toBe(true); + expect(next.walls.filter((w) => w.wallTypeId === "aw").length).toBe(4); + expect(next.wallTypes.length).toBe(2); + expect(next.openings?.length).toBe(1); + expect(next.openings?.[0].kind).toBe("door"); + expect(next.rooms?.map((x) => x.name).filter((n) => n === "Wohnen" || /^Raum \d$/.test(n)).length).toBe(2); + }); + + it("Auswahl: nur die gewählten Elemente", () => { + const p = project(); + const r = recognizeCommand.autoRun!(ctxOf(p, ["i"])); + expect(r.notice?.params).toMatchObject({ walls: 1, doors: 0, rooms: 0 }); + }); + + it("Bericht (B) und Quelle (E)", () => { + const p = project(); + const ctx = ctxOf(p); + const [, rep] = recognizeCommand.onInput(recognizeCommand.init(), { kind: "option", id: "report" }, ctx); + expect(rep.notice?.key).toBe("cmd.recognize.reportNotice"); + expect(String(rep.notice?.params?.text)).toMatch(/30|15/); + const [s1] = recognizeCommand.onInput(recognizeCommand.init(), { kind: "option", id: "source" }, ctx); + expect(recognizeCommand.options(s1)[0].value).toBe("Import"); + }); + + it("Bericht-Text zählt unklare Stellen je Grund", () => { + const txt = reportText({ + walls: 1, doors: 0, windows: 0, voids: 0, rooms: 0, arcWalls: 0, filledWalls: 0, unnamedRooms: 0, thicknesses: [0.3], layerFilter: true, + unclear: [{ code: "doorArc", x: 0, y: 0 }, { code: "doorArc", x: 1, y: 0 }, { code: "gapWide", x: 0, y: 0 }], + }); + expect(txt).toContain("2×"); + expect(txt).toContain("1×"); + }); + + it("ohne Zeichnung: Vorbedingung meldet, nichts erkannt → kein Commit", () => { + const p = { ...project(), drawings2d: [] }; + expect(recognizeCommand.precondition!(ctxOf(p))).toBe("cmd.recognize.noDrawing"); + const p2 = { ...project(), drawings2d: project().drawings2d.slice(3) }; + const [, r] = recognizeCommand.onConfirm(recognizeCommand.init(), ctxOf(p2)); + expect(r.commit).toBeUndefined(); + expect(r.notice?.key).toBe("cmd.recognize.nothing"); + }); +}); diff --git a/src/commands/cmds/recognize.ts b/src/commands/cmds/recognize.ts new file mode 100644 index 00000000..5605e262 --- /dev/null +++ b/src/commands/cmds/recognize.ts @@ -0,0 +1,146 @@ +// [154] Bauteile aus Zeichnung erkennen: aus den 2D-Linien eines Grundrisses (DXF/DWG-Import aus ArchiCAD, +// Vectorworks, AutoCAD) Wände, Öffnungen und Räume. Quelle: die gewählten 2D-Elemente, sonst die Zeichnung des +// aktiven Geschosses, sonst die erste Ebene mit Zeichnung (Option E schaltet durch). Beim Start zeigt die Vorschau +// alles Erkannte (Wandbänder, Türen/Fenster/Durchbrüche, Räume, unklare Stellen als Kreuz), die Meldung zählt; +// B zeigt den Bericht (unklar, mit Grund). Enter übernimmt als EIN Undo-Schritt ins aktive Geschoss (Höhe = +// Geschosshöhe). Die Erkennung rechnet der Kern (`drawing_recognize.rs`). + +import type { CmdOption, Command, CommandContext, CommandResult, CommandState, ToolDraft, Vec2 } from "../types"; +import { createPreview } from "../createCore"; +import { t, type TranslationKey } from "../../i18n"; +import { recognizeMutation, recognizeReport, recognizeSourceLevels } from "../../core"; +import type { RecognizeOptions, RecognizeReport } from "../../core"; + +interface RecognizeState extends CommandState { + /** Gewählte Quell-Ebene (Option E) und ihr Name für die Befehlszeile. */ + sticky: { src?: string; name?: string }; +} + +const selectedIds = (ctx: CommandContext): string[] => + ctx.selection.drawingIds ?? (ctx.selection.drawingId ? [ctx.selection.drawingId] : []); + +/** Quell-Ebene: gewählt, sonst das aktive Geschoss (hat es Zeichnung), sonst die erste Zeichnungsebene. */ +function sourceOf(s: RecognizeState, ctx: CommandContext): string { + const list = recognizeSourceLevels(ctx.project); + if (s.sticky?.src && list.includes(s.sticky.src)) return s.sticky.src; + if (list.includes(ctx.level.id)) return ctx.level.id; + const drawing = list.find((id) => ctx.project.drawingLevels.find((l) => l.id === id)?.kind === "drawing"); + return drawing ?? list[0] ?? ctx.level.id; +} + +function optionsOf(s: RecognizeState, ctx: CommandContext): RecognizeOptions { + return { + levelId: ctx.level.id, + floorHeight: ctx.level.floorHeight, + sourceLevelId: sourceOf(s, ctx), + ids: selectedIds(ctx), + categoryCode: ctx.defaultCategoryCode, + wallTypeId: ctx.activeWallTypeId, + typeName: t("cmd.recognize.typeName"), + roomName: t("cmd.recognize.roomName"), + }; +} + +interface Evaluated { + report: RecognizeReport; + draft: ToolDraft; +} + +// Je Mausschritt dieselbe Erkennung: gemerkt je Projektstand und Anfrage. +let cache: { project: unknown; key: string; value: Evaluated } | null = null; + +function evaluate(s: RecognizeState, ctx: CommandContext): Evaluated { + const o = optionsOf(s, ctx); + const key = JSON.stringify(o); + if (cache && cache.project === ctx.project && cache.key === key) return cache.value; + const report = recognizeReport(ctx.project, o); + const pv = createPreview(ctx, { cmd: "recognize", src: o.sourceLevelId, ids: o.ids, typeName: o.typeName, roomName: o.roomName }, []); + const value = { report, draft: { preview: pv.shapes, vertices: [] } }; + cache = { project: ctx.project, key, value }; + return value; +} + +const countParams = (r: RecognizeReport) => ({ + walls: r.walls, + doors: r.doors, + windows: r.windows, + voids: r.voids, + rooms: r.rooms, + unclear: r.unclear.length, +}); + +/** Kurzzeile am Cursor. */ +const hudText = (r: RecognizeReport): string => t("cmd.recognize.hud", countParams(r)); + +/** Bericht: unklare Stellen je Grund gezählt. */ +export function reportText(r: RecognizeReport): string { + const by = new Map(); + for (const u of r.unclear) by.set(u.code, (by.get(u.code) ?? 0) + 1); + const parts = [...by].map(([code, n]) => `${n}× ${t(`cmd.recognize.reason.${code}` as TranslationKey)}`); + const thick = r.thicknesses.map((x) => `${Math.round(x * 1000) / 10}`).join(" / "); + const head = t("cmd.recognize.reportHead", { thick: thick || "—", filled: r.filledWalls, arcs: r.arcWalls, unnamed: r.unnamedRooms }); + const filter = r.layerFilter ? ` ${t("cmd.recognize.layerFilter")}` : ""; + return parts.length ? `${head}${filter} ${t("cmd.recognize.unclearList", { list: parts.join("; ") })}` : `${head}${filter} ${t("cmd.recognize.noUnclear")}`; +} + +function show(s: RecognizeState, ctx: CommandContext): CommandResult { + const { report, draft } = evaluate(s, ctx); + if (report.walls === 0) return { draft: null, notice: { key: "cmd.recognize.nothing", kind: "warning" } }; + return { draft, notice: { key: "cmd.recognize.summary", params: countParams(report), kind: "info" } }; +} + +const done = (): [CommandState, CommandResult] => [{ phase: "confirm", lastPoint: null }, { draft: null, done: true }]; + +export const recognizeCommand: Command = { + name: "erkennen", + labelKey: "cmd.recognize.label", + floorOnly: true, + prompt: () => "cmd.recognize.prompt", + accepts: () => ["option"], + options: (state): CmdOption[] => { + const s = state as RecognizeState; + return [ + { id: "source", labelKey: "cmd.recognize.source", key: "E", value: s.sticky?.name ?? t("cmd.recognize.sourceAuto") }, + { id: "report", labelKey: "cmd.recognize.report", key: "B" }, + ]; + }, + precondition: (ctx) => (recognizeSourceLevels(ctx.project).length === 0 && selectedIds(ctx).length === 0 ? "cmd.recognize.noDrawing" : null), + init: (): RecognizeState => ({ phase: "confirm", lastPoint: null, sticky: {} }), + + autoRun: (ctx) => show({ phase: "confirm", lastPoint: null, sticky: {} }, ctx), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as RecognizeState; + if (input.kind === "option" && input.id === "source") { + const list = recognizeSourceLevels(ctx.project); + const cur = sourceOf(s, ctx); + const next = list[(list.indexOf(cur) + 1) % Math.max(1, list.length)] ?? cur; + const name = ctx.project.drawingLevels.find((l) => l.id === next)?.name; + const ns: RecognizeState = { ...s, sticky: { src: next, name } }; + return [ns, show(ns, ctx)]; + } + if (input.kind === "option" && input.id === "report") { + const { report, draft } = evaluate(s, ctx); + return [s, { draft, notice: { key: "cmd.recognize.reportNotice", params: { text: reportText(report) }, kind: "info" } }]; + } + return [s, { draft: evaluate(s, ctx).draft }]; + }, + + onMove: (state, point: Vec2, _snap, ctx): [CommandState, CommandResult] => { + const { report, draft } = evaluate(state as RecognizeState, ctx); + return [state, { draft: { ...draft, hud: { at: point, text: hudText(report) } } }]; + }, + + onConfirm: (state, ctx): [CommandState, CommandResult] => { + const s = state as RecognizeState; + const { report } = evaluate(s, ctx); + cache = null; + if (report.walls === 0) return [s, { draft: null, done: true, notice: { key: "cmd.recognize.nothing", kind: "warning" } }]; + const commit = recognizeMutation(optionsOf(s, ctx)); + return [{ phase: "confirm", lastPoint: null }, { draft: null, done: true, commit, notice: { key: "cmd.recognize.done", params: countParams(report), kind: "info" } }]; + }, + onCancel: () => { + cache = null; + return done(); + }, +}; diff --git a/src/commands/registry.ts b/src/commands/registry.ts index 1e46e655..77943803 100644 --- a/src/commands/registry.ts +++ b/src/commands/registry.ts @@ -37,6 +37,7 @@ import { scalebarCommand } from "./cmds/scalebar"; import { revcloudCommand } from "./cmds/revcloud"; import { pointmarkerCommand } from "./cmds/pointmarker"; import { wandCommand } from "./cmds/wand"; +import { recognizeCommand } from "./cmds/recognize"; import { wipeoutCommand } from "./cmds/wipeout"; import { textCommand } from "./cmds/text"; import { leaderCommand } from "./cmds/leader"; @@ -112,6 +113,7 @@ export const COMMANDS: Record = { revcloud: revcloudCommand, pointmarker: pointmarkerCommand, zauberstab: wandCommand, + erkennen: recognizeCommand, wipeout: wipeoutCommand, text: textCommand, leader: leaderCommand, @@ -234,6 +236,8 @@ export const ALIASES: Record = { revisionswolke: "revcloud", pm: "pointmarker", zs: "zauberstab", + bauteileerkennen: "erkennen", + recognize: "erkennen", punkt: "pointmarker", knoten: "pointmarker", wo: "wipeout", diff --git a/src/core/extra.ts b/src/core/extra.ts index b7b1f8f5..ae2bbd2d 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -88,3 +88,5 @@ export { lineEndsOf, lineEndsCode, lineEndsFromCode, lineEndsSvgAttrs, planLineE export type { LineEnds } from "../model/lineEnds"; export type { LineCap, LineJoin } from "../model/types"; export { standardOverrideRules } from "../model/standards"; +export { recognizeMutation, recognizeReport, recognizeSourceLevels } from "../io/recognizeDrawing"; +export type { RecognizeOptions, RecognizeReport, RecognizeUnclear } from "../io/recognizeDrawing"; diff --git a/src/i18n/de.ts b/src/i18n/de.ts index d4810064..f58ef120 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1962,6 +1962,30 @@ export const de = { "cmd.wand.label": "Zauberstab", "cmd.wand.point": "In eine umschlossene Fläche klicken:", "cmd.wand.hatch": "Schraffur", + "cmd.recognize.label": "Bauteile aus Zeichnung erkennen", + "cmd.recognize.prompt": "Erkannte Bauteile übernehmen (Enter), Quelle wählen (E) oder Bericht (B):", + "cmd.recognize.source": "Quelle", + "cmd.recognize.sourceAuto": "automatisch", + "cmd.recognize.report": "Bericht", + "cmd.recognize.typeName": "Wand {cm} cm (erkannt)", + "cmd.recognize.roomName": "Raum {n}", + "cmd.recognize.hud": "{walls} Wände · {doors} Türen · {windows} Fenster · {voids} Durchbrüche · {rooms} Räume · {unclear} unklar", + "cmd.recognize.summary": "Erkannt: {walls} Wände, {doors} Türen, {windows} Fenster, {voids} Durchbrüche, {rooms} Räume; unklar: {unclear}. Enter übernimmt, B zeigt den Bericht.", + "cmd.recognize.done": "Übernommen: {walls} Wände, {doors} Türen, {windows} Fenster, {voids} Durchbrüche, {rooms} Räume (ein Rückgängig-Schritt).", + "cmd.recognize.nothing": "Keine Wände erkannt (parallele Linien im Abstand 5–60 cm).", + "cmd.recognize.noDrawing": "Keine 2D-Zeichnung vorhanden – zuerst einen Grundriss (DXF/DWG) importieren.", + "cmd.recognize.reportNotice": "{text}", + "cmd.recognize.reportHead": "Wanddicken (cm): {thick}; mit Füllung bestätigt: {filled}; Bogenwände: {arcs}; Räume ohne Namen: {unnamed}.", + "cmd.recognize.layerFilter": "Nur Linien auf Wand-Layern verwendet.", + "cmd.recognize.unclearList": "Unklar: {list}.", + "cmd.recognize.noUnclear": "Nichts unklar.", + "cmd.recognize.reason.areaMismatch": "Flächenangabe weicht > 5 % vom Raum ab", + "cmd.recognize.reason.areaOutside": "Flächenangabe ausserhalb eines erkannten Raums", + "cmd.recognize.reason.lineUnpaired": "Wandlinie ohne Gegenlinie", + "cmd.recognize.reason.doorArc": "Türbogen ohne Wandlücke", + "cmd.recognize.reason.doorHalf": "halber Türbogen ohne Gegenflügel (als einflüglig angelegt)", + "cmd.recognize.reason.gapWide": "Lücke über 1.5 m ohne Tür/Fenster (nicht angelegt)", + "cmd.recognize.reason.tooMany": "zu viele Linien (über 60 000) – Auswahl verkleinern", "cmd.grid.label": "Achsraster", "cmd.grid.origin": "Ursprung des Achsrasters ( Radial ):", "cmd.grid.radial": "Radial", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index e17542c5..9643fcf5 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1951,6 +1951,30 @@ export const en: Record = { "cmd.wand.label": "Magic wand", "cmd.wand.point": "Click inside an enclosed area:", "cmd.wand.hatch": "Hatch", + "cmd.recognize.label": "Recognize elements from drawing", + "cmd.recognize.prompt": "Accept recognized elements (Enter), choose source (E) or report (B):", + "cmd.recognize.source": "Source", + "cmd.recognize.sourceAuto": "automatic", + "cmd.recognize.report": "Report", + "cmd.recognize.typeName": "Wall {cm} cm (recognized)", + "cmd.recognize.roomName": "Room {n}", + "cmd.recognize.hud": "{walls} walls · {doors} doors · {windows} windows · {voids} openings · {rooms} rooms · {unclear} unclear", + "cmd.recognize.summary": "Recognized: {walls} walls, {doors} doors, {windows} windows, {voids} wall openings, {rooms} rooms; unclear: {unclear}. Enter accepts, B shows the report.", + "cmd.recognize.done": "Added: {walls} walls, {doors} doors, {windows} windows, {voids} wall openings, {rooms} rooms (one undo step).", + "cmd.recognize.nothing": "No walls recognized (parallel lines 5–60 cm apart).", + "cmd.recognize.noDrawing": "No 2D drawing – import a floor plan (DXF/DWG) first.", + "cmd.recognize.reportNotice": "{text}", + "cmd.recognize.reportHead": "Wall thicknesses (cm): {thick}; confirmed by fill: {filled}; curved walls: {arcs}; rooms without name: {unnamed}.", + "cmd.recognize.layerFilter": "Only lines on wall layers used.", + "cmd.recognize.unclearList": "Unclear: {list}.", + "cmd.recognize.noUnclear": "Nothing unclear.", + "cmd.recognize.reason.areaMismatch": "area label differs from the room by > 5 %", + "cmd.recognize.reason.areaOutside": "area label outside any recognized room", + "cmd.recognize.reason.lineUnpaired": "wall line without a parallel partner", + "cmd.recognize.reason.doorArc": "door swing without a wall gap", + "cmd.recognize.reason.doorHalf": "half door swing without a second leaf (created as single leaf)", + "cmd.recognize.reason.gapWide": "gap over 1.5 m without door/window (not created)", + "cmd.recognize.reason.tooMany": "too many lines (over 60,000) – narrow the selection", "cmd.grid.label": "Structural grid", "cmd.grid.origin": "Grid origin ( Radial ):", "cmd.grid.radial": "Radial", diff --git a/src/io/recognizeDrawing.roundtrip.test.ts b/src/io/recognizeDrawing.roundtrip.test.ts new file mode 100644 index 00000000..a67bcbaa --- /dev/null +++ b/src/io/recognizeDrawing.roundtrip.test.ts @@ -0,0 +1,194 @@ +// [154] Rundreise: eigener DXF-Export eines Geschosses → DXF-Import (Layer als Kategorien, neue Zeichnungsebene) +// → „Bauteile aus Zeichnung erkennen“ → Wände/Öffnungen mit dem Original vergleichen (Quote auf der Konsole). +// Wände: Achse (beide Richtungen, ±1 cm) und Dicke (±1 mm); Öffnungen: Art und Pfosten (±2 cm), Türen zusätzlich +// Scharnierpunkt und Aufschlagseite. Mit `DOSSIER_RECOGNIZE_OUT=` werden Import und Ergebnis als .obp +// geschrieben (Bilder für den Bericht). + +import { writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { beforeAll, describe, expect, it } from "vitest"; +import { loadFileioForTests } from "../engine/fileioWasm.testing"; +import { parseDxf } from "./dxfParser"; +import { buildPlanDxf } from "../export/exportDxf"; +import { generatePlan } from "../plan/generatePlan"; +import { sampleProject } from "../model/sampleProject"; +import { buildComplexSampleProject } from "../model/sampleProjectComplex"; +import { flattenCategories } from "../model/types"; +import type { Opening, Project, Vec2, Wall } from "../model/types"; +import { ProjectDocument } from "../core/document"; +import { bulgeArc } from "../geometry/bulge"; +import { serializeProject } from "./projectFormat"; +import { recognizeMutation, recognizeReport, type RecognizeReport } from "./recognizeDrawing"; + +const OUT = process.env.DOSSIER_RECOGNIZE_OUT; + +const allCodes = (p: Project) => new Set(flattenCategories(p.layers).map((l) => l.code)); +const thickness = (p: Project, w: Wall) => (p.wallTypes.find((t) => t.id === w.wallTypeId)?.layers ?? []).reduce((s, l) => s + l.thickness, 0); +const dist = (a: Vec2, b: Vec2) => Math.hypot(a.x - b.x, a.y - b.y); + +interface Jambs { + kind: "door" | "window" | "void"; + a: Vec2; + b: Vec2; + /** Tür: Scharnierpunkt und Aufschlagseite (Einheitsvektor quer zur Wand). */ + hinge?: Vec2; + side?: Vec2; +} + +function jambs(p: Project, o: Opening): Jambs | null { + const w = p.walls.find((x) => x.id === o.hostWallId); + if (!w) return null; + const l = dist(w.start, w.end); + const u = { x: (w.end.x - w.start.x) / l, y: (w.end.y - w.start.y) / l }; + // Bogenwand: Lage als Bogenlänge auf der Achse ab `start`. + const arc = w.bulge ? bulgeArc(w.start, w.end, w.bulge) : null; + const at = (s: number) => + arc + ? { x: arc.center.x + arc.r * Math.cos(arc.a0 + Math.sign(arc.sweep) * (s / arc.r)), y: arc.center.y + arc.r * Math.sin(arc.a0 + Math.sign(arc.sweep) * (s / arc.r)) } + : { x: w.start.x + u.x * s, y: w.start.y + u.y * s }; + const voidish = o.kind === "door" && (o.doorType === "wandoeffnung" || p.doorTypes?.find((t) => t.id === o.typeId)?.kind === "wandoeffnung"); + const kind = voidish ? "void" : o.kind; + const j: Jambs = { kind, a: at(o.position), b: at(o.position + o.width) }; + if (kind === "door") { + j.hinge = at(o.position + (o.hinge === "end" ? o.width : 0)); + const k = (o.swing === "right" ? -1 : 1) * (o.openingDir === "out" ? -1 : 1); + j.side = { x: -u.y * k, y: u.x * k }; + } + return j; +} + +interface Quote { + walls: [number, number]; + /** Achsen-Abdeckung 0…1. */ + axis: number; + openings: [number, number]; + doors: [number, number]; + report: RecognizeReport; + imported: Project; + result: Project; +} + +/** Geschoss `levelId` von `orig` exportieren, in ein leeres Projekt mit denselben Typen importieren, erkennen. */ +function roundtrip(orig: Project, levelId: string): Quote { + const plan = generatePlan(orig, levelId, allCodes(orig)); + const dxf = buildPlanDxf(plan, orig, { scaleDenominator: 100, levelId }); + const parsed = parseDxf(dxf); + const base: Project = { ...orig, walls: [], openings: [], rooms: [], drawings2d: [], stairs: [], ceilings: [], roofs: [], columns: [] }; + const doc = new ProjectDocument(base); + const r = doc.importDrawing( + base, + parsed.src, + { + target: { kind: "new", name: "Import" }, + categoryMode: "byLayer", + activeCategoryCode: "20", + importMeshes: false, + levelNameTemplate: "Import {n}", + parentName: "Import", + dashStyleTemplate: "{pattern}", + }, + 0, + ); + if ("problems" in r) throw new Error(r.problems.join("; ")); + const imported = r.project; + const level = imported.drawingLevels.find((l) => l.id === levelId)!; + const opts = { levelId, floorHeight: level.floorHeight, sourceLevelId: r.levelId, wallTypeId: orig.wallTypes[0]?.id, typeName: "Wand {cm} cm (erkannt)" }; + const report = recognizeReport(imported, opts); + const result = recognizeMutation(opts)(imported); + doc.close(); + + const ow = orig.walls.filter((w) => w.floorId === levelId); + const nw = result.walls.filter((w) => w.floorId === levelId); + // Gleiche Wand: Dicke, Endpunkte (±1 cm), bei Bogenwänden derselbe Bogen (Bulge, umgekehrt mit Gegenzeichen). + const sameWall = (w: Wall, n: Wall) => { + if (Math.abs(thickness(orig, w) - thickness(result, n)) >= 1e-3) return false; + const fwd = dist(w.start, n.start) < 0.01 && dist(w.end, n.end) < 0.01; + const rev = dist(w.start, n.end) < 0.01 && dist(w.end, n.start) < 0.01; + const [bw, bn] = [w.bulge ?? 0, n.bulge ?? 0]; + return (fwd && Math.abs(bw - bn) < 1e-3) || (rev && Math.abs(bw + bn) < 1e-3); + }; + const wallOk = ow.filter((w) => nw.some((n) => sameWall(w, n))).length; + // Achsen-Abdeckung (gerade Wände): Anteil der Achslänge, die eine erkannte Achse gleicher Dicke trägt + // (zusammengelegte Wände über einen T-Stoss zählen hier voll). + const onAxis = (p: Vec2, n: Wall) => { + const l2 = (n.end.x - n.start.x) ** 2 + (n.end.y - n.start.y) ** 2; + const s = Math.max(0, Math.min(1, ((p.x - n.start.x) * (n.end.x - n.start.x) + (p.y - n.start.y) * (n.end.y - n.start.y)) / l2)); + return dist(p, { x: n.start.x + s * (n.end.x - n.start.x), y: n.start.y + s * (n.end.y - n.start.y) }) < 0.01; + }; + let [axisOk, axisAll] = [0, 0]; + for (const w of ow.filter((x) => !x.bulge)) { + const l = dist(w.start, w.end); + const k = Math.max(1, Math.round(l / 0.05)); + for (let i = 0; i < k; i++) { + const s = (i + 0.5) / k; + const p = { x: w.start.x + s * (w.end.x - w.start.x), y: w.start.y + s * (w.end.y - w.start.y) }; + axisAll += l / k; + if (nw.some((n) => !n.bulge && Math.abs(thickness(orig, w) - thickness(result, n)) < 1e-3 && onAxis(p, n))) axisOk += l / k; + } + } + const oo = (orig.openings ?? []).filter((o) => ow.some((w) => w.id === o.hostWallId)).map((o) => jambs(orig, o)).filter((j): j is Jambs => !!j); + const no = (result.openings ?? []).map((o) => jambs(result, o)).filter((j): j is Jambs => !!j); + const same = (x: Jambs, y: Jambs) => + x.kind === y.kind && ((dist(x.a, y.a) < 0.02 && dist(x.b, y.b) < 0.02) || (dist(x.a, y.b) < 0.02 && dist(x.b, y.a) < 0.02)); + const openOk = oo.filter((x) => no.some((y) => same(x, y))).length; + const od = oo.filter((x) => x.kind === "door"); + const doorOk = od.filter((x) => + no.some((y) => same(x, y) && dist(x.hinge!, y.hinge!) < 0.02 && dist(x.side!, y.side!) < 1e-6), + ).length; + return { walls: [wallOk, ow.length], axis: axisAll ? axisOk / axisAll : 1, openings: [openOk, oo.length], doors: [doorOk, od.length], report, imported, result }; +} + +const pct = ([a, b]: [number, number]) => `${a}/${b} (${b ? Math.round((100 * a) / b) : 100} %)`; + +function log(name: string, q: Quote) { + console.log( + `[154] ${name}: Wände ${pct(q.walls)} (Achsen ${Math.round(q.axis * 100)} %), Öffnungen ${pct(q.openings)}, Türen mit Anschlag/Aufschlag ${pct(q.doors)}; ` + + `erkannt ${q.report.walls} Wände, ${q.report.doors} Türen, ${q.report.windows} Fenster, ${q.report.voids} Durchbrüche, ${q.report.rooms} Räume, unklar ${q.report.unclear.length} (${[...new Set(q.report.unclear.map((u) => u.code))].join(", ")})`, + ); + if (OUT) { + writeFileSync(join(OUT, `${name}-import.obp`), serializeProject(q.imported)); + writeFileSync(join(OUT, `${name}-erkannt.obp`), serializeProject(q.result)); + } +} + +describe("[154] Rundreise DXF-Export → Import → Bauteile erkennen", () => { + beforeAll(loadFileioForTests); + + it("Musterhaus EG: alle Wände und Öffnungen, Tür mit Anschlag und Aufschlag", () => { + const q = roundtrip(sampleProject, "eg"); + log("musterhaus-eg", q); + expect(q.walls).toEqual([5, 5]); + expect(q.openings).toEqual([3, 3]); + expect(q.doors).toEqual([1, 1]); + // Wandtypen nach Dicke wiederverwendet, keine neuen. + expect(q.result.wallTypes.length).toBe(sampleProject.wallTypes.length); + expect(q.report.layerFilter).toBe(true); + // Raum mit Name aus dem Raumstempel. + expect(q.result.rooms?.some((r) => r.name === "Wohnen")).toBe(true); + }); + + it("Musterhaus OG", () => { + const q = roundtrip(sampleProject, "og"); + log("musterhaus-og", q); + expect(q.walls[0]).toBe(q.walls[1]); + expect(q.openings[0]).toBe(q.openings[1]); + }); + + it("Musterhaus komplex: Quote je Geschoss", () => { + const p = buildComplexSampleProject(); + const floors = p.drawingLevels.filter((l) => l.kind === "floor" && p.walls.some((w) => w.floorId === l.id)); + let [w, wn, o, on, ax] = [0, 0, 0, 0, 0]; + for (const l of floors) { + const q = roundtrip(p, l.id); + log(`komplex-${l.id}`, q); + w += q.walls[0]; + ax += q.axis / floors.length; + wn += q.walls[1]; + o += q.openings[0]; + on += q.openings[1]; + } + console.log(`[154] Musterhaus komplex gesamt: Wände ${pct([w, wn])} (Achsen ${Math.round(ax * 100)} %), Öffnungen ${pct([o, on])}`); + expect(wn).toBeGreaterThan(0); + expect(w / wn).toBeGreaterThan(0.6); + }, 120_000); +}); diff --git a/src/io/recognizeDrawing.ts b/src/io/recognizeDrawing.ts new file mode 100644 index 00000000..459e3a80 --- /dev/null +++ b/src/io/recognizeDrawing.ts @@ -0,0 +1,82 @@ +// [154] Bauteile aus Zeichnung erkennen — dünne Fassade über den Kern (`src-tauri/core/src/drawing_recognize.rs`): +// aus den 2D-Linien eines Grundrisses (DXF/DWG-Import) Wände, Öffnungen und Räume. Erkennung, Vorschau, Bericht +// und Ops rechnet der Kern; hier nur die Anfrage (Quell-Ebene, Auswahl, Namensvorlagen, Ziel-Geschoss). + +import type { Project } from "../model/types"; +import type { ProjectMutation } from "../core/opsBuild"; +import { cmdMutation, documentFor } from "../core/document"; + +/** Unklare Stelle: Grund (Schlüssel `cmd.recognize.reason.`) und Lage. */ +export interface RecognizeUnclear { + code: "areaMismatch" | "areaOutside" | "lineUnpaired" | "doorArc" | "doorHalf" | "gapWide" | "tooMany"; + x: number; + y: number; +} + +/** Bericht der Erkennung (Abfrage `recognize`). */ +export interface RecognizeReport { + walls: number; + doors: number; + windows: number; + voids: number; + rooms: number; + arcWalls: number; + /** Wände mit Füllung/Schraffur zwischen den Linien. */ + filledWalls: number; + unnamedRooms: number; + /** Erkannte Wanddicken (m, auf mm gerundet). */ + thicknesses: number[]; + /** Nur Linien auf Wand-Layern verwendet („Wand“, „Mauer“, „A-WALL“ …). */ + layerFilter: boolean; + unclear: RecognizeUnclear[]; +} + +export interface RecognizeOptions { + /** Ziel-Geschoss (Wände, Höhe). */ + levelId: string; + /** Geschosshöhe (Wandhöhe); fehlt → Kern-Vorgabe 2.6 m. */ + floorHeight?: number; + /** Ebene mit der Zeichnung; fehlt → `levelId`. Ohne Wirkung, wenn `ids` gesetzt ist. */ + sourceLevelId?: string; + /** Nur diese 2D-Elemente (Auswahl). */ + ids?: readonly string[]; + /** Kategorie, falls „20/21/60“ fehlen. */ + categoryCode?: string; + /** Aktiver Wandtyp (Baustoff neuer Wandtypen). */ + wallTypeId?: string; + /** Namensvorlage neuer Wandtypen, `{cm}` = Dicke. */ + typeName?: string; + /** Namensvorlage unbenannter Räume, `{n}` = laufende Nummer. */ + roomName?: string; +} + +let seq = 0; + +function request(o: RecognizeOptions): Record { + return { + cmd: "recognize", + src: o.sourceLevelId ?? o.levelId, + ids: o.ids && o.ids.length > 0 ? [...o.ids] : [], + typeName: o.typeName ?? "", + roomName: o.roomName ?? "", + ctx: { level: o.levelId, floorHeight: o.floorHeight ?? null, cat: o.categoryCode ?? "20", wallType: o.wallTypeId ?? "" }, + }; +} + +/** Bericht (Zähler, unklare Stellen) ohne Änderung am Projekt. */ +export function recognizeReport(project: Project, o: RecognizeOptions): RecognizeReport { + const { cmd: _cmd, ctx: _ctx, ...rest } = request(o); + return documentFor(project).createQuery({ q: "recognize", level: o.levelId, ...rest }); +} + +/** Änderung: neue Wandtypen, Wände, Öffnungen, Räume als EIN Undo-Schritt. */ +export function recognizeMutation(o: RecognizeOptions): ProjectMutation { + seq += 1; + return cmdMutation({ ...request(o), stamp: `${Date.now()}-r${seq}` }); +} + +/** Ebenen mit 2D-Zeichnung (Geschosse und Zeichnungsebenen), in Projekt-Reihenfolge. */ +export function recognizeSourceLevels(project: Project): string[] { + const used = new Set(project.drawings2d.map((d) => d.levelId)); + return project.drawingLevels.filter((l) => (l.kind === "floor" || l.kind === "drawing") && used.has(l.id)).map((l) => l.id); +}