[K2] Wand-Joins und Wand-Bänder in Rust (joins.rs, wall_bands.rs)

Gehrung/T-Stoss/Kreuzung samt Pro-Schicht-Cuts und Nah-Putz-Aussparungen
(computeJoins) sowie die Schichtbänder der 3D-Wände (Gehrungs-Kürzung je Band,
Decken-Dominanz pro Schicht, Terminierung, Öffnungs-Löcher mit Laibungs-
Rücksprung, schräge Oberkante unter Dächern) rechnet jetzt der Rust-Kern.
model/joins.ts und toWalls3d/bands.ts sammeln nur noch aus dem Project und
übergeben flach; Decken und Dächer gehen einmal je Geschoss an den Kern
(emitWalls statt emitWall je Wand). resolveJoinPriority ist Fassade.

Ergebnis bitgleich zur TS-Fassung (Vergleich computeJoins, projectToWalls3d
beide Pfade und generatePlan über 27 Projekte inkl. Zufallsgrundrissen;
Math.hypot wie V8 nachgebildet). computeJoins 720 Wände 37 -> 3.5 ms,
projectToWalls3d 1296 Wände 225 -> 40 ms.
This commit is contained in:
Claude committed 2026-10-27 21:56:55 +00:00
1 parent d9daed7c47
commit 9c1b0537e5
13 files changed
+2106 -1297

No files matched your search

