Merge branch 'worktree-agent-acb89ec95d3f38809' into claude/practical-noether-1hb2s1

# Conflicts:
#	TODO.md
This commit is contained in:
Claude committed 2026-11-07 15:22:52 +00:00
commit 6f35c5bc12
14 files changed
+2880 -2

No files matched your search

+37
View File
@@ -3508,6 +3508,43 @@ Format · [90] Versionsvergleich · [91] Assistent · [92] Speckle.
(beginnen mit Strich); DXF/DWG ohne Phase je Objekt (Linientyp beginnt am Anfang, Massstab stimmt); Metal-Pfad verkettet
abgeleitete gestrichelte Linien nur über das Ketten-Flag (Zeichnungen), React-SVG-Ansicht ohne Phase; nur Linux, nicht in
der Tauri-App/Metal angesehen. · 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 <p.obp> 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
+5 -1
View File
@@ -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<String, Value>, p: &Project, v: &Value) -> Option<Vec<Op>>
"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<String, Value>, 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<String, Value>, p: &Project, v: &Value) -> Option<Result
}
None => 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),
File diff suppressed because it is too large. Load diff
@@ -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<Value>) -> (Project, serde_json::Map<String, Value>) {
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::<Vec<_>>()})
}
/// Raum 5 × 4 (Achsen) mit Aussenwänden 30 cm und Innenwand 15 cm, Tür mit Bogen, Raumtext.
fn small_house() -> Vec<Value> {
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<Value> {
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<V> {
(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);
}
+1
View File
@@ -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;
+25 -1
View File
@@ -26,6 +26,9 @@
// Bauteile ([B4]); Bericht als JSON auf stdout
// dossier-cli <projekt.obp> import-mesh <datei.obj|stl|gltf|glb|ply> [--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 <projekt.obp> 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 <projekt.obp> model3d [--explode 3] [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png)
// dossier-cli pointcloud-info <datei.las|laz|e57|ply|xyz|pts> [--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<number> {
if (file === "mcp" && args.flags.has("app")) return runAppBridge(args);
if (!file || (!command && args.cmds.length === 0)) {
process.stderr.write(
"Aufruf: dossier-cli <projekt.obp> <info|validate|migrate|plan|section|elevation|dxf|dwg|ifc|import-ifc|import-mesh|step|obj|stl|glb|gltf|schedule|kennzahlen|raumprogramm|sun|model3d> [Optionen]\n" +
"Aufruf: dossier-cli <projekt.obp> <info|validate|migrate|plan|section|elevation|dxf|dwg|ifc|import-ifc|import-mesh|erkennen|step|obj|stl|glb|gltf|schedule|kennzahlen|raumprogramm|sun|model3d> [Optionen]\n" +
" dossier-cli convert <eingabe.dxf|dwg|ifc|pdf|obj|stl|gltf|glb|ply|obp> <ausgabe.obp|dxf|dwg|ifc|obj|stl|glb|gltf|step> [--cmd \"befehl …\"]…\n" +
" dossier-cli <projekt.obp> --cmd \"befehl …\" [--cmd …] ({last} = zuletzt geschriebene Datei)\n" +
" dossier-cli pointcloud-info <datei> [--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");
+100
View File
@@ -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");
});
});
+146
View File
@@ -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<string, number>();
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();
},
};
+4
View File
@@ -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<string, Command> = {
revcloud: revcloudCommand,
pointmarker: pointmarkerCommand,
zauberstab: wandCommand,
erkennen: recognizeCommand,
wipeout: wipeoutCommand,
text: textCommand,
leader: leaderCommand,
@@ -234,6 +236,8 @@ export const ALIASES: Record<string, string> = {
revisionswolke: "revcloud",
pm: "pointmarker",
zs: "zauberstab",
bauteileerkennen: "erkennen",
recognize: "erkennen",
punkt: "pointmarker",
knoten: "pointmarker",
wo: "wipeout",
+2
View File
@@ -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";
+24
View File
@@ -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",
+24
View File
@@ -1951,6 +1951,30 @@ export const en: Record<TranslationKey, string> = {
"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",
+194
View File
@@ -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=<ordner>` 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);
});
+82
View File
@@ -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.<code>`) 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<string, unknown> {
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<RecognizeReport>({ 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);
}