diff --git a/TODO.md b/TODO.md index d7385184..ecd8bbb2 100644 --- a/TODO.md +++ b/TODO.md @@ -1262,8 +1262,11 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). Ausschnitt. **Haarfugen** der Dachfläche in der Ansicht: Kontur in Füllfarbe 0.15 mm statt 0.05 mm. Wand ↔ Dach: [G2]. Wand ↔ Decke: bestehende Schicht-Dominanz (3D je Band nach Rang, Schnitt `subtract_dominant_bands`) im CLI-Schnitt des Beispielprojekts angesehen, nicht geändert. Offen: - 3D-Live-Schnitt-Deckel verschnittener Dächer, Kehlen symmetrisch je Schicht, Warnung bei gekappter Gaube in - der UI, Wand ↔ Decke für beliebige Polygone im Schnitt ([G6]). + 3D-Live-Schnitt-Deckel verschnittener Dächer, Kehlen symmetrisch je Schicht, Wand ↔ Decke für beliebige Polygone im Schnitt ([G6]). + - (30.10.) **Hinweis bei gekappter Gaube:** Kern-Abfrage `dormerStatus` (`dormer.rs::status`: gekappt/ungültig, + tatsächliche Stirnhöhe); Objekt-Info des Dachs zeigt je Gaube eine Warnung, ein Toast erscheint, wenn eine Gaube + durch Anlegen/Ändern neu gekappt (oder unbrauchbar) wird (`useDormerNotice`; beim Öffnen nur merken). Tests Rust + + vitest (`dormerStatus.test.ts`). Nicht in der Tauri-App geprüft. - (30.10.) Boolean-Werkzeug dafür: Manifold-Port `manifold-rust`, nicht truck — truck scheitert an Gaube und L-Ecke (bündige Unterseiten), `manifold-rust` rechnet beide exakt und dicht. Details und Plan: [107]. - ○ **[G6] Allgemeine Polygon-Dominanz im Schnitt** (nicht nur Rechtecke). · M @@ -1427,9 +1430,13 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). Tests: Rust (Bruchkanten, Kegelhügel ohne Überschwingen/flache Dreiecke, Prisma dicht, Unsinn), vitest. Geprüft im Linux-Container (CLI-Grundriss/-Schnitt/-Ansicht eines Hügels mit Baugrube angesehen; Erdreich-Schraffur über den Kern-Generator gerendert, das CLI-SVG zeigt keine Schraffuren), nicht in der Tauri-App. - Offen: swissALTI3D-Raster wird nicht geglättet (nur Äquidistanz 1 m gesetzt); Natural-Neighbour/Clough-Tocher statt - Hermite-Teilung; Höhenlinien unter der Beschriftung nicht unterbrochen; Luftbild-Farben fallen auf geändertem - Gelände weg; Erdreich-Band fest 1.5 m (nicht bis zur Planunterkante). · L + (30.10., Folge) **Höhenlinien** sind unter der Zähllinien-Beschriftung unterbrochen (Lücke = Textbreite + 0.4·Höhe je + Seite). **swissALTI3D-Glättung:** Importdialog „Glättung des Höhenrasters" (Rohdaten/leicht = 1/stark = 3 Durchgänge), + Kern `terrain::smooth_grid` (Binomialfilter [1 2 1] je Achse, Lücken bleiben). **Luftbild-Farben auf geändertem Gelände:** + `excavation::reproject_colors` überträgt die Vertex-Farben per Grundriss-Projektion (x, y) auf das Netz mit Baugruben + (3D). Erdreich-Band konfigurierbar (`earthDepth`, s. [68]). Tests Rust (Lücke, Glättung, Farben), vitest (Raster). + Offen: Natural-Neighbour/Clough-Tocher statt Hermite-Teilung; Erdreich-Band nicht „bis zur Planunterkante"; Glättung + ohne Kantenerhalt (Gebäude/Böschungen im Raster werden mitgeglättet). · L - ✅ **[T7] Rotationskörper/Loft im UI** (API besteht). · S–M — 30.10.: Befehle `revolve` (Profil + Achse aus 2 Plan-Punkten + Winkel; Achse waagrecht auf Höhe r_max, Profil auf einer Seite) und `loft` (≥ 2 Profile der Reihe nach, gleichmässig über die Höhe; Punktzahl durch Kantenteilung angeglichen) in `cmd_solid.rs`/`cmds/{revolve,loft}.ts`, Körper als `ExtrudedSolid.brep` (Objekt-Info, STEP, Kennwerte wie die Grundkörper); Kürzel `rev`/`lf`, Werkzeugpalette 3D. Tests Rust (Spezifikation, Ops, truck-Volumen/STEP), vitest (Befehlsablauf). Nicht in der Tauri-App getestet. Offen: Achse senkrecht/beliebig im Raum, Loft mit Führungskurve, Profil-Startpunkt-Ausrichtung beim Loft. - ✅ **[T8] Kollisionsprüfung im 3D zeigen** (heute nur Marker im Grundriss). · S — 30.10.: Treffer in Sitzung (`panels/clashSession.ts`), Panel „Kollisionen" (`ClashPanel`: Liste, Klick wählt beide Bauteile und fährt die 3D-Kamera auf die Durchdringung, `cameraBridge.focusCamera`), im 3D rote Hüllquader aller Treffer (`clashHighlightLines` in `viewportContent`); Prüflauf öffnet das Panel, Marker im Grundriss bleiben. Tests vitest (Linien, Auswahl, Kamera-Fokus). Nicht im echten WebGPU-Viewport/Tauri geprüft. Offen: Hüllquader statt exakter Durchdringungsgeometrie, Panel-Name zeigt Ids statt Bauteilnamen, Wiederholung/Ignorieren einzelner Treffer. @@ -1812,8 +1819,14 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). assoziativ [38] an Achse/Achsschnittpunkt. Befehl `grid` (Kürzel `achsraster`, `achsen`, Werkzeug „Achsraster"): Ursprung, dann Feldweiten als Text (`6 4.5 3x5`), Option Radial; Attribute-Panel: Blasenseite, Überstand, Blasen-Ø, Geschosse, 3D. Geprüft im Linux-Container (Rust, vitest, e2e, CLI-SVG Grundriss/Schnitt/Ansicht), nicht in der - Tauri-App/Metal. Offen: Achsbeschriftung je Achse im UI ändern, Blasenseite je Achse, Achsen als Autodim-Vorschlag, - IFC `IfcGrid`, Raster-Versatz je Geschoss. · M + Tauri-App/Metal. Offen: Achsen als Autodim-Vorschlag, Raster-Versatz je Geschoss. · M + - (30.10.) **Achsbeschriftung und Blasenseite je Achse** (`GridAxis.bubble`, optional, überschreibt `Grid.bubbles`; + `grid.rs`): Attribute-Panel listet alle Achsen (Strahl/Ring bei radial) mit Textfeld Beschriftung und Auswahl + Blasenseite (statt Objekt-Info, dort steht das Raster nicht). **IFC:** `IfcGrid` (`REC_GRID` in `ifc_data.rs`/ + `ifc_export.rs`, IFC4 und 2x3): a-Achsen = UAxes, b-Achsen = VAxes als `IfcGridAxis` mit `IfcPolyline` in Welt-XY + (Bögen in ≤ 5°-Sehnen, kein `IfcCircle`), ohne eigene Darstellung (2D-Kurven in 3D-Kontext scheitern in ifcopenshell), am Geschoss (genau ein + `levels`-Eintrag) sonst am Gebäude. Tests: Rust (Blasenseite), vitest `exportIfc.grid.test.ts` (Text IFC4/2x3 + + ifcopenshell `validate-ifc.py` gültig, Achsen lesbar; ortho und radial). - ◐ **[110] Linientyp ohne Strichstärke.** (30.10., Wunsch Maintainer: „Volllinie 0.5/0.35 soll es nicht geben") Ein Linienstil ist nur Muster (Volllinie, Strich, Punkt, Zickzack, Motiv) + Farbe; die Stärke trägt das Element (`Drawing2D.weightMm`, sonst Ebene), die Schraffur (neu `HatchStyle.lineWeight`, Default 0.13), @@ -1937,8 +1950,18 @@ Format · [90] Versionsvergleich · [91] Assistent · [92] Speckle. Layout-Tabelle „Erdarbeiten" ([111], Quelle `earthworks`), CLI `kennzahlen` → `erdarbeiten`. Baurecht ([63]): Geländehöhen an der Fassade (gewachsen/gestaltet, Ecken + alle ≤ 2 m), massgebendes Terrain = tiefster gewachsener Punkt an der Fassade (vereinfacht), Gesamthöhe dagegen geprüft (ohne Gelände wie bisher ±0.00). - Offen: Mengen je Baugrube gegen das gewachsene Terrain (Überlagerungen doppelt); Arbeitsraum als Abstand; - senkrechter Verbau (Spundwand) nur als 89.5°-Böschung; Griffe/Objekt-Info für den Umriss; IVHB-Terrain nach + (30.10., Folge) **Griffe** im Grundriss (genau eine gewählte Baugrube): Umriss-Ecken, Kanten (parallel ziehen) und + Sohlenhöhe (Kern `grips.rs` `excavationGrip`/`excavationEdge`; der Sohlen-Griff sitzt im Schwerpunkt, y um die Sohlenhöhe + versetzt, Ziehen setzt `bottom` auf 1 cm gerundet; Ecken als Vorschau bis zum Loslassen). **Arbeitsraum** + `workingSpace` (m): Umriss gilt als Gebäude-Grundfläche, Sohle um das Mass nach aussen (Gehrung ≤ 4×). **Verbau** + `edgeShoring` je Kante: senkrecht (89.5° im Rechner, ohne Böschungsschraffur), Panel: Kästchen je Kante. + **Überlagerung:** `volumes_union` wirkt die Baugruben der Reihe nach (wie das Netz), Differenz je Probe geht an + die jeweilige Grube — Summe = Vereinigung; Sohlenfläche ohne die der früheren Gruben (per Raster, ≈). + Erdreich-Band: `TerrainMesh.earthDepth` (Panel „Erdreich-Band im Schnitt", Default 1.5 m). Tests Rust + (Arbeitsraum/Verbau/Überlappung, Griffe), vitest (Mengen, Griffe). CLI-Grundriss/-Schnitt mit Arbeitsraum + Verbau + angesehen (Linux). Offen: Verbau als echte Wand im Schnitt mit Dicke/Schraffur; Überlappung der Sohlenfläche + nur gerastert; Arbeitsraum an konkaven Ecken ohne Selbstüberschneidungs-Prüfung; Griffe nicht in der Tauri-App + geprüft; IVHB-Terrain nach kantonalem Recht (Lotrechte statt tiefster Fassadenpunkt); nicht in der Tauri-App geprüft. - ◐ **[107] Manifold für Körper-Booleans (Schritt 1: trucksolid).** (30.10.) `manifold-rust` `=0.19.1` (Apache-2.0, diff --git a/src-tauri/core/src/dormer.rs b/src-tauri/core/src/dormer.rs index 73f0fb01..f9607b46 100644 --- a/src-tauri/core/src/dormer.rs +++ b/src-tauri/core/src/dormer.rs @@ -214,6 +214,37 @@ pub fn geometry(p: &Project, roof: &Roof, d: &Dormer) -> Option { Some(g2) } +/// Zustand einer Gaube für die Hülle ([G5]): am First gekappt (`clamped`, `effective_height` = tatsächliche +/// Stirnhöhe) oder nicht herstellbar (`invalid`). +#[derive(Debug, serde::Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct DormerStatus { + pub roof_id: String, + pub dormer_id: String, + pub clamped: bool, + pub invalid: bool, + pub effective_height: f64, +} + +/// Zustand aller Gauben des Projekts (nur solche, die gekappt oder ungültig sind, sind für die UI wichtig; +/// hier alle, damit die Hülle auch „wieder in Ordnung" erkennt). +pub fn status(p: &Project) -> Vec { + let mut out = Vec::new(); + for roof in p.roofs.as_deref().unwrap_or(&[]) { + for d in roof.dormers.as_deref().unwrap_or(&[]) { + let g = geometry(p, roof, d); + out.push(DormerStatus { + roof_id: roof.id.clone(), + dormer_id: d.id.clone(), + clamped: g.as_ref().is_some_and(|g| g.clamped), + invalid: g.is_none(), + effective_height: g.as_ref().map_or(0.0, |g| g.front_height), + }); + } + } + out +} + fn geometry_raw(p: &Project, roof: &Roof, d: &Dormer) -> Option { let frame = frame(p, roof, d)?; if !(finite_pos(d.width) && d.width >= 0.4 && d.width <= 30.0 && finite_pos(d.front_height) && d.front_height <= 10.0) { @@ -479,6 +510,18 @@ pub(crate) mod tests { .unwrap() } + #[test] + fn status_meldet_gekappte_gauben() { + let mut p = gable_project(); + let st = status(&p); + assert_eq!(st.len(), 1); + assert!(!st[0].clamped && !st[0].invalid && (st[0].effective_height - 1.6).abs() < 1e-9, "{st:?}"); + p.roofs.as_mut().unwrap()[0].dormers.as_mut().unwrap()[0].front_height = 6.0; + let st = status(&p); + assert!(st[0].clamped && !st[0].invalid && st[0].effective_height < 6.0 && st[0].effective_height > 0.3, "{st:?}"); + assert_eq!((st[0].roof_id.as_str(), st[0].dormer_id.as_str()), ("R1", "D1")); + } + #[test] fn zu_hohe_gaube_wird_vor_dem_first_gekappt() { let mut p = gable_project(); diff --git a/src-tauri/core/src/excavation.rs b/src-tauri/core/src/excavation.rs index 81b57433..586430fb 100644 --- a/src-tauri/core/src/excavation.rs +++ b/src-tauri/core/src/excavation.rs @@ -34,6 +34,8 @@ pub struct ExSpec { pub ring: Vec, pub bottom: f64, pub cut_tan: Vec, + /// Kante mit senkrechtem Verbau (Spundwand): keine Böschung, keine Schraffur. + pub shored: Vec, pub fill_tan: f64, pub berm_w: f64, pub berm_h: f64, @@ -65,6 +67,30 @@ fn signed_area(r: &[P2]) -> f64 { (0..n).map(|i| r[i][0] * r[(i + 1) % n][1] - r[(i + 1) % n][0] * r[i][1]).sum::() / 2.0 } +/// Umriss (gegen den Uhrzeigersinn) um `d` nach aussen versetzt: Gehrung an den Ecken, höchstens 4·d weit. +pub fn offset_ring(ring: &[P2], d: f64) -> Vec { + let n = ring.len(); + let normal = |i: usize| { + let (a, b) = (ring[i], ring[(i + 1) % n]); + let l = (b[0] - a[0]).hypot(b[1] - a[1]).max(1e-12); + [(b[1] - a[1]) / l, -(b[0] - a[0]) / l] + }; + (0..n) + .map(|i| { + let (n0, n1) = (normal((i + n - 1) % n), normal(i)); + let (mx, my) = (n0[0] + n1[0], n0[1] + n1[1]); + let k = 1.0 + n0[0] * n1[0] + n0[1] * n1[1]; + if k < 1e-6 { + return [ring[i][0] + n1[0] * d, ring[i][1] + n1[1] * d]; + } + let (sx, sy) = (mx * d / k, my * d / k); + let l = sx.hypot(sy); + let f = if l > 4.0 * d { 4.0 * d / l } else { 1.0 }; + [ring[i][0] + sx * f, ring[i][1] + sy * f] + }) + .collect() +} + impl ExSpec { /// Aus dem Modell; `dz` = Höhenbezug des Netzes ([`datum`]). `None` bei kaputtem Umriss. pub fn of(e: &Excavation, dz: f64) -> Option { @@ -78,21 +104,29 @@ impl ExSpec { } let n = ring.len(); let slope = e.slope.filter(|s| s.is_finite() && *s > 0.0).unwrap_or(DEFAULT_SLOPE); - let mut cut_tan: Vec = (0..n).map(|i| tan_deg(e.edge_slopes.as_ref().and_then(|v| v.get(i)).copied().filter(|s| s.is_finite() && *s > 0.0).unwrap_or(slope))).collect(); + let mut shored: Vec = (0..n).map(|i| e.edge_shoring.as_ref().and_then(|v| v.get(i)).copied().unwrap_or(false)).collect(); + let mut cut_tan: Vec = (0..n).map(|i| if shored[i] { tan_deg(89.5) } else { tan_deg(e.edge_slopes.as_ref().and_then(|v| v.get(i)).copied().filter(|s| s.is_finite() && *s > 0.0).unwrap_or(slope)) }).collect(); if signed_area(&ring) < 0.0 { // Kante i (p_i → p_i+1) wird nach dem Umdrehen Kante n−2−i (mod n). ring.reverse(); - let old = cut_tan.clone(); + let (old, old_s) = (cut_tan.clone(), shored.clone()); for i in 0..n { cut_tan[(2 * n - 2 - i) % n] = old[i]; + shored[(2 * n - 2 - i) % n] = old_s[i]; } } + // Arbeitsraum: Sohle um `workingSpace` nach aussen (Gehrung, höchstens 4× so weit an spitzen Ecken). + let ws = e.working_space.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(0.0); + if ws > 0.0 { + ring = offset_ring(&ring, ws); + } let bw = e.berm_width.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(0.0); let bh = e.berm_height.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(0.0); Some(ExSpec { ring, bottom: e.bottom + dz, cut_tan, + shored, fill_tan: tan_deg(e.fill_slope.filter(|s| s.is_finite() && *s > 0.0).unwrap_or(DEFAULT_FILL_SLOPE)), berm_w: if bh > 0.0 { bw } else { 0.0 }, berm_h: if bw > 0.0 { bh } else { 0.0 }, @@ -374,38 +408,68 @@ pub struct Volumes { pub bottom_area: f64, } -/// Integriert (t − neu) über ein Raster der Weite ≤ `h` (Mittelpunkte, höchstens ~1.5 Mio. Proben). +/// Mengen mehrerer Baugruben ohne Doppelzählung: die Baugruben wirken der Reihe nach (wie in [`site_terrain`]), +/// je Probe geht der Höhenunterschied einer Baugrube an sie allein — die Summe ist die Vereinigung. +/// Integriert über ein Raster der Weite ≤ `h` (Mittelpunkte, höchstens ~1.5 Mio. Proben). /// `footprint`: Gebäude-Grundfläche (Ringe); Abtrag darin zählt nicht zur Hinterfüllung. -pub fn volumes(orig: &Tin, ex: &ExSpec, h: f64, footprint: &[Vec]) -> Volumes { +/// Sohlenfläche = Fläche des Umrisses ohne die der vorherigen Baugruben (Überlappung per Raster). +pub fn volumes_union(orig: &Tin, specs: &[&ExSpec], h: f64, footprint: &[Vec]) -> Vec { + if specs.is_empty() { + return Vec::new(); + } let idx = TinIndex::new(orig); - let r = ex.reach_in(orig, &idx); - let b = ex.bbox(); - let reg = [b[0] - r, b[1] - r, b[2] + r, b[3] + r]; + let mut reg = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + for ex in specs { + let (b, r) = (ex.bbox(), ex.reach_in(orig, &idx)); + reg = [reg[0].min(b[0] - r), reg[1].min(b[1] - r), reg[2].max(b[2] + r), reg[3].max(b[3] + r)]; + } let (w, hh) = (reg[2] - reg[0], reg[3] - reg[1]); let mut h = h.max(1e-3); while (w / h).ceil() * (hh / h).ceil() > 1.5e6 { h *= 1.2; } - let (nx, ny) = ((w / h).ceil() as usize, (hh / h).ceil() as usize); + let (nx, ny) = (((w / h).ceil() as usize).max(1), ((hh / h).ceil() as usize).max(1)); let (hx, hy) = (w / nx as f64, hh / ny as f64); let cell = hx * hy; - let mut v = Volumes { bottom_area: signed_area(&ex.ring).abs(), ..Default::default() }; + let boxes: Vec<[f64; 4]> = specs.iter().map(|e| e.bbox()).collect(); + let overlaps: Vec = (0..specs.len()) + .map(|k| (0..k).any(|j| boxes[j][0] < boxes[k][2] && boxes[k][0] < boxes[j][2] && boxes[j][1] < boxes[k][3] && boxes[k][1] < boxes[j][3])) + .collect(); + let mut out: Vec = specs.iter().map(|e| Volumes { bottom_area: signed_area(&e.ring).abs(), ..Default::default() }).collect(); + let mut shared = vec![0.0; specs.len()]; for j in 0..ny { for i in 0..nx { let p = [reg[0] + (i as f64 + 0.5) * hx, reg[1] + (j as f64 + 0.5) * hy]; let Some(t) = idx.z_at(p[0], p[1]) else { continue }; - let dz = t - ex.apply(t, p); - if dz > 0.0 { - v.cut += dz * cell; - if !footprint.iter().any(|f| point_in_ring(p, f)) { - v.backfill += dz * cell; + let mut cur = t; + let outside_fp = !footprint.iter().any(|f| point_in_ring(p, f)); + for (k, ex) in specs.iter().enumerate() { + if overlaps[k] && p[0] >= boxes[k][0] && p[0] <= boxes[k][2] && p[1] >= boxes[k][1] && p[1] <= boxes[k][3] && point_in_ring(p, &ex.ring) && (0..k).any(|q| point_in_ring(p, &specs[q].ring)) { + shared[k] += cell; } - } else { - v.fill -= dz * cell; + let next = ex.apply(cur, p); + let dz = cur - next; + if dz > 0.0 { + out[k].cut += dz * cell; + if outside_fp { + out[k].backfill += dz * cell; + } + } else { + out[k].fill -= dz * cell; + } + cur = next; } } } - v + for (v, s) in out.iter_mut().zip(shared) { + v.bottom_area = (v.bottom_area - s).max(0.0); + } + out +} + +/// Mengen einer einzelnen Baugrube (s. [`volumes_union`]). +pub fn volumes(orig: &Tin, ex: &ExSpec, h: f64, footprint: &[Vec]) -> Volumes { + volumes_union(orig, &[ex], h, footprint).pop().unwrap_or_default() } // ── Gelände mit Baugruben, zwischengespeichert ────────────────────────────── @@ -492,6 +556,40 @@ pub fn terrain_model_mesh<'a>(p: &Project, t: &'a TerrainMesh) -> (std::borrow:: (Cow::Owned(pos), Cow::Owned(idx), st.modified.is_some()) } +/// [T6] Luftbild-Farben (flach r,g,b je Eckpunkt des Original-Netzes) auf das geänderte Gelände übertragen: +/// jeder neue Eckpunkt erhält die in der Grundrissprojektion (x, y) des Originals interpolierte Farbe +/// (Böschungen und Sohle bekommen so die Farbe des Bildes darüber); ausserhalb der nächste Eckpunkt. +pub fn reproject_colors(orig: &Tin, colors: &[f64], new: &Tin) -> Vec { + let idx = TinIndex::new(orig); + let col = |i: usize| -> [f64; 3] { [colors[3 * i], colors[3 * i + 1], colors[3 * i + 2]] }; + let mut out = Vec::with_capacity(new.xy.len() * 3); + for p in &new.xy { + let c = match idx.bary_at(p[0], p[1]) { + Some((t, l)) => { + let (a, b, c) = (col(t[0]), col(t[1]), col(t[2])); + [0, 1, 2].map(|k| l[0] * a[k] + l[1] * b[k] + l[2] * c[k]) + } + None => { + let n = orig.xy.iter().enumerate().min_by(|a, b| (a.1[0] - p[0]).hypot(a.1[1] - p[1]).total_cmp(&(b.1[0] - p[0]).hypot(b.1[1] - p[1]))).map_or(0, |x| x.0); + col(n) + } + }; + out.extend(c); + } + out +} + +/// Vertex-Farben des Geländes im Modell: unverändert, oder auf das Netz mit Baugruben übertragen. +/// `None` ohne (passende) Farben. +pub fn terrain_vertex_colors(p: &Project, t: &TerrainMesh) -> Option> { + let c = t.vertex_colors.as_ref().filter(|v| !v.is_empty())?; + let st = site_terrain(p, t); + match &st.modified { + None => Some(c.clone()), + Some(m) => (c.len() == st.orig.xy.len() * 3).then(|| reproject_colors(&st.orig, c, m)), + } +} + /// Mengen je Baugrube (gegen das gewachsene Terrain des ersten Netzes, das sie trifft). #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] @@ -507,18 +605,27 @@ pub struct ExQty { pub fn quantities(p: &Project) -> Vec { let fp: Vec> = crate::site_rules::building_footprint(p).iter().flat_map(|poly| poly.first().map(|r| r.iter().map(|v| [v.x, v.y]).collect::>())).collect(); - let mut out = Vec::new(); - for e in excavations(p) { - for t in terrains(p) { - let st = site_terrain(p, t); - let Some((_, spec, _)) = st.items.iter().find(|(id, ..)| *id == e.id) else { continue }; - let h = (spec.ring.iter().map(|q| q[0]).fold(f64::NEG_INFINITY, f64::max) - spec.ring.iter().map(|q| q[0]).fold(f64::INFINITY, f64::min)).max(1.0) / 400.0; - let v = volumes(&st.orig, spec, h.clamp(0.02, 0.5), &fp); - out.push(ExQty { id: e.id.clone(), name: e.name.clone(), bottom: e.bottom, bottom_area: v.bottom_area, cut: v.cut, fill: v.fill, backfill: v.backfill }); - break; + let mut done: Vec = Vec::new(); + // Je Gelände-Netz alle Baugruben, die es trifft, zusammen (Überlagerungen zählen einmal). + for t in terrains(p) { + let st = site_terrain(p, t); + let hits: Vec<&(String, ExSpec, Vec>)> = st.items.iter().filter(|(id, ..)| !done.iter().any(|q| q.id == *id)).collect(); + if hits.is_empty() { + continue; + } + let specs: Vec<&ExSpec> = hits.iter().map(|(_, s, _)| s).collect(); + let (x0, x1) = specs.iter().flat_map(|s| s.ring.iter().map(|q| q[0])).fold((f64::INFINITY, f64::NEG_INFINITY), |a, x| (a.0.min(x), a.1.max(x))); + let h = ((x1 - x0).max(1.0) / 400.0).clamp(0.02, 0.5); + let vols = volumes_union(&st.orig, &specs, h, &fp); + for ((id, ..), v) in hits.iter().zip(vols) { + let Some(e) = excavations(p).into_iter().find(|e| e.id == *id) else { continue }; + done.push(ExQty { id: e.id.clone(), name: e.name.clone(), bottom: e.bottom, bottom_area: v.bottom_area, cut: v.cut, fill: v.fill, backfill: v.backfill }); } } - out + // Reihenfolge wie im Modell. + let order: Vec<&str> = excavations(p).iter().map(|e| e.id.as_str()).collect(); + done.sort_by_key(|q| order.iter().position(|i| *i == q.id).unwrap_or(usize::MAX)); + done } /// Höhe des gewachsenen (`designed = false`) bzw. gestalteten Terrains im Modellbezug; `None` ohne Gelände. @@ -568,6 +675,9 @@ pub fn slope_hatch(t: &Tin, ex: &ExSpec, spacing: f64) -> Vec<(P2, P2)> { let (a, b) = (ex.ring[i], ex.ring[(i + 1) % n]); let len = (b[0] - a[0]).hypot(b[1] - a[1]); let nn = normal(i); + if ex.shored[i] { + continue; + } let k = (len / spacing).floor() as usize; let off = (len - k as f64 * spacing) / 2.0; for s in 0..=k { @@ -580,7 +690,7 @@ pub fn slope_hatch(t: &Tin, ex: &ExSpec, spacing: f64) -> Vec<(P2, P2)> { // Fächer an der konvexen Ecke b. let n2 = normal((i + 1) % n); let cross = nn[0] * n2[1] - nn[1] * n2[0]; - if cross > 1e-9 { + if cross > 1e-9 && !ex.shored[(i + 1) % n] { let a0 = nn[1].atan2(nn[0]); let mut a1 = n2[1].atan2(n2[0]); if a1 < a0 { @@ -671,6 +781,62 @@ mod tests { } } + #[test] + fn arbeitsraum_verbau_und_ueberlappung() { + // Arbeitsraum 1 m: Sohle 12 × 12 statt 10 × 10 (Gehrung), Mengen wachsen entsprechend. + let mut e = square(5.0, -3.0); + e.working_space = Some(1.0); + let ws = ExSpec::of(&e, 0.0).unwrap(); + assert!((signed_area(&ws.ring) - 144.0).abs() < 1e-9, "{}", signed_area(&ws.ring)); + // Senkrechter Verbau auf allen Kanten: Abtrag = Sohle × Tiefe (kaum Böschung), keine Schraffur. + let mut e = square(5.0, -3.0); + e.edge_shoring = Some(vec![true; 4]); + let sh = ExSpec::of(&e, 0.0).unwrap(); + let t = flat(0.0, 50.0); + let v = volumes(&t, &sh, 0.05, &[]); + assert!((v.cut - 300.0).abs() < 0.03 * 300.0, "{}", v.cut); + assert!(slope_hatch(&t, &sh, 0.5).is_empty()); + // Nur eine Kante verbaut: Hatch an den anderen drei bleibt, Index folgt dem Umlaufsinn (auch im Uhrzeigersinn). + let mut e = square(5.0, -3.0); + e.outline.reverse(); + e.edge_shoring = Some(vec![true, false, false, false]); + let one = ExSpec::of(&e, 0.0).unwrap(); + assert_eq!(one.shored.iter().filter(|b| **b).count(), 1); + // Überlagerung: zwei sich überdeckende Gruben zählen die gemeinsame Fläche einmal. + let mut a = square(5.0, -3.0); + a.id = "a".into(); + let mut b = square(5.0, -3.0); + b.id = "b".into(); + let (sa, sb) = (ExSpec::of(&a, 0.0).unwrap(), ExSpec::of(&b, 0.0).unwrap()); + let single = volumes(&t, &sa, 0.1, &[]); + let both = volumes_union(&t, &[&sa, &sb], 0.1, &[]); + assert!((both[0].cut + both[1].cut - single.cut).abs() < 1e-6, "{} vs {}", both[0].cut + both[1].cut, single.cut); + assert!(both[1].cut.abs() < 1e-6 && both[1].bottom_area < 1.0, "{:?}", both[1]); + // Teilweise versetzt: Summe < Summe der Einzelmengen, > jede einzelne. + let mut c = square(5.0, -3.0); + for q in &mut c.outline { + q.x += 6.0; + } + let sc = ExSpec::of(&c, 0.0).unwrap(); + let sep = volumes(&t, &sc, 0.1, &[]); + let u = volumes_union(&t, &[&sa, &sc], 0.1, &[]); + let sum = u[0].cut + u[1].cut; + assert!(sum < single.cut + sep.cut - 1.0 && sum > single.cut, "{sum}"); + } + + #[test] + fn luftbildfarben_auf_geaendertem_gelaende() { + // Original-Netz mit Farbverlauf in x; nach der Baugrube behalten alle neuen Punkte die Farbe ihrer (x, y). + let t = flat(0.0, 50.0); + let colors: Vec = t.xy.iter().flat_map(|p| [(p[0] + 50.0) / 100.0, 0.5, 0.25]).collect(); + let r = excavate(&t, &ExSpec::of(&square(5.0, -3.0), 0.0).unwrap()).unwrap(); + let c = reproject_colors(&t, &colors, &r.tin); + assert_eq!(c.len(), r.tin.xy.len() * 3); + for (p, q) in r.tin.xy.iter().zip(c.chunks(3)) { + assert!((q[0] - (p[0] + 50.0) / 100.0).abs() < 1e-9 && (q[1] - 0.5).abs() < 1e-9, "{p:?} {q:?}"); + } + } + #[test] fn auftrag_am_hang_und_bermen() { // Hang 10 %: Plattform auf ±0 schneidet bergseits ein und wird talseits geschüttet. diff --git a/src-tauri/core/src/grid.rs b/src-tauri/core/src/grid.rs index 2ff390a2..fa8191ef 100644 --- a/src-tauri/core/src/grid.rs +++ b/src-tauri/core/src/grid.rs @@ -84,7 +84,8 @@ impl<'a> Spec<'a> { /// Alle Achsen (Index: `a` zuerst, dann `b`). pub fn axes(&self) -> Vec { - let want = |start: bool| match self.bubbles { + // Blasenseite: die der Achse, sonst die des Rasters. + let want = |g: &GridAxis, start: bool| match g.bubble.unwrap_or(self.bubbles) { GridBubbles::Both => true, GridBubbles::Start => start, GridBubbles::End => !start, @@ -101,7 +102,7 @@ impl<'a> Spec<'a> { index: i as u32, label: g.label.clone(), shape: Shape::Line { a: p0, b: p1 }, - bubbles: [want(true).then_some((p0, d0)), want(false).then_some((p1, d1))], + bubbles: [want(g, true).then_some((p0, d0)), want(g, false).then_some((p1, d1))], }); } for (j, g) in self.b.iter().enumerate() { @@ -111,7 +112,7 @@ impl<'a> Spec<'a> { index: (self.a.len() + j) as u32, label: g.label.clone(), shape: Shape::Line { a: p0, b: p1 }, - bubbles: [want(true).then_some((p0, d0)), want(false).then_some((p1, d1))], + bubbles: [want(g, true).then_some((p0, d0)), want(g, false).then_some((p1, d1))], }); } return out; @@ -126,7 +127,7 @@ impl<'a> Spec<'a> { index: i as u32, label: g.label.clone(), shape: Shape::Line { a: self.origin, b: end }, - bubbles: [None, (self.bubbles != GridBubbles::Start).then_some((end, u))], + bubbles: [None, (g.bubble.unwrap_or(self.bubbles) != GridBubbles::Start).then_some((end, u))], }); } let (t0, t1) = Self::span(self.a); @@ -147,8 +148,8 @@ impl<'a> Spec<'a> { label: g.label.clone(), shape: Shape::Arc { c: self.origin, r, a0, a1 }, bubbles: [ - (!full && want(true)).then(|| (at(a0), tan(a0, -1.0))), - (if full { self.bubbles != GridBubbles::Start } else { want(false) }).then(|| (at(a1), tan(a1, 1.0))), + (!full && want(g, true)).then(|| (at(a0), tan(a0, -1.0))), + (if full { g.bubble.unwrap_or(self.bubbles) != GridBubbles::Start } else { want(g, false) }).then(|| (at(a1), tan(a1, 1.0))), ], }); } @@ -270,8 +271,8 @@ pub fn axes_from_bays(radial: bool, xs: &[f64], ys: &[f64]) -> (Vec, V } out }; - let a = cum(xs, true).iter().enumerate().map(|(i, p)| GridAxis { label: (i + 1).to_string(), pos: *p }).collect(); - let b = cum(ys, !radial).iter().enumerate().map(|(i, p)| GridAxis { label: letter_label(i), pos: *p }).collect(); + let a = cum(xs, true).iter().enumerate().map(|(i, p)| GridAxis { label: (i + 1).to_string(), pos: *p, ..Default::default() }).collect(); + let b = cum(ys, !radial).iter().enumerate().map(|(i, p)| GridAxis { label: letter_label(i), pos: *p, ..Default::default() }).collect(); (a, b) } @@ -330,13 +331,27 @@ pub fn section_axes(spec: &Spec, origin: P, dir: P, projected: bool) -> Vec<(Str out } +/// Verlauf einer Achse als Linienzug (Bögen in Schritten von höchstens 5°), z. B. für den IFC-Export. +pub fn polyline(ax: &Axis) -> Vec

{ + match ax.shape { + Shape::Line { a, b } => vec![a, b], + Shape::Arc { c, r, a0, a1 } => { + let n = (((a1 - a0).abs() / 5f64.to_radians()).ceil() as usize).max(2); + (0..=n).map(|i| { + let t = a0 + (a1 - a0) * i as f64 / n as f64; + (c.0 + r * t.cos(), c.1 + r * t.sin()) + }).collect() + } + } +} + #[cfg(test)] mod tests { use super::*; use crate::model::Vec2; fn ax(l: &str, p: f64) -> GridAxis { - GridAxis { label: l.into(), pos: p } + GridAxis { label: l.into(), pos: p, ..Default::default() } } fn ortho() -> Drawing2DGeom { @@ -386,6 +401,20 @@ mod tests { assert!(a.bubbles[0].is_none() && a.bubbles[1].is_some()); } + #[test] + fn blasenseite_je_achse() { + let mut g = ortho(); + if let Drawing2DGeom::Grid { a, .. } = &mut g { + a[0].bubble = Some(GridBubbles::Start); + a[1].bubble = Some(GridBubbles::End); + } + let axes = Spec::of(&g).unwrap().axes(); + assert!(axes[0].bubbles[0].is_some() && axes[0].bubbles[1].is_none()); + assert!(axes[1].bubbles[0].is_none() && axes[1].bubbles[1].is_some()); + // Achsen ohne eigene Seite folgen dem Raster (beide Enden). + assert!(axes[2].bubbles[0].is_some() && axes[2].bubbles[1].is_some()); + } + #[test] fn radial_strahlen_ringe() { let g = Drawing2DGeom::Grid { diff --git a/src-tauri/core/src/grips.rs b/src-tauri/core/src/grips.rs index 7be17bf0..5f7825ec 100644 --- a/src-tauri/core/src/grips.rs +++ b/src-tauri/core/src/grips.rs @@ -192,6 +192,13 @@ fn find<'a>(root: &'a Map, collection: &str, id: &str) -> Option< arr(root.get(collection)).iter().find(|e| id_of(e) == Some(id)) } +/// Mittelwert der Ecken eines Umrisses (Griff-Lage der Sohlenhöhe einer Baugruben). +pub fn ring_centroid(ring: &[Value]) -> (f64, f64) { + let n = ring.len().max(1) as f64; + let (sx, sy) = ring.iter().map(xy).fold((0.0, 0.0), |a, p| (a.0 + p.0, a.1 + p.1)); + (sx / n, sy / n) +} + fn replace(collection: &str, entity: Value) -> Op { Op::Replace { collection: collection.into(), entity } } @@ -407,6 +414,27 @@ pub fn run(lk: &Lookup, req: &Request) -> Result { let (index, (x, y)) = (r.n("index"), r.p("pt")); patch(coll, r.s("id"), &|e| Some(with(e, field, replace_at(e.get(field)?.as_array()?, index, &pt(x, y))))).into() } + // [68] Baugrube: Umriss-Ecke ziehen; der Index hinter der letzten Ecke ist der Sohlen-Griff + // (Lage = Schwerpunkt, y um die Sohlenhöhe versetzt: Ziehen setzt `bottom` = y − Schwerpunkt-y). + "excavationGrip" => { + let (index, (x, y)) = (r.n("index"), r.p("pt")); + patch("context", r.s("id"), &|e| { + let ring = field(e, "outline")?.as_array()?; + if index_in(index, ring.len()).is_some() { + return Some(with(e, "outline", replace_at(ring, index, &pt(x, y)))); + } + if index == ring.len() as f64 && y.is_finite() { + let c = ring_centroid(ring); + return Some(with(e, "bottom", js_num(((y - c.1) * 100.0).round() / 100.0))); + } + None + }) + .into() + } + "excavationEdge" => { + let (a, b, (dx, dy)) = (r.n("a"), r.n("b"), r.p("delta")); + patch("context", r.s("id"), &|e| Some(with(e, "outline", move_polygon_edge(field(e, "outline")?.as_array()?, a, b, dx, dy, true)?))).into() + } "ceilingBy" | "roofBy" => { let coll = if op == "ceilingBy" { "ceilings" } else { "roofs" }; let (dx, dy) = r.p("delta"); @@ -1391,6 +1419,22 @@ mod tests { assert!(res.ops[0].to_json()["entity"].get("bulge").is_none()); } + /// [68] Baugrube: Ecke, Kante und Sohlen-Griff (Index hinter der letzten Ecke). + #[test] + fn baugrube_griffe() { + let r = root(json!({"context": [{"id": "bg", "type": "excavation", "bottom": -2, "outline": [{"x": 0, "y": 0}, {"x": 4, "y": 0}, {"x": 4, "y": 4}, {"x": 0, "y": 4}]}]})); + let ent = |v: Value| run(&Lookup::plain(&r), &rq(v)).unwrap().ops[0].to_json()["entity"].clone(); + let e = ent(json!({"op": "excavationGrip", "id": "bg", "index": 2, "pt": [5, 6]})); + assert_eq!(e["outline"][2], json!({"x": 5, "y": 6})); + // Kante 0–1 um 1 nach unten: beide Ecken wandern. + let e = ent(json!({"op": "excavationEdge", "id": "bg", "a": 0, "b": 1, "delta": [0, -1]})); + assert_eq!((e["outline"][0]["y"].as_f64(), e["outline"][1]["y"].as_f64()), (Some(-1.0), Some(-1.0))); + // Sohlen-Griff: Schwerpunkt-y = 2, Ziel-y = −1 → Sohle −3. + let e = ent(json!({"op": "excavationGrip", "id": "bg", "index": 4, "pt": [2, -1]})); + assert_eq!(e["bottom"], json!(-3)); + assert_eq!(e["outline"][2], json!({"x": 4, "y": 4})); + } + #[test] fn wand_griff_und_sperre() { let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}, "extra": 1}]})); diff --git a/src-tauri/core/src/ifc_data.rs b/src-tauri/core/src/ifc_data.rs index a3676fb5..2a483f78 100644 --- a/src-tauri/core/src/ifc_data.rs +++ b/src-tauri/core/src/ifc_data.rs @@ -49,6 +49,7 @@ const REC_ATTACH: f64 = 14.0; const REC_OPENING_SOLID: f64 = 15.0; const REC_WALL_ARC: f64 = 16.0; const REC_WALL_ARC_SOLID: f64 = 17.0; +const REC_GRID: f64 = 18.0; /// Toleranz des Kerns (`wall_bands.rs::EPS`) für „Öffnung trifft Band". const BAND_EPS: f64 = 1e-4; @@ -1329,6 +1330,30 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result } f.num(REC_END_COLUMNS); + // ── Achsraster ([112]) → IfcGrid (U-/V-Achsen als Linienzüge in Welt-XY) ── + for d in &p.drawings2d { + let Some(spec) = crate::grid::Spec::of(&d.geom) else { continue }; + let Drawing2DGeom::Grid { levels, .. } = &d.geom else { continue }; + // Ein Geschoss: dort enthalten; mehrere oder alle: am Gebäude. + let only = match levels.as_deref() { + Some([one]) => Some(one.as_str()), + _ => None, + }; + let structure = only.map_or(-1.0, structure_of); + let axes = spec.axes(); + if axes.is_empty() { + continue; + } + let (id, name) = (f.str(&d.id), f.str(&format!("Achsraster {}", d.id))); + f.nums(&[REC_GRID, structure, id, name, spec.a.len() as f64, (axes.len() - spec.a.len()) as f64]); + for ax in &axes { + let pts: Vec = crate::grid::polyline(ax).into_iter().map(|(x, y)| Vec2 { x, y }).collect(); + let lab = f.str(&ax.label); + f.nums(&[lab]); + w_pts(&mut f, &pts); + } + } + // ── Klassifikation (Optionen), am Ende: alle Bauteile sind geschrieben ── if opt.ebkph { let refs: Vec<(String, String, String)> = @@ -1510,6 +1535,33 @@ mod tests { assert!(f.nums.iter().any(|v| *v > 2_683_000.0)); } + #[test] + fn achsraster_als_datensatz() { + let mut p = sample(); + let a = |l: &str, pos: f64| GridAxis { label: l.into(), pos, ..Default::default() }; + let geom = Drawing2DGeom::Grid { + origin: Vec2 { x: 0.0, y: 0.0 }, + angle: 0.0, + radial: None, + a: vec![a("1", 0.0), a("2", 5.0)], + b: vec![a("A", 0.0)], + extend: None, + bubbles: None, + bubble_mm: None, + levels: None, + show_3d: None, + }; + p.drawings2d.push(Drawing2D { id: "g".into(), r#type: "drawing2d".into(), level_id: p.drawing_levels[0].id.clone(), category_code: "00".into(), geom, ..Default::default() }); + let f = ifc_export_data(&p, &IfcOptions::default()).unwrap(); + let at = f.nums.windows(2).position(|w| w == [REC_END_COLUMNS, REC_GRID]).map(|i| i + 1); + assert!(at.is_some(), "kein Rasterdatensatz"); + // structure, id, name, n_u = 2, n_v = 1 + let i = at.unwrap(); + assert_eq!((f.nums[i + 4], f.nums[i + 5]), (2.0, 1.0)); + // Ohne Raster kein Datensatz. + assert!(!ifc_export_data(&sample(), &IfcOptions::default()).unwrap().nums.windows(2).any(|w| w == [REC_END_COLUMNS, REC_GRID])); + } + #[test] fn leeres_projekt_und_unbekannter_wandtyp() { let mut p = Project { id: "leer".into(), ..Default::default() }; diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs index acb3be2b..9bfde1f5 100644 --- a/src-tauri/core/src/model/generated.rs +++ b/src-tauri/core/src/model/generated.rs @@ -5117,6 +5117,10 @@ pub struct TerrainMesh { #[serde(rename = "contourIndexEvery", default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub contour_index_every: Option, + /// [T6] Tiefe des Erdreich-Bands im Schnitt unter dem Gelände in m (Default 1.5). + #[serde(rename = "earthDepth", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub earth_depth: Option, #[serde(flatten)] #[ts(skip)] pub extra: Extra, @@ -5155,6 +5159,15 @@ pub struct Excavation { #[serde(rename = "bermHeight", default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub berm_height: Option, + /// [68] Arbeitsraum in m: der Umriss gilt als Gebäude-Grundfläche, die Sohle liegt um dieses Mass + /// weiter aussen (Gehrung an den Ecken). Fehlt = 0 (Umriss = Sohle). + #[serde(rename = "workingSpace", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub working_space: Option, + /// [68] Senkrechter Verbau (Spundwand) je Kante (wie `edgeSlopes`): keine Böschung, Wand steht senkrecht. + #[serde(rename = "edgeShoring", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub edge_shoring: Option>, #[serde(flatten)] #[ts(skip)] pub extra: Extra, diff --git a/src-tauri/core/src/model/manual.rs b/src-tauri/core/src/model/manual.rs index eb1ab5e2..94031b45 100644 --- a/src-tauri/core/src/model/manual.rs +++ b/src-tauri/core/src/model/manual.rs @@ -206,6 +206,10 @@ pub enum SplineMode { pub struct GridAxis { pub label: String, pub pos: f64, + /// Blasenseite nur dieser Achse (überschreibt `Grid.bubbles`); fehlt = wie das Raster. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub bubble: Option, } /// Welche Achsenden eine Blase tragen. diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index 65c79bfd..002dfbc7 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -1823,15 +1823,15 @@ pub fn emit_context_meshes(p: &Project) -> Vec { for obj in p.context.as_deref().unwrap_or(&[]) { match obj { ContextObject::TerrainMesh(m) if m.positions.len() >= 9 && m.indices.len() >= 3 => { - // [T6] Baugruben schneiden das Gelände; Höhen im Modellbezug (Luftbild-Farben nur ungeändert). - let (pos, idx, changed) = crate::excavation::terrain_model_mesh(p, m); + // [T6] Baugruben schneiden das Gelände; Höhen im Modellbezug (Luftbild-Farben auf das geänderte Netz übertragen). + let (pos, idx, _) = crate::excavation::terrain_model_mesh(p, m); out.push(RMesh { crease_angle: None, positions: pos.into_owned(), indices: indices_u32(&idx), kind: "terrain", color: TERRAIN_RGB, - vertex_colors: if changed { None } else { m.vertex_colors.clone().filter(|v| !v.is_empty()) }, + vertex_colors: crate::excavation::terrain_vertex_colors(p, m), material_index: None, }) } diff --git a/src-tauri/core/src/plan/context.rs b/src-tauri/core/src/plan/context.rs index edf29a09..55dd224b 100644 --- a/src-tauri/core/src/plan/context.rs +++ b/src-tauri/core/src/plan/context.rs @@ -128,22 +128,33 @@ fn terrain_contours(c: &Ctx, t: &TerrainMesh, out: &mut Vec) { let w = if index { 0.25 } else { 0.1 }; let n = l.pts.len(); let segs = if l.closed { n } else { n - 1 }; - for i in 0..segs { - let (a, b) = (l.pts[i], l.pts[(i + 1) % n]); - out.push(ink_line(v2(a[0], a[1]), v2(b[0], b[1]), w, TERRAIN_INK, None)); - } - if !index { - continue; - } - // Beschriftung in der Mitte der Linie (nur, wenn sie lang genug ist). - let len: f64 = (0..segs).map(|i| (l.pts[(i + 1) % n][0] - l.pts[i][0]).hypot(l.pts[(i + 1) % n][1] - l.pts[i][1])).sum(); - if len < 12.0 * text_h { - continue; - } + let seg_len = |i: usize| (l.pts[(i + 1) % n][0] - l.pts[i][0]).hypot(l.pts[(i + 1) % n][1] - l.pts[i][1]); + let len: f64 = (0..segs).map(seg_len).sum(); + // Beschriftung in der Mitte der Zähllinie (nur, wenn sie lang genug ist); die Linie wird dort unterbrochen. + let text = crate::js_fmt::to_fixed(l.level, if iv.fract() == 0.0 { 0 } else { 1 }); + let half = 0.3 * text_h * text.chars().count() as f64; + let gap = (index && len >= 12.0 * text_h).then(|| (len / 2.0 - half - 0.4 * text_h, len / 2.0 + half + 0.4 * text_h)); let mut acc = 0.0; for i in 0..segs { let (a, b) = (l.pts[i], l.pts[(i + 1) % n]); - let d = (b[0] - a[0]).hypot(b[1] - a[1]); + let d = seg_len(i); + // Anteile (Bruchteile 0..1) des Segments ausserhalb der Lücke. + let mut spans = vec![(0.0, 1.0)]; + if let (Some((g0, g1)), true) = (gap, d > 0.0) { + let (f0, f1) = (((g0 - acc) / d).clamp(0.0, 1.0), ((g1 - acc) / d).clamp(0.0, 1.0)); + spans = [(0.0, f0), (f1, 1.0)].into_iter().filter(|(x, y)| y - x > 1e-9).collect(); + } + for (f0, f1) in spans { + let pt = |f: f64| v2(a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f); + out.push(ink_line(pt(f0), pt(f1), w, TERRAIN_INK, None)); + } + acc += d; + } + let Some(_) = gap else { continue }; + let mut acc = 0.0; + for i in 0..segs { + let (a, b) = (l.pts[i], l.pts[(i + 1) % n]); + let d = seg_len(i); if acc + d >= len / 2.0 && d > 0.0 { let f = (len / 2.0 - acc) / d; let mut ang = (b[1] - a[1]).atan2(b[0] - a[0]); @@ -151,8 +162,6 @@ fn terrain_contours(c: &Ctx, t: &TerrainMesh, out: &mut Vec) { ang += std::f64::consts::PI; } // Text mittig auf die Linie (Breite ≈ 0.6 · Höhe je Zeichen, Grundlinie ≈ −0.35 · Höhe). - let text = crate::js_fmt::to_fixed(l.level, if iv.fract() == 0.0 { 0 } else { 1 }); - let half = 0.3 * text_h * text.chars().count() as f64; let (c, s) = (ang.cos(), ang.sin()); let m = (a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f); out.push(Primitive::DrawingText { @@ -311,6 +320,11 @@ mod tests { assert!(labels.contains(&"5"), "{labels:?}"); let ex = out.iter().filter(|q| matches!(q, Primitive::Line { color: Some(c), .. } if c == EXCAVATION_INK)).count(); assert!(ex > 20, "{ex}"); + // Die Zähllinie ist unter ihrer Beschriftung unterbrochen: keine Linie läuft durch den Textmittelpunkt. + let at = out.iter().find_map(|q| if let Primitive::DrawingText { text, at, .. } = q { (text == "5").then_some(*at) } else { None }).unwrap(); + let near = out.iter().filter(|q| matches!(q, Primitive::Line { a, b, weight_mm, color: Some(c), .. } + if *weight_mm == 0.25 && c == TERRAIN_INK && (a.x.min(b.x) - 0.01..=a.x.max(b.x) + 0.01).contains(&at.x) && (a.y.min(b.y) - 0.01..=a.y.max(b.y) + 0.01).contains(&at.y))).count(); + assert_eq!(near, 0, "Linie läuft durch das Etikett bei {at:?}"); } #[test] diff --git a/src-tauri/core/src/plan/drawings.rs b/src-tauri/core/src/plan/drawings.rs index b6878fd7..a78b68dc 100644 --- a/src-tauri/core/src/plan/drawings.rs +++ b/src-tauri/core/src/plan/drawings.rs @@ -1178,7 +1178,7 @@ pub fn mv_geom(g: &Drawing2DGeom, f: &dyn Fn(Vec2) -> Vec2) -> Drawing2DGeom { let o = f(*origin); let ex = f(v(origin.x + angle.cos(), origin.y + angle.sin())); let flip = reverses_orientation(f); - let neg = |l: &Vec| l.iter().map(|x| GridAxis { label: x.label.clone(), pos: -x.pos }).collect::>(); + let neg = |l: &Vec| l.iter().map(|x| GridAxis { label: x.label.clone(), pos: -x.pos, bubble: x.bubble }).collect::>(); let ang = (ex.y - o.y).atan2(ex.x - o.x); let (a2, b2) = match (flip, radial == &Some(true)) { (false, _) => (a.clone(), b.clone()), diff --git a/src-tauri/core/src/plan/section.rs b/src-tauri/core/src/plan/section.rs index 8314f04f..66fdb3da 100644 --- a/src-tauri/core/src/plan/section.rs +++ b/src-tauri/core/src/plan/section.rs @@ -1554,17 +1554,23 @@ fn append_terrain_profiles(out: &mut Output, p: &Project, base: (f64, f64), u: ( append_earth(out, p, base, u); } -/// Tiefe des Erdreich-Bands unter der Geländelinie (m). +/// Tiefe des Erdreich-Bands unter der Geländelinie (m), wenn das Gelände keine `earthDepth` trägt. const EARTH_BAND: f64 = 1.5; +/// Tiefe des Erdreich-Bands: `earthDepth` des ersten Geländes, das eine positive Tiefe setzt. +fn earth_band(p: &Project) -> f64 { + crate::excavation::terrains(p).iter().find_map(|t| t.earth_depth.filter(|d| d.is_finite() && *d > 0.0)).unwrap_or(EARTH_BAND) +} + /// [T6]/[109] Erdreich: Band unter dem gestalteten Terrain mit SIA-Erdreich-Schraffur, ohne das /// Gebäude-Innere (Grundfläche im Schnitt, von der tiefsten Schnittfläche aufwärts); die geschnittenen /// Bauteile selbst liegen ohnehin darüber. fn append_earth(out: &mut Output, p: &Project, base: (f64, f64), u: (f64, f64)) { + let depth = earth_band(p); let mut band: Vec = Vec::new(); for pr in out.profiles.iter().filter(|pr| !pr.natural && pr.pts.len() >= 2) { let mut ring = pr.pts.clone(); - ring.extend(pr.pts.iter().rev().map(|q| [q[0], q[1] - EARTH_BAND])); + ring.extend(pr.pts.iter().rev().map(|q| [q[0], q[1] - depth])); band.push(vec![ring]); } if band.is_empty() { diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs index 676607ce..6f73f397 100644 --- a/src-tauri/core/src/queries.rs +++ b/src-tauri/core/src/queries.rs @@ -23,6 +23,7 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result json(&site_rules::check_project(p)), + ("dormerStatus", _) => json(&crate::dormer::status(p)), ("excavationQuantities", _) => json(&crate::excavation::quantities(p)), ("buildingFootprint", _) => json(&site_rules::building_footprint(p)), ("modelTop", _) => json(&site_rules::model_top(p)), diff --git a/src-tauri/core/src/terrain.rs b/src-tauri/core/src/terrain.rs index 5f043e64..013b098f 100644 --- a/src-tauri/core/src/terrain.rs +++ b/src-tauri/core/src/terrain.rs @@ -142,6 +142,11 @@ impl<'a> TinIndex<'a> { /// Höhe am Punkt (x, y); `None` ausserhalb des Netzes. pub fn z_at(&self, x: f64, y: f64) -> Option { + self.bary_at(x, y).map(|(t, l)| l[0] * self.tin.z[t[0]] + l[1] * self.tin.z[t[1]] + l[2] * self.tin.z[t[2]]) + } + + /// Dreieck (Eckindizes) und Schwerpunktkoordinaten am Punkt (x, y); `None` ausserhalb des Netzes. + pub fn bary_at(&self, x: f64, y: f64) -> Option<([usize; 3], [f64; 3])> { if !(x >= self.b[0] - 1e-9 && x <= self.b[2] + 1e-9 && y >= self.b[1] - 1e-9 && y <= self.b[3] + 1e-9) { return None; } @@ -159,7 +164,7 @@ impl<'a> TinIndex<'a> { let l0 = 1.0 - l1 - l2; const E: f64 = -1e-9; if l0 >= E && l1 >= E && l2 >= E { - return Some(l0 * t.z[a] + l1 * t.z[b] + l2 * t.z[c]); + return Some(([a, b, c], [l0, l1, l2])); } } None @@ -961,6 +966,43 @@ pub fn datum(reference_masl: Option, z: &[f64]) -> f64 { } } +/// [T6] Glättet ein Höhenraster (`z[j * nx + i]`, NaN = kein Messwert) mit `passes` Durchgängen eines +/// Binomialfilters [1 2 1]/4 je Achse. Fehlende Nachbarn zählen nicht (Gewichte werden renormiert), fehlende +/// Zellen bleiben fehlend. Falsche Grösse → Eingabe unverändert. +pub fn smooth_grid(z: &[f64], nx: usize, ny: usize, passes: u32) -> Vec { + if nx == 0 || ny == 0 || z.len() != nx * ny { + return z.to_vec(); + } + let mut cur = z.to_vec(); + for _ in 0..passes.min(20) { + for horizontal in [true, false] { + let src = cur.clone(); + for j in 0..ny { + for i in 0..nx { + let c = src[j * nx + i]; + if c.is_nan() { + continue; + } + let (a, b) = if horizontal { + (if i > 0 { src[j * nx + i - 1] } else { f64::NAN }, if i + 1 < nx { src[j * nx + i + 1] } else { f64::NAN }) + } else { + (if j > 0 { src[(j - 1) * nx + i] } else { f64::NAN }, if j + 1 < ny { src[(j + 1) * nx + i] } else { f64::NAN }) + }; + let (mut sum, mut w) = (2.0 * c, 2.0); + for v in [a, b] { + if !v.is_nan() { + sum += v; + w += 1.0; + } + } + cur[j * nx + i] = sum / w; + } + } + } + } + cur +} + #[cfg(test)] mod tests { use super::*; @@ -1063,4 +1105,17 @@ mod tests { assert_eq!(datum(Some(450.0), &[2.0, 5.0]), 0.0); assert_eq!(datum(None, &[452.0]), 0.0); } + + #[test] + fn raster_glaetten() { + // Spitze in der Mitte wird abgebaut, Summe grob erhalten, NaN bleibt NaN, Ebene bleibt eben. + let mut z = vec![0.0; 25]; + z[12] = 8.0; + z[0] = f64::NAN; + let g = smooth_grid(&z, 5, 5, 1); + assert!(g[12] < 8.0 && g[12] > 1.0 && g[11] > 0.0 && g[0].is_nan()); + assert!(smooth_grid(&vec![3.0; 25], 5, 5, 3).iter().all(|v| (v - 3.0).abs() < 1e-12)); + assert_eq!(smooth_grid(&z[..4], 5, 5, 1).len(), 4); + assert!(smooth_grid(&z, 5, 5, 0)[12] == 8.0); + } } diff --git a/src-tauri/core/src/web/cmd_create.rs b/src-tauri/core/src/web/cmd_create.rs index 4e70b912..543dbc9f 100644 --- a/src-tauri/core/src/web/cmd_create.rs +++ b/src-tauri/core/src/web/cmd_create.rs @@ -83,3 +83,10 @@ pub fn terrain_from_contours_opts_json(contours_json: &str, id: &str, smooth: f6 }; crate::cmd_solid::terrain_from_contours_with(c.as_array().map(Vec::as_slice).unwrap_or(&[]), id, o).to_string() } + +/// Höhenraster glätten ([T6], `crate::terrain::smooth_grid`): `z` zeilenweise (`nx` Spalten, NaN = kein Wert). +#[wasm_bindgen] +pub fn terrain_smooth_grid(z: &[f64], nx: f64, ny: f64, passes: f64) -> Vec { + let dim = |v: f64| if v.is_finite() && v >= 0.0 { v as usize } else { 0 }; + crate::terrain::smooth_grid(z, dim(nx), dim(ny), if passes.is_finite() && passes > 0.0 { passes as u32 } else { 0 }) +} diff --git a/src-tauri/fileio/src/ifc_export.rs b/src-tauri/fileio/src/ifc_export.rs index 88bd5362..862ecfcb 100644 --- a/src-tauri/fileio/src/ifc_export.rs +++ b/src-tauri/fileio/src/ifc_export.rs @@ -43,6 +43,8 @@ // zur nächsten Ecke als IfcTrimmedCurve auf IfcCircle, DXF-Sinn: positiv = Gegenuhrzeigersinn; // sonst Strecke), IfcExtrudedAreaSolid in +Z; Achse wie WALL_ARC. Öffnungen schneiden über // OPENING (IfcRelVoidsElement). +// GRID = 18 ([112] Achsraster → IfcGrid), structure, id, name, n_u, n_v, (label, PTS) × (n_u + n_v) +// Linienzüge in Welt-XY (Bögen schon in Sehnen zerlegt); Placement der Trägerstruktur, ohne Darstellung. // CEILING = 3, structure, id, name, TYPEREF, PSETS, PTS, n_inner, PTS × n_inner, z_rel, depth // (innere Ringe = Deckenaussparungen, IfcArbitraryProfileDefWithVoids) // OPENING = 4, wall_id, structure, opening_id, is_door (0/1), fill_name, PTS (Öffnungskörper), z_rel, @@ -138,6 +140,7 @@ pub const REC_ATTACH: f64 = 14.0; pub const REC_OPENING_SOLID: f64 = 15.0; pub const REC_WALL_ARC: f64 = 16.0; pub const REC_WALL_ARC_SOLID: f64 = 17.0; +pub const REC_GRID: f64 = 18.0; // ── IFC-GUID (Kompression nach IfcOpenShell `guid.compress`) ──────────────── @@ -932,6 +935,12 @@ impl Builder { } } + /// Offener Linienzug als IfcPolyline. + fn emit_open_polyline(&mut self, pts: &[(f64, f64)]) -> usize { + let ids: Vec = pts.iter().map(|p| self.add("IFCCARTESIANPOINT", list(&[fmt_real(p.0), fmt_real(p.1)]))).collect(); + self.add("IFCPOLYLINE", refs(&ids)) + } + /// Geschlossener Linienzug (erster Punkt am Ende wiederholt) als IfcPolyline. fn emit_closed_polyline(&mut self, ring: &[(f64, f64)]) -> usize { let mut pt_ids = Vec::with_capacity(ring.len() + 1); @@ -1339,6 +1348,7 @@ fn rec_name(code: f64) -> &'static str { c if c == REC_CLASSIFICATION => "CLASSIFICATION", c if c == REC_ZONE => "ZONE", c if c == REC_ATTACH => "ATTACH", + c if c == REC_GRID => "GRID", _ => "?", } } @@ -2191,6 +2201,29 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { w.add_pset(p, zone, &zone_key); } } + c if c == REC_GRID => { + let structure = r.structure(n_storeys)?; + let id = r.string()?; + let name = r.string()?; + let (n_u, n_v) = (r.idx()?, r.idx()?); + let mut axes = Vec::new(); + for _ in 0..n_u + n_v { + let tag = r.string()?; + let pts = r.pts()?; + let curve = w.emit_open_polyline(&pts); + axes.push(w.add("IFCGRIDAXIS", format!("{},#{curve},.T.", ifc_string(&tag)))); + } + let placement = w.emit_placement(0.0, w.placement_of(structure)); + let g = w.gid(&format!("grid/{id}")); + let u = refs(&axes[..n_u]); + let v = refs(&axes[n_u..]); + let entity = w.add( + "IFCGRID", + format!("{g},#{},{},$,$,#{placement},$,{u},{v},$", w.owner_history, ifc_string(&name)), + ); + w.add_to_containment(structure, entity); + w.elements.insert(format!("grid/{id}"), entity); + } c if c == REC_ATTACH => { let key = r.string()?; let psets = r.psets()?; diff --git a/src/App.tsx b/src/App.tsx index acd75aed..fa301045 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -20,6 +20,7 @@ import { addLegend, patchLegend, removeLegend } from "./analysis/legend"; import { lengthFromDisplay, unitsForLevel } from "./tools/displayUnits"; import { NON_LENGTH_FIELDS } from "./commands/parseInput"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useDormerNotice } from "./state/useDormerNotice"; import { collectVisibleCodes, flattenCategories, @@ -366,6 +367,7 @@ export default function App() { const applyChange = useStore((s) => s.applyChange); const groupChanges = useStore((s) => s.groupChanges); const notify = useStore((s) => s.notify); + useDormerNotice(project, notify); const undo = useStore((s) => s.undo); const redo = useStore((s) => s.redo); const canUndo = useStore((s) => s.canUndo); @@ -1188,6 +1190,12 @@ export default function App() { () => (project.ceilings ?? []).find((c) => c.id === selectedCeilingId) ?? null, [project.ceilings, selectedCeilingId], ); + // [68] Genau eine gewählte Baugrube (Griffe für Umriss und Sohle). + const selectedExcavation = useMemo(() => { + if (selectedContextObjectIds.length !== 1) return null; + const o = (project.context ?? []).find((c) => c.id === selectedContextObjectIds[0]); + return o && o.type === "excavation" ? o : null; + }, [project.context, selectedContextObjectIds]); const selectedRoom = useMemo( () => (project.rooms ?? []).find((r) => r.id === selectedRoomId) ?? null, [project.rooms, selectedRoomId], @@ -1670,6 +1678,8 @@ export default function App() { setWallThickness, updateOpening, moveCeilingGrip, + moveExcavationGrip, + moveExcavationEdge, moveCeilingBy, moveCeilingEdge, updateCeiling, @@ -1757,6 +1767,7 @@ export default function App() { project, selectedDrawing, selectedCeiling, + selectedExcavation, selectedRoom, selectedOpeningId, selectedStairId, @@ -1781,6 +1792,8 @@ export default function App() { moveStairBy, moveRoomGrip, moveCeilingGrip, + moveExcavationGrip, + moveExcavationEdge, moveGripOf, moveRoomEdge, moveCeilingEdge, diff --git a/src/analysis/dormerStatus.test.ts b/src/analysis/dormerStatus.test.ts new file mode 100644 index 00000000..0477d4b8 --- /dev/null +++ b/src/analysis/dormerStatus.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from "vitest"; +import type { Project, Roof } from "../model/types"; +import { sampleProject } from "../model/sampleProject"; +import { affectedKeys, dormerKey, dormerStatus, newlyAffected } from "./dormerStatus"; + +/** Satteldach 10 × 8 m, 45°, First bei y = 4, mit einer Sattelgaube bei y = 1. */ +function withDormer(frontHeight: number): Project { + const roof = { + id: "R1", + type: "roof", + floorId: "F", + categoryCode: "35", + outline: [{ x: 0, y: 0 }, { x: 10, y: 0 }, { x: 10, y: 8 }, { x: 0, y: 8 }], + shape: "sattel", + pitchDeg: 45, + overhang: 0.5, + ridgeAxis: "x", + baseElevation: 3, + thickness: 0.3, + dormers: [{ id: "D1", kind: "sattel", position: { x: 3, y: 1 }, width: 2.4, frontHeight }], + } as unknown as Roof; + return { ...sampleProject, roofs: [roof] }; +} + +describe("dormerStatus [G5]", () => { + it("meldet nichts ohne Gauben", () => { + expect(dormerStatus({ ...sampleProject, roofs: [] })).toEqual([]); + }); + + it("meldet die am First gekappte Gaube mit tatsächlicher Höhe", () => { + const ok = dormerStatus(withDormer(1.6)); + expect(ok).toHaveLength(1); + expect(ok[0]).toMatchObject({ roofId: "R1", dormerId: "D1", clamped: false, invalid: false }); + const hi = dormerStatus(withDormer(6)); + expect(hi[0].clamped).toBe(true); + expect(hi[0].effectiveHeight).toBeLessThan(6); + expect(hi[0].effectiveHeight).toBeGreaterThan(0.3); + }); + + it("newlyAffected nur beim Übergang auf gekappt", () => { + const before = affectedKeys(dormerStatus(withDormer(1.6))); + const now = dormerStatus(withDormer(6)); + expect(newlyAffected(before, now).map(dormerKey)).toEqual(["R1/D1"]); + expect(newlyAffected(affectedKeys(now), now)).toEqual([]); + }); +}); diff --git a/src/analysis/dormerStatus.ts b/src/analysis/dormerStatus.ts new file mode 100644 index 00000000..e3b1226d --- /dev/null +++ b/src/analysis/dormerStatus.ts @@ -0,0 +1,33 @@ +// Gauben ([G5]): Zustand aus dem Rust-Kern (`dormer.rs::status`). Eine zu hohe Gaube wird am First gekappt +// (`clamped`) oder ist nicht herstellbar (`invalid`) — die Hülle zeigt das als Hinweis (Objekt-Info, Toast). + +import type { Project } from "../model/types"; +import { documentFor } from "../core/document"; + +export interface DormerStatus { + roofId: string; + dormerId: string; + /** Über den First hinaus und darum gekappt. */ + clamped: boolean; + /** Nicht herstellbar (zu schmal/niedrig, Punkt nicht in einer geneigten Fläche …). */ + invalid: boolean; + /** Tatsächliche Stirnhöhe (m) nach dem Kappen; 0 bei `invalid`. */ + effectiveHeight: number; +} + +/** Zustand aller Gauben (leer ohne Gauben, ohne Kernaufruf). */ +export function dormerStatus(project: Project): DormerStatus[] { + if (!(project.roofs ?? []).some((r) => (r.dormers ?? []).length > 0)) return []; + return documentFor(project).query("dormerStatus"); +} + +/** Schlüssel einer Gaube für Mengenvergleiche. */ +export const dormerKey = (s: Pick) => `${s.roofId}/${s.dormerId}`; + +/** Gauben, die jetzt gekappt/ungültig sind, vorher aber nicht (`before` = Schlüssel des vorigen Stands). */ +export function newlyAffected(before: ReadonlySet, now: readonly DormerStatus[]): DormerStatus[] { + return now.filter((s) => (s.clamped || s.invalid) && !before.has(dormerKey(s))); +} + +/** Schlüssel der gekappten/ungültigen Gauben. */ +export const affectedKeys = (now: readonly DormerStatus[]): Set => new Set(now.filter((s) => s.clamped || s.invalid).map(dormerKey)); diff --git a/src/analysis/excavation.test.ts b/src/analysis/excavation.test.ts index b0a6a613..adde4850 100644 --- a/src/analysis/excavation.test.ts +++ b/src/analysis/excavation.test.ts @@ -64,3 +64,41 @@ describe("[T6] Gelände aus Höhenlinien", () => { expect(Math.max(...zs)).toBeGreaterThan(3); }); }); + +describe("[68] Arbeitsraum, Verbau, Überlagerung", () => { + const pit = (id: string, dx: number, extra: object = {}) => ({ + id, + type: "excavation" as const, + name: id, + outline: [{ x: -5 + dx, y: -5 }, { x: 5 + dx, y: -5 }, { x: 5 + dx, y: 5 }, { x: -5 + dx, y: 5 }], + bottom: -3, + slope: 45, + ...extra, + }); + const terrain = project().context![0]; + const withPits = (...pits: ReturnType[]): Project => ({ ...project(), context: [terrain, ...pits] }); + + it("Arbeitsraum vergrössert Sohle und Abtrag", () => { + const [plain] = excavationQuantities(withPits(pit("a", 0))); + const [ws] = excavationQuantities(withPits(pit("a", 0, { workingSpace: 1 }))); + expect(ws.bottomArea).toBeCloseTo(144, 6); + expect(ws.cut).toBeGreaterThan(plain.cut * 1.3); + }); + + it("senkrechter Verbau: Abtrag ≈ Sohle × Tiefe", () => { + const [q] = excavationQuantities(withPits(pit("a", 0, { edgeShoring: [true, true, true, true] }))); + expect(Math.abs(q.cut - 300) / 300).toBeLessThan(0.03); + }); + + it("überlappende Baugruben: Summe zählt die Überlagerung einmal", () => { + const [single] = excavationQuantities(withPits(pit("a", 0))); + const same = excavationQuantities(withPits(pit("a", 0), pit("b", 0))); + expect(same.map((q) => q.id)).toEqual(["a", "b"]); + expect(same[0].cut + same[1].cut).toBeCloseTo(single.cut, 3); + expect(same[1].bottomArea).toBeLessThan(1); + const shifted = excavationQuantities(withPits(pit("a", 0), pit("b", 6))); + const sum = shifted[0].cut + shifted[1].cut; + expect(sum).toBeGreaterThan(single.cut); + expect(sum).toBeLessThan(2 * single.cut - 10); + }); +}); diff --git a/src/core/document.ts b/src/core/document.ts index 88d22676..8e82b387 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -69,6 +69,7 @@ export type QueryName = | "ivhb" | "siteCheck" | "excavationQuantities" + | "dormerStatus" | "buildingFootprint" | "modelTop" | "shadows" diff --git a/src/export/exportIfc.grid.test.ts b/src/export/exportIfc.grid.test.ts new file mode 100644 index 00000000..40d8b6b2 --- /dev/null +++ b/src/export/exportIfc.grid.test.ts @@ -0,0 +1,68 @@ +// [112] Achsraster → IfcGrid im IFC-Export (IFC4 und IFC2x3), Prüfung mit ifcopenshell, wenn installiert. + +import { describe, expect, it } from "vitest"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import "../engine/fileioWasm.setup"; +import { exportIfcSpf } from "./exportIfc"; +import { sampleProject } from "../model/sampleProject"; +import type { Drawing2D, Project } from "../model/types"; + +const hasIfcOpenShell = spawnSync("python3", ["-c", "import ifcopenshell, ifcopenshell.validate, _pytest"]).status === 0; + +function gridProject(radial = false): Project { + const floor = sampleProject.drawingLevels.find((l) => l.kind === "floor")!; + const grid = { + id: "grid-1", + type: "drawing2d", + levelId: floor.id, + categoryCode: sampleProject.layers[0]?.code ?? "00", + geom: radial + ? { shape: "grid", origin: { x: 0, y: 0 }, angle: 0, radial: true, a: [{ label: "1", pos: 0 }, { label: "2", pos: 90 }], b: [{ label: "A", pos: 3 }, { label: "B", pos: 6 }] } + : { + shape: "grid", + origin: { x: 1, y: 2 }, + angle: 0, + a: [{ label: "1", pos: 0 }, { label: "2", pos: 5 }, { label: "3", pos: 9 }], + b: [{ label: "A", pos: 0 }, { label: "B", pos: 4 }], + }, + } as unknown as Drawing2D; + return { ...sampleProject, drawings2d: [...sampleProject.drawings2d, grid] }; +} + +describe("IfcGrid im Export [112]", () => { + it("IFC4: IfcGrid mit U-/V-Achsen und Beschriftung", () => { + const ifc = exportIfcSpf(gridProject()); + expect(ifc).toMatch(/^#\d+=IFCGRID\(/m); + const tags = [...ifc.matchAll(/^#\d+=IFCGRIDAXIS\('([^']*)'/gm)].map((m) => m[1]); + expect(tags).toEqual(["1", "2", "3", "A", "B"]); + // UAxes = 3, VAxes = 2. + const g = ifc.match(/^#\d+=IFCGRID\(.*,\((#\d+(?:,#\d+)*)\),\((#\d+(?:,#\d+)*)\),\$\);$/m)!; + expect(g[1].split(",")).toHaveLength(3); + expect(g[2].split(",")).toHaveLength(2); + }); + + it("ohne Raster kein IfcGrid; IFC2x3 ebenfalls", () => { + expect(exportIfcSpf(sampleProject)).not.toContain("IFCGRID("); + expect(exportIfcSpf(gridProject(), { schema: "IFC2X3" })).toMatch(/^#\d+=IFCGRID\(/m); + }); + + it.skipIf(!hasIfcOpenShell)("ifcopenshell: gültig, Achsen lesbar (rechtwinklig und radial)", () => { + for (const [name, p] of [["ortho", gridProject()], ["radial", gridProject(true)]] as const) { + const dir = mkdtempSync(join(tmpdir(), "dossier-ifc-grid-")); + const file = join(dir, `${name}.ifc`); + writeFileSync(file, exportIfcSpf(p)); + const r = spawnSync("python3", ["scripts/validate-ifc.py", file], { encoding: "utf8", timeout: 120_000 }); + expect(r.status, `${r.stdout}\n${r.stderr}`).toBe(0); + const read = spawnSync( + "python3", + ["-c", "import sys, ifcopenshell\nm = ifcopenshell.open(sys.argv[1])\ng = m.by_type('IfcGrid')[0]\nprint(len(g.UAxes), len(g.VAxes), ','.join(a.AxisTag for a in g.UAxes + g.VAxes))", file], + { encoding: "utf8" }, + ); + expect(read.status, read.stderr).toBe(0); + expect(read.stdout.trim()).toBe(name === "ortho" ? "3 2 1,2,3,A,B" : "2 2 1,2,A,B"); + } + }, 240_000); +}); diff --git a/src/geometry/grips.ts b/src/geometry/grips.ts index 8f57fae3..ab08d4c4 100644 --- a/src/geometry/grips.ts +++ b/src/geometry/grips.ts @@ -26,6 +26,8 @@ export type GripRequest = | { op: "ceilingGrip" | "roomGrip" | "roofGrip"; id: string; index: number; pt: P } | { op: "ceilingBy" | "roofBy" | "stairBy" | "roomBy" | "roomStamp"; id: string; delta: P } | { op: "ceilingEdge" | "roomEdge"; id: string; a: number; b: number; delta: P } + | { op: "excavationGrip"; id: string; index: number; pt: P } + | { op: "excavationEdge"; id: string; a: number; b: number; delta: P } | { op: "insertPoint"; id: string; seg: number; pt: P } | { op: "deletePoint"; id: string; index: number } | { op: "vertexType"; id: string; index: number; vertexType: "corner" | "arc" | "spline" } diff --git a/src/i18n/de.ts b/src/i18n/de.ts index d01c6282..b7351e9e 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -395,6 +395,12 @@ export const de = { "attr.grid.bubbleMm": "Blase Ø (mm)", "attr.grid.levels": "Sichtbar in", "attr.grid.show3d": "Im 3D-Modell zeigen", + "attr.grid.axis": "Achse bei {pos} m", + "attr.grid.ray": "Strahl bei {pos}°", + "attr.grid.ring": "Ring bei {pos} m", + "attr.grid.axisLabel": "Beschriftung der Achse", + "attr.grid.axisBubble": "Blasenseite dieser Achse", + "attr.grid.axisBubble.grid": "Wie Raster", "attr.grid.levels.all": "Allen Geschossen", "attr.grid.levels.here": "Nur diesem Geschoss", "attr.dim.gap": "Abstand Hilfslinie (mm)", @@ -508,6 +514,10 @@ export const de = { "objinfo.dormer.kind.flach": "Flachdachgaube", "objinfo.dormer.kind.walm": "Walmgaube", "objinfo.dormer.remove": "Gaube entfernen", + "objinfo.dormer.clamped": "Am First gekappt: Stirnhöhe nur {height} m (Gaube würde über den First ragen).", + "objinfo.dormer.invalid": "Nicht herstellbar: Breite, Höhe oder Lage prüfen.", + "dormer.clamped.toast": "Gaube am First gekappt: Stirnhöhe {height} m.", + "dormer.invalid.toast": "Gaube nicht herstellbar: Lage oder Masse prüfen.", "objinfo.dormer.width": "Breite (aussen)", "objinfo.dormer.frontHeight": "Stirnhöhe", "objinfo.dormer.pitch": "Neigung Gaubendach", @@ -2034,6 +2044,10 @@ export const de = { "site.excavation.bermHeight": "Berme alle [m]", "site.excavation.qty": "Abtrag {cut} m³ · Auftrag {fill} m³ · Hinterfüllung {backfill} m³", "site.excavation.noTerrain": "Kein Gelände unter der Baugrube", + "site.excavation.workingSpace": "Arbeitsraum [m]", + "site.excavation.shoring": "Verbau (senkrecht), Kante", + "site.excavation.shoringHint": "Gewählte Kanten: senkrechte Wand (Spundwand) statt Böschung", + "site.earthDepth": "Erdreich-Band im Schnitt [m]", "site.type.image": "Luftbild", "site.group.image": "Luftbild", "site.dwgHint": "DWG? Zuerst mit dem gratis ODA File Converter in DXF umwandeln.", @@ -2657,6 +2671,10 @@ export const de = { "ctxImport.terrain.resolution": "Auflösung", "ctxImport.terrain.res2": "2 m (schnell)", "ctxImport.terrain.res05": "0.5 m (fein, grössere Kacheln)", + "ctxImport.terrain.smooth": "Glättung des Höhenrasters", + "ctxImport.terrain.smooth0": "Rohdaten", + "ctxImport.terrain.smooth1": "Glätten (leicht)", + "ctxImport.terrain.smooth3": "Glätten (stark)", "ctxImport.src.osmBuildings": "OSM-Gebäude", "ctxImport.src.osmRoads": "OSM-Strassen", "ctxImport.src.osmWater": "OSM-Wasser", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index edf904c2..477778a5 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -393,6 +393,12 @@ export const en: Record = { "attr.grid.bubbleMm": "Bubble Ø (mm)", "attr.grid.levels": "Visible on", "attr.grid.show3d": "Show in 3D model", + "attr.grid.axis": "Axis at {pos} m", + "attr.grid.ray": "Ray at {pos}°", + "attr.grid.ring": "Ring at {pos} m", + "attr.grid.axisLabel": "Axis label", + "attr.grid.axisBubble": "Bubble side of this axis", + "attr.grid.axisBubble.grid": "As grid", "attr.grid.levels.all": "All levels", "attr.grid.levels.here": "This level only", "attr.dim.gap": "Extension gap (mm)", @@ -506,6 +512,10 @@ export const en: Record = { "objinfo.dormer.kind.flach": "Flat-roof dormer", "objinfo.dormer.kind.walm": "Hipped dormer", "objinfo.dormer.remove": "Remove dormer", + "objinfo.dormer.clamped": "Clamped at the ridge: front height only {height} m (the dormer would reach beyond the ridge).", + "objinfo.dormer.invalid": "Cannot be built: check width, height or position.", + "dormer.clamped.toast": "Dormer clamped at the ridge: front height {height} m.", + "dormer.invalid.toast": "Dormer cannot be built: check position or size.", "objinfo.dormer.width": "Width (outside)", "objinfo.dormer.frontHeight": "Front height", "objinfo.dormer.pitch": "Dormer roof pitch", @@ -2020,6 +2030,10 @@ export const en: Record = { "site.excavation.fillSlope": "Fill slope [°]", "site.excavation.bermWidth": "Berm [m]", "site.excavation.bermHeight": "Berm every [m]", + "site.excavation.workingSpace": "Working space [m]", + "site.excavation.shoring": "Shoring (vertical), edge", + "site.excavation.shoringHint": "Selected edges: vertical wall (sheet piling) instead of a slope", + "site.earthDepth": "Earth band in section [m]", "site.excavation.qty": "Cut {cut} m³ · Fill {fill} m³ · Backfill {backfill} m³", "site.excavation.noTerrain": "No terrain below the excavation", "site.type.image": "Aerial", @@ -2644,6 +2658,10 @@ export const en: Record = { "ctxImport.terrain.resolution": "Resolution", "ctxImport.terrain.res2": "2 m (fast)", "ctxImport.terrain.res05": "0.5 m (fine, larger tiles)", + "ctxImport.terrain.smooth": "Height grid smoothing", + "ctxImport.terrain.smooth0": "Raw data", + "ctxImport.terrain.smooth1": "Smooth (light)", + "ctxImport.terrain.smooth3": "Smooth (strong)", "ctxImport.src.osmBuildings": "OSM buildings", "ctxImport.src.osmRoads": "OSM roads", "ctxImport.src.osmWater": "OSM water", diff --git a/src/model/terrain.ts b/src/model/terrain.ts index a5f92729..9d5d580c 100644 --- a/src/model/terrain.ts +++ b/src/model/terrain.ts @@ -60,6 +60,21 @@ export interface TerrainGrid { name?: string; } +/** + * [T6] Glättet ein Höhenraster (Rust-Kern `terrain.rs::smooth_grid`): `passes` Durchgänge eines + * Binomialfilters je Achse (0 = unverändert). Zellen ohne Messwert (`null`) bleiben leer. + */ +export function smoothTerrainGrid(grid: TerrainGrid, passes: number): TerrainGrid { + if (!(passes > 0) || grid.xs.length === 0 || grid.ys.length === 0) return grid; + const nx = grid.xs.length; + const ny = grid.ys.length; + const flat = new Float64Array(nx * ny); + for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) flat[j * nx + i] = grid.z[j]?.[i] ?? Number.NaN; + const out = core().terrain_smooth_grid(flat, nx, ny, passes); + const z = grid.ys.map((_, j) => grid.xs.map((__, i) => (Number.isFinite(out[j * nx + i]) ? out[j * nx + i] : null))); + return { ...grid, z }; +} + /** * Baut ein Terrain-Mesh aus einem regulären Höhenraster (Quad-Gitter → zwei * Dreiecke je Zelle). Fehlende Zellen (`null`) werden ausgelassen; eine Zelle diff --git a/src/model/terrainGrid.test.ts b/src/model/terrainGrid.test.ts index d890de7c..81af3f7c 100644 --- a/src/model/terrainGrid.test.ts +++ b/src/model/terrainGrid.test.ts @@ -2,7 +2,7 @@ // (swisstopo-DTM-Profilraster → terrainMeshFromGrid). import { describe, it, expect } from "vitest"; -import { terrainMeshFromGrid } from "./terrain"; +import { smoothTerrainGrid, terrainMeshFromGrid } from "./terrain"; import type { TerrainGrid } from "./terrain"; describe("terrainMeshFromGrid", () => { @@ -54,3 +54,18 @@ describe("terrainMeshFromGrid", () => { expect(zs.sort((a, b) => a - b)).toEqual([5, 7, 9, 11]); }); }); + +describe("[T6] Höhenraster glätten", () => { + it("baut Spitzen ab, lässt Lücken und Ebenen", () => { + const xs = [0, 1, 2, 3, 4]; + const flat = Array.from({ length: 5 }, () => Array(5).fill(2)); + expect(smoothTerrainGrid({ xs, ys: xs, z: flat }, 3).z.flat().every((v) => Math.abs((v as number) - 2) < 1e-12)).toBe(true); + const z = Array.from({ length: 5 }, () => Array(5).fill(0)); + z[2][2] = 8; + z[0][0] = null; + const g = smoothTerrainGrid({ xs, ys: xs, z }, 1); + expect((g.z[2][2] as number) < 8 && (g.z[2][2] as number) > 1).toBe(true); + expect(g.z[0][0]).toBeNull(); + expect(smoothTerrainGrid({ xs, ys: xs, z }, 0)).toEqual({ xs, ys: xs, z }); + }); +}); diff --git a/src/model/types.generated.ts b/src/model/types.generated.ts index d36c78a4..58208b11 100644 --- a/src/model/types.generated.ts +++ b/src/model/types.generated.ts @@ -1176,6 +1176,15 @@ export type Excavation = { edgeSlopes?: Array; bermWidth?: number; bermHeight?: number; + /** + * [68] Arbeitsraum in m: der Umriss gilt als Gebäude-Grundfläche, die Sohle liegt um dieses Mass + * weiter aussen (Gehrung an den Ecken). Fehlt = 0 (Umriss = Sohle). + */ + workingSpace?: number; + /** + * [68] Senkrechter Verbau (Spundwand) je Kante (wie `edgeSlopes`): keine Böschung, Wand steht senkrecht. + */ + edgeShoring?: Array; }; /** Ein extrudierter Körper: geschlossenes Profil (Modell-Meter) + Höhe. */ @@ -1280,7 +1289,15 @@ export type FrameDetail = { }; /** Eine Achse des Achsrasters: Beschriftung und Lage (Abstand bzw. Winkel/Radius, s. `Grid`). */ -export type GridAxis = { label: string; pos: number }; +export type GridAxis = { + label: string; + pos: number; + /** Blasenseite nur dieser Achse (überschreibt `Grid.bubbles`); fehlt = wie das Raster. */ + bubble?: GridBubbles; +}; + +/** Welche Achsenden eine Blase tragen. */ +export type GridBubbles = "start" | "end" | "both"; /** * Raster-Regel: generiert Wände entlang gleichmäßiger X-/Y-Achsen. @@ -3025,6 +3042,8 @@ export type TerrainMesh = { contourInterval?: number; /** [T6] Jede n-te Höhenlinie ist Zähllinie (dicker, beschriftet). Default 5. */ contourIndexEvery?: number; + /** [T6] Tiefe des Erdreich-Bands im Schnitt unter dem Gelände in m (Default 1.5). */ + earthDepth?: number; }; /** Ein zusammenhängender Textabschnitt mit einheitlicher Formatierung. */ diff --git a/src/panels/AttributesPanel.tsx b/src/panels/AttributesPanel.tsx index 7a7b5b9b..c3967bdd 100644 --- a/src/panels/AttributesPanel.tsx +++ b/src/panels/AttributesPanel.tsx @@ -502,6 +502,7 @@ export function AttributesPanel() { Standard zurück. Die Masszahl selbst wird direkt im Plan am eigenen Griff verschoben (rastet nahe der Standardlage ein). */} {drawing?.geom.shape === "grid" && (() => { + const fmtAxis = (v: number) => (Math.round(v * 100) / 100).toString(); const geom = drawing.geom as Extract; const here = geom.levels?.includes(drawing.levelId) && geom.levels.length === 1; return ( @@ -529,6 +530,42 @@ export function AttributesPanel() { host.onSetGridProps(drawing.id, { show3d: e.target.checked })} /> + {(["a", "b"] as const).map((list) => + geom[list].map((ax, i) => ( + + {t(geom.radial ? (list === "a" ? "attr.grid.ray" : "attr.grid.ring") : "attr.grid.axis", { pos: fmtAxis(ax.pos) })} + + host.onSetGridProps(drawing.id, { [list]: geom[list].map((x, k) => (k === i ? { ...x, label: e.target.value } : x)) })} + /> + + + + )), + )} {t("attr.grid.levels")} { + const next = obj.outline.map((__, k) => (k === i ? e.target.checked : obj.edgeShoring?.[k] === true)); + host.onPatchContextObject(obj.id, { edgeShoring: next.some(Boolean) ? next : undefined }, `site-${obj.id}-edgeShoring`); + }} + /> + {i + 1} + + ))} + + x.id === obj.id)} /> )} diff --git a/src/panels/host.ts b/src/panels/host.ts index c5de6c7a..34e99ad9 100644 --- a/src/panels/host.ts +++ b/src/panels/host.ts @@ -300,7 +300,16 @@ export interface PanelHostValue { /** Achsraster ([112]): Blasenseite, Überstand (m), Blasen-Ø (Papier-mm), Geschosse (leer = alle). */ onSetGridProps: ( drawingId: string, - patch: { bubbles?: "start" | "end" | "both"; extend?: number; bubbleMm?: number; levels?: string[] | undefined; show3d?: boolean }, + patch: { + bubbles?: "start" | "end" | "both"; + extend?: number; + bubbleMm?: number; + levels?: string[] | undefined; + show3d?: boolean; + /** Achsen (Beschriftung, Lage, Blasenseite je Achse): ganze Liste ersetzen. */ + a?: import("../model/types").GridAxis[]; + b?: import("../model/types").GridAxis[]; + }, ) => void; onSetDimensionStyle: ( drawingId: string, diff --git a/src/state/excavationGrips.test.ts b/src/state/excavationGrips.test.ts new file mode 100644 index 00000000..7e27b81a --- /dev/null +++ b/src/state/excavationGrips.test.ts @@ -0,0 +1,39 @@ +// [68] Baugrube: Griffe für Umriss-Ecken, Kanten und Sohlenhöhe (Kern `grips.rs`, Griff-Lage `excavationGripPoints`). + +import { describe, expect, it } from "vitest"; +import { documentFor } from "../core/document"; +import { sampleProject } from "../model/sampleProject"; +import type { Excavation, Project } from "../model/types"; +import { excavationGripPoints } from "./useGripEditing"; + +const pit: Excavation = { + id: "bg", + type: "excavation", + name: "Baugrube", + outline: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }], + bottom: -2, +}; +const project = (): Project => ({ ...sampleProject, context: [pit] }); + +function commit(base: Project, req: object): Excavation { + const r = documentFor(base).commitGrip(base, req, undefined, 1); + if ("problems" in r) throw new Error(r.problems.join(";")); + return r.project.context!.find((c) => c.id === "bg") as Excavation; +} + +describe("Baugrube: Griffe", () => { + it("Griff-Punkte: Ecken plus Sohlen-Griff (Schwerpunkt, y + Sohle)", () => { + const pts = excavationGripPoints(pit); + expect(pts).toHaveLength(5); + expect(pts[4]).toEqual({ x: 2, y: 0 }); + }); + + it("Ecke, Kante und Sohle ziehen", () => { + const p = project(); + expect(commit(p, { op: "excavationGrip", id: "bg", index: 2, pt: [5, 6] }).outline[2]).toEqual({ x: 5, y: 6 }); + const edge = commit(p, { op: "excavationEdge", id: "bg", a: 0, b: 1, delta: [0, -1] }); + expect([edge.outline[0].y, edge.outline[1].y]).toEqual([-1, -1]); + // Sohlen-Griff liegt bei (2, 2 + bottom); auf y = −1 ziehen → bottom = −3. + expect(commit(p, { op: "excavationGrip", id: "bg", index: 4, pt: [2, -1] }).bottom).toBe(-3); + }); +}); diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index d7db2399..2cc3ac32 100644 --- a/src/state/projectSlice.ts +++ b/src/state/projectSlice.ts @@ -371,6 +371,9 @@ export interface ProjectSlice { // ── Decken-Editieren ────────────────────────────────────────────────────── /** Verschiebt EINEN Umriss-Vertex (per Index) einer Decke. */ moveCeilingGrip: (ceilingId: string, index: number, pt: Vec2) => void; + /** [68] Baugrube: Umriss-Ecke ziehen (Index = Ecke; Index = Eckenzahl: Sohlenhöhe). */ + moveExcavationGrip: (id: string, index: number, pt: Vec2) => void; + moveExcavationEdge: (id: string, aIndex: number, bIndex: number, delta: Vec2) => void; /** Verschiebt eine Decke (ganzer Umriss) um `delta`. */ moveCeilingBy: (ceilingId: string, delta: Vec2) => void; /** Verschiebt eine Umriss-KANTE (beide Vertices) einer Decke um `delta`. */ @@ -1178,6 +1181,11 @@ export function createProjectSlice( moveCeilingGrip: (ceilingId, index, pt) => applyGrip({ op: "ceilingGrip", id: ceilingId, index, pt: gripPt(pt) }, `moveCeilingGrip:${ceilingId}:${index}`), + moveExcavationGrip: (id, index, pt) => applyGrip({ op: "excavationGrip", id, index, pt: gripPt(pt) }, `moveExcavationGrip:${id}:${index}`), + + moveExcavationEdge: (id, aIndex, bIndex, delta) => + applyGrip({ op: "excavationEdge", id, a: aIndex, b: bIndex, delta: gripPt(delta) }, `moveExcavationEdge:${id}:${aIndex}:${bIndex}`), + moveCeilingBy: (ceilingId, delta) => applyGrip({ op: "ceilingBy", id: ceilingId, delta: gripPt(delta) }, `moveCeilingBy:${ceilingId}`), diff --git a/src/state/useDormerNotice.ts b/src/state/useDormerNotice.ts new file mode 100644 index 00000000..0724f8a7 --- /dev/null +++ b/src/state/useDormerNotice.ts @@ -0,0 +1,27 @@ +// Hinweis (Toast), sobald eine Gaube durch Anlegen oder Ändern am First gekappt wird ([G5]). Beim Öffnen +// eines Projekts nur merken, nicht melden (der Befund steht in der Objekt-Info des Dachs). + +import { useEffect, useRef } from "react"; +import type { Project } from "../model/types"; +import { affectedKeys, dormerStatus, newlyAffected } from "../analysis/dormerStatus"; +import type { DormerStatus } from "../analysis/dormerStatus"; +import { t } from "../i18n"; + +export function useDormerNotice(project: Project, notify: (msg: string, kind?: "info" | "warning" | "error") => void) { + const seen = useRef<{ id: string; keys: Set } | null>(null); + useEffect(() => { + let status: DormerStatus[]; + try { + status = dormerStatus(project); + } catch { + return; + } + const prev = seen.current; + seen.current = { id: project.id, keys: affectedKeys(status) }; + if (!prev || prev.id !== project.id) return; + for (const s of newlyAffected(prev.keys, status)) { + notify(s.invalid ? t("dormer.invalid.toast") : t("dormer.clamped.toast", { height: s.effectiveHeight.toFixed(2) }), "warning"); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [project.roofs, project.id, notify]); +} diff --git a/src/state/useGripEditing.ts b/src/state/useGripEditing.ts index d5584441..4ff4e885 100644 --- a/src/state/useGripEditing.ts +++ b/src/state/useGripEditing.ts @@ -7,7 +7,7 @@ import { useRef, useState, type RefObject } from "react"; import { add, dot, leftNormal, normalize, scale, sub, wallCorners } from "../model/geometry"; -import type { Ceiling, Drawing2D, EdgeGrip, Project, Room, Stair, Vec2 } from "../model/types"; +import type { Ceiling, Drawing2D, EdgeGrip, Excavation, Project, Room, Stair, Vec2 } from "../model/types"; import { wallTypeThickness } from "../model/types"; import { bulgeArcPoints, drawingVertices, surfaceOpeningGripPatch, surfaceOpeningGrips, surfaceOpeningInfo, wallArcBand } from "../core"; import { gripDrawingIdsFor } from "./gripLimits"; @@ -35,10 +35,20 @@ function arcApex(a: Vec2, b: Vec2, bulge: number): Vec2 { return add(scale(add(a, b), 0.5), scale(normalize(leftNormal(sub(b, a))), h * bulge)); } +/** Griff-Punkte einer Baugrube: Umriss-Ecken, dann der Sohlen-Griff (Schwerpunkt, y + Sohlenhöhe; Kern `grips.rs`). */ +export function excavationGripPoints(e: Excavation): Vec2[] { + const n = Math.max(1, e.outline.length); + const cx = e.outline.reduce((a, q) => a + q.x, 0) / n; + const cy = e.outline.reduce((a, q) => a + q.y, 0) / n; + return [...e.outline, { x: cx, y: cy + e.bottom }]; +} + export function useGripEditing(opts: { project: Project; selectedDrawing: Drawing2D | null; selectedCeiling: Ceiling | null; + /** [68] Einzeln gewählte Baugrube (Umriss-Ecken, Kanten, Sohlenhöhe als Griffe). */ + selectedExcavation?: Excavation | null; selectedRoom: Room | null; selectedOpeningId: string | null; selectedStairId: string | null; @@ -79,6 +89,8 @@ export function useGripEditing(opts: { moveStairBy: (id: string, delta: Vec2) => void; moveRoomGrip: (id: string, index: number, pt: Vec2) => void; moveCeilingGrip: (id: string, index: number, pt: Vec2) => void; + moveExcavationGrip: (id: string, index: number, pt: Vec2) => void; + moveExcavationEdge: (id: string, aIndex: number, bIndex: number, delta: Vec2) => void; moveGripOf: ( drawingId: string | null, wallId: string | null, @@ -108,6 +120,7 @@ export function useGripEditing(opts: { project, selectedDrawing, selectedCeiling, + selectedExcavation = null, selectedRoom, selectedOpeningId, selectedStairId, @@ -132,6 +145,8 @@ export function useGripEditing(opts: { moveStairBy, moveRoomGrip, moveCeilingGrip, + moveExcavationGrip, + moveExcavationEdge, moveGripOf, moveRoomEdge, moveCeilingEdge, @@ -275,6 +290,12 @@ export function useGripEditing(opts: { gripOwnerRange.push([0, 0]); return [stairMoveHandle(st)]; } + // [68] Baugrube: Umriss-Ecken + Sohlen-Griff (Lage: Schwerpunkt, y um die Sohlenhöhe versetzt). + if (modelEditable && selectedExcavation && !selectedCeiling && effectiveDrawingIds.length === 0 && selectedWallIds.length === 0) { + const pts = excavationGripPoints(selectedExcavation); + pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); }); + return pts; + } // Decke: die Umriss-Vertices als Griffe (nur bei genau einer gewählten Decke, // solange kein 2D-Element/Wand mitgewählt ist — kein Multi-Select für Decken). if (modelEditable && selectedCeiling && effectiveDrawingIds.length === 0 && selectedWallIds.length === 0) { @@ -386,6 +407,9 @@ export function useGripEditing(opts: { // Verschieben EINER Kante einer komplexen Polylinie, §Task B). const edgeGrips: EdgeGrip[] = (() => { // ringEdges/openEdges/polylineEdgeGrips: Kern (`geometry/grips.ts`, `grips.rs`). + if (modelEditable && selectedExcavation && !selectedCeiling && effectiveDrawingIds.length === 0 && selectedWallIds.length === 0) { + return ringEdges(selectedExcavation.outline, {}); + } // Decke: geschlossener Ring aus dem Umriss (Auswahl exklusiv, wie bei grips). if (modelEditable && selectedCeiling && effectiveDrawingIds.length === 0 && selectedWallIds.length === 0) { return ringEdges(selectedCeiling.outline, {}); @@ -525,7 +549,7 @@ export function useGripEditing(opts: { // Dasselbe für das Verschieben eines ganzen 2D-Elements (Gesamt-Delta) und für // Kanten-Griffe von Polylinien (Ziel-Delta): bis zum Loslassen nur Vorschau. const pendingWallGripRef = useRef<{ wallId: string; localIndex: number; flat: number; pt: Vec2 } | null>(null); - const pendingAreaGripRef = useRef<{ kind: "room" | "ceiling"; id: string; index: number; flat: number; pt: Vec2 } | null>(null); + const pendingAreaGripRef = useRef<{ kind: "room" | "ceiling" | "excavation"; id: string; index: number; flat: number; pt: Vec2 } | null>(null); const pendingAreaMoveRef = useRef<{ kind: "ceiling" | "room" | "stair"; id: string; total: Vec2 } | null>(null); const pendingWallMoveRef = useRef<{ wallId: string; total: Vec2 } | null>(null); /** Aufgeschobene Öffnungs-Verschiebung im Schnitt/in der Ansicht (neue `position`). */ @@ -634,7 +658,9 @@ export function useGripEditing(opts: { if (!owner?.drawingId && !owner?.wallId) { // Raum/Decke (exklusiv) — kein Owner, `localIndex` fehlt dann auch, also // ist der flache `index` selbst der Ring-Index. - const pts = selectedCeiling + const pts = selectedExcavation && !selectedCeiling + ? selectedExcavation.outline + : selectedCeiling ? selectedCeiling.outline : selectedRoom ? selectedRoom.boundary @@ -907,6 +933,12 @@ export function useGripEditing(opts: { if (st) moveStairBy(st.id, sub(pt, stairMoveHandle(st))); return; } + // [68] Baugrube: Sohlen-Griff sofort (Höhe), Ecken als Vorschau bis zum Setzen. + if (selectedExcavation && !selectedCeilingId && !selectedRoomId) { + if (index >= selectedExcavation.outline.length) moveExcavationGrip(selectedExcavation.id, index, pt); + else pendingAreaGripRef.current = { kind: "excavation", id: selectedExcavation.id, index, flat: index, pt }; + return; + } // Raum/Decke: Eckpunkt-Zug nur als Vorschau, Projekt erst beim Setzen. if (selectedRoomId || selectedCeilingId) { pendingAreaGripRef.current = selectedRoomId @@ -950,6 +982,8 @@ export function useGripEditing(opts: { const ring = pa.kind === "room" ? (project.rooms ?? []).find((r) => r.id === pa.id)?.boundary + : pa.kind === "excavation" + ? selectedExcavation?.outline : (project.ceilings ?? []).find((c) => c.id === pa.id)?.outline; if (!ring) return []; return [{ kind: "poly", pts: ring.map((q, i) => (i === pa.index ? pa.pt : q)), closed: true }]; @@ -994,6 +1028,7 @@ export function useGripEditing(opts: { pendingAreaGripRef.current = null; if (pa) { if (pa.kind === "room") moveRoomGrip(pa.id, pa.index, pa.pt); + else if (pa.kind === "excavation") moveExcavationGrip(pa.id, pa.index, pa.pt); else moveCeilingGrip(pa.id, pa.index, pa.pt); } const pw = pendingWallGripRef.current; @@ -1073,7 +1108,8 @@ export function useGripEditing(opts: { applyEdge(pend.edge, pend.delta); }; const applyEdge = (edge: EdgeGrip, delta: Vec2) => { - if (selectedRoomId) moveRoomEdge(selectedRoomId, edge.aIndex, edge.bIndex, delta); + if (selectedExcavation && !selectedRoomId && !selectedCeilingId) moveExcavationEdge(selectedExcavation.id, edge.aIndex, edge.bIndex, delta); + else if (selectedRoomId) moveRoomEdge(selectedRoomId, edge.aIndex, edge.bIndex, delta); else if (selectedCeilingId) moveCeilingEdge(selectedCeilingId, edge.aIndex, edge.bIndex, delta); else moveEdgeOf(edge.owner?.drawingId ?? selectedDrawingId, edge.owner?.wallId ?? selectedWallId, edge.aIndex, edge.bIndex, delta); }; diff --git a/src/state/useProjectActions.ts b/src/state/useProjectActions.ts index 1438a619..c257024a 100644 --- a/src/state/useProjectActions.ts +++ b/src/state/useProjectActions.ts @@ -372,6 +372,8 @@ export function useProjectActions( const setWallThickness = useStore((s) => s.setWallThickness); const updateOpening = useStore((s) => s.updateOpening); const moveCeilingGrip = useStore((s) => s.moveCeilingGrip); + const moveExcavationGrip = useStore((s) => s.moveExcavationGrip); + const moveExcavationEdge = useStore((s) => s.moveExcavationEdge); const moveCeilingBy = useStore((s) => s.moveCeilingBy); const moveCeilingEdge = useStore((s) => s.moveCeilingEdge); const updateCeiling = useStore((s) => s.updateCeiling); @@ -487,6 +489,8 @@ export function useProjectActions( setWallThickness, updateOpening, moveCeilingGrip, + moveExcavationGrip, + moveExcavationEdge, moveCeilingBy, moveCeilingEdge, updateCeiling, diff --git a/src/ui/ContextImportDialog.tsx b/src/ui/ContextImportDialog.tsx index 1d29d21e..55feefa6 100644 --- a/src/ui/ContextImportDialog.tsx +++ b/src/ui/ContextImportDialog.tsx @@ -22,7 +22,7 @@ import { fetchOsm } from "../io/osm"; import type { OsmSelection } from "../io/osm"; import { featuresToContextObjects } from "../io/geoContext"; import type { GeoFeature } from "../io/geoContext"; -import { terrainMeshFromGrid } from "../model/terrain"; +import { smoothTerrainGrid, terrainMeshFromGrid } from "../model/terrain"; import { makeOrigin } from "../io/lv95"; import type { GeoOrigin, LV95 } from "../io/lv95"; import type { ContextObject, TerrainMesh } from "../model/types"; @@ -125,6 +125,8 @@ export function ContextImportDialog({ const [sources, setSources] = useState(DEFAULT_SOURCES); // 2 m = Default (schneller/kleinere Kacheln); 0.5 m für Detailarbeit. const [terrainResolution, setTerrainResolution] = useState("2"); + // [T6] Glättung des swissALTI3D-Rasters vor dem Vernetzen: Durchgänge des Binomialfilters (0 = aus). + const [terrainSmooth, setTerrainSmooth] = useState(0); const [searching, setSearching] = useState(false); const [importing, setImporting] = useState(false); @@ -277,7 +279,7 @@ export function ContextImportDialog({ // Gelände-Höhenraster (echtes swissALTI3D-XYZ, native Auflösung) → Terrain-Mesh. let terrain: TerrainMesh | null = null; if (terrainResult?.grid) { - const mesh = terrainMeshFromGrid(terrainResult.grid); + const mesh = terrainMeshFromGrid(smoothTerrainGrid(terrainResult.grid, terrainSmooth)); if (mesh.positions.length >= 9) terrain = mesh; } @@ -553,6 +555,18 @@ export function ContextImportDialog({ +