+6 -2
View File
@@ -29,8 +29,12 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
SIA-416-Zuordnung (`roomArea.ts::balance`) und `checkRoomProgram` bleiben vorerst TS. Offen: `bulge.ts`
(Bogenformeln doppelt), Triangulierung, Straight Skeleton [B2]. · M
- ◐ **[K2] Geometrie-Ableitungen.** (27.10.) Dachgeometrie in Rust (`roof.rs`, `roof_skeleton.rs`;
`roofSkeleton.ts` gelöscht, ~2× schneller, Ergebnis bitgleich). Offen: Wand-Joins/-Bänder (`toWalls3d`),
Treppen, Räume. · L
`roofSkeleton.ts` gelöscht, ~2× schneller, Ergebnis bitgleich). Offen: Treppen, Räume. · L
- ✅ (27.10.) Wand-Joins und -Bänder in Rust (`joins.rs`, `wall_bands.rs`): Gehrung/T-Stoss/Kreuzung,
Pro-Schicht-Cuts, Nah-Putz-Aussparungen, Decken-Dominanz, Öffnungs-Löcher, `topDrop` unter Dächern.
`model/joins.ts` und `toWalls3d/bands.ts` sammeln nur noch aus dem `Project` und übergeben flach
(Decken/Dächer einmal je Geschoss). Ergebnis bitgleich (Vergleich über 27 Projekte inkl.
Zufallsgrundrisse), `computeJoins` ~10×, `projectToWalls3d` (1296 Wände) ~4× schneller.
- ○ **[K3] Plan, Schnitt, Ansicht in Rust**, Primitive direkt an render2d (ohne TS-Umweg). · L
- ○ **[K4] Modell und Ops in Rust** [2]; TS bekommt die Typen generiert (z. B. `ts-rs`). · XL
- **Fertig wenn** (je Etappe): TS-Fassung gelöscht, `npm run check` grün, App/CLI/IFC unverändert.
+834
View File
@@ -0,0 +1,834 @@
//! Wand-Verschneidung (Gehrung, T-Stoss, Kreuzung): berechnet je Wand die optionalen
//! Schnittlinien an Start- und Endpunkt, materialbewusste Pro-Schicht-Cuts am T-Stoss und die
//! Nah-Putz-Aussparungen der Durchgangswand. Portiert aus `src/model/joins.ts` (dort bleiben die
//! Typen und das Sammeln aus dem `Project`).
//!
//! Behandelt: L-Ecken (zwei Wandenden im Knoten), T-Knoten (drei Enden, zwei kollinear),
//! Mittelspannen-T-Stösse (freies Ende trifft auf die Seite einer anderen Wand) und
//! „+"-Kreuzungen (zwei kollineare Enden auf der Achse einer durchlaufenden Wand). Echte
//! Stern-Knoten (≥ 4 Enden ohne Durchgang) bleiben rechtwinklig.
//!
//! Die Rechenschritte folgen der TS-Fassung Operation für Operation (gleiche Term-Reihenfolge),
//! damit das Ergebnis bitgleich bleibt.
use kernel2d::{add, dot, left_normal, line_intersect, scale, sub, Vec2};
use std::collections::HashMap;
/// Referenzlinie einer Wand (`Wall.referenceLine` / `referenceOffset`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Reference {
Center,
Left,
Right,
/// Freier Versatz (Meter), übersteuert die benannte Referenzlinie.
Offset(f64),
}
/// Querversatz der Wandachse gegenüber der Wandmitte (`wallReferenceOffset` in `model/wall.ts`).
pub fn reference_offset(r: Reference, total_thickness: f64) -> f64 {
let half = total_thickness / 2.0;
match r {
// Math.max(-half, Math.min(half, v)) — Reihenfolge wie TS.
Reference::Offset(v) => (-half).max(half.min(v)),
Reference::Left => half,
Reference::Right => -half,
Reference::Center => 0.0,
}
}
/// Eine Schicht des Wandtyps: Dicke, Bauteil-Identität (`None` = Bauteil unbekannt) und
/// Verschneidungs-Rang (`Component.joinPriority`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct JoinLayer {
pub thickness: f64,
pub component: Option<u32>,
pub priority: f64,
}
/// Eine Wand für die Verschneidung. `layers = None`: Wandtyp unbekannt.
#[derive(Clone, Debug, PartialEq)]
pub struct JoinWall {
pub start: Vec2,
pub end: Vec2,
pub reference: Reference,
pub layers: Option<Vec<JoinLayer>>,
}
/// Unendliche Gerade (Stützpunkt + Richtung, nicht normiert).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Line {
pub point: Vec2,
pub dir: Vec2,
}
/// Pro-Schicht-Cuts eines materialbewussten T-Stosses (`LayerCuts` in TS).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LayerCuts {
pub start: Vec<Option<Line>>,
pub end: Vec<Option<Line>>,
pub start_side: Vec<Option<Line>>,
pub end_side: Vec<Option<Line>>,
}
/// Aussparung der Nah-Putz-Zone einer Durchgangswand (`SpanCutout` in TS).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SpanCutout {
pub from: f64,
pub to: f64,
pub off_a: f64,
pub off_b: f64,
}
/// Schnittlinien einer Wand (`WallCuts` in TS).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct WallCuts {
pub start_cut: Option<Line>,
pub end_cut: Option<Line>,
pub layer_cuts: Option<LayerCuts>,
pub span_cutouts: Vec<SpanCutout>,
}
/// Eine benötigte Angabe fehlt: Wandtyp oder Bauteil der Wand mit diesem Index ist unbekannt
/// (TS wirft dann denselben Fehler wie früher `getWallType`/`getComponent`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum JoinError {
UnknownWallType(usize),
UnknownComponent(usize),
}
/// Verschneidungs-Entscheidung zweier Bauteile am Stoss (`resolveJoinPriority` in TS).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum JoinResolution {
/// Gleiche Priorität und gleiche Komponente: verschmelzen, kein Cut.
Merge,
/// `b` gewinnt, `a` wird getrimmt.
TrimA,
/// `a` gewinnt, `b` wird getrimmt.
TrimB,
/// Gleiche Priorität, verschiedene Komponente: keine Rangfolge (getrimmt wie bisher).
Coexist,
}
pub fn resolve_join_priority(prio_a: f64, prio_b: f64, same_component: bool) -> JoinResolution {
if prio_a == prio_b {
if same_component {
JoinResolution::Merge
} else {
JoinResolution::Coexist
}
} else if prio_a > prio_b {
JoinResolution::TrimB
} else {
JoinResolution::TrimA
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum End {
Start,
End,
}
#[derive(Clone, Copy, Debug)]
struct WallEnd {
wall: usize,
end: End,
}
type R<T> = Result<T, JoinError>;
fn layers_of(walls: &[JoinWall], i: usize) -> R<&[JoinLayer]> {
walls[i].layers.as_deref().ok_or(JoinError::UnknownWallType(i))
}
/// `wallTypeThickness`: Summe der Schichtdicken (Reihenfolge wie `reduce`).
fn thickness(walls: &[JoinWall], i: usize) -> R<f64> {
Ok(layers_of(walls, i)?.iter().fold(0.0, |s, l| s + l.thickness))
}
fn component(i: usize, l: &JoinLayer) -> R<u32> {
l.component.ok_or(JoinError::UnknownComponent(i))
}
/// `Math.hypot(x, y)` wie V8 (Skalierung mit dem Maximum, kompensierte Summe) — `f64::hypot`
/// rundet im letzten Bit teils anders, das Ergebnis soll aber bitgleich zur TS-Fassung bleiben.
pub fn js_hypot(x: f64, y: f64) -> f64 {
let (ax, ay) = (x.abs(), y.abs());
if ax.is_infinite() || ay.is_infinite() {
return f64::INFINITY;
}
if ax.is_nan() || ay.is_nan() {
return f64::NAN;
}
let max = ax.max(ay);
if max == 0.0 {
return 0.0;
}
let mut sum = 0.0;
let mut comp = 0.0;
for v in [ax, ay] {
let n = v / max;
let summand = n * n - comp;
let pre = sum + summand;
comp = (pre - sum) - summand;
sum = pre;
}
sum.sqrt() * max
}
/// Vektorlänge wie `len` in `model/geometry.ts`.
pub fn len(a: Vec2) -> f64 {
js_hypot(a.x, a.y)
}
/// Normieren wie `normalize` in `model/geometry.ts` (Länge 0 → Divisor 1).
pub fn normalize(a: Vec2) -> Vec2 {
let l = len(a);
let l = if l == 0.0 { 1.0 } else { l };
Vec2::new(a.x / l, a.y / l)
}
/// `Math.round` (halbe Werte nach +∞).
fn js_round(x: f64) -> f64 {
if !x.is_finite() {
return x;
}
let f = x.floor();
if x - f >= 0.5 {
f + 1.0
} else {
f
}
}
/// Knoten-Schlüssel wie `roundKey` in TS (Raster 1e-4; −0 = 0; alle NaN gleich).
fn round_key(p: Vec2) -> (u64, u64) {
let r = |v: f64| {
let q = js_round(v * 1e4) / 1e4;
if q.is_nan() {
f64::NAN.to_bits()
} else if q == 0.0 {
0
} else {
q.to_bits()
}
};
(r(p.x), r(p.y))
}
fn point_of(w: &JoinWall, e: End) -> Vec2 {
match e {
End::Start => w.start,
End::End => w.end,
}
}
/// Achsrichtung start→end, normiert.
fn dir_of(w: &JoinWall) -> Vec2 {
normalize(sub(w.end, w.start))
}
fn set_cut(result: &mut [WallCuts], we: WallEnd, cut: Line) {
let c = &mut result[we.wall];
match we.end {
End::Start => c.start_cut = Some(cut),
End::End => c.end_cut = Some(cut),
}
}
/// Berechnet für jede Wand (Index = Eingabe-Reihenfolge) die Gehrungs-/Anschluss-Schnittlinien.
/// `walls` ist die bereits gefilterte Wandmenge (z. B. ein Geschoss).
pub fn compute_joins(walls: &[JoinWall]) -> Result<Vec<WallCuts>, JoinError> {
let mut result = vec![WallCuts::default(); walls.len()];
// Knotenkarte in Einfüge-Reihenfolge: gerundeter Endpunkt → dort endende Wandenden.
let mut index: HashMap<(u64, u64), usize> = HashMap::new();
let mut junctions: Vec<Vec<WallEnd>> = Vec::new();
let mut push = |p: Vec2, we: WallEnd| {
let key = round_key(p);
match index.get(&key) {
Some(&k) => junctions[k].push(we),
None => {
index.insert(key, junctions.len());
junctions.push(vec![we]);
}
}
};
for (i, w) in walls.iter().enumerate() {
push(w.start, WallEnd { wall: i, end: End::Start });
push(w.end, WallEnd { wall: i, end: End::End });
}
for ends in &junctions {
match ends.len() {
2 => {
if let Some(cut) = miter_line(walls, ends[0].wall, ends[0].end, ends[1].wall)? {
set_cut(&mut result, ends[0], cut);
set_cut(&mut result, ends[1], cut);
}
}
3 => apply_t_junction(walls, ends, &mut result)?,
// Freies Ende (Fall 2 unten) bzw. echter Stern-Knoten (bleibt rechtwinklig).
_ => {}
}
}
// Fall 2: jedes noch ungeschnittene Ende gegen die Mittelspanne aller anderen Wände prüfen
// (Mittelspannen-T und „+"-Kreuzung). Bereits geschnittene Enden bleiben unangetastet.
for ends in &junctions {
for &we in ends {
let c = &result[we.wall];
let cut = match we.end {
End::Start => c.start_cut,
End::End => c.end_cut,
};
if cut.is_none() {
apply_mid_span_tee(walls, we, &mut result)?;
}
}
}
Ok(result)
}
/// Gemeinsame Gehrungslinie zweier Wände A, B im Knoten (orientierungsbasierte Flächen-Paarung:
/// Aussen mit Aussen, Innen mit Innen — robust auch bei spitzen Winkeln). `None` bei kollinearen
/// Achsen.
fn miter_line(walls: &[JoinWall], ai: usize, a_end: End, bi: usize) -> R<Option<Line>> {
let (a, b) = (&walls[ai], &walls[bi]);
let j = point_of(a, a_end);
let t_a = thickness(walls, ai)?;
let t_b = thickness(walls, bi)?;
let u_a = dir_of(a);
let u_b = dir_of(b);
let n_a = left_normal(u_a);
let n_b = left_normal(u_b);
let off_a = reference_offset(a.reference, t_a);
let off_b = reference_offset(b.reference, t_b);
let p_la = add(j, scale(n_a, off_a + t_a / 2.0));
let p_ra = add(j, scale(n_a, off_a - t_a / 2.0));
let p_lb = add(j, scale(n_b, off_b + t_b / 2.0));
let p_rb = add(j, scale(n_b, off_b - t_b / 2.0));
let d_a = if a_end == End::Start { u_a } else { scale(u_a, -1.0) };
let b_at_start = len(sub(b.start, j)) <= len(sub(b.end, j));
let d_b = if b_at_start { u_b } else { scale(u_b, -1.0) };
let b_outer = if dot(n_b, d_a) < 0.0 { p_lb } else { p_rb };
let b_inner = if dot(n_b, d_a) < 0.0 { p_rb } else { p_lb };
let a_left_is_outer = dot(n_a, d_b) < 0.0;
let b_for_left = if a_left_is_outer { b_outer } else { b_inner };
let b_for_right = if a_left_is_outer { b_inner } else { b_outer };
let (Some(c1), Some(c2)) = (line_intersect(p_la, u_a, b_for_left, u_b), line_intersect(p_ra, u_a, b_for_right, u_b)) else {
return Ok(None);
};
let dir = sub(c2, c1);
if len(dir) < 1e-9 {
return Ok(None);
}
Ok(Some(Line { point: c1, dir }))
}
/// Fall 1 — T-Knoten: drei Enden im Knoten, zwei davon kollinear (Durchgang). Der Abzweig bekommt
/// einen Schnitt an der ihm zugewandten Fläche der Durchgangswand; ohne kollineares Paar bleibt
/// der Knoten rechtwinklig.
fn apply_t_junction(walls: &[JoinWall], ends: &[WallEnd], result: &mut [WallCuts]) -> R<()> {
let dirs: Vec<Vec2> = ends.iter().map(|e| dir_of(&walls[e.wall])).collect();
let mut through: Option<(usize, usize)> = None;
'outer: for i in 0..3 {
for k in i + 1..3 {
if 1.0 - dot(dirs[i], dirs[k]).abs() < 1e-6 {
through = Some((i, k));
break 'outer;
}
}
}
let Some((t0, t1)) = through else { return Ok(()) };
let branch_idx = (0..3).find(|&i| i != t0 && i != t1).unwrap_or(0);
let branch_end = ends[branch_idx];
let through_end = ends[t0];
let (bi, ti) = (branch_end.wall, through_end.wall);
let through_wall = &walls[ti];
let j = point_of(through_wall, through_end.end);
let t_t = thickness(walls, ti)?;
let u_t = dir_of(through_wall);
let n_t = left_normal(u_t);
let off_t = reference_offset(through_wall.reference, t_t);
let d_branch = if branch_end.end == End::Start { dir_of(&walls[bi]) } else { scale(dir_of(&walls[bi]), -1.0) };
let sign = if dot(n_t, d_branch) >= 0.0 { 1.0 } else { -1.0 };
let face_point = add(j, scale(n_t, off_t + sign * (t_t / 2.0)));
let face_cut = Line { point: face_point, dir: u_t };
set_cut(result, branch_end, face_cut);
apply_layer_cuts(walls, result, branch_end, ti, face_cut, j, u_t, sign)
}
/// Materialbewusste Pro-Schicht-Erweiterung eines T-Stoss-Cuts: Abzweig-Schichten gleichen
/// Materials wie das Rückgrat der Durchgangswand (oder prioritärer) laufen bis zur
/// Rückgrat-Nahfläche durch; angrenzende getrimmte Schichten bekommen eine seitliche Linie; die
/// Durchgangswand bekommt eine Nah-Putz-Aussparung über die Kernbreite. Setzt `layer_cuts` nur,
/// wenn mindestens eine Schicht verschmilzt.
#[allow(clippy::too_many_arguments)]
fn apply_layer_cuts(
walls: &[JoinWall],
result: &mut [WallCuts],
branch_end: WallEnd,
ti: usize,
face_cut: Line,
axis_point: Vec2,
through_dir: Vec2,
sign: f64,
) -> R<()> {
let bi = branch_end.wall;
let branch_layers = layers_of(walls, bi)?;
let through_layers = layers_of(walls, ti)?;
if branch_layers.is_empty() || through_layers.is_empty() {
return Ok(());
}
// Rückgrat der Durchgangswand: Schicht mit der höchsten joinPriority (erste gewinnt).
let mut backbone = (component(ti, &through_layers[0])?, through_layers[0].priority);
let mut backbone_idx = 0;
for (i, l) in through_layers.iter().enumerate() {
let c = component(ti, l)?;
if l.priority > backbone.1 {
backbone = (c, l.priority);
backbone_idx = i;
}
}
let n = branch_layers.len();
let mut merged = vec![false; n];
for (i, l) in branch_layers.iter().enumerate() {
let c = component(bi, l)?;
// "merge" (gleiches Rückgrat-Material) oder "trim-b" (Abzweig-Schicht selbst prioritärer)
// → die Schicht läuft durch.
merged[i] = matches!(resolve_join_priority(l.priority, backbone.1, c == backbone.0), JoinResolution::Merge | JoinResolution::TrimB);
}
if !merged.iter().any(|&m| m) {
return Ok(());
}
let lc = result[bi].layer_cuts.get_or_insert_with(|| LayerCuts {
start: vec![None; n],
end: vec![None; n],
start_side: vec![None; n],
end_side: vec![None; n],
});
if lc.start.len() != n {
return Ok(());
}
let t_t = through_layers.iter().fold(0.0, |s, l| s + l.thickness);
let off_t = reference_offset(walls[ti].reference, t_t);
let near = |i: usize| if sign > 0.0 { i > backbone_idx } else { i < backbone_idx };
let mut near_plaster = 0.0;
for (i, l) in through_layers.iter().enumerate() {
if near(i) {
near_plaster += l.thickness;
}
}
let n_t = left_normal(through_dir);
let merge_point = add(axis_point, scale(n_t, off_t + sign * (t_t / 2.0 - near_plaster)));
let merge_cut = Line { point: merge_point, dir: through_dir };
let side_line = merge_cut;
// Materialien des Nah-Putzes (Komponenten sind hier alle bekannt, s. Rückgrat-Suche).
let near_comps: Vec<Option<u32>> = through_layers.iter().enumerate().filter(|(i, _)| near(*i)).map(|(_, l)| l.component).collect();
let (face_arr, side_arr) = match branch_end.end {
End::Start => (&mut lc.start, &mut lc.start_side),
End::End => (&mut lc.end, &mut lc.end_side),
};
for i in 0..n {
face_arr[i] = Some(if merged[i] { merge_cut } else { face_cut });
let adj_merged = !merged[i] && ((i > 0 && merged[i - 1]) || (i + 1 < n && merged[i + 1]));
let merges_with_near = near_comps.contains(&branch_layers[i].component);
side_arr[i] = if adj_merged && !merges_with_near { Some(side_line) } else { None };
}
// Durchgangswand-Aussparung über die Kernbreite des Abzweigs (nur bei Nah-Putz).
if near_plaster > 1e-9 {
let total_branch = branch_layers.iter().fold(0.0, |s, l| s + l.thickness);
let ref_off_branch = reference_offset(walls[bi].reference, total_branch);
let mut b_off = ref_off_branch - total_branch / 2.0;
let mut core_lo = f64::INFINITY;
let mut core_hi = f64::NEG_INFINITY;
for (i, l) in branch_layers.iter().enumerate() {
let th = l.thickness;
if merged[i] {
if b_off < core_lo {
core_lo = b_off;
}
if b_off + th > core_hi {
core_hi = b_off + th;
}
}
b_off += th;
}
if core_hi > core_lo {
let n_branch = left_normal(dir_of(&walls[bi]));
let proj = dot(n_branch, through_dir);
let axis_at = dot(sub(axis_point, walls[ti].start), through_dir);
let e1 = axis_at + core_lo * proj;
let e2 = axis_at + core_hi * proj;
let off_a = off_t + sign * (t_t / 2.0);
let off_b = off_t + sign * (t_t / 2.0 - near_plaster);
result[ti].span_cutouts.push(SpanCutout { from: e1.min(e2), to: e1.max(e2), off_a, off_b });
}
}
Ok(())
}
/// Fall 2 — Mittelspannen-T-Stoss: trifft das Ende `free` auf die innere Spanne einer anderen
/// Wand (senkrecht höchstens halbe Dicke + 1 mm entfernt), bekommt es einen Schnitt an deren
/// zugewandter Fläche; bei mehreren Treffern gewinnt die nächstliegende Wand.
fn apply_mid_span_tee(walls: &[JoinWall], free: WallEnd, result: &mut [WallCuts]) -> R<()> {
let fi = free.wall;
let free_wall = &walls[fi];
let p = point_of(free_wall, free.end);
const END_GAP: f64 = 1e-4;
const TOL: f64 = 1e-3;
// (Wand, perp, dist, distAlong)
let mut best: Option<(usize, f64, f64, f64)> = None;
for (wi, w) in walls.iter().enumerate() {
if wi == fi {
continue;
}
let u = dir_of(w);
let w_len = len(sub(w.end, w.start));
if w_len < 1e-9 {
continue;
}
let rel = sub(p, w.start);
let dist_along = dot(rel, u);
if dist_along <= END_GAP || dist_along >= w_len - END_GAP {
continue;
}
let perp = dot(rel, left_normal(u));
let tw = thickness(walls, wi)?;
let dist = perp.abs();
if dist > tw / 2.0 + TOL {
continue;
}
if best.map_or(true, |b| dist < b.2) {
best = Some((wi, perp, dist, dist_along));
}
}
let Some((wi, perp, _, dist_along)) = best else { return Ok(()) };
let w = &walls[wi];
let tw = thickness(walls, wi)?;
let u_w = dir_of(w);
let n_w = left_normal(u_w);
let off_w = reference_offset(w.reference, tw);
let d_free = if free.end == End::Start { dir_of(free_wall) } else { scale(dir_of(free_wall), -1.0) };
let facing = dot(n_w, d_free);
let sign = if facing.abs() > 1e-6 {
if facing >= 0.0 {
1.0
} else {
-1.0
}
} else if perp >= 0.0 {
1.0
} else {
-1.0
};
let face_point = add(w.start, scale(n_w, off_w + sign * (tw / 2.0)));
let face_cut = Line { point: face_point, dir: u_w };
set_cut(result, free, face_cut);
let axis_point = add(w.start, scale(u_w, dist_along));
apply_layer_cuts(walls, result, free, wi, face_cut, axis_point, u_w, sign)
}
// ── Flache Kodierung ─────────────────────────────────────────────────────────
//
// Wände: [n, (sx, sy, ex, ey, refKind, refValue, typeOk, nLayers, (dicke, bauteil, prio)…)…]
// refKind: 0 Mitte, 1 links, 2 rechts, 3 freier Versatz (refValue); bauteil < 0 = unbekannt.
// Cuts einer Wand: [start(5), end(5), nLC, (start, end, startSide, endSide je nLC × 5),
// nSpan, (from, to, offA, offB)…]; Linie = (gesetzt 0/1, px, py, dx, dy).
/// Liest die Wände; `None` bei kaputten/unendlichen Daten.
pub fn decode_walls(buf: &[f64]) -> Option<Vec<JoinWall>> {
let mut r = crate::flat_read::Reader::new(buf);
let n = r.count()?;
let mut out = Vec::with_capacity(n.min(1 << 16));
for _ in 0..n {
let (sx, sy, ex, ey) = (r.num()?, r.num()?, r.num()?, r.num()?);
let (kind, value) = (r.num()?, r.num()?);
let type_ok = r.num()? != 0.0;
let nl = r.count()?;
if ![sx, sy, ex, ey].iter().all(|v| v.is_finite()) {
return None;
}
let reference = match kind as i64 {
1 => Reference::Left,
2 => Reference::Right,
3 if value.is_finite() => Reference::Offset(value),
3 => return None,
_ => Reference::Center,
};
let mut layers = Vec::with_capacity(nl.min(1 << 10));
for _ in 0..nl {
let (t, c, p) = (r.num()?, r.num()?, r.num()?);
if !t.is_finite() {
return None;
}
let component = (c.is_finite() && c >= 0.0 && c < 4e9).then_some(c as u32);
// Unbekanntes Bauteil: Priorität spielt keine Rolle (Fehler, sobald gebraucht).
let priority = if component.is_some() { p } else { f64::NAN };
layers.push(JoinLayer { thickness: t, component, priority });
}
out.push(JoinWall { start: Vec2::new(sx, sy), end: Vec2::new(ex, ey), reference, layers: type_ok.then_some(layers) });
}
Some(out)
}
fn push_line(out: &mut Vec<f64>, l: &Option<Line>) {
match l {
Some(l) => out.extend([1.0, l.point.x, l.point.y, l.dir.x, l.dir.y]),
None => out.extend([0.0; 5]),
}
}
/// Hängt die Cuts einer Wand flach an.
pub fn encode_cuts(out: &mut Vec<f64>, c: &WallCuts) {
push_line(out, &c.start_cut);
push_line(out, &c.end_cut);
match &c.layer_cuts {
Some(lc) => {
out.push(lc.start.len() as f64);
for arr in [&lc.start, &lc.end, &lc.start_side, &lc.end_side] {
for l in arr {
push_line(out, l);
}
}
}
None => out.push(0.0),
}
out.push(c.span_cutouts.len() as f64);
for s in &c.span_cutouts {
out.extend([s.from, s.to, s.off_a, s.off_b]);
}
}
fn read_line(r: &mut crate::flat_read::Reader) -> Option<Option<Line>> {
let (set, px, py, dx, dy) = (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?);
if set == 0.0 {
return Some(None);
}
if ![px, py, dx, dy].iter().all(|v| v.is_finite()) {
return None;
}
Some(Some(Line { point: Vec2::new(px, py), dir: Vec2::new(dx, dy) }))
}
/// Liest die Cuts einer Wand (Gegenstück zu [`encode_cuts`]).
pub fn decode_cuts(r: &mut crate::flat_read::Reader) -> Option<WallCuts> {
let start_cut = read_line(r)?;
let end_cut = read_line(r)?;
let n = r.count()?;
let layer_cuts = if n > 0 {
if n > 1 << 12 {
return None;
}
let mut arrs: [Vec<Option<Line>>; 4] = Default::default();
for a in arrs.iter_mut() {
for _ in 0..n {
a.push(read_line(r)?);
}
}
let [start, end, start_side, end_side] = arrs;
Some(LayerCuts { start, end, start_side, end_side })
} else {
None
};
let m = r.count()?;
let mut span_cutouts = Vec::with_capacity(m.min(1 << 10));
for _ in 0..m {
let s = SpanCutout { from: r.num()?, to: r.num()?, off_a: r.num()?, off_b: r.num()? };
if ![s.from, s.to, s.off_a, s.off_b].iter().all(|v| v.is_finite()) {
return None;
}
span_cutouts.push(s);
}
Some(WallCuts { start_cut, end_cut, layer_cuts, span_cutouts })
}
/// Ergebnis flach: `[0, (cuts je Wand)…]`; Fehler `[1, wandIndex]` (Wandtyp bzw. Bauteil
/// unbekannt — TS wirft); kaputte Eingabe: leer.
pub fn compute_joins_flat(buf: &[f64]) -> Vec<f64> {
let Some(walls) = decode_walls(buf) else { return vec![] };
match compute_joins(&walls) {
Ok(cuts) => {
let mut out = vec![0.0];
for c in &cuts {
encode_cuts(&mut out, c);
}
out
}
Err(JoinError::UnknownWallType(i)) | Err(JoinError::UnknownComponent(i)) => vec![1.0, i as f64],
}
}
#[cfg(test)]
mod tests {
use super::*;
fn layer(t: f64, c: u32, p: f64) -> JoinLayer {
JoinLayer { thickness: t, component: Some(c), priority: p }
}
fn wall(s: (f64, f64), e: (f64, f64), layers: Vec<JoinLayer>) -> JoinWall {
JoinWall { start: Vec2::new(s.0, s.1), end: Vec2::new(e.0, e.1), reference: Reference::Center, layers: Some(layers) }
}
fn mono(s: (f64, f64), e: (f64, f64), t: f64) -> JoinWall {
wall(s, e, vec![layer(t, 0, 10.0)])
}
/// Abstand eines Punkts von der Geraden.
fn dist(l: &Line, p: Vec2) -> f64 {
kernel2d::cross(l.dir, sub(p, l.point)).abs() / len(l.dir)
}
fn close(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-9
}
#[test]
fn l_ecke_gehrung_auf_diagonale() {
let w = vec![mono((0.0, 0.0), (5.0, 0.0), 0.4), mono((5.0, 0.0), (5.0, 4.0), 0.4)];
let c = compute_joins(&w).unwrap();
let a = c[0].end_cut.unwrap();
assert_eq!(c[1].start_cut, Some(a));
// Aussen-Apex (5.2, -0.2), Innen-Apex (4.8, 0.2).
assert!(dist(&a, Vec2::new(5.2, -0.2)) < 1e-9 && dist(&a, Vec2::new(4.8, 0.2)) < 1e-9);
assert_eq!(c[0].start_cut, None);
}
#[test]
fn spitze_ecke_paart_aussen_mit_aussen() {
let w = vec![mono((0.0, 0.0), (4.0, 0.0), 0.2), mono((4.0, 0.0), (1.0, 1.0), 0.2)];
let c = compute_joins(&w).unwrap();
let cut = c[0].end_cut.unwrap();
// Gleiche Dicken: die Gehrung ist die Winkelhalbierende durch den Knoten (über Kreuz
// gepaart stünde sie senkrecht dazu).
let bis = add(Vec2::new(-1.0, 0.0), normalize(Vec2::new(-3.0, 1.0)));
assert!(kernel2d::cross(normalize(cut.dir), normalize(bis)).abs() < 1e-9, "{cut:?}");
assert!(dist(&cut, Vec2::new(4.0, 0.0)) < 1e-9);
}
#[test]
fn t_knoten_schneidet_nur_abzweig() {
let w = vec![mono((0.0, 0.0), (3.0, 0.0), 0.3), mono((3.0, 0.0), (6.0, 0.0), 0.3), mono((3.0, 0.0), (3.0, 4.0), 0.2)];
let c = compute_joins(&w).unwrap();
assert_eq!(c[0].end_cut, None);
assert_eq!(c[1].start_cut, None);
let cut = c[2].start_cut.unwrap();
assert!(close(cut.point.y, 0.15) && close(cut.dir.y, 0.0));
}
#[test]
fn mittelspannen_t_und_kreuzung() {
// Durchlaufende Wand, oben ein Abzweig, unten/oben eine Kreuzung aus zwei Hälften.
let w = vec![
mono((0.0, 0.0), (10.0, 0.0), 0.3),
mono((2.0, 0.0), (2.0, 3.0), 0.2),
mono((6.0, -3.0), (6.0, 0.0), 0.2),
mono((6.0, 0.0), (6.0, 3.0), 0.2),
];
let c = compute_joins(&w).unwrap();
assert!(close(c[1].start_cut.unwrap().point.y, 0.15));
assert!(close(c[2].end_cut.unwrap().point.y, -0.15));
assert!(close(c[3].start_cut.unwrap().point.y, 0.15));
assert_eq!(c[0], WallCuts::default());
}
#[test]
fn freies_ende_bleibt_rechtwinklig() {
let w = vec![mono((0.0, 0.0), (10.0, 0.0), 0.3), mono((2.0, 1.0), (2.0, 3.0), 0.2)];
assert_eq!(compute_joins(&w).unwrap(), vec![WallCuts::default(); 2]);
}
#[test]
fn materialbewusster_t_stoss() {
// Durchgang: Putz(0) 0.02 | Backstein(1, prio 50) 0.15 | Putz(0) 0.015; Abzweig gleich.
let lay = || vec![layer(0.02, 0, 10.0), layer(0.15, 1, 50.0), layer(0.015, 0, 10.0)];
let w = vec![wall((0.0, 0.0), (10.0, 0.0), lay()), wall((4.0, 0.0), (4.0, 3.0), lay())];
let c = compute_joins(&w).unwrap();
let lc = c[1].layer_cuts.as_ref().unwrap();
let total: f64 = 0.185;
// Kern läuft bis zur Rückgrat-Nahfläche (Nah-Putz 0.015 auf der +n-Seite).
assert!(close(lc.start[1].unwrap().point.y, total / 2.0 - 0.015));
assert!(close(lc.start[0].unwrap().point.y, total / 2.0));
// Putz-Schichten sind materialgleich mit dem Nah-Putz → keine Seitenlinie.
assert_eq!(lc.start_side, vec![None; 3]);
assert_eq!(lc.end, vec![None; 3]);
// Durchgangswand bekommt die Nah-Putz-Aussparung über die Kernbreite.
let s = c[0].span_cutouts[0];
assert!(close(s.off_a, total / 2.0) && close(s.off_b, total / 2.0 - 0.015));
assert!(close(s.to - s.from, 0.15), "{s:?}");
}
#[test]
fn hypot_wie_js() {
assert_eq!(js_hypot(3.0, 4.0), 5.0);
assert_eq!(js_hypot(0.0, -0.0), 0.0);
assert!(js_hypot(f64::NAN, 1.0).is_nan());
assert_eq!(js_hypot(f64::INFINITY, f64::NAN), f64::INFINITY);
assert_eq!(normalize(Vec2::new(0.0, 0.0)), Vec2::new(0.0, 0.0));
}
#[test]
fn referenzlinie() {
assert_eq!(reference_offset(Reference::Left, 0.4), 0.2);
assert_eq!(reference_offset(Reference::Right, 0.4), -0.2);
assert_eq!(reference_offset(Reference::Offset(5.0), 0.4), 0.2);
assert_eq!(reference_offset(Reference::Offset(-0.05), 0.4), -0.05);
}
#[test]
fn unbekannter_typ_nur_wenn_gebraucht() {
let mut w = vec![mono((0.0, 0.0), (5.0, 0.0), 0.4), mono((5.0, 0.0), (5.0, 4.0), 0.4), mono((20.0, 0.0), (25.0, 0.0), 0.4)];
w[2].layers = None;
assert!(compute_joins(&w).is_ok()); // freistehend → nie gebraucht
w[1].layers = None;
assert_eq!(compute_joins(&w), Err(JoinError::UnknownWallType(1)));
}
#[test]
fn unsinn_ohne_panic() {
assert!(compute_joins_flat(&[]).is_empty());
assert!(compute_joins_flat(&[f64::NAN]).is_empty());
assert!(compute_joins_flat(&[1.0, 0.0, 0.0]).is_empty());
assert!(compute_joins_flat(&[1.0, f64::NAN, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0]).is_empty());
assert_eq!(compute_joins_flat(&[0.0]), vec![0.0]);
// Nulllängen-Wände und deckungsgleiche Enden.
let w = [
3.0, //
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.2, 0.0, 10.0, // Nulllänge, eine Schicht
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, // Nulllänge, ohne Schichten
0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, // Wandtyp unbekannt
];
let out = compute_joins_flat(&w);
assert_eq!(out.first(), Some(&0.0));
// Kaputte Cuts lesen.
let mut r = crate::flat_read::Reader::new(&[1.0, 0.0]);
assert!(decode_cuts(&mut r).is_none());
}
#[test]
fn cuts_hin_und_zurueck() {
let lay = || vec![layer(0.02, 0, 10.0), layer(0.15, 1, 50.0), layer(0.015, 0, 10.0)];
let w = vec![wall((0.0, 0.0), (10.0, 0.0), lay()), wall((4.0, 0.0), (4.0, 3.0), lay()), wall((10.0, 0.0), (10.0, 5.0), lay())];
for c in compute_joins(&w).unwrap() {
let mut buf = vec![];
encode_cuts(&mut buf, &c);
let mut r = crate::flat_read::Reader::new(&buf);
assert_eq!(decode_cuts(&mut r), Some(c));
}
}
}
+2
View File
@@ -13,6 +13,8 @@ pub mod sun;
pub mod site_rules;
pub mod auto_dimensions;
pub mod kennzahlen;
pub mod joins;
pub mod wall_bands;
#[cfg(feature = "web")]
mod web;
+969
View File
@@ -0,0 +1,969 @@
//! Wand-Schichtbänder für 3D/STL/OBJ/IFC: zerlegt EINE Wand in quer zur Dicke gestapelte
//! Materialbänder und schneidet daraus achsparallele Körper — mit Gehrungs-/Anschluss-Cuts
//! (aus [`crate::joins`]), Nah-Putz-Aussparungen der Durchgangswand, Decken-Dominanz pro Schicht,
//! Öffnungs-Löchern und schräger Oberkante unter Dachflächen (`top_drop`). Portiert aus
//! `src/plan/toWalls3d/bands.ts`; dort bleiben das Sammeln aus dem `Project` (Wandtyp, Öffnungen,
//! Decken-/Dachaufbau, Höhen) und die Darstellungs-Metadaten (Farbe, Schraffur, Material).
//!
//! Zwei Pfade wie in TS: `layered` (3D-Viewer: ein Körper je Band über die volle Achse, Öffnungen
//! als Löcher) und Schnitt-Eingabe (Pfeiler/Brüstung/Sturz-Segmente ohne Löcher).
use crate::joins::{js_hypot, reference_offset, Line, Reference, WallCuts};
use crate::roof::roof_underside_at;
use kernel2d::{add, dot, left_normal, line_intersect, point_in_outline, scale, sub, Vec2};
/// Toleranz der Wand-Ableitung (`EPS` in `toWalls3d/shared.ts`).
pub const EPS: f64 = 1e-4;
/// Schrittweite (Meter) der Dach-Unterkanten-Abtastung.
const ROOF_CLIP_STEP: f64 = 0.15;
/// Ein Schicht-Band: Dicke und Verschneidungs-Rang (`None`: keine Decken-Subtraktion).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BandIn {
pub thickness: f64,
pub priority: Option<f64>,
}
/// Eine Öffnung der Wand: Achsen-Intervall (Meter ab Wandstart), absolute z-Ausdehnung und ob
/// die innerste Schicht an der Laibung zurückspringt (`WindowType.innerLayerRecess`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct OpeningIn {
pub from: f64,
pub to: f64,
pub z_bottom: f64,
pub z_top: f64,
pub recess_inner_layer: bool,
}
/// Eine Decke desselben Geschosses: z-Ausdehnung, Umriss, Schichten (Dicke, Rang; `None` =
/// Bauteil unbekannt). `layers = None`: Deckentyp unbekannt.
#[derive(Clone, Debug, PartialEq)]
pub struct CeilingIn {
pub z_bottom: f64,
pub z_top: f64,
pub outline: Vec<Vec2>,
pub layers: Option<Vec<(f64, Option<f64>)>>,
}
/// Ein Dach desselben Geschosses: Traufhöhe, Summe der Schichtdicken, Traufe-Umriss, Flächen.
#[derive(Clone, Debug, PartialEq)]
pub struct RoofIn {
pub eaves_z: f64,
pub total_thickness: f64,
pub eaves: Vec<[f64; 2]>,
pub planes: Vec<Vec<[f64; 3]>>,
}
/// Terminierung am Deckenanschluss (`Wall.sliceTermination`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Termination {
Both,
Below,
Above,
}
/// Eine Wand mit allem, was die Bänder brauchen.
#[derive(Clone, Debug, PartialEq)]
pub struct WallIn {
pub start: Vec2,
pub end: Vec2,
pub z_bottom: f64,
pub z_top: f64,
pub layered: bool,
/// `true`: Bänder sind die Wandschichten (Versätze gestapelt); `false`: EIN Band über die
/// ganze Dicke, Versatz = Referenzversatz.
pub stacked: bool,
pub reference: Reference,
/// Wanddicke für die grobe Grundriss-Hülle (Decken-Vorfilter).
pub thickness_safe: f64,
pub termination: Termination,
pub bands: Vec<BandIn>,
pub openings: Vec<OpeningIn>,
pub cuts: WallCuts,
}
/// Decken und Dächer eines Geschosses — einmal je Geschoss gelesen, für alle seine Wände; die
/// Grundriss-Hüllen werden dabei vorab bestimmt.
#[derive(Clone, Debug, Default)]
pub struct FloorContext {
ceilings: Vec<(CeilingIn, Bounds)>,
roofs: Vec<(RoofIn, Bounds)>,
}
impl FloorContext {
pub fn new(ceilings: Vec<CeilingIn>, roofs: Vec<RoofIn>) -> Self {
FloorContext {
ceilings: ceilings
.into_iter()
.map(|c| {
let b = outline_bounds(c.outline.iter().map(|p| (p.x, p.y)));
(c, b)
})
.collect(),
roofs: roofs
.into_iter()
.map(|r| {
let b = outline_bounds(r.eaves.iter().map(|p| (p[0], p[1])));
(r, b)
})
.collect(),
}
}
}
/// Ein Wandkörper: Band-Index, Achse (versetzt), z-Bereich, Absenkung der Oberkante am
/// Anfang/Ende (`None` = flach), Löcher `[from, to, zBottom, zTop]` relativ zum Körper-Start.
#[derive(Clone, Debug, PartialEq)]
pub struct Piece {
pub band: usize,
pub start: Vec2,
pub end: Vec2,
pub z_bottom: f64,
pub z_top: f64,
pub top_drop: Option<[f64; 2]>,
pub holes: Vec<[f64; 4]>,
}
#[derive(Clone, Copy, Debug)]
struct Bounds {
min_x: f64,
max_x: f64,
min_y: f64,
max_y: f64,
}
fn wall_bounds(w: &WallIn, half: f64) -> Bounds {
Bounds {
min_x: w.start.x.min(w.end.x) - half,
max_x: w.start.x.max(w.end.x) + half,
min_y: w.start.y.min(w.end.y) - half,
max_y: w.start.y.max(w.end.y) + half,
}
}
fn outline_bounds(pts: impl Iterator<Item = (f64, f64)>) -> Bounds {
let mut b = Bounds { min_x: f64::INFINITY, max_x: f64::NEG_INFINITY, min_y: f64::INFINITY, max_y: f64::NEG_INFINITY };
for (x, y) in pts {
if x < b.min_x {
b.min_x = x;
}
if x > b.max_x {
b.max_x = x;
}
if y < b.min_y {
b.min_y = y;
}
if y > b.max_y {
b.max_y = y;
}
}
b
}
fn bounds_overlap(a: Bounds, b: Bounds) -> bool {
a.min_x <= b.max_x + EPS && a.max_x >= b.min_x - EPS && a.min_y <= b.max_y + EPS && a.max_y >= b.min_y - EPS
}
/// Decken-„Cutter": z-Band einer Deckenschicht, ihr Rang und der Decken-Umriss.
struct Cutter<'a> {
z_bottom: f64,
z_top: f64,
priority: f64,
outline: &'a [Vec2],
}
/// Decken, die die Wand pro Schicht einschneiden: dasselbe Geschoss (Aufrufer), vertikale
/// Überlappung, grober Grundriss-Überlapp; je Deckenschicht ein eigener Cutter (proportional auf
/// die Decken-z-Spanne verteilt, oben → unten), sonst einer über die volle Höhe mit dem höchsten
/// Rang.
fn ceiling_cutters<'a>(w: &WallIn, ctx: &'a FloorContext) -> Vec<Cutter<'a>> {
let wb = wall_bounds(w, w.thickness_safe / 2.0);
let mut out = Vec::new();
for (c, cb) in &ctx.ceilings {
if c.outline.len() < 3 {
continue;
}
if c.z_bottom >= w.z_top - EPS || c.z_top <= w.z_bottom + EPS {
continue;
}
if !bounds_overlap(wb, *cb) {
continue;
}
let total = c.layers.as_ref().map_or(0.0, |ls| ls.iter().fold(0.0, |s, l| s + l.0));
match &c.layers {
Some(ls) if !ls.is_empty() && total > EPS => {
let span = c.z_top - c.z_bottom;
let mut prefix_top = 0.0;
for &(th, prio) in ls {
let t = (th / total) * span;
let layer_top = c.z_top - prefix_top;
let layer_bottom = layer_top - t;
prefix_top += t;
if let Some(p) = prio {
out.push(Cutter { z_bottom: layer_bottom, z_top: layer_top, priority: p, outline: &c.outline });
}
}
}
_ => {
// Höchster Rang aller Schichten; ein unbekanntes Bauteil (oder Typ) → kein Cutter.
let Some(ls) = &c.layers else { continue };
let mut best: Option<f64> = None;
let mut known = true;
for &(_, p) in ls {
match p {
Some(p) => {
if best.map_or(true, |b| p > b) {
best = Some(p);
}
}
None => known = false,
}
}
if let (true, Some(p)) = (known, best) {
out.push(Cutter { z_bottom: c.z_bottom, z_top: c.z_top, priority: p, outline: &c.outline });
}
}
}
}
out
}
/// Achsen-Teilintervalle in `[lo, hi]`, auf denen die Mittellinie eines Bands (Querversatz
/// `offset`) im Umriss liegt: Raster ~5 cm (min. 32 Schritte), Übergänge per Bisektion.
fn band_coverage(w: &WallIn, u: Vec2, n: Vec2, offset: f64, outline: &[Vec2], lo: f64, hi: f64) -> Vec<[f64; 2]> {
if hi - lo <= EPS {
return vec![];
}
let base = add(w.start, scale(n, offset));
let inside = |t: f64| point_in_outline(add(base, scale(u, t)), outline);
let steps = 32f64.max(((hi - lo) / 0.05).ceil()) as usize;
let dt = (hi - lo) / steps as f64;
let mut out = Vec::new();
let mut prev_inside = inside(lo);
let mut start = if prev_inside { Some(lo) } else { None };
let mut prev_t = lo;
for i in 1..=steps {
let t = if i == steps { hi } else { lo + i as f64 * dt };
let now = inside(t);
if now != prev_inside {
let cross = bisect(&inside, prev_t, t);
if now {
start = Some(cross);
} else if let Some(s) = start.take() {
out.push([s, cross]);
}
}
prev_inside = now;
prev_t = t;
}
if let Some(s) = start {
out.push([s, hi]);
}
out
}
fn bisect(inside: &impl Fn(f64) -> bool, a: f64, b: f64) -> f64 {
let a_inside = inside(a);
let (mut lo, mut hi) = (a, b);
let mut i = 0;
while i < 40 && hi - lo > EPS * 0.01 {
let mid = (lo + hi) / 2.0;
if inside(mid) == a_inside {
lo = mid;
} else {
hi = mid;
}
i += 1;
}
(lo + hi) / 2.0
}
/// `[lo, hi]` minus die (geklemmten, vereinigten) Intervalle `holes`.
fn subtract_spans(lo: f64, hi: f64, holes: &[[f64; 2]]) -> Vec<[f64; 2]> {
let mut clipped: Vec<[f64; 2]> = holes
.iter()
.map(|&[a, b]| [lo.max(a.min(b)), hi.min(a.max(b))])
.filter(|&[a, b]| b > a + EPS)
.collect();
clipped.sort_by(|p, q| p[0].partial_cmp(&q[0]).unwrap_or(std::cmp::Ordering::Equal));
let mut parts = Vec::new();
let mut cursor = lo;
for [a, b] in clipped {
if a > cursor + EPS {
parts.push([cursor, a]);
}
if b > cursor {
cursor = b;
}
}
if cursor < hi - EPS {
parts.push([cursor, hi]);
}
parts
}
/// Decken-z-Cutter auf `[lo, hi]` je Terminierung: ausstanzen (beide), unter der Decke enden,
/// über der Decke beginnen.
fn terminate_or_subtract(lo: f64, hi: f64, cutters: &[[f64; 2]], term: Termination) -> Vec<[f64; 2]> {
if cutters.is_empty() {
return vec![[lo, hi]];
}
match term {
Termination::Below => {
let clip_top = cutters.iter().fold(f64::INFINITY, |m, c| m.min(c[0]));
let top = clip_top.min(hi);
if top > lo + EPS {
vec![[lo, top]]
} else {
vec![]
}
}
Termination::Above => {
let clip_bottom = cutters.iter().fold(f64::NEG_INFINITY, |m, c| m.max(c[1]));
let bottom = clip_bottom.max(lo);
if bottom < hi - EPS {
vec![[bottom, hi]]
} else {
vec![]
}
}
Termination::Both => subtract_spans(lo, hi, cutters),
}
}
/// Achsen-Distanz, an der die Band-Mittellinie die Schnittlinie trifft (`None`: parallel).
fn band_cut_distance(w: &WallIn, u: Vec2, n: Vec2, offset: f64, cut: &Line) -> Option<f64> {
let base = add(w.start, scale(n, offset));
let hit = line_intersect(base, u, cut.point, cut.dir)?;
Some(dot(sub(hit, w.start), u))
}
/// Sammelt die Körper; `emit_piece` des layered-Pfads je Band.
struct Emitter<'a> {
w: &'a WallIn,
out: Vec<Piece>,
}
impl Emitter<'_> {
/// `pushSegment`: Achsenstück [from, to] × [zb, zt], quer um `offset` versetzt.
fn push(&mut self, band: usize, from: f64, to: f64, zb: f64, zt: f64, offset: f64, holes: Vec<[f64; 4]>, drop: [f64; 2]) {
if to - from <= EPS || zt - zb <= EPS {
return;
}
let (dx, dy) = (self.w.end.x - self.w.start.x, self.w.end.y - self.w.start.y);
let len = js_hypot(dx, dy);
if len < 1e-9 {
return;
}
let (ux, uy) = (dx / len, dy / len);
let (ox, oy) = (-uy * offset, ux * offset);
let s = self.w.start;
self.out.push(Piece {
band,
start: Vec2::new(s.x + ux * from + ox, s.y + uy * from + oy),
end: Vec2::new(s.x + ux * to + ox, s.y + uy * to + oy),
z_bottom: zb,
z_top: zt,
top_drop: (drop[0] > EPS || drop[1] > EPS).then_some(drop),
holes,
});
}
}
/// Oberkante des Bands unter den Dächern: Dach-Unterkante entlang der Achse abtasten, zu geraden
/// Stücken (Toleranz 2 mm) zusammenfassen, Knicke exakt als Schnitt der Nachbargeraden; je Stück
/// ein Körper mit schräger Oberkante. Ohne Dach darüber: ein Körper, unverändert.
#[allow(clippy::too_many_arguments)]
fn clip_to_roofs(w: &WallIn, ctx: &FloorContext, u: Vec2, n: Vec2, offset: f64, a: f64, bb: f64, zb: f64, zt: f64, emit: &mut dyn FnMut(f64, f64, f64, f64, f64)) {
if zt - zb <= EPS || bb - a <= EPS {
return;
}
let wb = wall_bounds(w, offset.abs() + 0.01);
let roofs: Vec<&RoofIn> = ctx.roofs.iter().filter(|(r, rb)| r.eaves_z + 50.0 >= zb && bounds_overlap(wb, *rb)).map(|(r, _)| r).collect();
if roofs.is_empty() {
emit(a, bb, zb, zt, zt);
return;
}
let span = bb - a;
let count = 1usize.max((span / ROOF_CLIP_STEP).ceil() as usize);
let top_at = |t: f64| {
let tt = (bb - 1e-3).min((a + 1e-3).max(t));
let p = add(add(w.start, scale(u, tt)), scale(n, offset));
let mut clip = zt;
for r in &roofs {
if let Some(under) = roof_underside_at(&r.planes, r.total_thickness, p.x, p.y) {
if under < clip {
clip = under;
}
}
}
zb.max(clip)
};
let mut ts = Vec::with_capacity(count + 1);
let mut tops = Vec::with_capacity(count + 1);
for i in 0..=count {
ts.push(a + (span * i as f64) / count as f64);
tops.push(top_at(ts[i]));
}
const TOL: f64 = 0.002;
let mut runs: Vec<(usize, usize)> = Vec::new();
let mut i0 = 0;
while i0 < count {
let mut i1 = i0 + 1;
while i1 < count {
let k = i1 + 1;
let slope = (tops[k] - tops[i0]) / (ts[k] - ts[i0]);
let ok = (i0 + 1..=k).all(|m| (tops[i0] + slope * (ts[m] - ts[i0]) - tops[m]).abs() <= TOL);
if !ok {
break;
}
i1 = k;
}
runs.push((i0, i1));
i0 = i1;
}
let line = |r: (usize, usize)| {
let m = (tops[r.1] - tops[r.0]) / (ts[r.1] - ts[r.0]);
(m, tops[r.0] - m * ts[r.0])
};
let mut cuts = vec![a];
for r in 0..runs.len().saturating_sub(1) {
let l1 = line(runs[r]);
let l2 = line(runs[r + 1]);
let lo = ts[runs[r].1 - 1];
let hi = ts[count.min(runs[r].1 + 1)];
let mut x = ts[runs[r].1];
if (l1.0 - l2.0).abs() > 1e-9 {
let cx = (l2.1 - l1.1) / (l1.0 - l2.0);
if cx >= lo && cx <= hi {
x = cx;
}
}
cuts.push(x);
}
cuts.push(bb);
for (k, &r) in runs.iter().enumerate() {
let (sa, sb) = (cuts[k], cuts[k + 1]);
if sb - sa <= EPS {
continue;
}
let value_at = |x: f64| {
let l = line(r);
zt.min(zb.max(l.0 * x + l.1))
};
let (z0, z1) = (value_at(sa), value_at(sb));
if z0.max(z1) - zb > EPS {
emit(sa, sb, zb, z0, z1);
}
}
}
/// Band-Versätze (Mitte je Band, entlang der linken Normalen, relativ zur Achse).
fn band_offsets(w: &WallIn) -> Vec<f64> {
if !w.stacked {
return w.bands.iter().map(|b| reference_offset(w.reference, b.thickness)).collect();
}
let total = w.bands.iter().fold(0.0, |s, b| s + b.thickness);
let ref_off = reference_offset(w.reference, total);
let mut prefix = 0.0;
w.bands
.iter()
.map(|b| {
let o = ref_off - total / 2.0 + prefix + b.thickness / 2.0;
prefix += b.thickness;
o
})
.collect()
}
/// Alle Körper EINER Wand, in der Reihenfolge der früheren TS-Emission.
pub fn wall_bands(w: &WallIn, ctx: &FloorContext) -> Vec<Piece> {
let mut em = Emitter { w, out: Vec::new() };
let axis_len = js_hypot(w.end.x - w.start.x, w.end.y - w.start.y);
if axis_len < 1e-9 || w.z_top - w.z_bottom <= EPS {
return em.out;
}
let offsets = band_offsets(w);
let (z_bottom, z_top) = (w.z_bottom, w.z_top);
let mut cutouts = w.openings.clone();
cutouts.sort_by(|a, b| a.from.partial_cmp(&b.from).unwrap_or(std::cmp::Ordering::Equal));
if !w.layered {
// Schnitt-Pfad: Pfeiler/Brüstung/Sturz, je Segment alle Bänder.
let seg = |em: &mut Emitter, from: f64, to: f64, zb: f64, zt: f64| {
for (i, &off) in offsets.iter().enumerate() {
em.push(i, from, to, zb, zt, off, vec![], [0.0, 0.0]);
}
};
if cutouts.is_empty() {
seg(&mut em, 0.0, axis_len, z_bottom, z_top);
return em.out;
}
let mut cursor = 0.0f64;
for c in &cutouts {
let seg_from = cursor.max(c.from);
if c.from > cursor {
seg(&mut em, cursor, c.from, z_bottom, z_top);
}
if c.to > seg_from {
if c.z_bottom > z_bottom + EPS {
seg(&mut em, seg_from, c.to, z_bottom, c.z_bottom);
}
if c.z_top < z_top - EPS {
seg(&mut em, seg_from, c.to, c.z_top, z_top);
}
}
cursor = cursor.max(c.to);
}
if cursor < axis_len {
seg(&mut em, cursor, axis_len, z_bottom, z_top);
}
return em.out;
}
let cuts = &w.cuts;
let u = Vec2::new((w.end.x - w.start.x) / axis_len, (w.end.y - w.start.y) / axis_len);
let n = left_normal(u);
let cutters = ceiling_cutters(w, ctx);
let n_bands = w.bands.len();
for (li, b) in w.bands.iter().enumerate() {
let off = offsets[li];
// (1) Cuts an den Achsenenden (pro Schicht, falls materialbewusst).
let (s_cut, e_cut) = match &cuts.layer_cuts {
Some(lc) => (lc.start.get(li).copied().flatten(), lc.end.get(li).copied().flatten()),
None => (cuts.start_cut, cuts.end_cut),
};
let mut from0 = 0.0;
let mut to0 = axis_len;
if let Some(c) = s_cut {
if let Some(d) = band_cut_distance(w, u, n, off, &c) {
from0 = d;
}
}
if let Some(c) = e_cut {
if let Some(d) = band_cut_distance(w, u, n, off, &c) {
to0 = d;
}
}
// (2) Nah-Putz-Aussparungen, die dieses Band quer treffen.
let band_lo = off - b.thickness / 2.0;
let band_hi = off + b.thickness / 2.0;
let axis_holes: Vec<[f64; 2]> = cuts
.span_cutouts
.iter()
.filter(|c| band_lo < c.off_a.max(c.off_b) - EPS && band_hi > c.off_a.min(c.off_b) + EPS)
.map(|c| [c.from, c.to])
.collect();
let axis_pieces = subtract_spans(from0, to0, &axis_holes);
// (3) Decken-Subtraktion je Band dort, wo der Decken-Umriss die Band-Mittellinie deckt.
let mut band_z_cuts: Vec<[f64; 4]> = Vec::new(); // from, to, zBottom, zTop
if let Some(bp) = b.priority {
for cc in &cutters {
if cc.priority <= bp {
continue;
}
for [ca, cb] in band_coverage(w, u, n, off, cc.outline, from0, to0) {
band_z_cuts.push([ca, cb, cc.z_bottom, cc.z_top]);
}
}
}
let innermost = li == n_bands - 1;
let recess = b.thickness;
let mut emit_piece = |a: f64, bb: f64, zb: f64, zt_start: f64, zt_end: f64| {
emit_band_piece(&mut em, li, off, &cutouts, innermost, recess, a, bb, zb, zt_start, zt_end);
};
for [a, bb] in axis_pieces {
let local: Vec<[f64; 4]> = band_z_cuts
.iter()
.map(|c| [a.max(c[0]), bb.min(c[1]), c[2], c[3]])
.filter(|c| c[1] > c[0] + EPS)
.collect();
if local.is_empty() {
clip_to_roofs(w, ctx, u, n, off, a, bb, z_bottom, z_top, &mut emit_piece);
continue;
}
let mut xs = vec![a, bb];
for c in &local {
xs.push(c[0]);
xs.push(c[1]);
}
xs.sort_by(|p, q| p.partial_cmp(q).unwrap_or(std::cmp::Ordering::Equal));
xs.dedup();
for i in 0..xs.len() - 1 {
let (xa, xb) = (xs[i], xs[i + 1]);
if xb - xa <= EPS {
continue;
}
let mid = (xa + xb) / 2.0;
let z_cutters: Vec<[f64; 2]> = local.iter().filter(|c| c[0] <= mid && c[1] >= mid).map(|c| [c[2], c[3]]).collect();
for [zb, zt] in terminate_or_subtract(z_bottom, z_top, &z_cutters, w.termination) {
clip_to_roofs(w, ctx, u, n, off, xa, xb, zb, zt, &mut emit_piece);
}
}
}
}
em.out
}
/// Ein Körper eines Bands im layered-Pfad: Öffnungs-Löcher auf den Körper-Start umrechnen (an der
/// innersten Schicht mit Laibungs-Rücksprung geweitet); schräge Oberkante mit Löchern geht in
/// render3d nicht → gestuft annähern.
#[allow(clippy::too_many_arguments)]
fn emit_band_piece(em: &mut Emitter, li: usize, off: f64, cutouts: &[OpeningIn], innermost: bool, recess: f64, a: f64, bb: f64, zb: f64, zt_start: f64, zt_end: f64) {
let zt = zt_start.max(zt_end);
let holes: Vec<[f64; 4]> = cutouts
.iter()
.filter(|h| h.z_top > zb + EPS && h.z_bottom < zt - EPS)
.map(|h| {
if innermost && h.recess_inner_layer {
[h.from - a - recess, h.to - a + recess, h.z_bottom - recess, h.z_top + recess]
} else {
[h.from - a, h.to - a, h.z_bottom, h.z_top]
}
})
.collect();
if !holes.is_empty() && (zt_start - zt_end).abs() > EPS {
let k = 1usize.max(((bb - a) / ROOF_CLIP_STEP).ceil() as usize);
for i in 0..k {
let sa = a + ((bb - a) * i as f64) / k as f64;
let sb = a + ((bb - a) * (i + 1) as f64) / k as f64;
let zm = zt_start + ((zt_end - zt_start) * (i as f64 + 0.5)) / k as f64;
emit_band_piece(em, li, off, cutouts, innermost, recess, sa, sb, zb, zm, zm);
}
return;
}
em.push(li, a, bb, zb, zt, off, holes, [zt - zt_start, zt - zt_end]);
}
// ── Flache Kodierung ─────────────────────────────────────────────────────────
//
// Geschosse: [nGeschosse, (nDecken, (zBottom, zTop, nPkt, (x, y)…, typOk, nSchichten,
// (dicke, prio|NaN)…)…, nDächer, (traufZ, schichtdicke, nPkt, (x, y)…, nFlächen,
// (m, (x, y, z)…)…)…)…]
// Wände: [nWände, (geschoss, sx, sy, ex, ey, zBottom, zTop, layered, stacked, refKind, refValue,
// dickeHülle, terminierung (0 beide, 1 unten, 2 oben), nBänder, (dicke, prio|NaN)…,
// nÖffnungen, (from, to, zBottom, zTop, rücksprung)…, <Cuts wie joins::encode_cuts>)…]
// geschoss: Index in die Geschosse (ausserhalb = ohne Decken/Dächer).
// Ausgabe: [nWände, (nKörper, (band, x1, y1, x2, y2, zBottom, zTop, schräg 0/1, drop0, drop1,
// nLöcher, (from, to, zBottom, zTop)…)…)…] — nWände < Eingabe, wenn der Puffer mittendrin
// kaputt ist; eine Wand mit ungültigen Werten (NaN …) hat keine Körper.
use crate::flat_read::Reader;
fn fin(v: &[f64]) -> bool {
v.iter().all(|x| x.is_finite())
}
/// Liest die Decken und Dächer eines Geschosses; einzelne ungültige fallen weg.
fn decode_context(r: &mut Reader) -> Option<FloorContext> {
let nc = r.count()?;
let mut ceilings = Vec::with_capacity(nc.min(1 << 12));
for _ in 0..nc {
let (czb, czt) = (r.num()?, r.num()?);
let outline = r.ring()?;
let type_ok = r.num()? != 0.0;
let nl = r.count()?;
let mut layers = Vec::with_capacity(nl.min(1 << 10));
let mut ok = fin(&[czb, czt]) && outline.iter().all(|p| fin(p));
for _ in 0..nl {
let (t, p) = (r.num()?, r.num()?);
ok &= t.is_finite() && !p.is_infinite();
layers.push((t, (!p.is_nan()).then_some(p)));
}
if ok {
let outline = outline.into_iter().map(|p| Vec2::new(p[0], p[1])).collect();
ceilings.push(CeilingIn { z_bottom: czb, z_top: czt, outline, layers: type_ok.then_some(layers) });
}
}
let nr = r.count()?;
let mut roofs = Vec::with_capacity(nr.min(1 << 12));
for _ in 0..nr {
let (ez, total) = (r.num()?, r.num()?);
let eaves = r.ring()?;
let np = r.count()?;
let mut planes = Vec::with_capacity(np.min(1 << 12));
for _ in 0..np {
let m = r.count()?;
planes.push(r.points3(m)?);
}
if fin(&[ez, total]) && eaves.iter().all(|p| fin(p)) && planes.iter().flatten().all(|p| fin(p)) {
roofs.push(RoofIn { eaves_z: ez, total_thickness: total, eaves, planes });
}
}
Some(FloorContext::new(ceilings, roofs))
}
/// Liest eine Wand: `None` = Puffer kaputt (Abbruch), `Some((geschoss, None))` = Werte ungültig.
fn decode_wall(r: &mut Reader) -> Option<(f64, Option<WallIn>)> {
let floor = r.num()?;
let (sx, sy, ex, ey, zb, zt) = (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?);
let (layered, stacked, kind, value, thick, term) = (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?);
let mut ok = fin(&[sx, sy, ex, ey, zb, zt, thick]);
let reference = match kind as i64 {
1 => Reference::Left,
2 => Reference::Right,
3 => {
ok &= value.is_finite();
Reference::Offset(value)
}
_ => Reference::Center,
};
let termination = match term as i64 {
1 => Termination::Below,
2 => Termination::Above,
_ => Termination::Both,
};
let nb = r.count()?;
let mut bands = Vec::with_capacity(nb.min(1 << 10));
for _ in 0..nb {
let (t, p) = (r.num()?, r.num()?);
ok &= t.is_finite() && !p.is_infinite();
bands.push(BandIn { thickness: t, priority: (!p.is_nan()).then_some(p) });
}
let no = r.count()?;
let mut openings = Vec::with_capacity(no.min(1 << 12));
for _ in 0..no {
let o = [r.num()?, r.num()?, r.num()?, r.num()?];
let recess = r.num()? != 0.0;
ok &= fin(&o);
openings.push(OpeningIn { from: o[0], to: o[1], z_bottom: o[2], z_top: o[3], recess_inner_layer: recess });
}
let cuts = crate::joins::decode_cuts(r)?;
let wall = WallIn {
start: Vec2::new(sx, sy),
end: Vec2::new(ex, ey),
z_bottom: zb,
z_top: zt,
layered: layered != 0.0,
stacked: stacked != 0.0,
reference,
thickness_safe: thick,
termination,
bands,
openings,
cuts,
};
Some((floor, ok.then_some(wall)))
}
fn encode_pieces(out: &mut Vec<f64>, pieces: &[Piece]) {
out.push(pieces.len() as f64);
for p in pieces {
out.extend([p.band as f64, p.start.x, p.start.y, p.end.x, p.end.y, p.z_bottom, p.z_top]);
match p.top_drop {
Some([d0, d1]) => out.extend([1.0, d0, d1]),
None => out.extend([0.0, 0.0, 0.0]),
}
out.push(p.holes.len() as f64);
for h in &p.holes {
out.extend(h);
}
}
}
/// Wände + Geschosse flach → Körper je Wand flach (s. Kodierung oben); nie ein Panic.
pub fn wall_bands_flat(walls: &[f64], floors: &[f64]) -> Vec<f64> {
let mut fr = Reader::new(floors);
let mut contexts = Vec::new();
if let Some(n) = fr.count() {
for _ in 0..n {
match decode_context(&mut fr) {
Some(c) => contexts.push(c),
None => break,
}
}
}
let empty = FloorContext::default();
let mut out = vec![0.0];
let mut r = Reader::new(walls);
let Some(n) = r.count() else { return out };
let mut done = 0usize;
for _ in 0..n {
let Some((floor, wall)) = decode_wall(&mut r) else { break };
let ctx = if floor >= 0.0 && floor.fract() == 0.0 { contexts.get(floor as usize).unwrap_or(&empty) } else { &empty };
let pieces = wall.map(|w| wall_bands(&w, ctx)).unwrap_or_default();
encode_pieces(&mut out, &pieces);
done += 1;
}
out[0] = done as f64;
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::joins::{compute_joins, JoinLayer, JoinWall, SpanCutout};
fn base(start: (f64, f64), end: (f64, f64), bands: Vec<BandIn>) -> WallIn {
WallIn {
start: Vec2::new(start.0, start.1),
end: Vec2::new(end.0, end.1),
z_bottom: 0.0,
z_top: 2.6,
layered: true,
stacked: true,
reference: Reference::Center,
thickness_safe: bands.iter().map(|b| b.thickness).sum(),
termination: Termination::Both,
bands,
openings: vec![],
cuts: WallCuts::default(),
}
}
fn band(t: f64, p: f64) -> BandIn {
BandIn { thickness: t, priority: Some(p) }
}
fn close(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-9
}
fn bands_of(w: &WallIn) -> Vec<Piece> {
wall_bands(w, &FloorContext::default())
}
/// Achsen-Länge eines Körpers.
fn plen(p: &Piece) -> f64 {
js_hypot(p.end.x - p.start.x, p.end.y - p.start.y)
}
#[test]
fn schichten_gestapelt_und_referenzversetzt() {
let mut w = base((0.0, 0.0), (4.0, 0.0), vec![band(0.1, 10.0), band(0.2, 50.0)]);
let p = bands_of(&w);
assert_eq!(p.len(), 2);
assert!(close(p[0].start.y, -0.1) && close(p[1].start.y, 0.05));
w.reference = Reference::Left; // Stapel um die halbe Dicke nach +n verschoben
let p = bands_of(&w);
assert!(close(p[0].start.y, 0.05) && close(p[1].start.y, 0.2));
}
#[test]
fn l_ecke_kuerzt_und_verlaengert_je_band() {
let jw = |s: (f64, f64), e: (f64, f64)| JoinWall {
start: Vec2::new(s.0, s.1),
end: Vec2::new(e.0, e.1),
reference: Reference::Center,
layers: Some(vec![JoinLayer { thickness: 0.1, component: Some(0), priority: 10.0 }, JoinLayer { thickness: 0.2, component: Some(1), priority: 50.0 }]),
};
let cuts = compute_joins(&[jw((0.0, 0.0), (4.0, 0.0)), jw((4.0, 0.0), (4.0, 3.0))]).unwrap();
let mut w = base((0.0, 0.0), (4.0, 0.0), vec![band(0.1, 10.0), band(0.2, 50.0)]);
w.cuts = cuts[0].clone();
let p = bands_of(&w);
// Gehrung: das aussen liegende Band (−n, unten) ist länger als das innere.
assert!(close(p[0].end.x, 4.0 + 0.1) && close(p[1].end.x, 4.0 - 0.05), "{p:?}");
assert!(close(p[0].start.x, 0.0));
}
#[test]
fn t_stoss_aussparung_bricht_band_auf() {
let mut w = base((0.0, 0.0), (6.0, 0.0), vec![band(0.02, 10.0), band(0.15, 50.0), band(0.015, 10.0)]);
w.cuts.span_cutouts.push(SpanCutout { from: 2.0, to: 2.15, off_a: 0.0925, off_b: 0.0775 });
let p = bands_of(&w);
// Aussenputz und Kern durchgehend, Innenputz (Band 2) in zwei Stücken.
assert_eq!(p.iter().filter(|q| q.band == 2).count(), 2);
assert_eq!(p.iter().filter(|q| q.band == 1).count(), 1);
}
#[test]
fn oeffnung_am_rand_und_ruecksprung() {
let mut w = base((0.0, 0.0), (3.0, 0.0), vec![band(0.15, 50.0), band(0.02, 10.0)]);
w.openings.push(OpeningIn { from: 0.0, to: 0.9, z_bottom: 0.0, z_top: 2.1, recess_inner_layer: false });
w.openings.push(OpeningIn { from: 2.0, to: 3.0, z_bottom: 0.9, z_top: 2.1, recess_inner_layer: true });
let p = bands_of(&w);
assert_eq!(p.len(), 2);
assert_eq!(p[0].holes.len(), 2);
assert_eq!(p[0].holes[1], [2.0, 3.0, 0.9, 2.1]);
let r = p[1].holes[1];
assert!(close(r[0], 1.98) && close(r[1], 3.02) && close(r[2], 0.88) && close(r[3], 2.12));
// Schnitt-Pfad: Pfeiler/Brüstung/Sturz ohne Löcher.
w.layered = false;
w.stacked = false;
w.bands = vec![BandIn { thickness: 0.17, priority: None }];
let s = bands_of(&w);
// Sturz Tür, Pfeiler, Brüstung + Sturz Fenster (Tür bis zum Rand: kein Pfeiler davor).
assert_eq!(s.len(), 4, "{s:?}");
assert!(s.iter().all(|q| q.holes.is_empty() && q.top_drop.is_none()));
}
#[test]
fn decke_hoeherer_prioritaet_schneidet_nur_schwache_baender() {
let mut w = base((0.0, 0.0), (4.0, 0.0), vec![band(0.15, 50.0), band(0.02, 10.0)]);
w.z_top = 3.0;
let outline = vec![Vec2::new(-1.0, -1.0), Vec2::new(5.0, -1.0), Vec2::new(5.0, 5.0), Vec2::new(-1.0, 5.0)];
let ctx = FloorContext::new(vec![CeilingIn { z_bottom: 2.6, z_top: 2.8, outline, layers: Some(vec![(0.2, Some(30.0))]) }], vec![]);
let p = wall_bands(&w, &ctx);
assert_eq!(p.iter().filter(|q| q.band == 0).count(), 1); // Kern (50) läuft durch
let weak: Vec<_> = p.iter().filter(|q| q.band == 1).collect();
assert_eq!(weak.len(), 2);
assert!(close(weak[0].z_top, 2.6) && close(weak[1].z_bottom, 2.8));
// Terminierung „below": endet an der Deckenunterkante, kein Rest darüber.
w.termination = Termination::Below;
let p = wall_bands(&w, &ctx);
assert_eq!(p.iter().filter(|q| q.band == 1).count(), 1);
}
#[test]
fn wand_unter_pultdach_bekommt_schraege_oberkante() {
let mut w = base((0.0, 0.0), (4.0, 0.0), vec![band(0.2, 50.0)]);
w.z_top = 5.0;
// Ebene z = 2 + 0.5·x über [−1, 5]².
let plane = vec![[-1.0, -1.0, 1.5], [5.0, -1.0, 4.5], [5.0, 5.0, 4.5], [-1.0, 5.0, 1.5]];
let roof = RoofIn { eaves_z: 1.5, total_thickness: 0.0, eaves: plane.iter().map(|p| [p[0], p[1]]).collect(), planes: vec![plane] };
let ctx = FloorContext::new(vec![], vec![roof]);
let p = wall_bands(&w, &ctx);
assert_eq!(p.len(), 1, "{p:?}");
let d = p[0].top_drop.unwrap();
// Abtastung 1 mm innerhalb der Enden (wie TS) → Toleranz 1e-3.
let near = |a: f64, b: f64| (a - b).abs() < 1e-3;
assert!(near(p[0].z_top, 4.0) && near(d[0], 2.0) && d[1] == 0.0, "{p:?}");
// Mit Öffnung: gestuft, ohne top_drop.
w.openings.push(OpeningIn { from: 1.0, to: 2.0, z_bottom: 0.0, z_top: 2.0, recess_inner_layer: false });
let p = wall_bands(&w, &ctx);
assert!(p.len() > 10 && p.iter().all(|q| q.top_drop.is_none()));
let total: f64 = p.iter().map(plen).sum();
assert!(close(total, 4.0));
}
#[test]
fn unsinn_ohne_panic() {
assert_eq!(wall_bands_flat(&[], &[]), vec![0.0]);
assert_eq!(wall_bands_flat(&[f64::NAN; 40], &[f64::NAN]), vec![0.0]);
assert_eq!(wall_bands_flat(&[0.0; 3], &[1.0, 5.0]), vec![0.0]);
// Nulllänge, umgekehrte Höhen, Öffnung ausserhalb, Bänder ohne Dicke, entartete Decke/Dach.
let mut w = base((1.0, 1.0), (1.0, 1.0), vec![band(0.2, 50.0)]);
assert!(bands_of(&w).is_empty());
w.end = Vec2::new(2.0, 1.0);
w.z_top = -1.0;
assert!(bands_of(&w).is_empty());
w.z_top = 2.0;
w.openings.push(OpeningIn { from: 5.0, to: -3.0, z_bottom: 9.0, z_top: -9.0, recess_inner_layer: true });
w.bands.push(band(0.0, 1.0));
let ctx = FloorContext::new(
vec![CeilingIn { z_bottom: 0.5, z_top: 0.5, outline: vec![Vec2::new(0.0, 0.0); 3], layers: Some(vec![]) }],
vec![RoofIn { eaves_z: 0.0, total_thickness: 0.0, eaves: vec![], planes: vec![vec![]] }],
);
let _ = wall_bands(&w, &ctx);
// Flach: zwei Wände (die zweite mit NaN-Koordinate → keine Körper), ein Geschoss.
let wall = |x: f64| {
let mut b = vec![0.0, x, 1.0, 2.0, 1.0, 0.0, 2.0, 1.0, 1.0, 0.0, 0.0, 0.2, 0.0, 1.0, 0.2, 50.0, 0.0];
crate::joins::encode_cuts(&mut b, &WallCuts::default());
b
};
let mut buf = vec![2.0];
buf.extend(wall(1.0));
buf.extend(wall(f64::NAN));
let floors = [1.0, 0.0, 0.0];
let out = wall_bands_flat(&buf, &floors);
assert_eq!(out[0], 2.0);
assert_eq!(out[1], 1.0); // ein Körper
assert_eq!(*out.last().unwrap(), 0.0); // zweite Wand: keine Körper
// Abgeschnittener Puffer: nur die vollständige erste Wand.
assert_eq!(wall_bands_flat(&buf[..buf.len() - 1], &floors)[0], 1.0);
// Kaputte Geschosse: Wände ohne Decken/Dächer.
assert_eq!(wall_bands_flat(&buf, &[3.0, 1.0])[0], 2.0);
}
}
+22
View File
@@ -0,0 +1,22 @@
//! Bindungen der Wand-Verschneidung (`crate::joins`). Kodierung s. dort.
use wasm_bindgen::prelude::wasm_bindgen;
/// Wände flach → `[0, (Cuts je Wand)…]`; `[1, wandIndex]` = Wandtyp/Bauteil unbekannt;
/// kaputte Eingabe → leer.
#[wasm_bindgen]
pub fn compute_joins_flat(walls: &[f64]) -> Vec<f64> {
crate::joins::compute_joins_flat(walls)
}
/// Verschneidungs-Entscheidung: 0 merge, 1 trim-a, 2 trim-b, 3 coexist.
#[wasm_bindgen]
pub fn join_priority_resolution(prio_a: f64, prio_b: f64, same_component: bool) -> u8 {
use crate::joins::JoinResolution::*;
match crate::joins::resolve_join_priority(prio_a, prio_b, same_component) {
Merge => 0,
TrimA => 1,
TrimB => 2,
Coexist => 3,
}
}
+2
View File
@@ -10,6 +10,8 @@ mod sun;
mod site_rules;
mod auto_dimensions;
mod kennzahlen;
mod joins;
mod wall_bands;
use wasm_bindgen::prelude::wasm_bindgen;
+9
View File
@@ -0,0 +1,9 @@
//! Bindungen der Wand-Schichtbänder (`crate::wall_bands`). Kodierung s. dort.
use wasm_bindgen::prelude::wasm_bindgen;
/// Wände + Geschosse (Decken, Dächer) flach → Körper je Wand flach; nie ein Panic.
#[wasm_bindgen]
pub fn wall_bands_flat(walls: &[f64], floors: &[f64]) -> Vec<f64> {
crate::wall_bands::wall_bands_flat(walls, floors)
}
+7 -2
View File
@@ -159,6 +159,12 @@ export function roofUndersideAt(
x: number,
y: number,
): number | null {
const z = core().roof_underside_at(roofPlanesFlat(geo), totalLayerThickness, x, y);
return Number.isNaN(z) ? null : z;
}
/** Dachflächen als flacher Puffer `[n, (m, (x, y, z)…)…]` (Kodierung `roof.rs`), je Geometrie gemerkt. */
export function roofPlanesFlat(geo: RoofGeometry): Float64Array {
let flat = planesFlat.get(geo);
if (!flat) {
const vals = [geo.planes.length];
@@ -169,6 +175,5 @@ export function roofUndersideAt(
flat = Float64Array.from(vals);
planesFlat.set(geo, flat);
}
const z = core().roof_underside_at(flat, totalLayerThickness, x, y);
return Number.isNaN(z) ? null : z;
return flat;
}
+87 -476
View File
@@ -1,22 +1,16 @@
// Wand-Verschneidung (Gehrung): an einer Ecke, wo zwei Wände aufeinander­
// treffen, sollen sich die Schicht-Bänder nicht überlappen, sondern an einer
// gemeinsamen Gehrungslinie sauber stoßen. Dieses Modul berechnet pro Wand
// die optionalen Schnittlinien an Start- und Endpunkt.
// gemeinsamen Gehrungslinie sauber stoßen. Pro Wand entstehen die optionalen
// Schnittlinien an Start- und Endpunkt.
//
// Gerechnet wird im Rust-Kern (`src-tauri/core/src/joins.rs`); hier bleiben die
// Typen, das Sammeln der Wand-Angaben aus dem `Project` und die flache Übergabe.
import type { Component, Project, Vec2, Wall } from "./types";
import { getComponent, getWallType, wallTypeThickness } from "./types";
import { wallReferenceOffset } from "./wall";
import {
add,
dot,
leftNormal,
len,
lineIntersect,
normalize,
scale,
sub,
} from "./geometry";
import type { Component, Project, Wall } from "./types";
import { getComponent, getWallType } from "./types";
import type { Line } from "./geometry";
import { core } from "../engine/coreWasm";
import { FlatReader, FlatWriter } from "../geometry/coreFlat";
/**
* Pro-Schicht-Override der Nahflächen-Cuts (materialbewusster T-Stoss, siehe
@@ -89,25 +83,13 @@ export interface WallCuts {
*/
export type JoinPriorityResolution = "merge" | "trim-a" | "trim-b" | "coexist";
const RESOLUTIONS: JoinPriorityResolution[] = ["merge", "trim-a", "trim-b", "coexist"];
export function resolveJoinPriority(
a: Component,
b: Component,
): JoinPriorityResolution {
if (a.joinPriority === b.joinPriority) {
return a.id === b.id ? "merge" : "coexist";
}
return a.joinPriority > b.joinPriority ? "trim-b" : "trim-a";
}
/** Rundet eine Koordinate auf ein Gitter, um Endpunkte robust zu gruppieren. */
const roundKey = (p: Vec2): string => {
const r = (v: number) => Math.round(v * 1e4) / 1e4;
return `${r(p.x)},${r(p.y)}`;
};
interface WallEnd {
wallId: string;
end: "start" | "end";
return RESOLUTIONS[core().join_priority_resolution(a.joinPriority, b.joinPriority, a.id === b.id)] ?? "coexist";
}
/**
@@ -116,470 +98,99 @@ interface WallEnd {
* (drei Wandenden treffen sich, zwei davon kollinear), Mittelspannen-T-Stöße
* (ein freies Wandende trifft auf die Seite einer anderen Wand) UND „+"-
* Kreuzungen (zwei kollineare Wandenden treffen sich exakt auf der Achse einer
* dritten, durchlaufenden Wand — z. B. wenn eine durchgehende Trennwand von
* einer weiteren durchgehenden Wand gekreuzt wird). Nur echte Stern-Knoten
* (vier oder mehr Wand-STUMMEL enden alle exakt am selben Punkt, OHNE dass
* eine von ihnen als Durchgang erkennbar ist) bleiben rechtwinklig — dafür
* fehlt eine eindeutige Rangfolge, welches Ende „durch" und welches „Abzweig"
* wäre.
* dritten, durchlaufenden Wand). Echte Stern-Knoten (vier oder mehr Wand-
* STUMMEL am selben Punkt, keiner als Durchgang erkennbar) bleiben rechtwinklig.
* An T-Stössen kommen die materialbewussten Pro-Schicht-Cuts (`layerCuts`) und
* die Nah-Putz-Aussparungen der Durchgangswand (`spanCutouts`) dazu.
*
* `walls` ist die bereits gefilterte Wandmenge (z. B. ein Geschoss); die
* Gehrung wird nur innerhalb dieser Menge gebildet.
* Gehrung wird nur innerhalb dieser Menge gebildet. Wirft wie früher, wenn ein
* benötigter Wandtyp oder ein Bauteil unbekannt ist.
*/
export function computeJoins(
project: Project,
walls: Wall[],
): Map<string, WallCuts> {
const byId = new Map(walls.map((w) => [w.id, w]));
const w = new FlatWriter().num(walls.length);
const compIndex = new Map<string, number>();
for (const wall of walls) {
w.num(wall.start.x, wall.start.y, wall.end.x, wall.end.y);
if (wall.referenceOffset != null) w.num(3, wall.referenceOffset);
else w.num(wall.referenceLine === "left" ? 1 : wall.referenceLine === "right" ? 2 : 0, 0);
const wt = project.wallTypes.find((t) => t.id === wall.wallTypeId);
if (!wt) {
w.num(0, 0);
continue;
}
w.num(1, wt.layers.length);
for (const l of wt.layers) {
const comp = project.components.find((c) => c.id === l.componentId);
let idx = -1;
if (comp) {
idx = compIndex.get(comp.id) ?? compIndex.size;
compIndex.set(comp.id, idx);
}
w.num(l.thickness, idx, comp ? comp.joinPriority : Number.NaN);
}
}
const out = core().compute_joins_flat(w.done());
const r = new FlatReader(out);
const status = r.num();
if (status === 1) {
// Wandtyp oder Bauteil unbekannt: denselben Fehler werfen wie die Modell-Helfer.
const bad = walls[r.num()];
if (bad) for (const l of getWallType(project, bad).layers) getComponent(project, l.componentId);
throw new Error("computeJoins: unbekannter Wandtyp oder Bauteil");
}
const result = new Map<string, WallCuts>();
for (const w of walls) result.set(w.id, { startCut: null, endCut: null });
// Knotenkarte: gerundeter Endpunkt → Liste der dort endenden Wandenden.
const junctions = new Map<string, WallEnd[]>();
const push = (p: Vec2, we: WallEnd) => {
const key = roundKey(p);
const list = junctions.get(key);
if (list) list.push(we);
else junctions.set(key, [we]);
};
for (const w of walls) {
push(w.start, { wallId: w.id, end: "start" });
push(w.end, { wallId: w.id, end: "end" });
if (status !== 0) {
// Kaputte Eingabe (z. B. NaN-Koordinaten): keine Verschneidung.
for (const wall of walls) result.set(wall.id, { startCut: null, endCut: null });
return result;
}
for (const [, ends] of junctions) {
// Freies Ende → kein Schnitt hier (wird unten separat auf Mittelspannen-T
// geprüft, Fall 2).
if (ends.length === 1) continue;
if (ends.length === 2) {
const a = byId.get(ends[0].wallId)!;
const b = byId.get(ends[1].wallId)!;
const cut = miterLine(project, a, ends[0].end, b);
if (!cut) continue; // kollinear → kein Schnitt
setCut(result, ends[0], cut);
setCut(result, ends[1], cut);
continue;
}
if (ends.length === 3) {
applyTJunction(project, byId, ends, result);
continue;
}
// Echte Stern-Knoten (≥4 WANDENDEN treffen sich exakt hier, KEINS läuft
// als Durchgangswand weiter) bleiben vorerst rechtwinklig (Folge-Arbeit) —
// dafür gibt es (noch) keine eindeutige Rangfolge, welches Ende „durch"
// und welches „Abzweig" ist. Der weit häufigere Fall — eine durchlaufende
// Wand wird von zwei (oder mehr) an ihrem Knoten endenden Wänden gekreuzt,
// eine „+"/„X"-Kreuzung — greift unten in Fall 2, weil dort JEDES noch
// ungeschnittene Ende zusätzlich gegen die Mittelspanne aller anderen
// Wände geprüft wird (nicht nur echte Einzel-Enden wie bisher).
}
// Fall 2: Mittelspannen-T-Stoß, verallgemeinert. Jedes Wandende, das nach
// Fall 1 noch UNGESCHNITTEN ist — das schliesst nicht nur echte Einzel-Enden
// ein, sondern auch die beiden kollinearen Hälften eines 2er-/3er-Knotens
// (die bewusst ungeschnitten bleiben, s. o.) —, wird zusätzlich geprüft, ob
// es auf die Mittelspanne (nicht das Ende) einer WEITEREN, an diesem Knoten
// gar nicht beteiligten Wand trifft. Das deckt genau die „+"-Kreuzung ab:
// zwei kollineare Wandhälften enden an einem Punkt, DURCH den eine dritte,
// durchlaufende Wand hindurchläuft (sonst für Fall 1 unsichtbar, weil sie
// dort keinen eigenen Endpunkt hat) — beide Hälften bekommen unabhängig
// voneinander (mit jeweils eigenem Vorzeichen/zugewandter Fläche) einen
// Schnitt gegen die durchlaufende Wand, die selbst unangetastet bleibt.
// Bereits geschnittene Enden (L-Ecke, T-Abzweig) werden NICHT erneut
// angefasst — additiv, bit-identisch zum bisherigen Verhalten überall sonst.
for (const [, ends] of junctions) {
for (const end of ends) {
const cuts = result.get(end.wallId)!;
if (end.end === "start" ? cuts.startCut : cuts.endCut) continue;
applyMidSpanTee(project, byId, walls, end, result);
}
}
for (const wall of walls) result.set(wall.id, readWallCuts(r));
return result;
}
/** Trägt eine Schnittlinie am passenden Ende einer Wand ein. */
function setCut(result: Map<string, WallCuts>, we: WallEnd, cut: Line): void {
const cuts = result.get(we.wallId)!;
if (we.end === "start") cuts.startCut = cut;
else cuts.endCut = cut;
// ── Flache Kodierung der Cuts (s. `joins.rs`), auch für `toWalls3d/bands.ts` ──
function writeLine(w: FlatWriter, l: Line | null | undefined): void {
if (l) w.num(1, l.point.x, l.point.y, l.dir.x, l.dir.y);
else w.num(0, 0, 0, 0, 0);
}
/** Achsrichtung start→end, normalisiert. */
const dirOf = (w: Wall): Vec2 => normalize(sub(w.end, w.start));
/**
* Gemeinsame Gehrungslinie zweier Wände A, B, die sich im Knoten J treffen.
* Robust gegen beliebige Wicklung, ungleiche Dicken und JEDEN Öffnungswinkel
* (inkl. spitzer): Die Wandflächen werden orientierungsbasiert (vorzeichen­
* richtig) gepaart — A's Außenfläche verschneidet B's Außenfläche zum äußeren
* Apex, A's Innenfläche B's Innenfläche zum inneren Apex. „Außen" ist jeweils
* die vom Körper der anderen Wand ABGEWANDTE Fläche. Die Gerade durch beide
* Apexe ist die Gehrung; sie trennt beide Wandbänder überlappungsfrei.
*
* Die frühere Distanz-Heuristik („nächstgelegene B-Fläche") kippt bei spitzen
* Winkeln — dort wird die falsche Fläche zur näheren, sodass Außen mit Innen
* gepaart wird und die Poché-Bänder sich kreuzweise überlappen.
*/
function miterLine(
project: Project,
a: Wall,
aEnd: "start" | "end",
b: Wall,
): Line | null {
const j = aEnd === "start" ? a.start : a.end;
const tA = wallTypeThickness(getWallType(project, a));
const tB = wallTypeThickness(getWallType(project, b));
const uA = dirOf(a);
const uB = dirOf(b);
const nA = leftNormal(uA);
const nB = leftNormal(uB);
// Referenzlinien-Versatz: liegt die Achse nicht mittig, sind die beiden
// Wandflächen um diesen Betrag entlang +n verschoben (außen −T/2+off, innen
// +T/2+off). Für „center" (Default) ist off=0 → unverändert.
const offA = wallReferenceOffset(a, tA);
const offB = wallReferenceOffset(b, tB);
// Flächen-Stützpunkte am Knoten: linke Fläche liegt auf +n, rechte auf −n
// (inkl. Referenzversatz).
const pLA = add(j, scale(nA, offA + tA / 2));
const pRA = add(j, scale(nA, offA - tA / 2));
const pLB = add(j, scale(nB, offB + tB / 2));
const pRB = add(j, scale(nB, offB - tB / 2));
// Auslauf-Richtungen der Achsen vom Knoten weg, in den jeweiligen Wandkörper.
const dA = aEnd === "start" ? uA : scale(uA, -1);
const bAtStart = len(sub(b.start, j)) <= len(sub(b.end, j));
const dB = bAtStart ? uB : scale(uB, -1);
// Orientierungsbasierte, vorzeichenrichtige Flächen-Paarung. „Außen" ist die
// vom Körper der anderen Wand ABGEWANDTE Fläche: A's +nA-Fläche (pLA) liegt
// außen, wenn nA·dB < 0; B's +nB-Fläche (pLB) außen, wenn nB·dA < 0. Gepaart
// wird Außen-mit-Außen und Innen-mit-Innen — nie über Kreuz. (nA·dB = 0 tritt
// nur bei kollinearen Achsen auf; dann sind die Flächen parallel und
// lineIntersect liefert unten ohnehin null.)
const bOuter = dot(nB, dA) < 0 ? pLB : pRB;
const bInner = dot(nB, dA) < 0 ? pRB : pLB;
const aLeftIsOuter = dot(nA, dB) < 0;
const bForLeft = aLeftIsOuter ? bOuter : bInner;
const bForRight = aLeftIsOuter ? bInner : bOuter;
// c1 an A's linke Fläche (pLA), c2 an A's rechte (pRA) gebunden — Reihenfolge
// wie zuvor, damit rechte/stumpfe Ecken bit-identisch bleiben; nur die
// B-Partnerwahl ist jetzt orientierungs- statt distanzbasiert.
const c1 = lineIntersect(pLA, uA, bForLeft, uB);
const c2 = lineIntersect(pRA, uA, bForRight, uB);
if (!c1 || !c2) return null;
const dir = sub(c2, c1);
if (len(dir) < 1e-9) return null;
return { point: c1, dir };
function readLine(r: FlatReader): Line | null {
const set = r.num();
const point = { x: r.num(), y: r.num() };
const dir = { x: r.num(), y: r.num() };
return set === 1 ? { point, dir } : null;
}
/**
* Fall 1 — T-Knoten: drei Wandenden treffen sich im selben (gerundeten)
* Knoten. Typisch sind zwei davon kollinear (die zwei Hälften der
* Durchgangswand, die geometrisch als eine Achse durchläuft) und das dritte
* zweigt ab. Die kollinearen zwei bleiben ungeschnitten; der Abzweig bekommt
* einen Schnitt entlang der ihm zugewandten Fläche der Durchgangswand.
* Findet sich kein eindeutig kollineares Paar (z. B. echter Y-/X-Knoten),
* bleibt der Knoten unangetastet (rechtwinklig).
*/
function applyTJunction(
project: Project,
byId: Map<string, Wall>,
ends: WallEnd[],
result: Map<string, WallCuts>,
): void {
const dirs = ends.map((e) => dirOf(byId.get(e.wallId)!));
// Suche das (näherungsweise) kollineare Paar: |cos(Winkel der Achsen)| ≈ 1.
let throughPair: [number, number] | null = null;
for (let i = 0; i < 3 && !throughPair; i++) {
for (let k = i + 1; k < 3; k++) {
if (1 - Math.abs(dot(dirs[i], dirs[k])) < 1e-6) {
throughPair = [i, k];
break;
}
}
}
if (!throughPair) return; // kein eindeutiger Durchgang erkennbar
const branchIdx = [0, 1, 2].find(
(i) => i !== throughPair![0] && i !== throughPair![1],
)!;
const branchEnd = ends[branchIdx];
const throughEnd = ends[throughPair[0]];
const branchWall = byId.get(branchEnd.wallId)!;
const throughWall = byId.get(throughEnd.wallId)!;
const j = throughEnd.end === "start" ? throughWall.start : throughWall.end;
const tT = wallTypeThickness(getWallType(project, throughWall));
const uT = dirOf(throughWall);
const nT = leftNormal(uT);
const offT = wallReferenceOffset(throughWall, tT);
// Auslaufrichtung des Abzweigs vom Knoten weg, in seinen eigenen Körper
// (gleiche Konvention wie dA/dB in miterLine).
const dBranch =
branchEnd.end === "start"
? dirOf(branchWall)
: scale(dirOf(branchWall), -1);
// Zugewandte Fläche: die Seite der Durchgangsachse, zu der der Abzweig
// zeigt (positive nT-Seite, wenn der Abzweig dorthin ausläuft).
const sign = dot(nT, dBranch) >= 0 ? 1 : -1;
const facePoint = add(j, scale(nT, offT + sign * (tT / 2)));
const faceCut: Line = { point: facePoint, dir: uT };
setCut(result, branchEnd, faceCut);
applyLayerCuts(project, result, branchEnd, branchWall, throughWall, faceCut, j, uT, sign);
/** Hängt die Cuts einer Wand flach an (fehlend = keine Cuts). */
export function writeWallCuts(w: FlatWriter, cuts: WallCuts | undefined): void {
writeLine(w, cuts?.startCut);
writeLine(w, cuts?.endCut);
const lc = cuts?.layerCuts;
const n = lc ? lc.start.length : 0;
w.num(n);
if (lc) for (const arr of [lc.start, lc.end, lc.startSide, lc.endSide]) for (let i = 0; i < n; i++) writeLine(w, arr[i]);
const sc = cuts?.spanCutouts ?? [];
w.num(sc.length);
for (const s of sc) w.num(s.from, s.to, s.offA, s.offB);
}
/**
* Materialbewusste Pro-Schicht-Erweiterung eines T-Stoss-Cuts (siehe
* {@link resolveJoinPriority}): vergleicht jede Schicht der ABZWEIG-Wand mit
* dem Rückgrat (höchste `joinPriority`) der DURCHGANGSWAND. Verschmilzt eine
* Schicht (gleiche Komponente + Priorität wie das Rückgrat, oder die
* Abzweig-Schicht ist sogar prioritärer), bekommt sie einen Cut an der
* NAHFLÄCHE DES RÜCKGRAT-KERNS der Durchgangswand: der verschmelzende Abzweig-
* Kern (z. B. Backstein) sticht nur durch den Nah-Putz der Durchgangswand und
* stoppt am Durchgangs-Kern — er läuft NICHT bis zur Achse durch und überlappt
* die Durchgangswand nicht (dort verschmelzen die beiden Kerne nahtlos).
* Getrimmte Schichten, die direkt an eine verschmelzende Nachbarschicht
* grenzen, bekommen zusätzlich eine seitliche Cut-Linie an eben dieser
* Rückgrat-Nahfläche (L-Anschluss, z. B. Putz neben durchstechendem Kern).
*
* Setzt `WallCuts.layerCuts` NUR, wenn mindestens eine Schicht verschmilzt —
* sonst bleibt das Feld `undefined` (additiv, bit-identisches Default-
* Verhalten für den ganz überwiegenden Fall ohne Materialübereinstimmung).
*
* `sign` ist die Nahseite der Durchgangswand (der Abzweig-zugewandte `nT`-
* Vorzeichen, aus {@link applyTJunction}/{@link applyMidSpanTee}); er bestimmt,
* welche Durchgangswand-Schichten als Nah-Putz vor dem Rückgrat liegen.
*/
function applyLayerCuts(
project: Project,
result: Map<string, WallCuts>,
branchEnd: WallEnd,
branchWall: Wall,
throughWall: Wall,
faceCut: Line,
axisPoint: Vec2,
throughDir: Vec2,
sign: number,
): void {
const branchWt = getWallType(project, branchWall);
const throughWt = getWallType(project, throughWall);
if (branchWt.layers.length === 0 || throughWt.layers.length === 0) return;
// Rückgrat der Durchgangswand: die Schicht mit der höchsten joinPriority
// (Index mitgeführt, um die Nah-Putz-Dicke davor zu bestimmen).
let backbone = getComponent(project, throughWt.layers[0].componentId);
let backboneIdx = 0;
for (let i = 0; i < throughWt.layers.length; i++) {
const c = getComponent(project, throughWt.layers[i].componentId);
if (c.joinPriority > backbone.joinPriority) {
backbone = c;
backboneIdx = i;
}
/** Liest die Cuts einer Wand; `layerCuts`/`spanCutouts` nur, wenn vorhanden. */
export function readWallCuts(r: FlatReader): WallCuts {
const cuts: WallCuts = { startCut: readLine(r), endCut: readLine(r) };
const n = r.count();
if (n > 0) {
const arr = () => Array.from({ length: n }, () => readLine(r));
cuts.layerCuts = { start: arr(), end: arr(), startSide: arr(), endSide: arr() };
}
const n = branchWt.layers.length;
const merged: boolean[] = new Array(n);
for (let i = 0; i < n; i++) {
const comp = getComponent(project, branchWt.layers[i].componentId);
const res = resolveJoinPriority(comp, backbone);
// "merge": identisches Rückgrat-Material -> durchgehender Kern.
// "trim-b": die Abzweig-Schicht ist SELBST prioritärer als das Rückgrat
// der Durchgangswand -> sie gewinnt ebenfalls und läuft durch (die
// Durchgangswand könnten wir hier nicht schneiden, ausserhalb des Scopes).
merged[i] = res === "merge" || res === "trim-b";
}
if (!merged.some(Boolean)) return; // keine Materialübereinstimmung -> Default
const cuts = result.get(branchWall.id)!;
if (!cuts.layerCuts) {
cuts.layerCuts = {
start: new Array(n).fill(null),
end: new Array(n).fill(null),
startSide: new Array(n).fill(null),
endSide: new Array(n).fill(null),
};
}
const lc = cuts.layerCuts;
if (lc.start.length !== n) return; // Schicht-Anzahl passt nicht zusammen (sollte nicht vorkommen)
const faceArr = branchEnd.end === "start" ? lc.start : lc.end;
const sideArr = branchEnd.end === "start" ? lc.startSide : lc.endSide;
// Nahflächen-Cut des verschmelzenden Kerns: von der Durchgangswand-Nahfläche
// (`offT + sign·tT/2`) um die Nah-Putz-Dicke nach innen versetzt — also genau
// die dem Abzweig zugewandte Fläche des Rückgrat-Kerns. Nah-Putz = Summe der
// Durchgangswand-Schichten, die zwischen der Nahseite (sign) und dem Rückgrat
// liegen. Die Schichten stapeln entlang +nT (Index 0 = −tT/2); auf der
// +nT-Nahseite (sign>0) sind das die Schichten HINTER dem Rückgrat
// (Index > backboneIdx), auf der −nT-Nahseite die davor (Index < backboneIdx).
const tT = wallTypeThickness(throughWt);
const offT = wallReferenceOffset(throughWall, tT);
let nearPlaster = 0;
for (let i = 0; i < throughWt.layers.length; i++) {
if (sign > 0 ? i > backboneIdx : i < backboneIdx)
nearPlaster += throughWt.layers[i].thickness;
}
const nT = leftNormal(throughDir);
const mergePoint = add(
axisPoint,
scale(nT, offT + sign * (tT / 2 - nearPlaster)),
);
const mergeCut: Line = { point: mergePoint, dir: throughDir };
// Getrimmte Nachbarschichten schließen mit ihrer L-Seitenlinie an eben dieser
// Rückgrat-Nahfläche (nicht an der Wandachse) — dort endet der Kern und die
// Nachbarschicht kappt ihre Breite.
const sideLine: Line = mergeCut;
// Materialien des durchgehenden Nah-Putzes der Durchgangswand (dieselbe
// sign-Seite wie die nearPlaster-Summe oben). Ist die getrimmte Abzweig-Schicht
// materialgleich mit einer davon, füllt der Nah-Putz den Abzweig-Putz an dieser
// Stelle durchgehend (der spanCutout schneidet nur die KERN-Breite aus, nicht
// die schmalen Putzflanken) → Putz-L OHNE Trennnaht, also KEINE L-Seitenlinie.
const nearPlasterComps = new Set<string>();
for (let i = 0; i < throughWt.layers.length; i++) {
if (sign > 0 ? i > backboneIdx : i < backboneIdx)
nearPlasterComps.add(throughWt.layers[i].componentId);
}
for (let i = 0; i < n; i++) {
faceArr[i] = merged[i] ? mergeCut : faceCut;
const adjMerged =
!merged[i] && ((i > 0 && merged[i - 1]) || (i < n - 1 && merged[i + 1]));
const mergesWithNearPlaster = nearPlasterComps.has(branchWt.layers[i].componentId);
sideArr[i] = adjMerged && !mergesWithNearPlaster ? sideLine : null;
}
// Durchgangswand-Aussparung (Phase 1c): den Nah-Putz der Durchgangswand über
// die Breite des durchstechenden Abzweig-Kerns ECHT ausschneiden. Nur nötig,
// wenn davor überhaupt Nah-Putz liegt (nearPlaster > 0) — sonst schliesst der
// Kern flächenbündig an und es gibt nichts aufzubrechen.
if (nearPlaster > 1e-9) {
// Kernbreite des Abzweigs im Quer-Offset (Offset-Konvention der Bänder:
// gestapelt entlang leftNormal ab refOff − total/2). Die verschmelzenden
// Schichten (`merged`) bilden den Kern; Lo/Hi = ihre Offset-Hülle.
const totalBranch = wallTypeThickness(branchWt);
const refOffBranch = wallReferenceOffset(branchWall, totalBranch);
let bOff = refOffBranch - totalBranch / 2;
let coreLo = Infinity;
let coreHi = -Infinity;
for (let i = 0; i < n; i++) {
const th = branchWt.layers[i].thickness;
if (merged[i]) {
if (bOff < coreLo) coreLo = bOff;
if (bOff + th > coreHi) coreHi = bOff + th;
}
bOff += th;
}
if (coreHi > coreLo) {
// Projektion der Kern-Offsethülle auf die Durchgangsachse: der Achsenpunkt
// liegt bei `axisAt` (Meter ab Durchgangs-Start), ein Abzweig-Offset `o`
// verschiebt sich entlang der Achse um `o · (nBranch · uT)`.
const nBranch = leftNormal(dirOf(branchWall));
const proj = dot(nBranch, throughDir);
const axisAt = dot(sub(axisPoint, throughWall.start), throughDir);
const e1 = axisAt + coreLo * proj;
const e2 = axisAt + coreHi * proj;
// Quer-Offsetbereich = Nah-Putz-Zone der Durchgangswand: Nahfläche (offA)
// bis Rückgrat-Nahfläche (offB, = mergeCut-Offset). Beide in derselben
// Offset-Konvention wie die Schicht-Bänder der Durchgangswand.
const offA = offT + sign * (tT / 2);
const offB = offT + sign * (tT / 2 - nearPlaster);
const throughCuts = result.get(throughWall.id);
if (throughCuts) {
(throughCuts.spanCutouts ??= []).push({
from: Math.min(e1, e2),
to: Math.max(e1, e2),
offA,
offB,
});
}
}
const m = r.count();
if (m > 0) {
cuts.spanCutouts = [];
for (let k = 0; k < m; k++) cuts.spanCutouts.push({ from: r.num(), to: r.num(), offA: r.num(), offB: r.num() });
}
}
/**
* Fall 2 — Mittelspannen-T-Stoß: prüft, ob das freie Wandende `freeEnd` auf
* die innere Spanne einer anderen Wand trifft (projizierter Parameter im
* Inneren, nicht an deren Endpunkten) und dabei senkrecht nah genug an deren
* Achse liegt (≤ halbe Dicke + Toleranz). Bei Treffer bekommt das freie Ende
* einen Schnitt entlang der zugewandten Fläche der getroffenen Wand; bei
* mehreren Treffern gewinnt die nächstliegende Wand.
*/
function applyMidSpanTee(
project: Project,
byId: Map<string, Wall>,
walls: Wall[],
freeEnd: WallEnd,
result: Map<string, WallCuts>,
): void {
const freeWall = byId.get(freeEnd.wallId)!;
const p = freeEnd.end === "start" ? freeWall.start : freeWall.end;
const endGap = 1e-4; // Mindestabstand zu den Wandenden für „innere Spanne"
const tol = 1e-3; // Toleranz für den senkrechten Abstand zur Wandfläche
let best: { wall: Wall; perp: number; dist: number; distAlong: number } | null = null;
for (const w of walls) {
if (w.id === freeWall.id) continue;
const u = dirOf(w);
const wLen = len(sub(w.end, w.start));
if (wLen < 1e-9) continue;
const rel = sub(p, w.start);
const distAlong = dot(rel, u);
if (distAlong <= endGap || distAlong >= wLen - endGap) continue; // an Endpunkt, kein Mittelspann
const perp = dot(rel, leftNormal(u));
const tw = wallTypeThickness(getWallType(project, w));
const dist = Math.abs(perp);
if (dist > tw / 2 + tol) continue;
if (!best || dist < best.dist) best = { wall: w, perp, dist, distAlong };
}
if (!best) return; // kein Treffer → rechtwinklig
const w = best.wall;
const tw = wallTypeThickness(getWallType(project, w));
const uW = dirOf(w);
const nW = leftNormal(uW);
const offW = wallReferenceOffset(w, tw);
// Zugewandte Seite: primär aus der AUSLAUFRICHTUNG des freien Endes in
// seinen eigenen Körper (wie `dBranch`/`sign` in applyTJunction) — nicht aus
// der lateralen Position `perp`. Bei einer „+"-Kreuzung (zwei kollineare
// Enden treffen exakt auf der ACHSE der durchlaufenden Wand, `perp≈0`) ist
// `perp` für beide Enden identisch und liefert für BEIDE dieselbe (falsche)
// Seite; die Auslaufrichtung unterscheidet sie dagegen korrekt (linke Hälfte
// läuft nach −u aus, rechte nach +u — je die gegenüberliegende Fläche der
// Durchgangswand). Nur wenn die Auslaufrichtung (nahezu) parallel zur
// Durchgangsachse liegt (dot≈0 — geometrisch entartet für einen T-Stoss),
// bleibt `perp` als Fallback (bisheriges Verhalten).
const dFree =
freeEnd.end === "start" ? dirOf(freeWall) : scale(dirOf(freeWall), -1);
const facing = dot(nW, dFree);
const sign = Math.abs(facing) > 1e-6 ? (facing >= 0 ? 1 : -1) : best.perp >= 0 ? 1 : -1;
const facePoint = add(w.start, scale(nW, offW + sign * (tw / 2)));
const faceCut: Line = { point: facePoint, dir: uW };
setCut(result, freeEnd, faceCut);
// Achsenpunkt auf der getroffenen Wand, auf Höhe der Projektion des freien
// Endes (nicht zwingend w.start) — Anker für die materialbewusste
// Pro-Schicht-Erweiterung (analog zum T-Knoten-Fall).
const axisPoint = add(w.start, scale(uW, best.distAlong));
applyLayerCuts(project, result, freeEnd, freeWall, w, faceCut, axisPoint, uW, sign);
return cuts;
}
+3 -3
View File
@@ -239,10 +239,10 @@ export function wallLayersReversedInU(owner: Wall, uWorld: Vec2): boolean {
// `projectToWalls3d` zerlegt EINE Wand mit Öffnungen in mehrere Teilquader
// (Pfeiler/Brüstung/Sturz) — die Emission ist also nicht 1:1 Wand→Element.
// Um einen `index` wieder auf seine Quellwand zurückzuführen, wird hier exakt
// dieselbe Segmentierungs-/Skip-Logik wie `emitWall`/`pushSegment`
// (toWalls3d.ts) repliziert — NICHT die Geometrie, nur welches Quellelement
// dieselbe Segmentierungs-/Skip-Logik wie `emitWalls` (Schnitt-Pfad in
// `src-tauri/core/src/wall_bands.rs`) repliziert — NICHT die Geometrie, nur welches Quellelement
// pro emittiertem Segment "besitzt". Bleibt diese Zählung nicht exakt parallel
// zu `emitWall`, verschieben sich die Indizes und die Hatch-Auflösung wird
// zu `emitWalls`, verschieben sich die Indizes und die Hatch-Auflösung wird
// falsch (harmlos: der Aufrufer fällt dann pro Cut-Polygon auf die generische
// Schnitt-Schraffur zurück, siehe `resolveWallSectionStyle`/`generatePlan.ts`).
const OWNER_EPS = 1e-4;
+3 -3
View File
@@ -63,7 +63,7 @@ import {
type RVec2,
type RWall,
} from "./toWalls3d/shared";
import { emitWall } from "./toWalls3d/bands";
import { emitWalls } from "./toWalls3d/bands";
import { emitSlabs } from "./toWalls3d/ceilings";
import { emitStairMeshes, emitStairRailings, emitStairs } from "./toWalls3d/stairs";
import { emitExtrudedSolids, TRUCK_MESH_READY_EVENT } from "./toWalls3d/extrusions";
@@ -147,7 +147,7 @@ export function projectToWalls3d(project: Project, layered = true): RWall[] {
// Dominanz macht toSection.ts). Anders als im 2D wird hier NICHT nach
// Sichtbarkeit gefiltert — 3D zeigt alle Wände, alle nehmen an den Joins teil.
const joins = layered ? computeJoinsByFloor(project) : undefined;
for (const w of project.walls) emitWall(out, project, w, layered, joins?.get(w.id));
emitWalls(out, project, project.walls, layered, joins);
return out;
}
@@ -364,7 +364,7 @@ export function pickGeometry(
* entlang der Wandlänge, Normale (Dicke) senkrecht dazu in der XZ-Ebene,
* Y = Höhe. Aus den 8 Ecken werden die 12 Kanten des Quaders emittiert.
* Wände MIT Öffnungen bestehen aus mehreren Teilquadern (Pfeiler/Brüstung/
* Sturz, s. emitWall) — alle tragen dieselbe `wallId` und werden hier ALLE
* Sturz, s. emitWalls) — alle tragen dieselbe `wallId` und werden hier ALLE
* umrandet, sodass Öffnungsränder mit hervorgehoben werden.
* • Decke: der Umriss oben (zTop) und unten (zBottom) je als geschlossener
* Kantenzug, plus eine vertikale Kante an jeder Umriss-Ecke.
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -262,7 +262,7 @@ export interface RWall {
/**
* Echte rechteckige Löcher (Fenster/Türen) in DIESEM Wandkörper (siehe
* {@link RHole}). Nur im 3D-Viewer-Pfad (`projectToModel3d` mit
* `layeredWalls:true`) gesetzt: dort emittiert `emitWall` EINEN RWall pro
* `layeredWalls:true`) gesetzt: dort emittiert `emitWalls` EINEN RWall pro
* Schicht-Band über die volle Achse mit ALLEN Öffnungen als `holes` — statt der
* Pfeiler/Brüstung/Sturz-Segment-Boxen. So bildet EIN Körper auch versetzt
* übereinanderliegende Fenster ab (das kann die Segment-Zerlegung nicht). Der