diff --git a/TODO.md b/TODO.md index 2dd96f74..4c956f28 100644 --- a/TODO.md +++ b/TODO.md @@ -104,7 +104,8 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern Offen: `drawing2d.ts` (950 Zeilen) ist nach diesen Schritten Stil-Auflösung und Verteiler über Formen (Bemassung, Kote, Detailverweis, Massstabsbalken, Block über `scaleGeom`); der Rechenanteil liegt in Rust. Der Verteiler zieht mit dem Modell nach Rust [K4] — vorher würde ein Rust-`Drawing2D` doppelt gepflegt. Danach: [K3c] Schnitt/Ansicht, [K3d] Aufräumen. - - ○ **[K3c] Schnitt und Ansicht** (`toSection`, `toElevation`, `meshSection`) im selben Puffer-Format. + - ◐ **[K3c] Schnitt und Ansicht** (`toSection`, `toElevation`, `meshSection`) im selben Puffer-Format. + ✅ Schnitt-Bänder: Dominanz-Subtraktion, Verschmelzung, Rechteck-Vereinigung (`plan_section.rs`, 28.10.). - ○ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. Nachteile (bewusst): Übergang mit doppelter Datenhaltung, Format muss TS/Rust gleich bleiben (Versionsnummer + Hin-und-zurück-Tests), Text-Layout bleibt bis [K4] in TS. diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 7e29298f..0bd4953f 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -38,6 +38,7 @@ pub mod plan_walls; pub mod opening_geom; pub mod plan_openings; pub mod plan_misc; +pub mod plan_section; pub mod curves; #[cfg(feature = "web")] diff --git a/src-tauri/core/src/plan_section.rs b/src-tauri/core/src/plan_section.rs new file mode 100644 index 00000000..76f8bf2d --- /dev/null +++ b/src-tauri/core/src/plan_section.rs @@ -0,0 +1,365 @@ +//! Schnitt-Bänder ([K3c]): Dominanz-Subtraktion und Verschmelzung achsparalleler Schnitt-Rechtecke +//! (`toSection.ts`: `subtractDominantBands`, `mergeSameComponentBands`) sowie die Vereinigung zu +//! Aussenringen (`unionRectOutlines`). Stil, Füllung, Schraffur und Herkunft hängen in TS an den +//! Bändern; Rust rechnet nur auf Rechtecken. Rechenreihenfolge wie in TS. +//! +//! ## Dominanz +//! `dominant_bands(in)` mit `in = [n, Band × n]`, Band = `[gueltig, uMin, uMax, vMin, vMax, prio, comp]` +//! (`gueltig` 0 = weniger als 3 Ecken; `prio` NaN = keine; `comp` < 0 = keine Komponente) → +//! `[m, Eintrag × m]`, Eintrag = `[quelle, istRechteck, uMin, uMax, vMin, vMax]`. `istRechteck` 0 = +//! Quellband unverändert übernehmen, sonst neues Rechteck mit Stil von `quelle`. +//! +//! ## Umrisse +//! `union_outlines(in)` mit `in = [n, (uMin, uMax, vMin, vMax) × n]` → `[r, (k, x, y × k) × r]`. + +use crate::jsnum::{max, min}; +use std::collections::HashMap; + +const RECT_EPS: f64 = 1e-6; + +#[derive(Clone, Copy)] +struct Rect { + u_min: f64, + u_max: f64, + v_min: f64, + v_max: f64, +} + +#[derive(Clone, Copy)] +struct Band { + rect: Option, + prio: Option, + comp: Option, +} + +struct Out { + src: usize, + rect: Option, +} + +fn subtract_rect(base: Rect, cutter: Rect) -> Vec { + let o_min_u = max(base.u_min, cutter.u_min); + let o_max_u = min(base.u_max, cutter.u_max); + let o_min_v = max(base.v_min, cutter.v_min); + let o_max_v = min(base.v_max, cutter.v_max); + if o_max_u - o_min_u <= RECT_EPS || o_max_v - o_min_v <= RECT_EPS { + return vec![base]; + } + let mut out = Vec::new(); + let mut push = |r: Rect| { + if r.u_max - r.u_min > RECT_EPS && r.v_max - r.v_min > RECT_EPS { + out.push(r); + } + }; + push(Rect { u_min: base.u_min, u_max: o_min_u, v_min: base.v_min, v_max: base.v_max }); + push(Rect { u_min: o_max_u, u_max: base.u_max, v_min: base.v_min, v_max: base.v_max }); + push(Rect { u_min: o_min_u, u_max: o_max_u, v_min: base.v_min, v_max: o_min_v }); + push(Rect { u_min: o_min_u, u_max: o_max_u, v_min: o_max_v, v_max: base.v_max }); + out +} + +fn rect_union_if_rect(a: Rect, b: Rect) -> Option { + let e = RECT_EPS; + let a_in_b = b.u_min - a.u_min <= e && a.u_max - b.u_max <= e && b.v_min - a.v_min <= e && a.v_max - b.v_max <= e; + if a_in_b { + return Some(b); + } + let b_in_a = a.u_min - b.u_min <= e && b.u_max - a.u_max <= e && a.v_min - b.v_min <= e && b.v_max - a.v_max <= e; + if b_in_a { + return Some(a); + } + let u_aligned = (a.u_min - b.u_min).abs() <= e && (a.u_max - b.u_max).abs() <= e; + let v_aligned = (a.v_min - b.v_min).abs() <= e && (a.v_max - b.v_max).abs() <= e; + let v_touch = a.v_max >= b.v_min - e && b.v_max >= a.v_min - e; + let u_touch = a.u_max >= b.u_min - e && b.u_max >= a.u_min - e; + if (u_aligned && v_touch) || (v_aligned && u_touch) { + return Some(Rect { + u_min: min(a.u_min, b.u_min), + u_max: max(a.u_max, b.u_max), + v_min: min(a.v_min, b.v_min), + v_max: max(a.v_max, b.v_max), + }); + } + None +} + +fn merge_same_component(bands: &[Band], list: Vec) -> Vec { + let mut out = list; + let mut merged = true; + while merged { + merged = false; + let mut i = 0; + while i < out.len() && !merged { + let bi = bands[out[i].src]; + // Verschmolzene Rechtecke erben Komponente/Priorität des Quellbands. + if bi.comp.is_none() || bi.prio.is_none() { + i += 1; + continue; + } + let ri = match out[i].rect.or(bi.rect) { + Some(r) => r, + None => { + i += 1; + continue; + } + }; + for j in i + 1..out.len() { + let bj = bands[out[j].src]; + if bj.comp != bi.comp || bj.prio != bi.prio { + continue; + } + let rj = match out[j].rect.or(bj.rect) { + Some(r) => r, + None => continue, + }; + if let Some(u) = rect_union_if_rect(ri, rj) { + out[i].rect = Some(u); + out.remove(j); + merged = true; + break; + } + } + i += 1; + } + } + out +} + +pub fn dominant_bands(inp: &[f64]) -> Vec { + if inp.is_empty() || !inp[0].is_finite() || inp[0] < 0.0 { + return Vec::new(); + } + let n = inp[0] as usize; + if inp.len() != 1 + 7 * n { + return Vec::new(); + } + let bands: Vec = (0..n) + .map(|k| { + let b = &inp[1 + 7 * k..8 + 7 * k]; + Band { + rect: (b[0] != 0.0).then_some(Rect { u_min: b[1], u_max: b[2], v_min: b[3], v_max: b[4] }), + prio: (!b[5].is_nan()).then_some(b[5]), + comp: (b[6] >= 0.0).then_some(b[6] as i64), + } + }) + .collect(); + let mut out: Vec = Vec::new(); + for i in 0..n { + let (base, prio) = match (bands[i].rect, bands[i].prio) { + (Some(r), Some(p)) => (r, p), + _ => { + out.push(Out { src: i, rect: None }); + continue; + } + }; + let mut pieces = vec![base]; + for j in 0..n { + if pieces.is_empty() { + break; + } + if j == i { + continue; + } + let (cutter, other) = match (bands[j].rect, bands[j].prio) { + (Some(c), Some(p)) => (c, p), + _ => continue, + }; + if other <= prio { + continue; + } + let mut next = Vec::new(); + for p in pieces { + next.extend(subtract_rect(p, cutter)); + } + pieces = next; + } + for p in pieces { + out.push(Out { src: i, rect: Some(p) }); + } + } + let out = merge_same_component(&bands, out); + let mut f = Vec::with_capacity(1 + 6 * out.len()); + f.push(out.len() as f64); + for o in &out { + match o.rect { + Some(r) => f.extend([o.src as f64, 1.0, r.u_min, r.u_max, r.v_min, r.v_max]), + None => f.extend([o.src as f64, 0.0, 0.0, 0.0, 0.0, 0.0]), + } + } + f +} + +fn signed_area(ring: &[(f64, f64)]) -> f64 { + let mut a = 0.0; + for i in 0..ring.len() { + let (x0, y0) = ring[i]; + let (x1, y1) = ring[(i + 1) % ring.len()]; + a += x0 * y1 - x1 * y0; + } + a / 2.0 +} + +fn sorted_unique(mut v: Vec) -> Vec { + v.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + v.dedup_by(|a, b| *a == *b); + v +} + +pub fn union_outlines(inp: &[f64]) -> Vec { + if inp.is_empty() || !inp[0].is_finite() || inp[0] < 0.0 { + return Vec::new(); + } + let n = inp[0] as usize; + if inp.len() != 1 + 4 * n || inp.iter().any(|v| !v.is_finite()) { + return Vec::new(); + } + let rects: Vec = (0..n) + .map(|k| Rect { u_min: inp[1 + 4 * k], u_max: inp[2 + 4 * k], v_min: inp[3 + 4 * k], v_max: inp[4 + 4 * k] }) + .collect(); + let xs = sorted_unique(rects.iter().flat_map(|r| [r.u_min, r.u_max]).collect()); + let ys = sorted_unique(rects.iter().flat_map(|r| [r.v_min, r.v_max]).collect()); + if xs.len() < 2 || ys.len() < 2 { + return vec![0.0]; + } + let nx = xs.len() - 1; + let ny = ys.len() - 1; + let mut cell = vec![vec![false; ny]; nx]; + for i in 0..nx { + for j in 0..ny { + let cx = (xs[i] + xs[i + 1]) / 2.0; + let cy = (ys[j] + ys[j + 1]) / 2.0; + cell[i][j] = rects.iter().any(|r| cx > r.u_min && cx < r.u_max && cy > r.v_min && cy < r.v_max); + } + } + let at = |i: isize, j: isize| i >= 0 && j >= 0 && (i as usize) < nx && (j as usize) < ny && cell[i as usize][j as usize]; + // Gerichtete Randkanten in Einfügereihenfolge (wie `Map`: erneutes `set` behält die Position). + let mut keys: Vec<(usize, usize)> = Vec::new(); + let mut next: HashMap<(usize, usize), (usize, usize)> = HashMap::new(); + let mut set = |k: (usize, usize), v: (usize, usize)| { + if next.insert(k, v).is_none() { + keys.push(k); + } + }; + for i in 0..nx { + for j in 0..ny { + if !cell[i][j] { + continue; + } + let (ii, jj) = (i as isize, j as isize); + if !at(ii, jj - 1) { + set((i, j), (i + 1, j)); + } + if !at(ii + 1, jj) { + set((i + 1, j), (i + 1, j + 1)); + } + if !at(ii, jj + 1) { + set((i + 1, j + 1), (i, j + 1)); + } + if !at(ii - 1, jj) { + set((i, j + 1), (i, j)); + } + } + } + let mut rings: Vec> = Vec::new(); + let mut used: std::collections::HashSet<(usize, usize)> = std::collections::HashSet::new(); + for &start in &keys { + if used.contains(&start) { + continue; + } + let mut ring: Vec<(f64, f64)> = Vec::new(); + let mut k = start; + while !used.contains(&k) { + used.insert(k); + ring.push((xs[k.0], ys[k.1])); + match next.get(&k) { + Some(&nk) => k = nk, + None => break, + } + } + let len = ring.len(); + let simple: Vec<(f64, f64)> = ring + .iter() + .enumerate() + .filter(|(idx, p)| { + let a = ring[(idx + len - 1) % len]; + let b = ring[(idx + 1) % len]; + !((a.0 == p.0 && p.0 == b.0) || (a.1 == p.1 && p.1 == b.1)) + }) + .map(|(_, p)| *p) + .collect(); + if simple.len() >= 4 && signed_area(&simple) > 0.0 { + rings.push(simple); + } + } + let mut f = vec![rings.len() as f64]; + for r in &rings { + f.push(r.len() as f64); + for p in r { + f.push(p.0); + f.push(p.1); + } + } + f +} + +#[cfg(test)] +mod tests { + use super::*; + + fn band(u0: f64, u1: f64, v0: f64, v1: f64, prio: f64, comp: f64) -> [f64; 7] { + [1.0, u0, u1, v0, v1, prio, comp] + } + + #[test] + fn hoehere_prioritaet_schneidet_weg() { + let mut inp = vec![2.0]; + inp.extend(band(0.0, 1.0, 0.0, 1.0, 10.0, 0.0)); + inp.extend(band(0.0, 1.0, 0.5, 1.0, 100.0, 1.0)); + let f = dominant_bands(&inp); + // Basis behält die untere Hälfte, Cutter bleibt ganz. + assert_eq!(f[0], 2.0); + assert_eq!(&f[1..7], &[0.0, 1.0, 0.0, 1.0, 0.0, 0.5]); + } + + fn r(u0: f64, u1: f64, v0: f64, v1: f64) -> Rect { + Rect { u_min: u0, u_max: u1, v_min: v0, v_max: v1 } + } + + #[test] + fn rechteck_subtraktion() { + // Kein Überlapp, nur Berührung, volle Überdeckung, Ecke, Randstreifen. + assert_eq!(subtract_rect(r(0.0, 1.0, 0.0, 1.0), r(2.0, 3.0, 2.0, 3.0)).len(), 1); + assert_eq!(subtract_rect(r(0.0, 1.0, 0.0, 1.0), r(1.0, 2.0, 0.0, 1.0)).len(), 1); + assert!(subtract_rect(r(1.0, 2.0, 1.0, 2.0), r(0.0, 3.0, 0.0, 3.0)).is_empty()); + let ecke = subtract_rect(r(0.0, 2.0, 0.0, 2.0), r(1.0, 3.0, 1.0, 3.0)); + let flaeche: f64 = ecke.iter().map(|x| (x.u_max - x.u_min) * (x.v_max - x.v_min)).sum(); + assert_eq!((ecke.len(), flaeche), (2, 3.0)); + let rand = subtract_rect(r(0.0, 2.0, 0.0, 2.0), r(-1.0, 3.0, 1.0, 3.0)); + assert_eq!(rand.len(), 1); + assert_eq!((rand[0].v_min, rand[0].v_max), (0.0, 1.0)); + } + + #[test] + fn gleiche_komponente_verschmilzt() { + let mut inp = vec![2.0]; + inp.extend(band(0.0, 1.0, 0.0, 1.0, 10.0, 3.0)); + inp.extend(band(1.0, 2.0, 0.0, 1.0, 10.0, 3.0)); + let f = dominant_bands(&inp); + assert_eq!(f[0], 1.0); + assert_eq!(&f[1..7], &[0.0, 1.0, 0.0, 2.0, 0.0, 1.0]); + } + + #[test] + fn l_form_ergibt_einen_ring() { + let f = union_outlines(&[2.0, 0.0, 2.0, 0.0, 1.0, 0.0, 1.0, 0.0, 2.0]); + assert_eq!(f[0], 1.0); + assert_eq!(f[1], 6.0); + } + + #[test] + fn unsinn_ist_leer() { + assert!(dominant_bands(&[f64::NAN]).is_empty()); + assert!(dominant_bands(&[2.0, 1.0]).is_empty()); + assert!(union_outlines(&[1.0, f64::NAN, 1.0, 0.0, 1.0]).is_empty()); + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index a38c29db..9ab6f102 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -29,6 +29,7 @@ mod plan_stairs; mod plan_walls; mod plan_openings; mod plan_misc; +mod plan_section; mod curves; mod hatch; diff --git a/src-tauri/core/src/web/plan_section.rs b/src-tauri/core/src/web/plan_section.rs new file mode 100644 index 00000000..9d696f8f --- /dev/null +++ b/src-tauri/core/src/web/plan_section.rs @@ -0,0 +1,15 @@ +//! Bindungen der Schnitt-Bänder (`crate::plan_section`). Layouts s. dort. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Dominanz-Subtraktion und Verschmelzung der Schnitt-Rechtecke; Unsinn → leer. +#[wasm_bindgen] +pub fn section_dominant_bands_flat(input: &[f64]) -> Vec { + crate::plan_section::dominant_bands(input) +} + +/// Aussenringe der Vereinigung achsparalleler Rechtecke; Unsinn → leer. +#[wasm_bindgen] +pub fn section_union_outlines_flat(input: &[f64]) -> Vec { + crate::plan_section::union_outlines(input) +} diff --git a/src/plan/toSection.boolean.test.ts b/src/plan/toSection.boolean.test.ts index d0da8a55..52005dcc 100644 --- a/src/plan/toSection.boolean.test.ts +++ b/src/plan/toSection.boolean.test.ts @@ -4,16 +4,14 @@ * die schwächere per achsparalleler Rechteck-Subtraktion weg. Gleiche Priorität * koexistiert (kein Schnitt). * - * Getestet ohne WASM: - * 1. `subtractRect` direkt (Ecken-/Kanten-/Enthalten-/Kein-Overlap-Fälle). - * 2. `subtractDominantBands` gegen den Nutzer-Testfall — ELEMENTÜBERGREIFEND: + * Getestet über den Rust-Kern (`plan_section.rs`): + * `subtractDominantBands` gegen den Nutzer-Testfall — ELEMENTÜBERGREIFEND: * ein Decken-Beton-Band (100) schneidet ein überlappendes Wand-Putz-Band * (10) weg; Beton bleibt voll; gleiche Priorität koexistiert. */ import { describe, it, expect } from "vitest"; import { - subtractRect, subtractDominantBands, type Rect, type SectionCutPolygon, @@ -24,14 +22,6 @@ function r(uMin: number, uMax: number, vMin: number, vMax: number): Rect { return { uMin, uMax, vMin, vMax }; } -/** Rechteck einer Rest-Menge normalisieren (auf 1e-9 gerundet, sortiert) für stabile Vergleiche. */ -function norm(rects: Rect[]): Rect[] { - const round = (x: number) => Math.round(x * 1e9) / 1e9; - return rects - .map((x) => ({ uMin: round(x.uMin), uMax: round(x.uMax), vMin: round(x.vMin), vMax: round(x.vMax) })) - .sort((a, b) => a.uMin - b.uMin || a.vMin - b.vMin); -} - /** Ein achsparalleles Cut-Band mit joinPriority. */ function band( uMin: number, @@ -83,50 +73,6 @@ function area(items: Array): number { }, 0); } -describe("subtractRect: achsparallele Rechteck-Subtraktion", () => { - it("kein Overlap → base unverändert", () => { - expect(norm(subtractRect(r(0, 1, 0, 1), r(2, 3, 2, 3)))).toEqual(norm([r(0, 1, 0, 1)])); - }); - - it("nur Kantenberührung (Fläche 0) → base unverändert", () => { - // cutter grenzt bei u=1 an, überlappt aber nicht. - expect(norm(subtractRect(r(0, 1, 0, 1), r(1, 2, 0, 1)))).toEqual(norm([r(0, 1, 0, 1)])); - }); - - it("cutter enthält base vollständig → leere Restmenge", () => { - expect(subtractRect(r(1, 2, 1, 2), r(0, 3, 0, 3))).toEqual([]); - }); - - it("cutter mittig in base → 4 Rest-Rechtecke, Flächenbilanz stimmt", () => { - const rest = subtractRect(r(0, 3, 0, 3), r(1, 2, 1, 2)); - expect(rest).toHaveLength(4); - // 9 (base) − 1 (overlap) = 8. - expect(area(rest)).toBeCloseTo(8, 9); - // Rechtecke sind disjunkt: Summe der Einzelflächen = Gesamtfläche. - const sum = rest.reduce((s, x) => s + (x.uMax - x.uMin) * (x.vMax - x.vMin), 0); - expect(sum).toBeCloseTo(8, 9); - }); - - it("Ecküberlappung → 2 Rest-Rechtecke (L-Form)", () => { - // cutter überdeckt die obere-rechte Ecke von base. - const rest = subtractRect(r(0, 2, 0, 2), r(1, 3, 1, 3)); - // overlap = [1,2]×[1,2] (Fläche 1). Rest = 4 − 1 = 3. - expect(area(rest)).toBeCloseTo(3, 9); - expect(norm(rest)).toEqual( - norm([ - r(0, 1, 0, 2), // links, volle Höhe - r(1, 2, 0, 1), // mittlerer Streifen unten - ]), - ); - }); - - it("Kantenüberlappung (cutter deckt einen Randstreifen) → 1 Rest-Rechteck", () => { - // cutter deckt den oberen Rand v∈[1,2] über die volle Breite. - const rest = subtractRect(r(0, 2, 0, 2), r(-1, 3, 1, 3)); - expect(norm(rest)).toEqual(norm([r(0, 2, 0, 1)])); - }); -}); - describe("subtractDominantBands: stärkere Schicht schneidet schwächere", () => { it("Nutzer-Testfall ELEMENTÜBERGREIFEND: Decken-Beton(100) schneidet Wand-Putz(10) weg", () => { // Wand-Putz-Band (Element B): schwach, joinPriority 10, u∈[0,2], v∈[0,3]. diff --git a/src/plan/toSection.ts b/src/plan/toSection.ts index cbd9daa7..dd551428 100644 --- a/src/plan/toSection.ts +++ b/src/plan/toSection.ts @@ -27,6 +27,7 @@ import { projectToModel3d } from "./toWalls3d"; import { subtractVoidsInSection } from "./voids"; import { appendBodySections, appendTerrainProfiles } from "./sectionExtras"; import { loadEngine3d } from "../engine/engine3d"; +import { core } from "../engine/coreWasm"; import { HATCH_INK, HATCH_PAPER, @@ -582,8 +583,6 @@ function ceilingRepresentativePriority(project: Project, ceiling: Ceiling): numb // ── Schnitt-Boolean-Dominanz (achsparallele Rechteck-Subtraktion) ─────────── // Kleine Toleranz für Überlappungs-/Rest-Rechtecke: Null-/Negativflächen und // Rest-Streifen dünner als EPS werden verworfen (Float-Rauschen der u-/v-Meter). -const RECT_EPS = 1e-6; - /** Achsparalleles Rechteck in (u, v)-Metern. */ export interface Rect { uMin: number; @@ -605,177 +604,52 @@ function rectOfBand(band: SectionCutPolygon): Rect | null { }; } -/** - * Rechteck-minus-Rechteck (beide achsparallel): `base` ohne die Überlappung mit - * `cutter`, zerlegt in 0–4 disjunkte Rest-Rechtecke (links/rechts über die volle - * Höhe, dann oben/unten im mittleren u-Streifen — überlappungsfrei). Kein echter - * Überlapp (Fläche ≤ EPS in u oder v) ⇒ `base` bleibt ganz. Vollständige - * Überdeckung ⇒ leere Liste. Rest-Streifen dünner als EPS werden verworfen. - */ -export function subtractRect(base: Rect, cutter: Rect): Rect[] { - const oMinU = Math.max(base.uMin, cutter.uMin); - const oMaxU = Math.min(base.uMax, cutter.uMax); - const oMinV = Math.max(base.vMin, cutter.vMin); - const oMaxV = Math.min(base.vMax, cutter.vMax); - // Kein (nennenswerter) Überlapp — `base` unverändert. - if (oMaxU - oMinU <= RECT_EPS || oMaxV - oMinV <= RECT_EPS) return [base]; - - const out: Rect[] = []; - const push = (r: Rect) => { - if (r.uMax - r.uMin > RECT_EPS && r.vMax - r.vMin > RECT_EPS) out.push(r); - }; - // Links / rechts der Überlappung, jeweils über die volle Basis-Höhe. - push({ uMin: base.uMin, uMax: oMinU, vMin: base.vMin, vMax: base.vMax }); - push({ uMin: oMaxU, uMax: base.uMax, vMin: base.vMin, vMax: base.vMax }); - // Unten / oben im mittleren u-Streifen (nur der von der Überlappung befreite Rest). - push({ uMin: oMinU, uMax: oMaxU, vMin: base.vMin, vMax: oMinV }); - push({ uMin: oMinU, uMax: oMaxU, vMin: oMaxV, vMax: base.vMax }); - return out; -} - /** * Globale Schnitt-Dominanz: für jedes Band wird die Rechteck-Überlappung ALLER * Bänder mit STRIKT höherer `joinPriority` subtrahiert (elementübergreifend — * z. B. schneidet ein Decken-Beton-Band 100 ein überlappendes Wand-Putz-Band 10 - * weg). Gleiche Priorität schneidet NICHT (koexistiert → durchgehende Fläche). - * Bänder ohne `joinPriority` (unauflösbares Bauteil) nehmen weder als Basis noch - * als Cutter teil und bleiben unverändert erhalten. - * - * Kanten: jedes emittierte Rest-Rechteck erhält in `generateSectionPlan` seine - * eigene Schnitt-Umrisslinie (unverändert). An der Schnittkante fällt die - * Rest-Rechteck-Kante mit der Kante des stärkeren Bands zusammen — das ist die - * gewünschte Material-/Fugenlinie zwischen den Schichten; im Inneren einer - * Schicht entstehen durch die überlappungsfreie Zerlegung keine falschen Kanten. + * weg). Gleiche Priorität schneidet NICHT. Bänder ohne `joinPriority` nehmen + * weder als Basis noch als Cutter teil. Danach verschmelzen angrenzende Bänder + * gleicher `componentId` + Priorität zu einem Körper (keine innere Trennlinie). + * Die Rechenarbeit liegt im Rust-Kern (`plan_section.rs`, [K3c]); hier nur + * Ein-/Ausgabe der Bänder samt Stil. */ export function subtractDominantBands(bands: SectionCutPolygon[]): SectionCutPolygon[] { - const rects = bands.map(rectOfBand); + const ids = new Map(); + const b: number[] = [bands.length]; + for (const band of bands) { + const r = rectOfBand(band); + let comp = -1; + if (band.componentId !== undefined) { + comp = ids.get(band.componentId) ?? ids.size; + ids.set(band.componentId, comp); + } + b.push(r ? 1 : 0, r?.uMin ?? 0, r?.uMax ?? 0, r?.vMin ?? 0, r?.vMax ?? 0, + band.joinPriority ?? Number.NaN, comp); + } + const f = core().section_dominant_bands_flat(Float64Array.from(b)); const out: SectionCutPolygon[] = []; - for (let i = 0; i < bands.length; i++) { - const band = bands[i]; - const base = rects[i]; - const prio = band.joinPriority; - // Nicht-rechteckig oder ohne Priorität: unverändert durchreichen. - if (base === null || prio === undefined) { - out.push(band); - continue; - } - let pieces: Rect[] = [base]; - for (let j = 0; j < bands.length && pieces.length > 0; j++) { - if (j === i) continue; - const otherPrio = bands[j].joinPriority; - const cutter = rects[j]; - if (cutter === null || otherPrio === undefined || otherPrio <= prio) continue; - const next: Rect[] = []; - for (const p of pieces) next.push(...subtractRect(p, cutter)); - pieces = next; - } - for (const p of pieces) out.push(bandFromRect(band, p)); - } - // MERGE-Regel: nach der Dominanz-Subtraktion angrenzende/überlappende Bänder - // gleicher Komponente + Priorität zu einem Körper verschmelzen (keine innere - // Trennlinie durch gleichartiges Material). Die Subtraktion oben bleibt davon - // unberührt (bit-identisch) — hier werden nur gleichartige Reste vereinigt. - return mergeSameComponentBands(out); -} - -/** - * Union zweier achsparalleler Rechtecke, ABER NUR wenn das Ergebnis EXAKT wieder - * ein Rechteck ist — sonst `null`. Zwei Fälle liefern eine rechteckige Union - * (jeweils mit `RECT_EPS`-Toleranz): - * • Enthaltensein: eines liegt vollständig im anderen ⇒ das umschließende. - * • Achs-Deckung + Berührung: in einer Achse deckungsgleich (gleiche min/max) - * UND in der anderen berührend/überlappend (kein Spalt) ⇒ Bounding-Box. - * Teil-/Eck-Überlappungen (Union wäre L-förmig) und Bänder mit Spalt liefern - * `null` — sie dürfen NICHT verschmolzen werden (die Bounding-Box deckte sonst - * leere Fläche ab). Genau die im Schnitt vorkommenden bündigen Rechtecke. - */ -function rectUnionIfRect(a: Rect, b: Rect): Rect | null { - const E = RECT_EPS; - // Enthaltensein (inkl. Deckungsgleichheit): Union = umschließendes Rechteck. - const aInB = - b.uMin - a.uMin <= E && a.uMax - b.uMax <= E && b.vMin - a.vMin <= E && a.vMax - b.vMax <= E; - if (aInB) return { uMin: b.uMin, uMax: b.uMax, vMin: b.vMin, vMax: b.vMax }; - const bInA = - a.uMin - b.uMin <= E && b.uMax - a.uMax <= E && a.vMin - b.vMin <= E && b.vMax - a.vMax <= E; - if (bInA) return { uMin: a.uMin, uMax: a.uMax, vMin: a.vMin, vMax: a.vMax }; - - const uAligned = Math.abs(a.uMin - b.uMin) <= E && Math.abs(a.uMax - b.uMax) <= E; - const vAligned = Math.abs(a.vMin - b.vMin) <= E && Math.abs(a.vMax - b.vMax) <= E; - // Berührung/Überlappung in der jeweils ANDEREN Achse (kein Spalt größer EPS). - const vTouch = a.vMax >= b.vMin - E && b.vMax >= a.vMin - E; - const uTouch = a.uMax >= b.uMin - E && b.uMax >= a.uMin - E; - if ((uAligned && vTouch) || (vAligned && uTouch)) { - return { - uMin: Math.min(a.uMin, b.uMin), - uMax: Math.max(a.uMax, b.uMax), - vMin: Math.min(a.vMin, b.vMin), - vMax: Math.max(a.vMax, b.vMax), - }; - } - return null; -} - -/** - * MERGE-Phase der Schnitt-Dominanz (vgl. `resolveJoinPriority` "merge", - * src/model/joins.ts): Bänder mit GLEICHER `componentId` UND gleicher - * `joinPriority`, deren achsparallele Rechtecke sich berühren/überlappen und - * eine rechteckige Union bilden (`rectUnionIfRect`), werden zu EINEM Band - * zusammengefasst — so entsteht an der Berührkante keine innere Trennlinie durch - * gleichartiges Material (z. B. zwei Backstein-Kerne, Beton-Decke an Beton-Wand). - * - * Bänder VERSCHIEDENER Komponenten (auch bei gleicher Priorität) bleiben - * getrennt (coexist). Bänder ohne `componentId`/`joinPriority` oder ohne - * Rechteck-Form nehmen nicht teil und werden unverändert durchgereicht — daher - * ist die Phase für die bestehenden Dominanz-Tests (keine `componentId`) ein - * No-op. Iterativ bis zum Fixpunkt (Ketten aus ≥3 Rechtecken verschmelzen - * schrittweise); die Reihenfolge bleibt erhalten (das verschmolzene Rechteck - * ersetzt das erste Band an seiner Position). - */ -function mergeSameComponentBands(bands: SectionCutPolygon[]): SectionCutPolygon[] { - const out = bands.slice(); - for (let merged = true; merged; ) { - merged = false; - for (let i = 0; i < out.length && !merged; i++) { - const bi = out[i]; - if (bi.componentId === undefined || bi.joinPriority === undefined) continue; - const ri = rectOfBand(bi); - if (!ri) continue; - for (let j = i + 1; j < out.length; j++) { - const bj = out[j]; - if (bj.componentId !== bi.componentId || bj.joinPriority !== bi.joinPriority) continue; - const rj = rectOfBand(bj); - if (!rj) continue; - const u = rectUnionIfRect(ri, rj); - if (!u) continue; - out[i] = bandFromRect(bi, u); - out.splice(j, 1); - merged = true; // Fixpunkt-Neustart: neu entstandene Nachbarschaften erfassen - break; - } - } + for (let k = 0, i = 1; k < f[0]; k++, i += 6) { + const src = bands[f[i]]; + out.push(f[i + 1] === 0 ? src : { + component: src.component, + color: src.color, + pts: [ + [f[i + 2], f[i + 5]], + [f[i + 3], f[i + 5]], + [f[i + 3], f[i + 4]], + [f[i + 2], f[i + 4]], + ], + fill: src.fill, + hatch: src.hatch, + joinPriority: src.joinPriority, + componentId: src.componentId, + sourceId: src.sourceId, + }); } return out; } -/** Erzeugt aus einem Rest-`Rect` ein Cut-Band, das Stil/Referenz von `src` erbt. */ -function bandFromRect(src: SectionCutPolygon, r: Rect): SectionCutPolygon { - return { - component: src.component, - color: src.color, - pts: [ - [r.uMin, r.vMax], - [r.uMax, r.vMax], - [r.uMax, r.vMin], - [r.uMin, r.vMin], - ], - fill: src.fill, - hatch: src.hatch, - joinPriority: src.joinPriority, - componentId: src.componentId, - sourceId: src.sourceId, - }; -} - /** * Zerlegt das EINE geschnittene Deckenrechteck (`cp`, vier Ecken in u/v-Metern) * in liegende Teil-Rechtecke je Schicht des Deckentyps `wt` — das Schnitt- @@ -1384,69 +1258,19 @@ export function mergeMonolithCuts( /** * Äussere Umrisse der Vereinigung achsparalleler Rechtecke (Raster über alle * Kanten-Koordinaten, Randkanten verketten). Liefert je zusammenhängender - * Fläche den Aussenring (CCW); Innenringe (Löcher) entfallen. + * Fläche den Aussenring (CCW); Innenringe (Löcher) entfallen. Rechnet der Kern. */ export function unionRectOutlines(rects: Rect[]): Array> { - const xs = [...new Set(rects.flatMap((r) => [r.uMin, r.uMax]))].sort((a, b) => a - b); - const ys = [...new Set(rects.flatMap((r) => [r.vMin, r.vMax]))].sort((a, b) => a - b); - const nx = xs.length - 1; - const ny = ys.length - 1; - if (nx < 1 || ny < 1) return []; - const filled = (i: number, j: number): boolean => { - if (i < 0 || j < 0 || i >= nx || j >= ny) return false; - const cx = (xs[i] + xs[i + 1]) / 2; - const cy = (ys[j] + ys[j + 1]) / 2; - return rects.some((r) => cx > r.uMin && cx < r.uMax && cy > r.vMin && cy < r.vMax); - }; - const cell: boolean[][] = []; - for (let i = 0; i < nx; i++) { - cell.push([]); - for (let j = 0; j < ny; j++) cell[i].push(filled(i, j)); - } - const at = (i: number, j: number) => i >= 0 && j >= 0 && i < nx && j < ny && cell[i][j]; - // Gerichtete Randkanten (Fläche links → CCW), als Gitterpunkt-Paare. - const next = new Map(); - const key = (i: number, j: number) => `${i},${j}`; - for (let i = 0; i < nx; i++) { - for (let j = 0; j < ny; j++) { - if (!cell[i][j]) continue; - if (!at(i, j - 1)) next.set(key(i, j), [i + 1, j]); // unten, nach rechts - if (!at(i + 1, j)) next.set(key(i + 1, j), [i + 1, j + 1]); // rechts, nach oben - if (!at(i, j + 1)) next.set(key(i + 1, j + 1), [i, j + 1]); // oben, nach links - if (!at(i - 1, j)) next.set(key(i, j + 1), [i, j]); // links, nach unten - } - } + const b: number[] = [rects.length]; + for (const r of rects) b.push(r.uMin, r.uMax, r.vMin, r.vMax); + const f = core().section_union_outlines_flat(Float64Array.from(b)); const rings: Array> = []; - const used = new Set(); - for (const start of next.keys()) { - if (used.has(start)) continue; + let i = 1; + for (let k = 0; k < (f[0] ?? 0); k++) { + const count = f[i++]; const ring: Array<[number, number]> = []; - let k = start; - while (!used.has(k)) { - used.add(k); - const [i, j] = k.split(",").map(Number); - ring.push([xs[i], ys[j]]); - const n = next.get(k); - if (!n) break; - k = key(n[0], n[1]); - } - // Kollineare Zwischenpunkte entfernen. - const simple = ring.filter((p, idx) => { - const a = ring[(idx + ring.length - 1) % ring.length]; - const b = ring[(idx + 1) % ring.length]; - return !((a[0] === p[0] && p[0] === b[0]) || (a[1] === p[1] && p[1] === b[1])); - }); - if (simple.length >= 4 && signedArea(simple) > 0) rings.push(simple); + for (let j = 0; j < count; j++, i += 2) ring.push([f[i], f[i + 1]]); + rings.push(ring); } return rings; } - -function signedArea(ring: Array<[number, number]>): number { - let a = 0; - for (let i = 0; i < ring.length; i++) { - const [x0, y0] = ring[i]; - const [x1, y1] = ring[(i + 1) % ring.length]; - a += x0 * y1 - x1 * y0; - } - return a / 2; -}