Rust-Kern: Dachgeometrie (roof.rs, roof_skeleton.rs) aus dem TS-Kern portiert
Alle Dachformen (flach/pult/sattel/walm/mansarde/zelt, Kruppelwalm, Ueberstand Traufe/Ortgang, First entlang x/y) und das Skelett fuer L/T/U- und schiefe Umrisse (Kehlen, Giebel, Mansard-Knick, konvexe Zerlegung) rechnet jetzt dossier-core; Polygon-Booleans direkt ueber i_overlay ohne WASM-Grenze. roof.ts uebergibt die Dachparameter flach (roof_geometry_flat) und baut daraus die RoofGeometry; Memo je Dach-Objekt bleibt in TS. roofUndersideAt rechnet ebenfalls in Rust ueber die gemerkten flachen Dachflaechen. roofSkeleton.ts geloescht, seine Hilfsfunktionen sind in Rust getestet; roofSkeleton.test.ts prueft dieselben Erwartungen ueber roofGeometry. Ergebnis bitgleich mit der TS-Fassung (10 Referenzdaecher), ungecacht 2.9 -> 1.3 ms je 10 Daecher, roofUndersideAt 1.3 -> 0.75 us je Aufruf. Rust-Tests je Dachform und fuer Unsinn-Eingaben.
This commit is contained in:
9 files changed
+1433
-946
No files matched your search
@@ -39,7 +39,7 @@ die Grenze als flache `Float64Array`s. truck (`trucksolid`) bleibt eigenes WASM-
|
||||
| Ort | Inhalt |
|
||||
|---|---|
|
||||
| `src/model` | Typen (`types.ts`), Wand/Decke/Dach-Logik, Verbindungen, Ansichts-Typen (`viewTypes.ts`) |
|
||||
| `src/geometry` | reine Geometrie: Dach-Skelett (`roofSkeleton.ts`), kernel2d, Treppen, Räume |
|
||||
| `src/geometry` | reine Geometrie: kernel2d, Treppen, Räume; `roof.ts` = Hülle um die Rust-Dachgeometrie |
|
||||
| `src/plan` | Ableitung: `generatePlan`, `toSection`, `toElevation`, `toWalls3d`, `toRenderScene`, `voids.ts` |
|
||||
| `src/views/plan` | React-Plan-Ansicht, Renderer-Hooks (native Metal / WASM-WebGPU) |
|
||||
| `src/viewport` | 3D-Viewport (`Wasm3DViewport`), Raycast, Griffe |
|
||||
@@ -50,7 +50,7 @@ die Grenze als flache `Float64Array`s. truck (`trucksolid`) bleibt eigenes WASM-
|
||||
| `src/net` | einziges Tor ins Netz (`netFetch`, Offline-Modus, Host-Liste) |
|
||||
| `src-tauri/render2d, render3d` | die zwei Anzeige-Engines (Rust → WASM/Metal) |
|
||||
| `src-tauri/trucksolid` | B-Rep (truck 0.6): Körper, Booleans, STEP, Kennwerte, Kollision |
|
||||
| `src-tauri/core` | Rust-Kern (`dossier-core`): Polygon-Booleans (i_overlay), wächst etappenweise |
|
||||
| `src-tauri/core` | Rust-Kern (`dossier-core`): Polygon-Booleans (i_overlay), Dachgeometrie (`roof.rs`, `roof_skeleton.rs`), wächst etappenweise |
|
||||
| `src-tauri/kernel2d, dwgimport` | 2D-Geometrie-Referenz, DWG-Import |
|
||||
|
||||
## Konventionen
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
pub mod flat;
|
||||
pub mod polygon_bool;
|
||||
pub mod roof;
|
||||
pub mod roof_skeleton;
|
||||
|
||||
#[cfg(feature = "web")]
|
||||
mod web;
|
||||
@@ -0,0 +1,685 @@
|
||||
//! Dach-Geometrie: leitet aus Grundriss-Umriss + Dachform + Neigung die Grundriss-Linien
|
||||
//! (Traufe/First/Grat/Knick) UND die 3D-Dachflächen ab.
|
||||
//!
|
||||
//! - Rechteck (und Satteldach auf schiefem Umriss): auf der BOUNDING-BOX des Umrisses, First
|
||||
//! entlang einer Hauptachse — deckt alle Standardformen (Flach/Pult/Sattel/Walm/Mansarde/
|
||||
//! Zelt, Krüppelwalm) exakt ab.
|
||||
//! - Rechtwinklig, nicht rechteckig (L/T/U …): Walm/Sattel/Mansarde/Zelt über das Skelett
|
||||
//! ([`crate::roof_skeleton`]), Pult als eine Ebene über dem Umriss.
|
||||
//! - Beliebiger einfacher Umriss: allseitig gleich geneigte Formen über das Skelett.
|
||||
//!
|
||||
//! Koordinaten: Grundriss (x, y) in Metern; 3D-Punkte [x, y, z] mit z = Höhe.
|
||||
//! Portiert aus `src/geometry/roof.ts` (dort bleiben Typen, Memo und `roofBaseElevation`).
|
||||
|
||||
use crate::roof_skeleton::{clean_ring, convex_pieces, hip_roof, is_rectilinear_non_rect, is_skeleton_roofable, offset_ring, signed_area, Axis, Knee, Line, Offset, P2, P3};
|
||||
|
||||
/// Dachform (`RoofShape` im TS-Modell).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Shape {
|
||||
Flach,
|
||||
Pult,
|
||||
Sattel,
|
||||
Walm,
|
||||
Mansarde,
|
||||
Zelt,
|
||||
}
|
||||
|
||||
/// Untertyp der Mansarde.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum MansardType {
|
||||
Giebel,
|
||||
Walm,
|
||||
Zelt,
|
||||
}
|
||||
|
||||
/// Dachparameter (Auszug aus `Roof`); `None` = Feld fehlt (Standardwert wie im Modell).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RoofParams {
|
||||
pub outline: Vec<P2>,
|
||||
pub shape: Shape,
|
||||
pub pitch_deg: f64,
|
||||
pub pitch_upper_deg: Option<f64>,
|
||||
pub mansard_type: MansardType,
|
||||
pub mansard_knee_ratio: Option<f64>,
|
||||
pub half_hip_ratio: Option<f64>,
|
||||
pub overhang: f64,
|
||||
pub overhang_gable: Option<f64>,
|
||||
pub ridge_axis: Axis,
|
||||
}
|
||||
|
||||
/// Vollständige Dach-Geometrie (Grundriss-Linien + 3D-Flächen), wie `RoofGeometry` in TS.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct RoofGeometry {
|
||||
/// Traufe-Umriss (inkl. Überstand), offener Ring.
|
||||
pub eaves: Vec<P2>,
|
||||
pub ridges: Vec<Line>,
|
||||
pub hips: Vec<Line>,
|
||||
pub breaks: Vec<Line>,
|
||||
pub planes: Vec<Vec<P3>>,
|
||||
/// Giebelflächen (vertikale Polygone).
|
||||
pub gables: Vec<Vec<P3>>,
|
||||
/// Firsthöhe über der Traufe (Meter).
|
||||
pub ridge_height: f64,
|
||||
}
|
||||
|
||||
const DEG: f64 = std::f64::consts::PI / 180.0;
|
||||
|
||||
/// Nicht-negativ; NaN → 0 (fehlerhafte Eingaben ergeben ein flaches statt ein kaputtes Dach).
|
||||
fn nn(v: f64) -> f64 {
|
||||
if v.is_nan() {
|
||||
0.0
|
||||
} else {
|
||||
v.max(0.0)
|
||||
}
|
||||
}
|
||||
|
||||
fn knee_ratio(p: &RoofParams) -> f64 {
|
||||
p.mansard_knee_ratio.unwrap_or(0.4).clamp(0.05, 0.49)
|
||||
}
|
||||
|
||||
fn upper_tan(p: &RoofParams) -> f64 {
|
||||
(nn(p.pitch_upper_deg.unwrap_or(p.pitch_deg / 2.0)) * DEG).tan()
|
||||
}
|
||||
|
||||
/// Kanonische Berechnung mit First entlang der X-Achse auf dem Rechteck [x0,x1]×[y0,y1]
|
||||
/// (Traufe, inkl. Überstand) auf Traufhöhe `e`. „First entlang Y“ entsteht im Aufrufer durch
|
||||
/// Transponieren (x↔y).
|
||||
fn compute_canonical(x0: f64, y0: f64, x1: f64, y1: f64, e: f64, p: &RoofParams) -> RoofGeometry {
|
||||
let xc = (x0 + x1) / 2.0;
|
||||
let yc = (y0 + y1) / 2.0;
|
||||
let half_w = (x1 - x0) / 2.0;
|
||||
let half_d = (y1 - y0) / 2.0;
|
||||
let a = nn(p.pitch_deg) * DEG;
|
||||
let tan = a.tan();
|
||||
let h = half_d * tan; // Firsthöhe (Sattel/Walm/Mansarde)
|
||||
let eaves = vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
|
||||
let geo = |ridges, hips, breaks, planes, gables, ridge_height| RoofGeometry { eaves: eaves.clone(), ridges, hips, breaks, planes, gables, ridge_height };
|
||||
|
||||
match p.shape {
|
||||
Shape::Flach => geo(vec![], vec![], vec![], vec![vec![[x0, y0, e], [x1, y0, e], [x1, y1, e], [x0, y1, e]]], vec![], 0.0),
|
||||
|
||||
Shape::Pult => {
|
||||
// Eine Fläche: tiefe Seite y0 auf Traufe, hohe Seite y1 auf e+H.
|
||||
let hh = (y1 - y0) * tan;
|
||||
geo(
|
||||
vec![[[x0, y1], [x1, y1]]], // hohe Kante (First-Ersatz)
|
||||
vec![],
|
||||
vec![],
|
||||
vec![vec![[x0, y0, e], [x1, y0, e], [x1, y1, e + hh], [x0, y1, e + hh]]],
|
||||
vec![vec![[x0, y0, e], [x0, y1, e + hh], [x0, y1, e]], vec![[x1, y0, e], [x1, y1, e + hh], [x1, y1, e]]],
|
||||
hh,
|
||||
)
|
||||
}
|
||||
|
||||
Shape::Sattel => {
|
||||
let rz = e + h;
|
||||
let hh = p.half_hip_ratio.unwrap_or(0.0).clamp(0.0, 0.9);
|
||||
if hh > 1e-6 && half_w > half_d * hh + 1e-6 {
|
||||
// Krüppelwalm: oberer Giebelteil (Anteil `hh` der Firsthöhe) als kleine
|
||||
// Walmflächen gleicher Neigung — Walmlauf = halbe Tiefe · hh, First verkürzt.
|
||||
let kz = e + h * (1.0 - hh);
|
||||
let yk0 = y0 + half_d * (1.0 - hh);
|
||||
let yk1 = y1 - half_d * (1.0 - hh);
|
||||
let d = half_d * hh;
|
||||
return geo(
|
||||
vec![[[x0 + d, yc], [x1 - d, yc]]],
|
||||
vec![[[x0, yk0], [x0 + d, yc]], [[x0, yk1], [x0 + d, yc]], [[x1, yk0], [x1 - d, yc]], [[x1, yk1], [x1 - d, yc]]],
|
||||
vec![],
|
||||
vec![
|
||||
vec![[x0, y0, e], [x1, y0, e], [x1, yk0, kz], [x1 - d, yc, rz], [x0 + d, yc, rz], [x0, yk0, kz]],
|
||||
vec![[x0, y1, e], [x1, y1, e], [x1, yk1, kz], [x1 - d, yc, rz], [x0 + d, yc, rz], [x0, yk1, kz]],
|
||||
vec![[x0, yk0, kz], [x0, yk1, kz], [x0 + d, yc, rz]],
|
||||
vec![[x1, yk0, kz], [x1, yk1, kz], [x1 - d, yc, rz]],
|
||||
],
|
||||
vec![vec![[x0, y0, e], [x0, y1, e], [x0, yk1, kz], [x0, yk0, kz]], vec![[x1, y0, e], [x1, y1, e], [x1, yk1, kz], [x1, yk0, kz]]],
|
||||
h,
|
||||
);
|
||||
}
|
||||
geo(
|
||||
vec![[[x0, yc], [x1, yc]]],
|
||||
vec![],
|
||||
vec![],
|
||||
vec![vec![[x0, y0, e], [x1, y0, e], [x1, yc, rz], [x0, yc, rz]], vec![[x0, y1, e], [x1, y1, e], [x1, yc, rz], [x0, yc, rz]]],
|
||||
vec![vec![[x0, y0, e], [x0, y1, e], [x0, yc, rz]], vec![[x1, y0, e], [x1, y1, e], [x1, yc, rz]]],
|
||||
h,
|
||||
)
|
||||
}
|
||||
|
||||
Shape::Walm => {
|
||||
let rz = e + h;
|
||||
// First um die halbe Tiefe an beiden Enden verkürzt (45°-Grate bei gleicher
|
||||
// Neigung). Bei schmalem Baukörper (half_w < half_d) degeneriert er zum Punkt.
|
||||
let (mut ra, mut rb) = (x0 + half_d, x1 - half_d);
|
||||
if ra > rb {
|
||||
ra = xc;
|
||||
rb = xc;
|
||||
}
|
||||
geo(
|
||||
vec![[[ra, yc], [rb, yc]]],
|
||||
vec![[[x0, y0], [ra, yc]], [[x0, y1], [ra, yc]], [[x1, y0], [rb, yc]], [[x1, y1], [rb, yc]]],
|
||||
vec![],
|
||||
vec![
|
||||
vec![[x0, y0, e], [x1, y0, e], [rb, yc, rz], [ra, yc, rz]],
|
||||
vec![[x0, y1, e], [x1, y1, e], [rb, yc, rz], [ra, yc, rz]],
|
||||
vec![[x0, y0, e], [x0, y1, e], [ra, yc, rz]],
|
||||
vec![[x1, y0, e], [x1, y1, e], [rb, yc, rz]],
|
||||
],
|
||||
vec![],
|
||||
h,
|
||||
)
|
||||
}
|
||||
|
||||
Shape::Mansarde => {
|
||||
// Steile untere Neigung (pitch_deg) bis zur Knicklinie, dann flache obere
|
||||
// (pitch_upper_deg, sonst halbe Hauptneigung). Untertyp: Knick an ZWEI Seiten
|
||||
// (Giebel) oder RINGSUM (Walm/Zelt).
|
||||
let tan_low = tan;
|
||||
let tan_up = upper_tan(p);
|
||||
let ratio = knee_ratio(p);
|
||||
if p.mansard_type == MansardType::Giebel {
|
||||
let d1 = half_d * ratio;
|
||||
let z1 = e + d1 * tan_low;
|
||||
let z2 = z1 + (half_d - d1) * tan_up;
|
||||
let yf = y0 + d1;
|
||||
let yb = y1 - d1;
|
||||
return geo(
|
||||
vec![[[x0, yc], [x1, yc]]],
|
||||
vec![],
|
||||
vec![[[x0, yf], [x1, yf]], [[x0, yb], [x1, yb]]],
|
||||
vec![
|
||||
vec![[x0, y0, e], [x1, y0, e], [x1, yf, z1], [x0, yf, z1]],
|
||||
vec![[x0, yf, z1], [x1, yf, z1], [x1, yc, z2], [x0, yc, z2]],
|
||||
vec![[x0, y1, e], [x1, y1, e], [x1, yb, z1], [x0, yb, z1]],
|
||||
vec![[x0, yb, z1], [x1, yb, z1], [x1, yc, z2], [x0, yc, z2]],
|
||||
],
|
||||
vec![
|
||||
vec![[x0, y0, e], [x0, yf, z1], [x0, yc, z2], [x0, yb, z1], [x0, y1, e]],
|
||||
vec![[x1, y0, e], [x1, yf, z1], [x1, yc, z2], [x1, yb, z1], [x1, y1, e]],
|
||||
],
|
||||
z2 - e,
|
||||
);
|
||||
}
|
||||
// Allseitige Mansarde: steiler Sockel ringsum bis zur Knicklinie (inneres
|
||||
// Rechteck), darüber flacher Walm bzw. flache Spitze.
|
||||
let d_low = half_w.min(half_d) * ratio;
|
||||
let z1 = e + d_low * tan_low;
|
||||
let (ix0, iy0, ix1, iy1) = (x0 + d_low, y0 + d_low, x1 - d_low, y1 - d_low);
|
||||
let ihalf_d = (iy1 - iy0) / 2.0;
|
||||
let ihalf_w = (ix1 - ix0) / 2.0;
|
||||
let mut planes = vec![
|
||||
vec![[x0, y0, e], [x1, y0, e], [ix1, iy0, z1], [ix0, iy0, z1]],
|
||||
vec![[x1, y1, e], [x0, y1, e], [ix0, iy1, z1], [ix1, iy1, z1]],
|
||||
vec![[x0, y1, e], [x0, y0, e], [ix0, iy0, z1], [ix0, iy1, z1]],
|
||||
vec![[x1, y0, e], [x1, y1, e], [ix1, iy1, z1], [ix1, iy0, z1]],
|
||||
];
|
||||
let mut hips: Vec<Line> = vec![[[x0, y0], [ix0, iy0]], [[x1, y0], [ix1, iy0]], [[x1, y1], [ix1, iy1]], [[x0, y1], [ix0, iy1]]];
|
||||
let breaks: Vec<Line> = vec![[[ix0, iy0], [ix1, iy0]], [[ix1, iy0], [ix1, iy1]], [[ix1, iy1], [ix0, iy1]], [[ix0, iy1], [ix0, iy0]]];
|
||||
if p.mansard_type == MansardType::Walm {
|
||||
// Oberer Walm auf dem inneren Rechteck (First entlang X).
|
||||
let z2 = z1 + ihalf_d * tan_up;
|
||||
let (mut ra, mut rb) = (ix0 + ihalf_d, ix1 - ihalf_d);
|
||||
if ra > rb {
|
||||
ra = xc;
|
||||
rb = xc;
|
||||
}
|
||||
hips.extend([[[ix0, iy0], [ra, yc]], [[ix1, iy0], [rb, yc]], [[ix1, iy1], [rb, yc]], [[ix0, iy1], [ra, yc]]]);
|
||||
planes.extend([
|
||||
vec![[ix0, iy0, z1], [ix1, iy0, z1], [rb, yc, z2], [ra, yc, z2]],
|
||||
vec![[ix1, iy1, z1], [ix0, iy1, z1], [ra, yc, z2], [rb, yc, z2]],
|
||||
vec![[ix0, iy1, z1], [ix0, iy0, z1], [ra, yc, z2]],
|
||||
vec![[ix1, iy0, z1], [ix1, iy1, z1], [rb, yc, z2]],
|
||||
]);
|
||||
return geo(vec![[[ra, yc], [rb, yc]]], hips, breaks, planes, vec![], z2 - e);
|
||||
}
|
||||
// Zelt: flache Spitze über der Mitte des inneren Rechtecks.
|
||||
let z2 = z1 + ihalf_w.min(ihalf_d) * tan_up;
|
||||
hips.extend([[[ix0, iy0], [xc, yc]], [[ix1, iy0], [xc, yc]], [[ix1, iy1], [xc, yc]], [[ix0, iy1], [xc, yc]]]);
|
||||
planes.extend([
|
||||
vec![[ix0, iy0, z1], [ix1, iy0, z1], [xc, yc, z2]],
|
||||
vec![[ix1, iy0, z1], [ix1, iy1, z1], [xc, yc, z2]],
|
||||
vec![[ix1, iy1, z1], [ix0, iy1, z1], [xc, yc, z2]],
|
||||
vec![[ix0, iy1, z1], [ix0, iy0, z1], [xc, yc, z2]],
|
||||
]);
|
||||
geo(vec![], hips, breaks, planes, vec![], z2 - e)
|
||||
}
|
||||
|
||||
Shape::Zelt => {
|
||||
// Allseitig zur Spitze über der Mitte.
|
||||
let hz = half_w.min(half_d) * tan;
|
||||
let az = e + hz;
|
||||
geo(
|
||||
vec![],
|
||||
vec![[[x0, y0], [xc, yc]], [[x1, y0], [xc, yc]], [[x1, y1], [xc, yc]], [[x0, y1], [xc, yc]]],
|
||||
vec![],
|
||||
vec![
|
||||
vec![[x0, y0, e], [x1, y0, e], [xc, yc, az]],
|
||||
vec![[x1, y0, e], [x1, y1, e], [xc, yc, az]],
|
||||
vec![[x1, y1, e], [x0, y1, e], [xc, yc, az]],
|
||||
vec![[x0, y1, e], [x0, y0, e], [xc, yc, az]],
|
||||
],
|
||||
vec![],
|
||||
hz,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn swap_line(l: &Line) -> Line {
|
||||
[[l[0][1], l[0][0]], [l[1][1], l[1][0]]]
|
||||
}
|
||||
|
||||
fn swap3(v: &P3) -> P3 {
|
||||
[v[1], v[0], v[2]]
|
||||
}
|
||||
|
||||
/// Dach-Geometrie aus Form/Neigung/Überstand + Traufhöhe `eaves_z`. Kaputte Eingaben
|
||||
/// (kein endlicher Umrisspunkt) ergeben eine leere Geometrie, nie einen Panic.
|
||||
pub fn roof_geometry(p: &RoofParams, eaves_z: f64) -> RoofGeometry {
|
||||
let outline: Vec<P2> = p.outline.iter().copied().filter(|q| q[0].is_finite() && q[1].is_finite()).collect();
|
||||
if outline.is_empty() {
|
||||
return RoofGeometry::default();
|
||||
}
|
||||
let e = if eaves_z.is_finite() { eaves_z } else { 0.0 };
|
||||
let p = &RoofParams { outline, ..p.clone() };
|
||||
// Walm/Sattel/Mansarde/Zelt über einem rechtwinkligen, nicht-rechteckigen Grundriss
|
||||
// (L/T/U …): echte Flächen mit Graten und Kehlen statt Bounding-Box. Zelt/Mansard-Zelt:
|
||||
// eine einzelne Spitze gibt es dort nicht — Gegenstück ist das allseitig geneigte Skelett.
|
||||
if matches!(p.shape, Shape::Walm | Shape::Sattel | Shape::Mansarde | Shape::Zelt) && is_rectilinear_non_rect(&p.outline) {
|
||||
return skeleton_roof(p, e);
|
||||
}
|
||||
// Beliebiger einfacher Umriss: nur allseitig gleich geneigte Formen — Giebel brauchen
|
||||
// achsparallele Kanten und bleiben bei der Bounding-Box.
|
||||
let allround = matches!(p.shape, Shape::Walm | Shape::Zelt) || (p.shape == Shape::Mansarde && p.mansard_type != MansardType::Giebel);
|
||||
if allround && is_skeleton_roofable(&p.outline) {
|
||||
return skeleton_roof(p, e);
|
||||
}
|
||||
if p.shape == Shape::Pult && is_rectilinear_non_rect(&p.outline) {
|
||||
return rectilinear_pult(p, e);
|
||||
}
|
||||
let (mut x0, mut y0, mut x1, mut y1) = bbox(&p.outline);
|
||||
let oe = nn(p.overhang); // Traufüberstand (senkrecht zum First)
|
||||
let og = nn(p.overhang_gable.unwrap_or(p.overhang)); // Ortgang (entlang First)
|
||||
// Entlang der Firstachse wirkt der Ortgang-, quer dazu der Traufüberstand.
|
||||
let (ox, oy) = if p.ridge_axis == Axis::X { (og, oe) } else { (oe, og) };
|
||||
x0 -= ox;
|
||||
y0 -= oy;
|
||||
x1 += ox;
|
||||
y1 += oy;
|
||||
if p.ridge_axis == Axis::X {
|
||||
return compute_canonical(x0, y0, x1, y1, e, p);
|
||||
}
|
||||
let g = compute_canonical(y0, x0, y1, x1, e, p);
|
||||
RoofGeometry {
|
||||
eaves: g.eaves.iter().map(|q| [q[1], q[0]]).collect(),
|
||||
ridges: g.ridges.iter().map(swap_line).collect(),
|
||||
hips: g.hips.iter().map(swap_line).collect(),
|
||||
breaks: g.breaks.iter().map(swap_line).collect(),
|
||||
planes: g.planes.iter().map(|pl| pl.iter().map(swap3).collect()).collect(),
|
||||
gables: g.gables.iter().map(|pl| pl.iter().map(swap3).collect()).collect(),
|
||||
ridge_height: g.ridge_height,
|
||||
}
|
||||
}
|
||||
|
||||
fn bbox(pts: &[P2]) -> (f64, f64, f64, f64) {
|
||||
let mut b = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
|
||||
for q in pts {
|
||||
b.0 = b.0.min(q[0]);
|
||||
b.1 = b.1.min(q[1]);
|
||||
b.2 = b.2.max(q[0]);
|
||||
b.3 = b.3.max(q[1]);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Umriss gesäubert und gegen den Uhrzeigersinn.
|
||||
fn ccw_ring(outline: &[P2]) -> Vec<P2> {
|
||||
let mut ring = clean_ring(outline);
|
||||
if signed_area(&ring) < 0.0 {
|
||||
ring.reverse();
|
||||
}
|
||||
ring
|
||||
}
|
||||
|
||||
/// Ob die Kante a→b entlang der Firstachse läuft (dort Traufe, quer dazu Ortgang).
|
||||
fn along_ridge(a: P2, b: P2, axis: Axis) -> bool {
|
||||
let along_x = (b[0] - a[0]).abs() > (b[1] - a[1]).abs();
|
||||
along_x == (axis == Axis::X)
|
||||
}
|
||||
|
||||
/// Skelett-Dach (Walm/Sattel/Mansarde/Zelt) auf beliebigem einfachem Umriss: Traufe = Umriss um
|
||||
/// den Überstand nach aussen versetzt, Flächen/Linien aus [`hip_roof`].
|
||||
fn skeleton_roof(p: &RoofParams, e: f64) -> RoofGeometry {
|
||||
let ring = ccw_ring(&p.outline);
|
||||
let oe = nn(p.overhang);
|
||||
let og = nn(p.overhang_gable.unwrap_or(p.overhang));
|
||||
// Satteldach: Kanten quer zum First sind Ortgang (eigener Überstand), sonst Traufe.
|
||||
let per_edge = |a: P2, b: P2| if along_ridge(a, b, p.ridge_axis) { oe } else { og };
|
||||
let eaves = offset_ring(&ring, if p.shape == Shape::Sattel { Offset::PerEdge(&per_edge) } else { Offset::Const(oe) });
|
||||
let tan = (nn(p.pitch_deg) * DEG).tan();
|
||||
let gabled = p.shape == Shape::Sattel || (p.shape == Shape::Mansarde && p.mansard_type == MansardType::Giebel);
|
||||
let axis = if gabled { Some(p.ridge_axis) } else { None };
|
||||
let knee = if p.shape == Shape::Mansarde {
|
||||
// Knick bei `mansard_knee_ratio` der maximalen Dachtiefe (Abstand First–Traufe).
|
||||
let depth = hip_roof(&eaves, 1.0, 0.0, axis, None).ridge_height;
|
||||
Some(Knee { d: depth * knee_ratio(p), tan_up: upper_tan(p) })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let sk = hip_roof(&eaves, tan, e, axis, knee);
|
||||
RoofGeometry { eaves, ridges: sk.ridges, hips: sk.hips, breaks: sk.breaks, planes: sk.planes, gables: sk.gables, ridge_height: sk.ridge_height }
|
||||
}
|
||||
|
||||
/// Pultdach auf rechtwinkligem Grundriss: EINE Ebene über dem (um Traufe/Ortgang geweiteten)
|
||||
/// Umriss. Tief bei kleinstem y (First entlang x) bzw. x (First entlang y); Kanten quer zum
|
||||
/// First bekommen senkrechte Giebel.
|
||||
fn rectilinear_pult(p: &RoofParams, e: f64) -> RoofGeometry {
|
||||
let ring = ccw_ring(&p.outline);
|
||||
let oe = nn(p.overhang);
|
||||
let og = nn(p.overhang_gable.unwrap_or(p.overhang));
|
||||
let per_edge = |a: P2, b: P2| if along_ridge(a, b, p.ridge_axis) { oe } else { og };
|
||||
let eaves = offset_ring(&ring, Offset::PerEdge(&per_edge));
|
||||
let tan = (nn(p.pitch_deg) * DEG).tan();
|
||||
let s = |q: P2| if p.ridge_axis == Axis::X { q[1] } else { q[0] };
|
||||
let smin = eaves.iter().map(|&q| s(q)).fold(f64::INFINITY, f64::min);
|
||||
let smax = eaves.iter().map(|&q| s(q)).fold(f64::NEG_INFINITY, f64::max);
|
||||
let up = |q: P2| -> P3 { [q[0], q[1], e + tan * (s(q) - smin)] };
|
||||
let n = eaves.len();
|
||||
let gables = (0..n)
|
||||
.filter_map(|i| {
|
||||
let (a, b) = (eaves[i], eaves[(i + 1) % n]);
|
||||
(!along_ridge(a, b, p.ridge_axis)).then(|| vec![[a[0], a[1], e], [b[0], b[1], e], up(b), up(a)])
|
||||
})
|
||||
.collect();
|
||||
let planes = convex_pieces(&eaves).into_iter().map(|pc| pc.into_iter().map(up).collect()).collect();
|
||||
RoofGeometry { eaves, ridges: vec![], hips: vec![], breaks: vec![], planes, gables, ridge_height: (smax - smin) * tan }
|
||||
}
|
||||
|
||||
/// Punkt-in-Polygon (Ray-Casting), 2D-Aufsicht.
|
||||
fn point_in_polygon(x: f64, y: f64, poly: &[P3]) -> bool {
|
||||
let n = poly.len();
|
||||
let mut inside = false;
|
||||
let mut j = n.wrapping_sub(1);
|
||||
for i in 0..n {
|
||||
let (a, b) = (poly[i], poly[j]);
|
||||
let dy = b[1] - a[1];
|
||||
let dy = if dy == 0.0 { 1e-12 } else { dy };
|
||||
if (a[1] > y) != (b[1] > y) && x < (b[0] - a[0]) * (y - a[1]) / dy + a[0] {
|
||||
inside = !inside;
|
||||
}
|
||||
j = i;
|
||||
}
|
||||
inside
|
||||
}
|
||||
|
||||
/// Dach-UNTERKANTE an einem Grundriss-Punkt (x, y): Oberkante der ersten Dachfläche, die den
|
||||
/// Punkt in der Aufsicht enthält (Ebene über die Newell-Normale), minus die Schichtdicke
|
||||
/// `total_layer_thickness`; `None` ausserhalb aller Flächen. Dient dem Wand-Zuschnitt unter
|
||||
/// geneigten Dächern (`toWalls3d/bands.ts`).
|
||||
pub fn roof_underside_at(planes: &[Vec<P3>], total_layer_thickness: f64, x: f64, y: f64) -> Option<f64> {
|
||||
for pts in planes {
|
||||
if pts.len() < 3 || !point_in_polygon(x, y, pts) {
|
||||
continue;
|
||||
}
|
||||
let (mut a, mut b, mut c) = (0.0, 0.0, 0.0);
|
||||
for i in 0..pts.len() {
|
||||
let p = pts[i];
|
||||
let q = pts[(i + 1) % pts.len()];
|
||||
a += (p[1] - q[1]) * (p[2] + q[2]);
|
||||
b += (p[2] - q[2]) * (p[0] + q[0]);
|
||||
c += (p[0] - q[0]) * (p[1] + q[1]);
|
||||
}
|
||||
if c.abs() < 1e-9 {
|
||||
continue; // (nahezu) senkrechte Fläche
|
||||
}
|
||||
let top = pts[0][2] - (a * (x - pts[0][0]) + b * (y - pts[0][1])) / c;
|
||||
return Some(top - nn(total_layer_thickness));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// ── Flache Kodierung für die WASM-Grenze ─────────────────────────────────────
|
||||
//
|
||||
// Eingabe: [shape, pitchDeg, pitchUpperDeg, mansardType, mansardKneeRatio, halfHipRatio,
|
||||
// overhang, overhangGable, ridgeAxis, nPts, x0, y0, …]
|
||||
// shape: 0 flach, 1 pult, 2 sattel, 3 walm, 4 mansarde, 5 zelt;
|
||||
// mansardType: 0 giebel, 1 walm, 2 zelt; ridgeAxis: 0 x, 1 y; NaN = Feld fehlt.
|
||||
// Ausgabe: [ridgeHeight, nEaves, (x, y)…, nRidges, (x, y, x, y)…, nHips, …, nBreaks, …,
|
||||
// nPlanes, (n, (x, y, z)…)…, nGables, (n, (x, y, z)…)…]
|
||||
|
||||
fn opt(v: f64) -> Option<f64> {
|
||||
v.is_finite().then_some(v)
|
||||
}
|
||||
|
||||
/// Liest die Dachparameter; `None` bei zu kurzen/kaputten Daten.
|
||||
pub fn decode_params(buf: &[f64]) -> Option<RoofParams> {
|
||||
let head = buf.get(..10)?;
|
||||
let shape = match head[0] as i64 {
|
||||
1 => Shape::Pult,
|
||||
2 => Shape::Sattel,
|
||||
3 => Shape::Walm,
|
||||
4 => Shape::Mansarde,
|
||||
5 => Shape::Zelt,
|
||||
_ => Shape::Flach,
|
||||
};
|
||||
let mansard_type = match head[3] as i64 {
|
||||
1 => MansardType::Walm,
|
||||
2 => MansardType::Zelt,
|
||||
_ => MansardType::Giebel,
|
||||
};
|
||||
let n = head[9];
|
||||
if !(n.is_finite() && n >= 0.0 && n.fract() == 0.0) {
|
||||
return None;
|
||||
}
|
||||
let pts = buf.get(10..10 + 2 * n as usize)?;
|
||||
Some(RoofParams {
|
||||
outline: pts.chunks_exact(2).map(|c| [c[0], c[1]]).collect(),
|
||||
shape,
|
||||
pitch_deg: head[1],
|
||||
pitch_upper_deg: opt(head[2]),
|
||||
mansard_type,
|
||||
mansard_knee_ratio: opt(head[4]),
|
||||
half_hip_ratio: opt(head[5]),
|
||||
overhang: head[6],
|
||||
overhang_gable: opt(head[7]),
|
||||
ridge_axis: if head[8] == 1.0 { Axis::Y } else { Axis::X },
|
||||
})
|
||||
}
|
||||
|
||||
fn push_lines(out: &mut Vec<f64>, lines: &[Line]) {
|
||||
out.push(lines.len() as f64);
|
||||
for l in lines {
|
||||
out.extend_from_slice(&[l[0][0], l[0][1], l[1][0], l[1][1]]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Flächenliste `[n, (m, (x, y, z)…)…]` anhängen.
|
||||
pub fn push_polys3(out: &mut Vec<f64>, polys: &[Vec<P3>]) {
|
||||
out.push(polys.len() as f64);
|
||||
for pl in polys {
|
||||
out.push(pl.len() as f64);
|
||||
for v in pl {
|
||||
out.extend_from_slice(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Liest eine Flächenliste `[n, (m, (x, y, z)…)…]`; `None` bei kaputten Daten.
|
||||
pub fn decode_polys3(buf: &[f64]) -> Option<Vec<Vec<P3>>> {
|
||||
let count = |v: f64| (v.is_finite() && v >= 0.0 && v.fract() == 0.0 && v < 1e9).then_some(v as usize);
|
||||
let n = count(*buf.first()?)?;
|
||||
let mut i = 1;
|
||||
let mut out = Vec::with_capacity(n.min(1 << 16));
|
||||
for _ in 0..n {
|
||||
let m = count(*buf.get(i)?)?;
|
||||
i += 1;
|
||||
let pts = buf.get(i..i + 3 * m)?;
|
||||
i += 3 * m;
|
||||
out.push(pts.chunks_exact(3).map(|c| [c[0], c[1], c[2]]).collect());
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
pub fn encode_geometry(g: &RoofGeometry) -> Vec<f64> {
|
||||
let mut out = vec![g.ridge_height, g.eaves.len() as f64];
|
||||
for p in &g.eaves {
|
||||
out.extend_from_slice(p);
|
||||
}
|
||||
push_lines(&mut out, &g.ridges);
|
||||
push_lines(&mut out, &g.hips);
|
||||
push_lines(&mut out, &g.breaks);
|
||||
push_polys3(&mut out, &g.planes);
|
||||
push_polys3(&mut out, &g.gables);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const RECT: [P2; 4] = [[0.0, 0.0], [6.0, 0.0], [6.0, 4.0], [0.0, 4.0]];
|
||||
const L: [P2; 6] = [[0.0, 0.0], [11.0, 0.0], [11.0, 4.0], [8.0, 4.0], [8.0, 6.0], [0.0, 6.0]];
|
||||
|
||||
fn params(outline: &[P2], shape: Shape) -> RoofParams {
|
||||
RoofParams {
|
||||
outline: outline.to_vec(),
|
||||
shape,
|
||||
pitch_deg: 45.0,
|
||||
pitch_upper_deg: None,
|
||||
mansard_type: MansardType::Giebel,
|
||||
mansard_knee_ratio: None,
|
||||
half_hip_ratio: None,
|
||||
overhang: 0.0,
|
||||
overhang_gable: None,
|
||||
ridge_axis: Axis::X,
|
||||
}
|
||||
}
|
||||
|
||||
fn close(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-9
|
||||
}
|
||||
|
||||
fn plan_area(g: &RoofGeometry) -> f64 {
|
||||
g.planes.iter().map(|p| signed_area(&p.iter().map(|v| [v[0], v[1]]).collect::<Vec<_>>()).abs()).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flach() {
|
||||
let g = roof_geometry(¶ms(&RECT, Shape::Flach), 3.0);
|
||||
assert_eq!(g.planes.len(), 1);
|
||||
assert!(g.planes[0].iter().all(|v| v[2] == 3.0));
|
||||
assert!(g.ridges.is_empty() && g.ridge_height == 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pult() {
|
||||
let g = roof_geometry(¶ms(&RECT, Shape::Pult), 0.0);
|
||||
assert_eq!(g.planes.len(), 1);
|
||||
assert!(close(g.ridge_height, 4.0));
|
||||
assert_eq!(g.gables.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sattel_und_kruppelwalm() {
|
||||
let g = roof_geometry(¶ms(&RECT, Shape::Sattel), 0.0);
|
||||
assert_eq!((g.planes.len(), g.gables.len()), (2, 2));
|
||||
assert!(close(g.ridge_height, 2.0));
|
||||
assert_eq!(g.ridges, vec![[[0.0, 2.0], [6.0, 2.0]]]);
|
||||
let k = roof_geometry(&RoofParams { half_hip_ratio: Some(0.3), ..params(&RECT, Shape::Sattel) }, 0.0);
|
||||
assert_eq!(k.planes.len(), 4);
|
||||
assert!(close(k.ridges[0][0][0], 0.6) && close(k.ridges[0][1][0], 5.4));
|
||||
assert!(close(plan_area(&k), 24.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn walm() {
|
||||
let g = roof_geometry(¶ms(&RECT, Shape::Walm), 0.0);
|
||||
assert_eq!((g.planes.len(), g.hips.len(), g.gables.len()), (4, 4, 0));
|
||||
assert!(close(g.ridges[0][0][0], 2.0) && close(g.ridges[0][1][0], 4.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zelt() {
|
||||
let g = roof_geometry(¶ms(&RECT, Shape::Zelt), 0.0);
|
||||
assert_eq!((g.planes.len(), g.hips.len()), (4, 4));
|
||||
assert!(close(g.ridge_height, 2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mansarde_alle_untertypen() {
|
||||
let g = roof_geometry(¶ms(&RECT, Shape::Mansarde), 0.0);
|
||||
assert_eq!((g.planes.len(), g.breaks.len(), g.gables.len()), (4, 2, 2));
|
||||
assert!(g.ridge_height > 0.8 && g.ridge_height < 2.0);
|
||||
let w = roof_geometry(&RoofParams { mansard_type: MansardType::Walm, ..params(&RECT, Shape::Mansarde) }, 0.0);
|
||||
assert_eq!((w.planes.len(), w.breaks.len(), w.hips.len()), (8, 4, 8));
|
||||
let z = roof_geometry(&RoofParams { mansard_type: MansardType::Zelt, ..params(&RECT, Shape::Mansarde) }, 0.0);
|
||||
assert_eq!((z.planes.len(), z.ridges.len(), z.hips.len()), (8, 0, 8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_entlang_y_und_ueberstand() {
|
||||
let g = roof_geometry(&RoofParams { ridge_axis: Axis::Y, overhang: 0.5, overhang_gable: Some(1.0), ..params(&RECT, Shape::Sattel) }, 0.0);
|
||||
// Ortgang (1.0) entlang y, Traufe (0.5) entlang x.
|
||||
assert_eq!(g.eaves[0], [-0.5, -1.0]);
|
||||
assert_eq!(g.eaves[2], [6.5, 5.0]);
|
||||
assert!(close(g.ridges[0][0][0], 3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skelett_formen_auf_l() {
|
||||
for shape in [Shape::Walm, Shape::Sattel, Shape::Mansarde, Shape::Zelt, Shape::Pult] {
|
||||
let g = roof_geometry(¶ms(&L, shape), 0.0);
|
||||
assert!(close(plan_area(&g), 60.0), "{shape:?}: {}", plan_area(&g));
|
||||
}
|
||||
let pult = roof_geometry(¶ms(&L, Shape::Pult), 0.0);
|
||||
assert!(close(pult.ridge_height, 6.0));
|
||||
assert_eq!(pult.gables.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unterkante() {
|
||||
let g = roof_geometry(¶ms(&RECT, Shape::Sattel), 10.0);
|
||||
assert!(close(roof_underside_at(&g.planes, 0.3, 3.0, 1.0).unwrap(), 10.7));
|
||||
assert!(roof_underside_at(&g.planes, 0.3, 30.0, 1.0).is_none());
|
||||
assert!((roof_underside_at(&g.planes, -1.0, 3.0, 2.0 - 1e-9).unwrap() - 12.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kodierung_hin_und_zurueck() {
|
||||
let buf = [3.0, 30.0, f64::NAN, 1.0, 0.3, f64::NAN, 0.5, f64::NAN, 1.0, 3.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0];
|
||||
let p = decode_params(&buf).unwrap();
|
||||
assert_eq!((p.shape, p.mansard_type, p.ridge_axis, p.outline.len()), (Shape::Walm, MansardType::Walm, Axis::Y, 3));
|
||||
assert_eq!((p.pitch_upper_deg, p.mansard_knee_ratio), (None, Some(0.3)));
|
||||
let g = roof_geometry(¶ms(&RECT, Shape::Walm), 0.0);
|
||||
let enc = encode_geometry(&g);
|
||||
// Flächen stehen hinter Kopf, Traufe und drei Linienlisten.
|
||||
let off = 2 + 2 * 4 + 1 + 4 * g.ridges.len() + 1 + 4 * g.hips.len() + 1;
|
||||
assert_eq!(decode_polys3(&enc[off..]).unwrap(), g.planes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsinn_ohne_panic() {
|
||||
assert!(decode_params(&[]).is_none());
|
||||
assert!(decode_params(&[0.0; 9]).is_none());
|
||||
assert!(decode_params(&[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 1.0]).is_none());
|
||||
assert!(decode_params(&[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, f64::NAN]).is_none());
|
||||
assert!(decode_polys3(&[2.0, 1.0]).is_none());
|
||||
// Leerer Umriss → leere Geometrie.
|
||||
assert_eq!(roof_geometry(¶ms(&[], Shape::Walm), 0.0), RoofGeometry::default());
|
||||
assert_eq!(roof_geometry(¶ms(&[[f64::NAN, 1.0]], Shape::Sattel), 0.0), RoofGeometry::default());
|
||||
// NaN in Parametern und Höhe: kein Panic, endliche Werte.
|
||||
for shape in [Shape::Flach, Shape::Pult, Shape::Sattel, Shape::Walm, Shape::Mansarde, Shape::Zelt] {
|
||||
for outline in [&RECT[..], &L[..], &[[0.0, 0.0], [1.0, 1.0]][..], &[[2.0, 2.0]][..]] {
|
||||
let p = RoofParams {
|
||||
pitch_deg: f64::NAN,
|
||||
overhang: f64::NAN,
|
||||
half_hip_ratio: Some(f64::NAN),
|
||||
mansard_knee_ratio: Some(f64::INFINITY),
|
||||
..params(outline, shape)
|
||||
};
|
||||
let g = roof_geometry(&p, f64::NAN);
|
||||
assert!(g.planes.iter().flatten().all(|v| v.iter().all(|c| c.is_finite())), "{shape:?}");
|
||||
}
|
||||
}
|
||||
let _ = roof_underside_at(&[vec![[0.0, 0.0, 0.0]], vec![]], f64::NAN, f64::NAN, 0.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,617 @@
|
||||
//! Dachflächen über beliebigen einfachen Grundrissen (L/T/U/Z, Fünfeck, schiefe Winkel):
|
||||
//! echte Flächen mit Graten UND Kehlen statt der Bounding-Box-Vereinfachung aus [`crate::roof`].
|
||||
//!
|
||||
//! Modell (Straight-Skeleton-Dach bei gleicher Neigung ringsum): jede Traufkante e „regiert“
|
||||
//! in ihrem Keil — begrenzt von der Kante selbst und den Winkelhalbierenden an ihren Enden (an
|
||||
//! einer einspringenden Ecke wird die Halbierende zur Kehle). Die Dachhöhe ist die NIEDRIGSTE
|
||||
//! Ebene aller Kanten, deren Keil den Punkt enthält:
|
||||
//! z(p) = e + tan(Neigung) · min{ dist(p, Gerade f) | p ∈ Keil(f) }.
|
||||
//! Die Fläche von e = (Traufpolygon ∩ Keil(e)) minus alle Bereiche, in denen eine andere Kante
|
||||
//! tiefer liegt (Polygon-Booleans aus [`crate::polygon_bool`]). Danach in KONVEXE Teilflächen
|
||||
//! zerlegt (Ohr-Schnitt + Hertel–Mehlhorn), weil Renderer/Schnitt konvexe Flächen erwarten.
|
||||
//!
|
||||
//! Portiert aus `src/geometry/roofSkeleton.ts` (TS-Fassung gelöscht).
|
||||
|
||||
use crate::flat::Polygon;
|
||||
use crate::polygon_bool;
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// Grundriss-Punkt (x, y) in Metern.
|
||||
pub type P2 = [f64; 2];
|
||||
/// 3D-Punkt (x, y, z = Höhe) in Metern.
|
||||
pub type P3 = [f64; 3];
|
||||
/// Grundriss-Linie.
|
||||
pub type Line = [P2; 2];
|
||||
|
||||
/// Firstrichtung: entlang der X- oder Y-Achse.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Axis {
|
||||
X,
|
||||
Y,
|
||||
}
|
||||
|
||||
/// Mansarde: ab Traufabstand `d` flacher (Steigung `tan_up`).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Knee {
|
||||
pub d: f64,
|
||||
pub tan_up: f64,
|
||||
}
|
||||
|
||||
/// Ergebnis: Dachflächen (konvex, 3D), Grundriss-Linien, Firsthöhe.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SkeletonRoof {
|
||||
pub planes: Vec<Vec<P3>>,
|
||||
pub ridges: Vec<Line>,
|
||||
pub hips: Vec<Line>,
|
||||
/// Knicklinien der Mansarde.
|
||||
pub breaks: Vec<Line>,
|
||||
/// Senkrechte Giebelflächen (nur Satteldach, s. `ridge_axis`).
|
||||
pub gables: Vec<Vec<P3>>,
|
||||
pub ridge_height: f64,
|
||||
}
|
||||
|
||||
/// Ausgabe-Raster (Meter): entfernt Rundungsrauschen der Polygon-Booleans.
|
||||
const SNAP: f64 = 1e-6;
|
||||
fn snap(v: f64) -> f64 {
|
||||
(v / SNAP).round() * SNAP
|
||||
}
|
||||
|
||||
/// Eingabe-Raster der Polygon-Booleans: exakt zusammenfallende Punkte.
|
||||
const ROUND: f64 = 1e-9;
|
||||
fn rnd(v: f64) -> f64 {
|
||||
(v / ROUND).round() * ROUND
|
||||
}
|
||||
|
||||
/// Signierte Fläche (CCW > 0).
|
||||
pub fn signed_area(pts: &[P2]) -> f64 {
|
||||
let n = pts.len();
|
||||
let mut a = 0.0;
|
||||
for i in 0..n {
|
||||
let p = pts[i];
|
||||
let q = pts[(i + 1) % n];
|
||||
a += p[0] * q[1] - q[0] * p[1];
|
||||
}
|
||||
a / 2.0
|
||||
}
|
||||
|
||||
/// Doppelte und kollineare Punkte entfernen.
|
||||
pub fn clean_ring(pts: &[P2]) -> Vec<P2> {
|
||||
let n = pts.len();
|
||||
let mut out: Vec<P2> = (0..n)
|
||||
.filter(|&i| {
|
||||
let p = pts[i];
|
||||
let q = pts[(i + 1) % n];
|
||||
(p[0] - q[0]).hypot(p[1] - q[1]) > 1e-9
|
||||
})
|
||||
.map(|i| pts[i])
|
||||
.collect();
|
||||
let mut changed = true;
|
||||
while changed && out.len() > 3 {
|
||||
changed = false;
|
||||
let m = out.len();
|
||||
for i in 0..m {
|
||||
let a = out[(i + m - 1) % m];
|
||||
let b = out[i];
|
||||
let c = out[(i + 1) % m];
|
||||
let cr = (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]);
|
||||
if cr.abs() < 1e-9 {
|
||||
out.remove(i);
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn axis_parallel(p: P2, q: P2) -> bool {
|
||||
(p[0] - q[0]).abs() < 1e-9 || (p[1] - q[1]).abs() < 1e-9
|
||||
}
|
||||
|
||||
/// Ob alle Kanten achsparallel sind (und es mehr als ein Rechteck ist).
|
||||
pub fn is_rectilinear_non_rect(outline: &[P2]) -> bool {
|
||||
let pts = clean_ring(outline);
|
||||
let n = pts.len();
|
||||
n > 4 && (0..n).all(|i| axis_parallel(pts[i], pts[(i + 1) % n]))
|
||||
}
|
||||
|
||||
/// Versatz je Kante: überall gleich oder je Kante (a, b) verschieden (Traufe/Ortgang).
|
||||
pub enum Offset<'a> {
|
||||
Const(f64),
|
||||
PerEdge(&'a dyn Fn(P2, P2) -> f64),
|
||||
}
|
||||
|
||||
/// Ring (CCW) nach aussen versetzen (Traufüberstand) — Gehrung an jeder Ecke (Schnitt der
|
||||
/// beiden versetzten Kantengeraden), auch bei schiefen Winkeln.
|
||||
pub fn offset_ring(ring: &[P2], dist: Offset) -> Vec<P2> {
|
||||
if let Offset::Const(d) = dist {
|
||||
if d <= 0.0 {
|
||||
return ring.to_vec();
|
||||
}
|
||||
}
|
||||
let n = ring.len();
|
||||
// Aussen-Normale (Einheit) + Versatz je Kante (CCW → rechte Normale).
|
||||
let edges: Vec<(f64, f64, f64)> = (0..n)
|
||||
.map(|i| {
|
||||
let p = ring[i];
|
||||
let q = ring[(i + 1) % n];
|
||||
let len = (q[0] - p[0]).hypot(q[1] - p[1]);
|
||||
let len = if len == 0.0 { 1.0 } else { len };
|
||||
let d = match &dist {
|
||||
Offset::Const(d) => *d,
|
||||
Offset::PerEdge(f) => f(p, q),
|
||||
};
|
||||
((q[1] - p[1]) / len, -(q[0] - p[0]) / len, d)
|
||||
})
|
||||
.collect();
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let p = ring[i];
|
||||
let a = edges[(i + n - 1) % n];
|
||||
let b = edges[i];
|
||||
let det = a.0 * b.1 - a.1 * b.0;
|
||||
// (fast) kollineare Nachbarkanten: einfach entlang der Normale versetzen.
|
||||
if det.abs() < 1e-6 {
|
||||
return [p[0] + a.0 * a.2, p[1] + a.1 * a.2];
|
||||
}
|
||||
let mut dx = (a.2 * b.1 - b.2 * a.1) / det;
|
||||
let mut dy = (a.0 * b.2 - b.0 * a.2) / det;
|
||||
// Sehr spitze Ecken: Gehrungsspitze begrenzen.
|
||||
let lim = 4.0 * a.2.max(b.2);
|
||||
let len = dx.hypot(dy);
|
||||
if len > lim && len > 0.0 {
|
||||
dx *= lim / len;
|
||||
dy *= lim / len;
|
||||
}
|
||||
[p[0] + dx, p[1] + dy]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Schneiden sich zwei Strecken echt (nicht nur an einem gemeinsamen Endpunkt)?
|
||||
fn segments_cross(a: P2, b: P2, c: P2, d: P2) -> bool {
|
||||
let o = |p: P2, q: P2, r: P2| (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]);
|
||||
let (d1, d2, d3, d4) = (o(a, b, c), o(a, b, d), o(c, d, a), o(c, d, b));
|
||||
d1 * d2 < -1e-12 && d3 * d4 < -1e-12
|
||||
}
|
||||
|
||||
/// Ob der Umriss ein einfaches (selbstüberschneidungsfreies) Polygon ist, das KEIN
|
||||
/// achsparalleles Rechteck ist — dafür liefert [`hip_roof`] für gleichmässig geneigte Dächer
|
||||
/// (Walm/Zelt) die echten Flächen statt der Bounding-Box.
|
||||
pub fn is_skeleton_roofable(outline: &[P2]) -> bool {
|
||||
let pts = clean_ring(outline);
|
||||
let n = pts.len();
|
||||
if n < 3 {
|
||||
return false;
|
||||
}
|
||||
if n == 4 && (0..n).all(|i| axis_parallel(pts[i], pts[(i + 1) % n])) {
|
||||
return false; // Rechteck: Bounding-Box-Dach reicht
|
||||
}
|
||||
if signed_area(&pts).abs() < 1e-6 {
|
||||
return false;
|
||||
}
|
||||
for i in 0..n {
|
||||
for j in (i + 2)..n {
|
||||
if i == 0 && j == n - 1 {
|
||||
continue; // benachbarte Kanten
|
||||
}
|
||||
if segments_cross(pts[i], pts[(i + 1) % n], pts[j], pts[(j + 1) % n]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Konvexes Polygon gegen die Halbebene f(p) ≥ 0 schneiden (Sutherland–Hodgman).
|
||||
pub fn clip_half(poly: &[P2], f: impl Fn(P2) -> f64) -> Vec<P2> {
|
||||
let n = poly.len();
|
||||
let mut out = Vec::with_capacity(n + 2);
|
||||
for i in 0..n {
|
||||
let a = poly[i];
|
||||
let b = poly[(i + 1) % n];
|
||||
let fa = f(a);
|
||||
let fb = f(b);
|
||||
if fa >= 0.0 {
|
||||
out.push(a);
|
||||
}
|
||||
if (fa >= 0.0) != (fb >= 0.0) {
|
||||
let t = fa / (fa - fb);
|
||||
out.push([a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn to_ring(pts: &[P2]) -> Vec<P2> {
|
||||
pts.iter().map(|p| [rnd(p[0]), rnd(p[1])]).collect()
|
||||
}
|
||||
|
||||
struct Edge {
|
||||
a: P2,
|
||||
b: P2,
|
||||
/// Innen-Normale (Einheit).
|
||||
n: P2,
|
||||
}
|
||||
|
||||
/// Walm-/Sattel-/Mansarddach-Flächen über dem Traufring `eaves_in` (beliebige Orientierung)
|
||||
/// bei Neigung `tan` und Traufhöhe `e`. `ridge_axis` gesetzt → Satteldach: Kanten quer zu
|
||||
/// dieser Firstrichtung sind senkrechte Giebel (Ortgang). `knee` → Mansarde.
|
||||
pub fn hip_roof(eaves_in: &[P2], tan: f64, e: f64, ridge_axis: Option<Axis>, knee: Option<Knee>) -> SkeletonRoof {
|
||||
let mut eaves = clean_ring(eaves_in);
|
||||
if eaves.len() < 3 || eaves.iter().any(|p| !p[0].is_finite() || !p[1].is_finite()) {
|
||||
return SkeletonRoof::default();
|
||||
}
|
||||
if signed_area(&eaves) < 0.0 {
|
||||
eaves.reverse();
|
||||
}
|
||||
let n = eaves.len();
|
||||
let edges: Vec<Edge> = (0..n)
|
||||
.map(|i| {
|
||||
let a = eaves[i];
|
||||
let b = eaves[(i + 1) % n];
|
||||
let len = (b[0] - a[0]).hypot(b[1] - a[1]);
|
||||
let len = if len == 0.0 { 1.0 } else { len };
|
||||
Edge { a, b, n: [-(b[1] - a[1]) / len, (b[0] - a[0]) / len] }
|
||||
})
|
||||
.collect();
|
||||
// Giebelkante = quer zur Firstrichtung: keine Neigung, begrenzt nur die Nachbarkeile.
|
||||
let is_gable: Vec<bool> = edges
|
||||
.iter()
|
||||
.map(|ed| match ridge_axis {
|
||||
None => false,
|
||||
Some(Axis::X) => (ed.b[0] - ed.a[0]).abs() < (ed.b[1] - ed.a[1]).abs(),
|
||||
Some(Axis::Y) => (ed.b[1] - ed.a[1]).abs() < (ed.b[0] - ed.a[0]).abs(),
|
||||
})
|
||||
.collect();
|
||||
let dist = |k: usize, p: P2| (p[0] - edges[k].a[0]) * edges[k].n[0] + (p[1] - edges[k].a[1]) * edges[k].n[1];
|
||||
let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
|
||||
for p in &eaves {
|
||||
min_x = min_x.min(p[0]);
|
||||
min_y = min_y.min(p[1]);
|
||||
max_x = max_x.max(p[0]);
|
||||
max_y = max_y.max(p[1]);
|
||||
}
|
||||
let pad = (max_x - min_x + max_y - min_y) * 2.0 + 10.0;
|
||||
let big = [[min_x - pad, min_y - pad], [max_x + pad, min_y - pad], [max_x + pad, max_y + pad], [min_x - pad, max_y + pad]];
|
||||
// Keil je Kante: Innenseite der Kante ∩ Innenseiten der beiden Halbierenden.
|
||||
let wedge: Vec<Vec<P2>> = (0..n)
|
||||
.map(|k| {
|
||||
let ed = &edges[k];
|
||||
let prev = &edges[(k + n - 1) % n];
|
||||
let next = &edges[(k + 1) % n];
|
||||
// An Giebelkanten steht die Keilgrenze senkrecht zur Traufe (= Verlängerung des Giebels).
|
||||
let bis_a = if is_gable[(k + n - 1) % n] { ed.n } else { [ed.n[0] + prev.n[0], ed.n[1] + prev.n[1]] };
|
||||
let bis_b = if is_gable[(k + 1) % n] { ed.n } else { [ed.n[0] + next.n[0], ed.n[1] + next.n[1]] };
|
||||
let side = |o: P2, dir: P2, r: P2| {
|
||||
let s = (dir[0] * (r[1] - o[1]) - dir[1] * (r[0] - o[0])).signum();
|
||||
let s = if s == 0.0 || s.is_nan() { 1.0 } else { s };
|
||||
move |p: P2| s * (dir[0] * (p[1] - o[1]) - dir[1] * (p[0] - o[0]))
|
||||
};
|
||||
let mut w = clip_half(&big, |p| dist(k, p));
|
||||
// Giebelgrenze minimal nach aussen schieben: deckungsgleich mit der Traufring-Kante
|
||||
// würde der Polygon-Boolean an kollinearen Segmenten scheitern.
|
||||
let len = (ed.b[0] - ed.a[0]).hypot(ed.b[1] - ed.a[1]);
|
||||
let len = if len == 0.0 { 1.0 } else { len };
|
||||
let ux = (ed.b[0] - ed.a[0]) / len * 1e-4;
|
||||
let uy = (ed.b[1] - ed.a[1]) / len * 1e-4;
|
||||
let oa = if is_gable[(k + n - 1) % n] { [ed.a[0] - ux, ed.a[1] - uy] } else { ed.a };
|
||||
let ob = if is_gable[(k + 1) % n] { [ed.b[0] + ux, ed.b[1] + uy] } else { ed.b };
|
||||
w = clip_half(&w, side(oa, bis_a, ed.b));
|
||||
w = clip_half(&w, side(ob, bis_b, ed.a));
|
||||
w
|
||||
})
|
||||
.collect();
|
||||
let eaves_poly: Vec<Polygon> = vec![vec![to_ring(&eaves)]];
|
||||
let mut out = SkeletonRoof::default();
|
||||
let mut line_keys: HashSet<[i64; 4]> = HashSet::new();
|
||||
// Liegt der Punkt auf der Traufkante k (Gerade UND innerhalb der Strecke)?
|
||||
let on_seg = |k: usize, p: P2| {
|
||||
let Edge { a, b, .. } = edges[k];
|
||||
let len2 = (b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2);
|
||||
let len2 = if len2 == 0.0 { 1.0 } else { len2 };
|
||||
let t = ((p[0] - a[0]) * (b[0] - a[0]) + (p[1] - a[1]) * (b[1] - a[1])) / len2;
|
||||
dist(k, p).abs() < 1e-5 && t > -1e-6 && t < 1.0 + 1e-6
|
||||
};
|
||||
let on_eaves = |p: P2, q: P2| (0..n).any(|k| on_seg(k, p) && on_seg(k, q));
|
||||
|
||||
for k in 0..n {
|
||||
if is_gable[k] || wedge[k].len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let mut face = polygon_bool::intersection(&eaves_poly, &[vec![to_ring(&wedge[k])]]);
|
||||
// Bereiche, in denen eine andere Kante tiefer liegt, abziehen.
|
||||
let mut subtract: Vec<Polygon> = Vec::new();
|
||||
for f in 0..n {
|
||||
if f == k || is_gable[f] || wedge[f].len() < 3 {
|
||||
continue;
|
||||
}
|
||||
// Deckungsgleiche Ebenen (gleiche Gerade/Normale, z. B. zwei Traufkanten einer Flucht
|
||||
// mit Versatz dazwischen): g ≡ 0 — nur EINE der beiden Flächen darf die andere
|
||||
// abziehen, sonst fällt der überlappende Teil aus beiden heraus (Lücke im Dach).
|
||||
let coplanar = (edges[k].n[0] - edges[f].n[0]).abs() < 1e-9
|
||||
&& (edges[k].n[1] - edges[f].n[1]).abs() < 1e-9
|
||||
&& dist(f, edges[k].a).abs() < 1e-9;
|
||||
if coplanar && f > k {
|
||||
continue;
|
||||
}
|
||||
// dist_f(p) < dist_k(p) ⇔ g(p) = dist_k(p) − dist_f(p) > 0
|
||||
let lower = clip_half(&wedge[f], |p| dist(k, p) - dist(f, p));
|
||||
if lower.len() >= 3 && signed_area(&lower).abs() > 1e-9 {
|
||||
subtract.push(vec![to_ring(&lower)]);
|
||||
}
|
||||
}
|
||||
if !subtract.is_empty() && !face.is_empty() {
|
||||
face = polygon_bool::difference(&face, &subtract);
|
||||
}
|
||||
let z = |p: P2| {
|
||||
let d = dist(k, p).max(0.0);
|
||||
match knee {
|
||||
Some(kn) => e + tan * d.min(kn.d) + kn.tan_up * (d - kn.d).max(0.0),
|
||||
None => e + tan * d,
|
||||
}
|
||||
};
|
||||
for poly in &face {
|
||||
let Some(ring) = poly.first() else { continue };
|
||||
let outer = clean_ring(&ring.iter().map(|p| [snap(p[0]), snap(p[1])]).collect::<Vec<_>>());
|
||||
if outer.len() < 3 || signed_area(&outer).abs() < 1e-6 {
|
||||
continue;
|
||||
}
|
||||
for piece in convex_pieces(&outer) {
|
||||
// Mansarde: Teilfläche an der Knicklinie (Traufabstand = knee.d) teilen.
|
||||
let parts = match knee {
|
||||
Some(kn) => vec![clip_half(&piece, |p| kn.d - dist(k, p)), clip_half(&piece, |p| dist(k, p) - kn.d)],
|
||||
None => vec![piece.clone()],
|
||||
};
|
||||
for part in parts {
|
||||
if part.len() < 3 || signed_area(&part).abs() < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
out.planes.push(part.iter().map(|&p| [p[0], p[1], z(p)]).collect());
|
||||
}
|
||||
if let Some(kn) = knee {
|
||||
let low = clip_half(&piece, |p| kn.d - dist(k, p));
|
||||
let m = low.len();
|
||||
for i in 0..m {
|
||||
let p = low[i];
|
||||
let q = low[(i + 1) % m];
|
||||
if (dist(k, p) - kn.d).abs() < 1e-6 && (dist(k, q) - kn.d).abs() < 1e-6 {
|
||||
out.breaks.push([p, q]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Grat-/Kehl-/Firstlinien: Flächenränder, die nicht auf der Traufe liegen.
|
||||
let m = outer.len();
|
||||
for i in 0..m {
|
||||
let p = outer[i];
|
||||
let q = outer[(i + 1) % m];
|
||||
if on_eaves(p, q) {
|
||||
continue;
|
||||
}
|
||||
let r = |v: f64| (v * 1e5).round() as i64;
|
||||
let kp = [r(p[0]), r(p[1])];
|
||||
let kq = [r(q[0]), r(q[1])];
|
||||
let key = if kp < kq { [kp[0], kp[1], kq[0], kq[1]] } else { [kq[0], kq[1], kp[0], kp[1]] };
|
||||
if !line_keys.insert(key) {
|
||||
continue;
|
||||
}
|
||||
let (zp, zq) = (z(p), z(q));
|
||||
out.ridge_height = out.ridge_height.max(zp - e).max(zq - e);
|
||||
if (zp - zq).abs() < 1e-6 {
|
||||
out.ridges.push([p, q]);
|
||||
} else {
|
||||
out.hips.push([p, q]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Giebelflächen: Profil = alle Flächenecken auf der Giebelkante, nach Lage sortiert.
|
||||
for (k, ed) in edges.iter().enumerate() {
|
||||
if !is_gable[k] {
|
||||
continue;
|
||||
}
|
||||
let len2 = (ed.b[0] - ed.a[0]).powi(2) + (ed.b[1] - ed.a[1]).powi(2);
|
||||
let mut top: Vec<(f64, P3)> = Vec::new();
|
||||
for pl in &out.planes {
|
||||
for &v in pl {
|
||||
let t = ((v[0] - ed.a[0]) * (ed.b[0] - ed.a[0]) + (v[1] - ed.a[1]) * (ed.b[1] - ed.a[1])) / len2;
|
||||
if dist(k, [v[0], v[1]]).abs() < 1e-5 && t > -1e-6 && t < 1.0 + 1e-6 {
|
||||
top.push((t, v));
|
||||
}
|
||||
}
|
||||
}
|
||||
top.sort_by(|p, q| p.0.partial_cmp(&q.0).unwrap_or(std::cmp::Ordering::Equal));
|
||||
let mut prof: Vec<(f64, P3)> = Vec::new();
|
||||
for (i, p) in top.iter().enumerate() {
|
||||
if i == 0 || (p.0 - top[i - 1].0).abs() > 1e-6 {
|
||||
prof.push(*p);
|
||||
}
|
||||
}
|
||||
if prof.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let mut poly: Vec<P3> = vec![[ed.a[0], ed.a[1], e], [ed.b[0], ed.b[1], e]];
|
||||
poly.extend(prof.iter().rev().map(|p| p.1));
|
||||
out.gables.push(poly);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ── Konvexe Zerlegung ───────────────────────────────────────────────────────
|
||||
|
||||
fn cross(o: P2, a: P2, b: P2) -> f64 {
|
||||
(a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
|
||||
}
|
||||
|
||||
fn is_convex(poly: &[P2]) -> bool {
|
||||
let n = poly.len();
|
||||
(0..n).all(|i| cross(poly[i], poly[(i + 1) % n], poly[(i + 2) % n]) >= -1e-12)
|
||||
}
|
||||
|
||||
/// Ohr-Schnitt eines einfachen CCW-Polygons → Dreiecke (Indizes).
|
||||
fn ear_clip(poly: &[P2]) -> Vec<Vec<usize>> {
|
||||
let mut idx: Vec<usize> = (0..poly.len()).collect();
|
||||
let mut tris = Vec::new();
|
||||
let in_tri = |p: P2, a: P2, b: P2, c: P2| cross(a, b, p) >= -1e-12 && cross(b, c, p) >= -1e-12 && cross(c, a, p) >= -1e-12;
|
||||
let mut guard = 0;
|
||||
while idx.len() > 3 && guard < 10000 {
|
||||
guard += 1;
|
||||
let mut cut = false;
|
||||
let m = idx.len();
|
||||
for i in 0..m {
|
||||
let (ia, ib, ic) = (idx[(i + m - 1) % m], idx[i], idx[(i + 1) % m]);
|
||||
let (a, b, c) = (poly[ia], poly[ib], poly[ic]);
|
||||
if cross(a, b, c) <= 1e-12 {
|
||||
continue; // einspringend/entartet
|
||||
}
|
||||
if idx.iter().any(|&j| j != ia && j != ib && j != ic && in_tri(poly[j], a, b, c)) {
|
||||
continue;
|
||||
}
|
||||
tris.push(vec![ia, ib, ic]);
|
||||
idx.remove(i);
|
||||
cut = true;
|
||||
break;
|
||||
}
|
||||
if !cut {
|
||||
break; // numerisch entartet: Rest als Fächer
|
||||
}
|
||||
}
|
||||
for i in 1..idx.len().saturating_sub(1) {
|
||||
tris.push(vec![idx[0], idx[i], idx[i + 1]]);
|
||||
}
|
||||
tris
|
||||
}
|
||||
|
||||
/// Konvexe Teilpolygone (beliebiger Umlaufsinn, Ausgabe CCW): Ohr-Schnitt, dann
|
||||
/// Hertel–Mehlhorn-Verschmelzen.
|
||||
pub fn convex_pieces(poly_in: &[P2]) -> Vec<Vec<P2>> {
|
||||
let mut poly = poly_in.to_vec();
|
||||
if signed_area(&poly) < 0.0 {
|
||||
poly.reverse();
|
||||
}
|
||||
if is_convex(&poly) {
|
||||
return vec![poly];
|
||||
}
|
||||
let mut pieces = ear_clip(&poly);
|
||||
let mut merged = true;
|
||||
while merged {
|
||||
merged = false;
|
||||
'outer: for i in 0..pieces.len() {
|
||||
for j in (i + 1)..pieces.len() {
|
||||
let (a, b) = (&pieces[i], &pieces[j]);
|
||||
// Gemeinsame Kante (u→v in A, v→u in B) suchen.
|
||||
for s in 0..a.len() {
|
||||
let u = a[s];
|
||||
let v = a[(s + 1) % a.len()];
|
||||
let Some(t) = (0..b.len()).find(|&k| b[k] == v && b[(k + 1) % b.len()] == u) else { continue };
|
||||
// A ab v rundum bis u, dann B ab u (ohne u) bis vor v.
|
||||
let mut cand: Vec<usize> = (0..a.len()).map(|k| a[(s + 1 + k) % a.len()]).collect();
|
||||
cand.extend((2..b.len()).map(|k| b[(t + k) % b.len()]));
|
||||
if is_convex(&cand.iter().map(|&q| poly[q]).collect::<Vec<_>>()) {
|
||||
let (lo, hi) = (i.min(j), i.max(j));
|
||||
pieces.remove(hi);
|
||||
pieces.remove(lo);
|
||||
pieces.push(cand);
|
||||
merged = true;
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pieces.into_iter().map(|pc| pc.into_iter().map(|q| poly[q]).collect()).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const L: [P2; 6] = [[0.0, 0.0], [11.0, 0.0], [11.0, 4.0], [8.0, 4.0], [8.0, 6.0], [0.0, 6.0]];
|
||||
|
||||
fn plan_area(pts: &[P3]) -> f64 {
|
||||
signed_area(&pts.iter().map(|p| [p[0], p[1]]).collect::<Vec<_>>()).abs()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn walm_auf_l_deckt_grundriss_mit_kehle() {
|
||||
let r = hip_roof(&L, 1.0, 0.0, None, None);
|
||||
let total: f64 = r.planes.iter().map(|p| plan_area(p)).sum();
|
||||
assert!((total - 60.0).abs() < 1e-6, "{total}");
|
||||
assert!((r.ridge_height - 3.0).abs() < 1e-6);
|
||||
for p in &r.planes {
|
||||
assert_eq!(convex_pieces(&p.iter().map(|v| [v[0], v[1]]).collect::<Vec<_>>()).len(), 1);
|
||||
}
|
||||
// Kehle: einspringende Ecke (8,4) steigt zum Kehlpunkt (6,2).
|
||||
let hit = |a: P2, b: P2| (a == [8.0, 4.0] && b == [6.0, 2.0]) || (b == [8.0, 4.0] && a == [6.0, 2.0]);
|
||||
assert!(r.hips.iter().any(|l| hit(l[0], l[1])), "{:?}", r.hips);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sattel_auf_l_hat_drei_giebel() {
|
||||
let r = hip_roof(&L, 1.0, 0.0, Some(Axis::X), None);
|
||||
let total: f64 = r.planes.iter().map(|p| plan_area(p)).sum();
|
||||
assert!((total - 60.0).abs() < 1e-6);
|
||||
assert_eq!(r.gables.len(), 3);
|
||||
let g = r.gables.iter().find(|g| g.iter().all(|v| v[0] == 0.0)).unwrap();
|
||||
assert!((g.iter().map(|v| v[2]).fold(0.0, f64::max) - 3.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mansarde_knick_teilt_flaechen() {
|
||||
let r = hip_roof(&L, 1.0, 0.0, None, Some(Knee { d: 1.0, tan_up: 0.0 }));
|
||||
let total: f64 = r.planes.iter().map(|p| plan_area(p)).sum();
|
||||
assert!((total - 60.0).abs() < 1e-6);
|
||||
assert!(!r.breaks.is_empty());
|
||||
assert!((r.ridge_height - 1.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn erkennung_der_umrisse() {
|
||||
assert!(is_rectilinear_non_rect(&L));
|
||||
let rect = [[0.0, 0.0], [4.0, 0.0], [4.0, 3.0], [0.0, 3.0]];
|
||||
assert!(!is_rectilinear_non_rect(&rect));
|
||||
assert!(!is_skeleton_roofable(&rect));
|
||||
assert!(is_skeleton_roofable(&[[0.0, 0.0], [8.0, 0.0], [10.0, 5.0], [4.0, 8.0], [-2.0, 5.0]]));
|
||||
// Schleife (Achterform) ist nicht einfach.
|
||||
assert!(!is_skeleton_roofable(&[[0.0, 0.0], [4.0, 4.0], [4.0, 0.0], [0.0, 4.0]]));
|
||||
// Kollineare und doppelte Punkte fallen weg.
|
||||
assert_eq!(clean_ring(&[[0.0, 0.0], [2.0, 0.0], [4.0, 0.0], [4.0, 0.0], [4.0, 3.0], [0.0, 3.0]]).len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn konvexe_zerlegung_erhaelt_flaeche() {
|
||||
let pcs = convex_pieces(&L);
|
||||
assert!(pcs.len() >= 2);
|
||||
let total: f64 = pcs.iter().map(|p| signed_area(p)).sum();
|
||||
assert!((total - 60.0).abs() < 1e-9);
|
||||
for p in &pcs {
|
||||
assert!(is_convex(p));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn versatz_mit_gehrung() {
|
||||
let o = offset_ring(&L, Offset::Const(0.5));
|
||||
assert_eq!(o[0], [-0.5, -0.5]);
|
||||
assert_eq!(o[3], [8.5, 4.5]);
|
||||
let f = |a: P2, b: P2| if (b[0] - a[0]).abs() > (b[1] - a[1]).abs() { 0.5 } else { 1.0 };
|
||||
let o = offset_ring(&L, Offset::PerEdge(&f));
|
||||
assert_eq!(o[0], [-1.0, -0.5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsinn_ohne_panic() {
|
||||
assert!(hip_roof(&[], 1.0, 0.0, None, None).planes.is_empty());
|
||||
assert!(hip_roof(&[[0.0, 0.0], [1.0, 1.0]], 1.0, 0.0, None, None).planes.is_empty());
|
||||
// NaN-Punkte fallen beim Säubern weg, der Rest bleibt ein gültiges Dach.
|
||||
let r = hip_roof(&[[f64::NAN, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.5]], 1.0, 0.0, None, None);
|
||||
assert!(r.planes.iter().flatten().all(|v| v.iter().all(|c| c.is_finite())));
|
||||
let _ = hip_roof(&L, f64::NAN, f64::INFINITY, Some(Axis::Y), Some(Knee { d: f64::NAN, tan_up: f64::NAN }));
|
||||
assert!(convex_pieces(&[]).len() <= 1);
|
||||
let _ = convex_pieces(&[[0.0, 0.0], [1.0, 0.0]]);
|
||||
let _ = offset_ring(&[], Offset::Const(1.0));
|
||||
assert!(!is_skeleton_roofable(&[]));
|
||||
assert!(!is_rectilinear_non_rect(&[]));
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
//! WASM-Modul lahm, [14]).
|
||||
|
||||
mod polygon;
|
||||
mod roof;
|
||||
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
//! Bindungen der Dach-Geometrie (`crate::roof`). Kodierung s. dort.
|
||||
|
||||
use crate::roof::{decode_params, decode_polys3, encode_geometry, roof_geometry, roof_underside_at as underside};
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
/// Dachparameter (flach) + Traufhöhe → flache `RoofGeometry`; kaputte Eingaben → leere Geometrie.
|
||||
#[wasm_bindgen]
|
||||
pub fn roof_geometry_flat(params: &[f64], eaves_z: f64) -> Vec<f64> {
|
||||
let geo = decode_params(params).map(|p| roof_geometry(&p, eaves_z)).unwrap_or_default();
|
||||
encode_geometry(&geo)
|
||||
}
|
||||
|
||||
/// Dach-Unterkante an (x, y) über den flachen Dachflächen `[n, (m, (x, y, z)…)…]`; NaN = ausserhalb.
|
||||
#[wasm_bindgen]
|
||||
pub fn roof_underside_at(planes: &[f64], total_layer_thickness: f64, x: f64, y: f64) -> f64 {
|
||||
decode_polys3(planes).and_then(|pl| underside(&pl, total_layer_thickness, x, y)).unwrap_or(f64::NAN)
|
||||
}
|
||||
+81
-486
@@ -1,17 +1,15 @@
|
||||
// Dach-Geometrie: leitet aus einem (rechteckigen) Grundriss-Umriss + Dachform +
|
||||
// Neigung die Grundriss-Linien (Traufe/First/Grat/Knick) UND die 3D-Dachflächen
|
||||
// ab. Bewusst auf der BOUNDING-BOX des Umrisses gerechnet (First entlang einer
|
||||
// Hauptachse) — die gängige, intuitive Vereinfachung, die alle Standardformen
|
||||
// (Flach/Pult/Sattel/Walm/Mansarde/Zelt) exakt und ohne Straight-Skeleton abdeckt.
|
||||
// Dach-Geometrie: Grundriss-Linien (Traufe/First/Grat/Knick) und 3D-Dachflächen eines Dachs.
|
||||
// Gerechnet wird im Rust-Kern (`src-tauri/core/src/roof.rs`, Skelett für L/T/U und schiefe
|
||||
// Umrisse in `roof_skeleton.rs`); hier bleiben die Typen, die flache Übergabe an die WASM-Grenze,
|
||||
// die Memoisierung und `roofBaseElevation` (liest das Projekt).
|
||||
//
|
||||
// Koordinaten: Grundriss (x, y) in Metern; 3D-Punkte als [x, y, z] mit z = Höhe.
|
||||
// Reine Datenschicht (kein React/Store), voll unit-testbar.
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import type { Project, Roof, Vec2 } from "../model/types";
|
||||
import type { Project, Roof, RoofShape, Vec2 } from "../model/types";
|
||||
import { getFloor } from "../model/types";
|
||||
import { cleanRing, convexPieces, isRectilinearNonRect, isSkeletonRoofable, offsetRectilinear, rectilinearHipRoof } from "./roofSkeleton";
|
||||
import { core } from "../engine/coreWasm";
|
||||
|
||||
/** 3D-Punkt [x, y, z=Höhe] in Modell-Metern. */
|
||||
export type Vec3 = [number, number, number];
|
||||
@@ -39,8 +37,6 @@ export interface RoofGeometry {
|
||||
ridgeHeight: number;
|
||||
}
|
||||
|
||||
const DEG = Math.PI / 180;
|
||||
|
||||
/** Bounding-Box eines Umrisses. */
|
||||
export function roofBBox(outline: Vec2[]): { x0: number; y0: number; x1: number; y1: number } {
|
||||
let x0 = Infinity;
|
||||
@@ -71,485 +67,91 @@ export function roofBaseElevation(project: Project, roof: Roof): number {
|
||||
}
|
||||
}
|
||||
|
||||
const P = (x: number, y: number): Vec2 => ({ x, y });
|
||||
// ── Flache Übergabe (Kodierung s. `roof.rs`) ────────────────────────────────
|
||||
|
||||
/**
|
||||
* Kanonische Berechnung mit First entlang der X-Achse auf dem Rechteck
|
||||
* [x0,x1]×[y0,y1] (Traufe, inkl. Überstand) auf Traufhöhe `e`. Die „y"-First-
|
||||
* Richtung wird im Wrapper durch Transponieren (x↔y) erreicht.
|
||||
*/
|
||||
function computeCanonical(
|
||||
x0: number,
|
||||
y0: number,
|
||||
x1: number,
|
||||
y1: number,
|
||||
e: number,
|
||||
roof: Roof,
|
||||
): RoofGeometry {
|
||||
const xc = (x0 + x1) / 2;
|
||||
const yc = (y0 + y1) / 2;
|
||||
const halfW = (x1 - x0) / 2;
|
||||
const halfD = (y1 - y0) / 2;
|
||||
const a = Math.max(0, roof.pitchDeg) * DEG;
|
||||
const tan = Math.tan(a);
|
||||
const h = halfD * tan; // Firsthöhe (Sattel/Walm/Mansarde)
|
||||
const SHAPE_CODE: Record<RoofShape, number> = { flach: 0, pult: 1, sattel: 2, walm: 3, mansarde: 4, zelt: 5 };
|
||||
const MANSARD_CODE = { giebel: 0, walm: 1, zelt: 2 } as const;
|
||||
|
||||
const eaves: Vec2[] = [P(x0, y0), P(x1, y0), P(x1, y1), P(x0, y1)];
|
||||
const flat = (): RoofGeometry => ({
|
||||
eaves,
|
||||
ridges: [],
|
||||
hips: [],
|
||||
breaks: [],
|
||||
planes: [{ pts: [[x0, y0, e], [x1, y0, e], [x1, y1, e], [x0, y1, e]] }],
|
||||
gables: [],
|
||||
ridgeHeight: 0,
|
||||
});
|
||||
|
||||
switch (roof.shape) {
|
||||
case "flach":
|
||||
return flat();
|
||||
|
||||
case "pult": {
|
||||
// Eine Fläche: tiefe Seite y0 auf Traufe, hohe Seite y1 auf e+H.
|
||||
const H = (y1 - y0) * tan;
|
||||
return {
|
||||
eaves,
|
||||
ridges: [[P(x0, y1), P(x1, y1)]], // hohe Kante (First-Ersatz)
|
||||
hips: [],
|
||||
breaks: [],
|
||||
planes: [{ pts: [[x0, y0, e], [x1, y0, e], [x1, y1, e + H], [x0, y1, e + H]] }],
|
||||
gables: [
|
||||
[[x0, y0, e], [x0, y1, e + H], [x0, y1, e]],
|
||||
[[x1, y0, e], [x1, y1, e + H], [x1, y1, e]],
|
||||
],
|
||||
ridgeHeight: H,
|
||||
};
|
||||
}
|
||||
|
||||
case "sattel": {
|
||||
const rz = e + h;
|
||||
const hh = Math.min(0.9, Math.max(0, roof.halfHipRatio ?? 0));
|
||||
if (hh > 1e-6 && halfW > halfD * hh + 1e-6) {
|
||||
// Krüppelwalm: oberer Giebelteil (Anteil `hh` der Firsthöhe) als kleine Walmflächen
|
||||
// gleicher Neigung — Walmlauf = halbe Tiefe · hh, First entsprechend verkürzt.
|
||||
const kz = e + h * (1 - hh);
|
||||
const yk0 = y0 + halfD * (1 - hh);
|
||||
const yk1 = y1 - halfD * (1 - hh);
|
||||
const d = halfD * hh;
|
||||
return {
|
||||
eaves,
|
||||
ridges: [[P(x0 + d, yc), P(x1 - d, yc)]],
|
||||
hips: [
|
||||
[P(x0, yk0), P(x0 + d, yc)],
|
||||
[P(x0, yk1), P(x0 + d, yc)],
|
||||
[P(x1, yk0), P(x1 - d, yc)],
|
||||
[P(x1, yk1), P(x1 - d, yc)],
|
||||
],
|
||||
breaks: [],
|
||||
planes: [
|
||||
{ pts: [[x0, y0, e], [x1, y0, e], [x1, yk0, kz], [x1 - d, yc, rz], [x0 + d, yc, rz], [x0, yk0, kz]] },
|
||||
{ pts: [[x0, y1, e], [x1, y1, e], [x1, yk1, kz], [x1 - d, yc, rz], [x0 + d, yc, rz], [x0, yk1, kz]] },
|
||||
{ pts: [[x0, yk0, kz], [x0, yk1, kz], [x0 + d, yc, rz]] },
|
||||
{ pts: [[x1, yk0, kz], [x1, yk1, kz], [x1 - d, yc, rz]] },
|
||||
],
|
||||
gables: [
|
||||
[[x0, y0, e], [x0, y1, e], [x0, yk1, kz], [x0, yk0, kz]],
|
||||
[[x1, y0, e], [x1, y1, e], [x1, yk1, kz], [x1, yk0, kz]],
|
||||
],
|
||||
ridgeHeight: h,
|
||||
};
|
||||
}
|
||||
return {
|
||||
eaves,
|
||||
ridges: [[P(x0, yc), P(x1, yc)]],
|
||||
hips: [],
|
||||
breaks: [],
|
||||
planes: [
|
||||
{ pts: [[x0, y0, e], [x1, y0, e], [x1, yc, rz], [x0, yc, rz]] },
|
||||
{ pts: [[x0, y1, e], [x1, y1, e], [x1, yc, rz], [x0, yc, rz]] },
|
||||
],
|
||||
gables: [
|
||||
[[x0, y0, e], [x0, y1, e], [x0, yc, rz]],
|
||||
[[x1, y0, e], [x1, y1, e], [x1, yc, rz]],
|
||||
],
|
||||
ridgeHeight: h,
|
||||
};
|
||||
}
|
||||
|
||||
case "walm": {
|
||||
const rz = e + h;
|
||||
// First um die halbe Tiefe an beiden Enden verkürzt (45°-Grate bei
|
||||
// gleicher Neigung). Bei schmalem Baukörper (halfW<halfD) degeneriert er
|
||||
// zum Punkt (xc) → Walm wird zeltartig.
|
||||
let ra = x0 + halfD;
|
||||
let rb = x1 - halfD;
|
||||
if (ra > rb) ra = rb = xc;
|
||||
return {
|
||||
eaves,
|
||||
ridges: [[P(ra, yc), P(rb, yc)]],
|
||||
hips: [
|
||||
[P(x0, y0), P(ra, yc)],
|
||||
[P(x0, y1), P(ra, yc)],
|
||||
[P(x1, y0), P(rb, yc)],
|
||||
[P(x1, y1), P(rb, yc)],
|
||||
],
|
||||
breaks: [],
|
||||
planes: [
|
||||
{ pts: [[x0, y0, e], [x1, y0, e], [rb, yc, rz], [ra, yc, rz]] },
|
||||
{ pts: [[x0, y1, e], [x1, y1, e], [rb, yc, rz], [ra, yc, rz]] },
|
||||
{ pts: [[x0, y0, e], [x0, y1, e], [ra, yc, rz]] },
|
||||
{ pts: [[x1, y0, e], [x1, y1, e], [rb, yc, rz]] },
|
||||
],
|
||||
gables: [],
|
||||
ridgeHeight: h,
|
||||
};
|
||||
}
|
||||
|
||||
case "mansarde": {
|
||||
// Mansarde: steile untere Neigung (pitchDeg) bis zur Knicklinie, dann
|
||||
// flache obere (pitchUpperDeg ?? halbe Hauptneigung). Untertyp steuert, ob
|
||||
// die Knickform an ZWEI Seiten sitzt (Giebel) oder RINGSUM (Walm/Zelt).
|
||||
const aLow = a;
|
||||
const aUp = Math.max(0, roof.pitchUpperDeg ?? roof.pitchDeg / 2) * DEG;
|
||||
const ratio = Math.min(0.49, Math.max(0.05, roof.mansardKneeRatio ?? 0.4));
|
||||
const mType = roof.mansardType ?? "giebel";
|
||||
|
||||
if (mType === "giebel") {
|
||||
// Mansard-Satteldach: Knick nur an den beiden Traufseiten, Giebel an den
|
||||
// Enden (bisheriges Verhalten, jetzt mit parametrierbarem Knick).
|
||||
const d1 = halfD * ratio;
|
||||
const z1 = e + d1 * Math.tan(aLow);
|
||||
const z2 = z1 + (halfD - d1) * Math.tan(aUp);
|
||||
const yf = y0 + d1;
|
||||
const yb = y1 - d1;
|
||||
return {
|
||||
eaves,
|
||||
ridges: [[P(x0, yc), P(x1, yc)]],
|
||||
hips: [],
|
||||
breaks: [
|
||||
[P(x0, yf), P(x1, yf)],
|
||||
[P(x0, yb), P(x1, yb)],
|
||||
],
|
||||
planes: [
|
||||
{ pts: [[x0, y0, e], [x1, y0, e], [x1, yf, z1], [x0, yf, z1]] },
|
||||
{ pts: [[x0, yf, z1], [x1, yf, z1], [x1, yc, z2], [x0, yc, z2]] },
|
||||
{ pts: [[x0, y1, e], [x1, y1, e], [x1, yb, z1], [x0, yb, z1]] },
|
||||
{ pts: [[x0, yb, z1], [x1, yb, z1], [x1, yc, z2], [x0, yc, z2]] },
|
||||
],
|
||||
gables: [
|
||||
[[x0, y0, e], [x0, yf, z1], [x0, yc, z2], [x0, yb, z1], [x0, y1, e]],
|
||||
[[x1, y0, e], [x1, yf, z1], [x1, yc, z2], [x1, yb, z1], [x1, y1, e]],
|
||||
],
|
||||
ridgeHeight: z2 - e,
|
||||
};
|
||||
}
|
||||
|
||||
// Allseitige Mansarde (Walm/Zelt): steiler Sockel ringsum bis zur
|
||||
// Knicklinie (inneres Rechteck), darüber flacher Walm bzw. flache Spitze.
|
||||
const dLow = Math.min(halfW, halfD) * ratio;
|
||||
const z1 = e + dLow * Math.tan(aLow);
|
||||
const ix0 = x0 + dLow;
|
||||
const iy0 = y0 + dLow;
|
||||
const ix1 = x1 - dLow;
|
||||
const iy1 = y1 - dLow;
|
||||
const ihalfD = (iy1 - iy0) / 2;
|
||||
const ihalfW = (ix1 - ix0) / 2;
|
||||
// Sockel-Trapeze (4 Seiten, steil) + Sockel-Grate (Ecken aussen→innen) +
|
||||
// Knicklinie (inneres Rechteck) sind beiden allseitigen Formen gemein.
|
||||
const socketPlanes = [
|
||||
{ pts: [[x0, y0, e], [x1, y0, e], [ix1, iy0, z1], [ix0, iy0, z1]] as Vec3[] },
|
||||
{ pts: [[x1, y1, e], [x0, y1, e], [ix0, iy1, z1], [ix1, iy1, z1]] as Vec3[] },
|
||||
{ pts: [[x0, y1, e], [x0, y0, e], [ix0, iy0, z1], [ix0, iy1, z1]] as Vec3[] },
|
||||
{ pts: [[x1, y0, e], [x1, y1, e], [ix1, iy1, z1], [ix1, iy0, z1]] as Vec3[] },
|
||||
];
|
||||
const socketHips: [Vec2, Vec2][] = [
|
||||
[P(x0, y0), P(ix0, iy0)],
|
||||
[P(x1, y0), P(ix1, iy0)],
|
||||
[P(x1, y1), P(ix1, iy1)],
|
||||
[P(x0, y1), P(ix0, iy1)],
|
||||
];
|
||||
const kneeBreaks: [Vec2, Vec2][] = [
|
||||
[P(ix0, iy0), P(ix1, iy0)],
|
||||
[P(ix1, iy0), P(ix1, iy1)],
|
||||
[P(ix1, iy1), P(ix0, iy1)],
|
||||
[P(ix0, iy1), P(ix0, iy0)],
|
||||
];
|
||||
|
||||
if (mType === "walm") {
|
||||
// Oberer Walm auf dem inneren Rechteck (First entlang X).
|
||||
const z2 = z1 + ihalfD * Math.tan(aUp);
|
||||
let ra = ix0 + ihalfD;
|
||||
let rb = ix1 - ihalfD;
|
||||
if (ra > rb) ra = rb = xc;
|
||||
return {
|
||||
eaves,
|
||||
ridges: [[P(ra, yc), P(rb, yc)]],
|
||||
hips: [
|
||||
...socketHips,
|
||||
[P(ix0, iy0), P(ra, yc)],
|
||||
[P(ix1, iy0), P(rb, yc)],
|
||||
[P(ix1, iy1), P(rb, yc)],
|
||||
[P(ix0, iy1), P(ra, yc)],
|
||||
],
|
||||
breaks: kneeBreaks,
|
||||
planes: [
|
||||
...socketPlanes,
|
||||
{ pts: [[ix0, iy0, z1], [ix1, iy0, z1], [rb, yc, z2], [ra, yc, z2]] },
|
||||
{ pts: [[ix1, iy1, z1], [ix0, iy1, z1], [ra, yc, z2], [rb, yc, z2]] },
|
||||
{ pts: [[ix0, iy1, z1], [ix0, iy0, z1], [ra, yc, z2]] },
|
||||
{ pts: [[ix1, iy0, z1], [ix1, iy1, z1], [rb, yc, z2]] },
|
||||
],
|
||||
gables: [],
|
||||
ridgeHeight: z2 - e,
|
||||
};
|
||||
}
|
||||
|
||||
// "zelt": flache Spitze über der Mitte des inneren Rechtecks.
|
||||
const z2 = z1 + Math.min(ihalfW, ihalfD) * Math.tan(aUp);
|
||||
return {
|
||||
eaves,
|
||||
ridges: [],
|
||||
hips: [
|
||||
...socketHips,
|
||||
[P(ix0, iy0), P(xc, yc)],
|
||||
[P(ix1, iy0), P(xc, yc)],
|
||||
[P(ix1, iy1), P(xc, yc)],
|
||||
[P(ix0, iy1), P(xc, yc)],
|
||||
],
|
||||
breaks: kneeBreaks,
|
||||
planes: [
|
||||
...socketPlanes,
|
||||
{ pts: [[ix0, iy0, z1], [ix1, iy0, z1], [xc, yc, z2]] },
|
||||
{ pts: [[ix1, iy0, z1], [ix1, iy1, z1], [xc, yc, z2]] },
|
||||
{ pts: [[ix1, iy1, z1], [ix0, iy1, z1], [xc, yc, z2]] },
|
||||
{ pts: [[ix0, iy1, z1], [ix0, iy0, z1], [xc, yc, z2]] },
|
||||
],
|
||||
gables: [],
|
||||
ridgeHeight: z2 - e,
|
||||
};
|
||||
}
|
||||
|
||||
case "zelt": {
|
||||
// Allseitig zur Spitze über der Mitte.
|
||||
const hz = Math.min(halfW, halfD) * tan;
|
||||
const az = e + hz;
|
||||
return {
|
||||
eaves,
|
||||
ridges: [],
|
||||
hips: [
|
||||
[P(x0, y0), P(xc, yc)],
|
||||
[P(x1, y0), P(xc, yc)],
|
||||
[P(x1, y1), P(xc, yc)],
|
||||
[P(x0, y1), P(xc, yc)],
|
||||
],
|
||||
breaks: [],
|
||||
planes: [
|
||||
{ pts: [[x0, y0, e], [x1, y0, e], [xc, yc, az]] },
|
||||
{ pts: [[x1, y0, e], [x1, y1, e], [xc, yc, az]] },
|
||||
{ pts: [[x1, y1, e], [x0, y1, e], [xc, yc, az]] },
|
||||
{ pts: [[x0, y1, e], [x0, y0, e], [xc, yc, az]] },
|
||||
],
|
||||
gables: [],
|
||||
ridgeHeight: hz,
|
||||
};
|
||||
}
|
||||
function encodeRoof(roof: Roof): Float64Array {
|
||||
const pts = roof.outline;
|
||||
const buf = new Float64Array(10 + 2 * pts.length);
|
||||
buf[0] = SHAPE_CODE[roof.shape] ?? 0;
|
||||
buf[1] = roof.pitchDeg;
|
||||
buf[2] = roof.pitchUpperDeg ?? NaN;
|
||||
buf[3] = MANSARD_CODE[roof.mansardType ?? "giebel"] ?? 0;
|
||||
buf[4] = roof.mansardKneeRatio ?? NaN;
|
||||
buf[5] = roof.halfHipRatio ?? NaN;
|
||||
buf[6] = roof.overhang;
|
||||
buf[7] = roof.overhangGable ?? NaN;
|
||||
buf[8] = roof.ridgeAxis === "y" ? 1 : 0;
|
||||
buf[9] = pts.length;
|
||||
for (let i = 0; i < pts.length; i++) {
|
||||
buf[10 + 2 * i] = pts[i].x;
|
||||
buf[11 + 2 * i] = pts[i].y;
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
const swap2 = (p: Vec2): Vec2 => ({ x: p.y, y: p.x });
|
||||
const swap3 = (p: Vec3): Vec3 => [p[1], p[0], p[2]];
|
||||
const swapLine = (l: [Vec2, Vec2]): [Vec2, Vec2] => [swap2(l[0]), swap2(l[1])];
|
||||
/** Flächen der Geometrie als flacher Puffer `[n, (m, (x, y, z)…)…]` (für `roofUndersideAt`). */
|
||||
const planesFlat = new WeakMap<RoofGeometry, Float64Array>();
|
||||
|
||||
function decodeGeometry(b: Float64Array): RoofGeometry {
|
||||
let i = 0;
|
||||
const ridgeHeight = b[i++];
|
||||
const pt = (): Vec2 => ({ x: b[i++], y: b[i++] });
|
||||
const eaves: Vec2[] = [];
|
||||
for (let n = b[i++]; n > 0; n--) eaves.push(pt());
|
||||
const lines = (): [Vec2, Vec2][] => {
|
||||
const out: [Vec2, Vec2][] = [];
|
||||
for (let n = b[i++]; n > 0; n--) out.push([pt(), pt()]);
|
||||
return out;
|
||||
};
|
||||
const ridges = lines();
|
||||
const hips = lines();
|
||||
const breaks = lines();
|
||||
const planesStart = i;
|
||||
const polys = (): Vec3[][] => {
|
||||
const out: Vec3[][] = [];
|
||||
for (let n = b[i++]; n > 0; n--) {
|
||||
const poly: Vec3[] = [];
|
||||
for (let m = b[i++]; m > 0; m--) poly.push([b[i++], b[i++], b[i++]]);
|
||||
out.push(poly);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
const planes = polys().map((pts) => ({ pts }));
|
||||
const planesEnd = i;
|
||||
const gables = polys();
|
||||
const geo: RoofGeometry = { eaves, ridges, hips, breaks, planes, gables, ridgeHeight };
|
||||
planesFlat.set(geo, b.subarray(planesStart, planesEnd));
|
||||
return geo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dach-Geometrie aus Form/Neigung/Überstand + Traufhöhe `eavesZ`. Rechnet auf
|
||||
* der Bounding-Box des Umrisses, um `overhang` nach aussen geweitet. Für
|
||||
* `ridgeAxis:"y"` wird kanonisch (First entlang X) gerechnet und danach x↔y
|
||||
* transponiert.
|
||||
* Dach-Geometrie aus Form/Neigung/Überstand + Traufhöhe `eavesZ` (Rust-Kern). Rechteck: auf der
|
||||
* Bounding-Box des Umrisses, um den Überstand geweitet, First entlang `ridgeAxis`; L/T/U und
|
||||
* schiefe Umrisse: Skelett mit Graten, Kehlen und Giebeln.
|
||||
*/
|
||||
export function roofGeometry(roof: Roof, eavesZ: number): RoofGeometry {
|
||||
// Memo je Dach-Objekt: Dächer sind immutabel (structural sharing), die Berechnung (Skelett über
|
||||
// Polygon-Booleans) kostet ~50 ms je Dach und wird je Ableitung (3D, Schnitt, Pick, Highlight …)
|
||||
// mehrfach gebraucht — vorher rechnete jeder Aufruf neu (projectToModel3d: ~550 ms bei 10 Dächern).
|
||||
// Memo je Dach-Objekt: Dächer sind immutabel (structural sharing), die Geometrie wird je
|
||||
// Ableitung (3D, Schnitt, Pick, Highlight …) mehrfach gebraucht — ungecacht rechnete
|
||||
// projectToModel3d bei 10 Dächern ~550 ms (TS-Skelett), mit Memo ~3 ms.
|
||||
const hit = roofGeometryCache.get(roof);
|
||||
if (hit && hit.eavesZ === eavesZ) return hit.geo;
|
||||
const geo = roofGeometryUncached(roof, eavesZ);
|
||||
const geo = decodeGeometry(core().roof_geometry_flat(encodeRoof(roof), eavesZ));
|
||||
roofGeometryCache.set(roof, { eavesZ, geo });
|
||||
return geo;
|
||||
}
|
||||
|
||||
const roofGeometryCache = new WeakMap<Roof, { eavesZ: number; geo: RoofGeometry }>();
|
||||
|
||||
function roofGeometryUncached(roof: Roof, eavesZ: number): RoofGeometry {
|
||||
// Walmdach über einem rechtwinkligen, nicht-rechteckigen Grundriss (L/T/U …):
|
||||
// echte Flächen mit Graten und Kehlen statt Bounding-Box (s. roofSkeleton.ts).
|
||||
// Zeltdach/Mansard-Zelt auf L/T/U: eine einzelne Spitze gibt es dort nicht — sinnvolles
|
||||
// Gegenstück ist das allseitig geneigte Skelett-Dach (wie Walm, ohne Giebel).
|
||||
if (
|
||||
(roof.shape === "walm" || roof.shape === "sattel" || roof.shape === "mansarde" || roof.shape === "zelt") &&
|
||||
isRectilinearNonRect(roof.outline)
|
||||
) {
|
||||
return rectilinearWalm(roof, eavesZ);
|
||||
}
|
||||
// Beliebiger einfacher Umriss (Fünfeck, Pfeil, schiefe Winkel, gedrehtes Rechteck):
|
||||
// nur allseitig gleich geneigte Formen (Walm/Zelt/Mansard-Walm/-Zelt) — Giebel brauchen
|
||||
// achsparallele Kanten und bleiben bei der Bounding-Box.
|
||||
const allround =
|
||||
roof.shape === "walm" ||
|
||||
roof.shape === "zelt" ||
|
||||
(roof.shape === "mansarde" && (roof.mansardType ?? "giebel") !== "giebel");
|
||||
if (allround && isSkeletonRoofable(roof.outline)) {
|
||||
return rectilinearWalm(roof, eavesZ);
|
||||
}
|
||||
if (roof.shape === "pult" && isRectilinearNonRect(roof.outline)) {
|
||||
return rectilinearPult(roof, eavesZ);
|
||||
}
|
||||
const bb = roofBBox(roof.outline);
|
||||
const oe = Math.max(0, roof.overhang); // Traufüberstand (senkrecht zum First)
|
||||
const og = Math.max(0, roof.overhangGable ?? roof.overhang); // Ortgang (entlang First)
|
||||
// Der First liegt entlang der `ridgeAxis`-Achse: dort wirkt der Ortgang-, quer
|
||||
// dazu der Traufüberstand. In OUTLINE-Koordinaten je nach Firstrichtung mappen.
|
||||
const ox = roof.ridgeAxis === "x" ? og : oe;
|
||||
const oy = roof.ridgeAxis === "x" ? oe : og;
|
||||
let x0 = bb.x0 - ox;
|
||||
let y0 = bb.y0 - oy;
|
||||
let x1 = bb.x1 + ox;
|
||||
let y1 = bb.y1 + oy;
|
||||
const flip = roof.ridgeAxis === "y";
|
||||
if (flip) {
|
||||
[x0, y0, x1, y1] = [y0, x0, y1, x1];
|
||||
}
|
||||
const g = computeCanonical(x0, y0, x1, y1, eavesZ, roof);
|
||||
if (!flip) return g;
|
||||
return {
|
||||
eaves: g.eaves.map(swap2),
|
||||
ridges: g.ridges.map(swapLine),
|
||||
hips: g.hips.map(swapLine),
|
||||
breaks: g.breaks.map(swapLine),
|
||||
planes: g.planes.map((pl) => ({ pts: pl.pts.map(swap3) })),
|
||||
gables: g.gables.map((poly) => poly.map(swap3)),
|
||||
ridgeHeight: g.ridgeHeight,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Walmdach auf rechtwinkligem Grundriss: Traufe = Umriss um den Traufüberstand
|
||||
* nach aussen versetzt (ringsum gleich — beim Walm ist jede Kante Traufe),
|
||||
* Flächen/Linien aus {@link rectilinearHipRoof}.
|
||||
*/
|
||||
function rectilinearWalm(roof: Roof, eavesZ: number): RoofGeometry {
|
||||
let ring = cleanRing(roof.outline);
|
||||
let area = 0;
|
||||
for (let i = 0; i < ring.length; i++) {
|
||||
const p = ring[i];
|
||||
const q = ring[(i + 1) % ring.length];
|
||||
area += p.x * q.y - q.x * p.y;
|
||||
}
|
||||
if (area < 0) ring = [...ring].reverse();
|
||||
const oe = Math.max(0, roof.overhang);
|
||||
const og = Math.max(0, roof.overhangGable ?? roof.overhang);
|
||||
// Satteldach: Kanten quer zum First sind Ortgang (eigener Überstand), sonst Traufe.
|
||||
const eaves = offsetRectilinear(
|
||||
ring,
|
||||
roof.shape === "sattel"
|
||||
? (a, b) => {
|
||||
const alongX = Math.abs(b.x - a.x) > Math.abs(b.y - a.y);
|
||||
return alongX === (roof.ridgeAxis === "x") ? oe : og;
|
||||
}
|
||||
: oe,
|
||||
);
|
||||
const tan = Math.tan(Math.max(0, roof.pitchDeg) * DEG);
|
||||
const gabled = roof.shape === "sattel" || (roof.shape === "mansarde" && (roof.mansardType ?? "giebel") === "giebel");
|
||||
const ridgeAxis = gabled ? roof.ridgeAxis : undefined;
|
||||
let knee: { d: number; tanUp: number } | undefined;
|
||||
if (roof.shape === "mansarde") {
|
||||
// Knick bei `mansardKneeRatio` der maximalen Dachtiefe (Abstand First–Traufe).
|
||||
const depth = rectilinearHipRoof(eaves, 1, 0, ridgeAxis).ridgeHeight;
|
||||
const ratio = Math.min(0.49, Math.max(0.05, roof.mansardKneeRatio ?? 0.4));
|
||||
const aUp = Math.max(0, roof.pitchUpperDeg ?? roof.pitchDeg / 2) * DEG;
|
||||
knee = { d: depth * ratio, tanUp: Math.tan(aUp) };
|
||||
}
|
||||
const sk = rectilinearHipRoof(eaves, tan, eavesZ, ridgeAxis, knee);
|
||||
return {
|
||||
eaves,
|
||||
ridges: sk.ridges,
|
||||
hips: sk.hips,
|
||||
breaks: sk.breaks,
|
||||
planes: sk.planes.map((pts) => ({ pts })),
|
||||
gables: sk.gables,
|
||||
ridgeHeight: sk.ridgeHeight,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Pultdach auf rechtwinkligem Grundriss: EINE Ebene über dem (um Traufe/Ortgang
|
||||
* geweiteten) Umriss. Tief bei kleinstem y (First entlang x) bzw. x (First entlang y),
|
||||
* Steigung wie beim Rechteck-Pult; Kanten quer zum First bekommen senkrechte Giebel.
|
||||
*/
|
||||
function rectilinearPult(roof: Roof, eavesZ: number): RoofGeometry {
|
||||
let ring = cleanRing(roof.outline);
|
||||
let area = 0;
|
||||
for (let i = 0; i < ring.length; i++) {
|
||||
const p = ring[i];
|
||||
const q = ring[(i + 1) % ring.length];
|
||||
area += p.x * q.y - q.x * p.y;
|
||||
}
|
||||
if (area < 0) ring = [...ring].reverse();
|
||||
const oe = Math.max(0, roof.overhang);
|
||||
const og = Math.max(0, roof.overhangGable ?? roof.overhang);
|
||||
const ax = roof.ridgeAxis === "x";
|
||||
const eaves = offsetRectilinear(ring, (a, b) => {
|
||||
const alongX = Math.abs(b.x - a.x) > Math.abs(b.y - a.y);
|
||||
return alongX === ax ? oe : og;
|
||||
});
|
||||
const tan = Math.tan(Math.max(0, roof.pitchDeg) * DEG);
|
||||
const s = (p: Vec2) => (ax ? p.y : p.x);
|
||||
const smin = Math.min(...eaves.map(s));
|
||||
const smax = Math.max(...eaves.map(s));
|
||||
const z = (p: Vec2) => eavesZ + tan * (s(p) - smin);
|
||||
const up = (p: Vec2): Vec3 => [p.x, p.y, z(p)];
|
||||
const base = (p: Vec2): Vec3 => [p.x, p.y, eavesZ];
|
||||
const gables: Vec3[][] = [];
|
||||
eaves.forEach((a, i) => {
|
||||
const b = eaves[(i + 1) % eaves.length];
|
||||
const alongX = Math.abs(b.x - a.x) > Math.abs(b.y - a.y);
|
||||
if (alongX === ax) return;
|
||||
gables.push([base(a), base(b), up(b), up(a)]);
|
||||
});
|
||||
return {
|
||||
eaves,
|
||||
ridges: [], // höchste Kante(n): Rand bei smax
|
||||
hips: [],
|
||||
breaks: [],
|
||||
planes: convexPieces(eaves).map((pc) => ({ pts: pc.map(up) })),
|
||||
gables,
|
||||
ridgeHeight: (smax - smin) * tan,
|
||||
};
|
||||
}
|
||||
|
||||
/** Punkt-in-Polygon (Ray-Casting), 2D-Aufsicht. */
|
||||
function pointInPolygon2D(p: Vec2, poly: Vec2[]): boolean {
|
||||
let inside = false;
|
||||
const n = poly.length;
|
||||
for (let i = 0, j = n - 1; i < n; j = i++) {
|
||||
const a = poly[i];
|
||||
const b = poly[j];
|
||||
const intersect =
|
||||
a.y > p.y !== b.y > p.y &&
|
||||
p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y || 1e-12) + a.x;
|
||||
if (intersect) inside = !inside;
|
||||
}
|
||||
return inside;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dach-UNTERKANTE (Innenseite der untersten Schicht) an einem Grundriss-Punkt
|
||||
* (x,y) — `null`, wenn der Punkt ausserhalb aller Dachflächen liegt (Aufsicht).
|
||||
* Ebenengleichung je Fläche über die Newell-Normale (identische Herleitung wie
|
||||
* `toSection.ts::appendRoofSections`, dort inline für den Vertikalschnitt) minus
|
||||
* `totalLayerThickness` (Summe aller Dachschicht-Dicken, s. `roofLayers`).
|
||||
* Dient dem Wand-Zuschnitt unter geneigten Dächern ({@link trimWallTopForRoofs}
|
||||
* in `toWalls3d.ts`) — vermeidet, dass ein flacher Wand-Top die Dachfläche
|
||||
* durchdringt (Z-Fighting).
|
||||
* Ebene der ersten Fläche, die den Punkt enthält, minus `totalLayerThickness`
|
||||
* (Summe aller Dachschicht-Dicken, s. `roofLayers`). Dient dem Wand-Zuschnitt unter
|
||||
* geneigten Dächern (`toWalls3d/bands.ts`) — vermeidet, dass ein flacher Wand-Top die
|
||||
* Dachfläche durchdringt (Z-Fighting).
|
||||
*/
|
||||
export function roofUndersideAt(
|
||||
geo: RoofGeometry,
|
||||
@@ -557,23 +159,16 @@ export function roofUndersideAt(
|
||||
x: number,
|
||||
y: number,
|
||||
): number | null {
|
||||
for (const pl of geo.planes) {
|
||||
const pts = pl.pts;
|
||||
if (pts.length < 3) continue;
|
||||
if (!pointInPolygon2D({ x, y }, pts.map((p) => ({ x: p[0], y: p[1] })))) continue;
|
||||
let A = 0;
|
||||
let B = 0;
|
||||
let C = 0;
|
||||
for (let i = 0; i < pts.length; i++) {
|
||||
const c = pts[i];
|
||||
const d = pts[(i + 1) % pts.length];
|
||||
A += (c[1] - d[1]) * (c[2] + d[2]);
|
||||
B += (c[2] - d[2]) * (c[0] + d[0]);
|
||||
C += (c[0] - d[0]) * (c[1] + d[1]);
|
||||
let flat = planesFlat.get(geo);
|
||||
if (!flat) {
|
||||
const vals = [geo.planes.length];
|
||||
for (const pl of geo.planes) {
|
||||
vals.push(pl.pts.length);
|
||||
for (const v of pl.pts) vals.push(v[0], v[1], v[2]);
|
||||
}
|
||||
if (Math.abs(C) < 1e-9) continue; // (nahezu) vertikale Fläche
|
||||
const topZ = pts[0][2] - (A * (x - pts[0][0]) + B * (y - pts[0][1])) / C;
|
||||
return topZ - Math.max(0, totalLayerThickness);
|
||||
flat = Float64Array.from(vals);
|
||||
planesFlat.set(geo, flat);
|
||||
}
|
||||
return null;
|
||||
const z = core().roof_underside_at(flat, totalLayerThickness, x, y);
|
||||
return Number.isNaN(z) ? null : z;
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Roof, Vec2 } from "../model/types";
|
||||
import { roofGeometry } from "./roof";
|
||||
import { convexPieces, isRectilinearNonRect, rectilinearHipRoof } from "./roofSkeleton";
|
||||
|
||||
// Das Skelett rechnet der Rust-Kern (`src-tauri/core/src/roof_skeleton.rs`, dort auch die Tests
|
||||
// der Hilfsfunktionen: Säubern, Versatz, konvexe Zerlegung, Umriss-Erkennung). Hier wird es über
|
||||
// `roofGeometry` geprüft: Walm/Sattel mit 45° ohne Überstand auf Traufhöhe 0 entspricht dem
|
||||
// früheren direkten Aufruf `rectilinearHipRoof(L, 1, 0[, "x"])`.
|
||||
|
||||
const L: Vec2[] = [{ x: 0, y: 0 }, { x: 11, y: 0 }, { x: 11, y: 4 }, { x: 8, y: 4 }, { x: 8, y: 6 }, { x: 0, y: 6 }];
|
||||
|
||||
@@ -14,14 +18,32 @@ const planArea = (pts: number[][]) => {
|
||||
return Math.abs(a) / 2;
|
||||
};
|
||||
|
||||
describe("rectilinearHipRoof (L-Grundriss)", () => {
|
||||
const r = rectilinearHipRoof(L, 1, 0);
|
||||
const skeleton = (outline: Vec2[], shape: "walm" | "sattel", ridgeAxis: "x" | "y" = "x") => {
|
||||
const g = roofGeometry({ id: "R", type: "roof", floorId: "eg", categoryCode: "31", outline, shape, pitchDeg: 45, overhang: 0, ridgeAxis } as unknown as Roof, 0);
|
||||
return { ...g, planes: g.planes.map((p) => p.pts) };
|
||||
};
|
||||
|
||||
/** Konvex (CCW oder CW, kollineare Punkte erlaubt). */
|
||||
const isConvex = (pts: number[][]) => {
|
||||
let sign = 0;
|
||||
for (let i = 0; i < pts.length; i++) {
|
||||
const [a, b, c] = [pts[i], pts[(i + 1) % pts.length], pts[(i + 2) % pts.length]];
|
||||
const cr = (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]);
|
||||
if (Math.abs(cr) < 1e-12) continue;
|
||||
if (sign !== 0 && Math.sign(cr) !== sign) return false;
|
||||
sign = Math.sign(cr);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
describe("Skelett-Walmdach (L-Grundriss)", () => {
|
||||
const r = skeleton(L, "walm");
|
||||
it("Flächen decken den Grundriss exakt (44 + 18 = 62 m² … L = 11·4 + 8·2)", () => {
|
||||
const total = r.planes.reduce((s, p) => s + planArea(p), 0);
|
||||
expect(total).toBeCloseTo(11 * 4 + 8 * 2, 6);
|
||||
});
|
||||
it("alle Flächen konvex, Höhe = Abstand zur Traufe, Firsthöhe 3 m (halbe Breite 6 → Flügel 4 m: 2 m … )", () => {
|
||||
for (const p of r.planes) expect(convexPieces(p.map(([x, y]) => ({ x, y }))).length).toBe(1);
|
||||
for (const p of r.planes) expect(isConvex(p)).toBe(true);
|
||||
expect(r.ridgeHeight).toBeCloseTo(3, 6);
|
||||
});
|
||||
it("Kehle: einspringende Ecke (8,4) steigt zum Kehlpunkt (6,2)", () => {
|
||||
@@ -32,7 +54,6 @@ describe("rectilinearHipRoof (L-Grundriss)", () => {
|
||||
describe("roofGeometry", () => {
|
||||
const base = { id: "R", type: "roof", floorId: "eg", categoryCode: "31", outline: L, shape: "walm", pitchDeg: 45, overhang: 0, ridgeAxis: "x" } as unknown as Roof;
|
||||
it("Walm auf L nutzt das Skelett, Rechteck bleibt Bounding-Box", () => {
|
||||
expect(isRectilinearNonRect(L)).toBe(true);
|
||||
// Sechs Dachebenen (Süd, Ost, Nord und West des Hauptbaus, Kehl- und Flügelfläche); wie viele
|
||||
// konvexe Stücke je Ebene entstehen, hängt vom Polygon-Kern ab und wird nicht geprüft.
|
||||
const g = roofGeometry(base, 0);
|
||||
@@ -52,7 +73,7 @@ describe("roofGeometry", () => {
|
||||
});
|
||||
|
||||
describe("Satteldach auf L-Grundriss", () => {
|
||||
const r = rectilinearHipRoof(L, 1, 0, "x");
|
||||
const r = skeleton(L, "sattel");
|
||||
it("Flächen decken den Grundriss, Giebel statt Walm-Schrägen", () => {
|
||||
const total = r.planes.reduce((s, p) => s + planArea(p), 0);
|
||||
expect(total).toBeCloseTo(11 * 4 + 8 * 2, 6);
|
||||
@@ -67,7 +88,7 @@ describe("Satteldach auf L-Grundriss", () => {
|
||||
describe("Satteldach, First entlang y", () => {
|
||||
it("gedrehter L-Grundriss liefert dieselbe Flächensumme und Giebel quer zu y", () => {
|
||||
const Lt = L.map((p) => ({ x: p.y, y: p.x }));
|
||||
const r = rectilinearHipRoof(Lt, 1, 0, "y");
|
||||
const r = skeleton(Lt, "sattel", "y");
|
||||
expect(r.planes.reduce((s, p) => s + planArea(p), 0)).toBeCloseTo(11 * 4 + 8 * 2, 6);
|
||||
expect(r.gables.length).toBe(3);
|
||||
});
|
||||
|
||||
@@ -1,451 +0,0 @@
|
||||
// Walmdach über einem RECHTWINKLIGEN, nicht-rechteckigen Grundriss (L/T/U/Z …):
|
||||
// echte Dachflächen mit Graten UND Kehlen statt der Bounding-Box-Vereinfachung
|
||||
// aus `roof.ts` (dort wurde z. B. ein L-Grundriss mit einem Rechteck-Walmdach
|
||||
// überdeckt — Dach über Luft, im Schnitt/in der Ansicht sichtbar falsch).
|
||||
//
|
||||
// Modell (Straight-Skeleton-Dach bei gleicher Neigung ringsum, für achs-
|
||||
// parallele Kanten): jede Traufkante e "regiert" in ihrem Keil — begrenzt von
|
||||
// der Kante selbst und den beiden 45°-Winkelhalbierenden an ihren Enden (an
|
||||
// einer einspringenden Ecke wird die Halbierende zur Kehle). Die Dachhöhe ist
|
||||
// die NIEDRIGSTE Ebene aller Kanten, deren Keil den Punkt enthält:
|
||||
// z(p) = e + tan(Neigung) · min{ dist(p, Gerade f) | p ∈ Keil(f) }.
|
||||
// Die Fläche von e = (Traufpolygon ∩ Keil(e)) minus alle Bereiche, in denen eine
|
||||
// andere Kante tiefer liegt. Polygon-Booleans über den Rust-Kern (`polygonBool`)
|
||||
// (Martinez, wie `editors/booleanOps.ts`). Danach in KONVEXE Teilflächen zerlegt
|
||||
// (Ohr-Schnitt + Hertel–Mehlhorn), weil Renderer/Schnitt konvexe Flächen
|
||||
// erwarten (Fächer-Triangulierung, Cyrus–Beck).
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import * as polygonClipping from "./polygonBool";
|
||||
import type { MultiPolygon, Ring } from "./polygonBool";
|
||||
import type { Vec2 } from "../model/types";
|
||||
import type { Vec3 } from "./roof";
|
||||
|
||||
/** Ausgabe-Raster (Meter): entfernt Rundungsrauschen der Polygon-Booleans. */
|
||||
const SNAP = 1e-6;
|
||||
const snap = (v: number) => Math.round(v / SNAP) * SNAP;
|
||||
|
||||
/** Signierte Fläche (CCW > 0). */
|
||||
function signedArea(pts: Vec2[]): number {
|
||||
let a = 0;
|
||||
for (let i = 0; i < pts.length; i++) {
|
||||
const p = pts[i];
|
||||
const q = pts[(i + 1) % pts.length];
|
||||
a += p.x * q.y - q.x * p.y;
|
||||
}
|
||||
return a / 2;
|
||||
}
|
||||
|
||||
/** Doppelte und kollineare Punkte entfernen. */
|
||||
export function cleanRing(pts: Vec2[]): Vec2[] {
|
||||
let out = pts.filter((p, i) => {
|
||||
const q = pts[(i + 1) % pts.length];
|
||||
return Math.hypot(p.x - q.x, p.y - q.y) > 1e-9;
|
||||
});
|
||||
let changed = true;
|
||||
while (changed && out.length > 3) {
|
||||
changed = false;
|
||||
for (let i = 0; i < out.length; i++) {
|
||||
const a = out[(i + out.length - 1) % out.length];
|
||||
const b = out[i];
|
||||
const c = out[(i + 1) % out.length];
|
||||
const cr = (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x);
|
||||
if (Math.abs(cr) < 1e-9) {
|
||||
out = out.filter((_, k) => k !== i);
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Ob alle Kanten achsparallel sind (und es mehr als ein Rechteck ist). */
|
||||
export function isRectilinearNonRect(outline: Vec2[]): boolean {
|
||||
const pts = cleanRing(outline);
|
||||
if (pts.length <= 4) return false;
|
||||
return pts.every((p, i) => {
|
||||
const q = pts[(i + 1) % pts.length];
|
||||
return Math.abs(p.x - q.x) < 1e-9 || Math.abs(p.y - q.y) < 1e-9;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Ring (CCW) um `dist` nach aussen versetzen (Traufüberstand) — Gehrung an jeder
|
||||
* Ecke (Schnitt der beiden versetzten Kantengeraden), auch bei schiefen Winkeln.
|
||||
* `dist` kann je Kante verschieden sein (Traufe/Ortgang).
|
||||
*/
|
||||
export function offsetRectilinear(ring: Vec2[], dist: number | ((a: Vec2, b: Vec2) => number)): Vec2[] {
|
||||
if (typeof dist === "number" && dist <= 0) return ring.map((p) => ({ ...p }));
|
||||
const n = ring.length;
|
||||
// Aussen-Normale (Einheit) + Versatz je Kante (CCW → rechte Normale).
|
||||
const edges = ring.map((p, i) => {
|
||||
const q = ring[(i + 1) % n];
|
||||
const len = Math.hypot(q.x - p.x, q.y - p.y) || 1;
|
||||
return { nx: (q.y - p.y) / len, ny: -(q.x - p.x) / len, d: typeof dist === "number" ? dist : dist(p, q) };
|
||||
});
|
||||
return ring.map((p, i) => {
|
||||
const a = edges[(i + n - 1) % n];
|
||||
const b = edges[i];
|
||||
const det = a.nx * b.ny - a.ny * b.nx;
|
||||
// (fast) kollineare Nachbarkanten: einfach entlang der Normale versetzen.
|
||||
if (Math.abs(det) < 1e-6) return { x: p.x + a.nx * a.d, y: p.y + a.ny * a.d };
|
||||
let dx = (a.d * b.ny - b.d * a.ny) / det;
|
||||
let dy = (a.nx * b.d - b.nx * a.d) / det;
|
||||
// Sehr spitze Ecken: Gehrungsspitze begrenzen.
|
||||
const lim = 4 * Math.max(a.d, b.d);
|
||||
const len = Math.hypot(dx, dy);
|
||||
if (len > lim && len > 0) {
|
||||
dx *= lim / len;
|
||||
dy *= lim / len;
|
||||
}
|
||||
return { x: p.x + dx, y: p.y + dy };
|
||||
});
|
||||
}
|
||||
|
||||
/** Schneiden sich zwei Strecken echt (nicht nur an einem gemeinsamen Endpunkt)? */
|
||||
function segmentsCross(a: Vec2, b: Vec2, c: Vec2, d: Vec2): boolean {
|
||||
const o = (p: Vec2, q: Vec2, r: Vec2) => (q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x);
|
||||
const d1 = o(a, b, c), d2 = o(a, b, d), d3 = o(c, d, a), d4 = o(c, d, b);
|
||||
return d1 * d2 < -1e-12 && d3 * d4 < -1e-12;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ob der Umriss ein einfaches (selbstüberschneidungsfreies) Polygon ist, das KEIN
|
||||
* achsparalleles Rechteck ist — dafür liefert das Skelett ({@link rectilinearHipRoof})
|
||||
* für gleichmässig geneigte Dächer (Walm/Zelt) die echten Flächen statt der Bounding-Box.
|
||||
*/
|
||||
export function isSkeletonRoofable(outline: Vec2[]): boolean {
|
||||
const pts = cleanRing(outline);
|
||||
const n = pts.length;
|
||||
if (n < 3) return false;
|
||||
if (n === 4) {
|
||||
const axisRect =
|
||||
pts.every((p, i) => {
|
||||
const q = pts[(i + 1) % n];
|
||||
return Math.abs(p.x - q.x) < 1e-9 || Math.abs(p.y - q.y) < 1e-9;
|
||||
});
|
||||
if (axisRect) return false; // Rechteck: Bounding-Box-Dach reicht
|
||||
}
|
||||
if (Math.abs(signedArea(pts)) < 1e-6) return false;
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = i + 2; j < n; j++) {
|
||||
if (i === 0 && j === n - 1) continue; // benachbarte Kanten
|
||||
if (segmentsCross(pts[i], pts[(i + 1) % n], pts[j], pts[(j + 1) % n])) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Konvexes Polygon gegen die Halbebene f(p) ≥ 0 schneiden (Sutherland–Hodgman). */
|
||||
function clipHalf(poly: Vec2[], f: (p: Vec2) => number): Vec2[] {
|
||||
const out: Vec2[] = [];
|
||||
for (let i = 0; i < poly.length; i++) {
|
||||
const a = poly[i];
|
||||
const b = poly[(i + 1) % poly.length];
|
||||
const fa = f(a);
|
||||
const fb = f(b);
|
||||
if (fa >= 0) out.push(a);
|
||||
if ((fa >= 0) !== (fb >= 0)) {
|
||||
const t = fa / (fa - fb);
|
||||
out.push({ x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y) });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Polygon-Booleans brauchen exakt zusammenfallende Punkte: auf ein feines Raster runden. */
|
||||
let ROUND = 1e-9;
|
||||
const rnd = (v: number) => Math.round(v / ROUND) * ROUND;
|
||||
const toRing = (pts: Vec2[]): Ring => pts.map((p) => [rnd(p.x), rnd(p.y)] as [number, number]);
|
||||
|
||||
interface EdgeInfo {
|
||||
a: Vec2;
|
||||
b: Vec2;
|
||||
/** Innen-Normale (Einheit). */
|
||||
n: Vec2;
|
||||
}
|
||||
|
||||
/** Ergebnis: Dachflächen (konvex, 3D), Grundriss-Linien, Firsthöhe. */
|
||||
export interface SkeletonRoof {
|
||||
planes: Vec3[][];
|
||||
ridges: [Vec2, Vec2][];
|
||||
hips: [Vec2, Vec2][];
|
||||
/** Knicklinien der Mansarde. */
|
||||
breaks: [Vec2, Vec2][];
|
||||
/** Senkrechte Giebelflächen (nur Satteldach, s. `ridgeAxis`). */
|
||||
gables: Vec3[][];
|
||||
ridgeHeight: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walmdach-Flächen über dem rechtwinkligen Traufring `eaves` (beliebige
|
||||
* Orientierung) bei Neigung `tan` und Traufhöhe `e`.
|
||||
*/
|
||||
function buildHipRoof(
|
||||
eavesIn: Vec2[],
|
||||
tan: number,
|
||||
e: number,
|
||||
/** Gesetzt → Satteldach: Kanten quer zu dieser Firstrichtung sind senkrechte Giebel (Ortgang). */
|
||||
ridgeAxis?: "x" | "y",
|
||||
/** Mansarde: ab Traufabstand `d` flacher (Steigung `tanUp`); Knicklinien landen in `breaks`. */
|
||||
knee?: { d: number; tanUp: number },
|
||||
): SkeletonRoof {
|
||||
let eaves = cleanRing(eavesIn);
|
||||
if (signedArea(eaves) < 0) eaves = [...eaves].reverse();
|
||||
const n = eaves.length;
|
||||
const edges: EdgeInfo[] = eaves.map((a, i) => {
|
||||
const b = eaves[(i + 1) % n];
|
||||
const len = Math.hypot(b.x - a.x, b.y - a.y) || 1;
|
||||
return { a, b, n: { x: -(b.y - a.y) / len, y: (b.x - a.x) / len } };
|
||||
});
|
||||
// Giebelkante = quer zur Firstrichtung: keine Neigung, begrenzt nur die Nachbarkeile.
|
||||
const isGable = edges.map((ed) =>
|
||||
ridgeAxis === undefined
|
||||
? false
|
||||
: ridgeAxis === "x"
|
||||
? Math.abs(ed.b.x - ed.a.x) < Math.abs(ed.b.y - ed.a.y)
|
||||
: Math.abs(ed.b.y - ed.a.y) < Math.abs(ed.b.x - ed.a.x),
|
||||
);
|
||||
const dist = (k: number, p: Vec2) => (p.x - edges[k].a.x) * edges[k].n.x + (p.y - edges[k].a.y) * edges[k].n.y;
|
||||
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
|
||||
for (const p of eaves) {
|
||||
minX = Math.min(minX, p.x); minY = Math.min(minY, p.y);
|
||||
maxX = Math.max(maxX, p.x); maxY = Math.max(maxY, p.y);
|
||||
}
|
||||
const pad = (maxX - minX + maxY - minY) * 2 + 10;
|
||||
const big: Vec2[] = [
|
||||
{ x: minX - pad, y: minY - pad },
|
||||
{ x: maxX + pad, y: minY - pad },
|
||||
{ x: maxX + pad, y: maxY + pad },
|
||||
{ x: minX - pad, y: maxY + pad },
|
||||
];
|
||||
// Keil je Kante: Innenseite der Kante ∩ Innenseiten der beiden Halbierenden.
|
||||
const wedge = edges.map((ed, k) => {
|
||||
const prev = edges[(k + n - 1) % n];
|
||||
const next = edges[(k + 1) % n];
|
||||
// An Giebelkanten steht die Keilgrenze senkrecht zur Traufe (= Verlängerung des Giebels).
|
||||
const bisA = isGable[(k + n - 1) % n] ? ed.n : { x: ed.n.x + prev.n.x, y: ed.n.y + prev.n.y };
|
||||
const bisB = isGable[(k + 1) % n] ? ed.n : { x: ed.n.x + next.n.x, y: ed.n.y + next.n.y };
|
||||
const side = (o: Vec2, dir: Vec2, ref: Vec2) => {
|
||||
const s = Math.sign(dir.x * (ref.y - o.y) - dir.y * (ref.x - o.x)) || 1;
|
||||
return (p: Vec2) => s * (dir.x * (p.y - o.y) - dir.y * (p.x - o.x));
|
||||
};
|
||||
let w = clipHalf(big, (p) => dist(k, p));
|
||||
// Giebelgrenze minimal nach aussen schieben: deckungsgleich mit der Traufring-Kante
|
||||
// würde der Polygon-Boolean an kollinearen Segmenten scheitern.
|
||||
const len = Math.hypot(ed.b.x - ed.a.x, ed.b.y - ed.a.y) || 1;
|
||||
const ux = ((ed.b.x - ed.a.x) / len) * 1e-4;
|
||||
const uy = ((ed.b.y - ed.a.y) / len) * 1e-4;
|
||||
const oa = isGable[(k + n - 1) % n] ? { x: ed.a.x - ux, y: ed.a.y - uy } : ed.a;
|
||||
const ob = isGable[(k + 1) % n] ? { x: ed.b.x + ux, y: ed.b.y + uy } : ed.b;
|
||||
w = clipHalf(w, side(oa, bisA, ed.b));
|
||||
w = clipHalf(w, side(ob, bisB, ed.a));
|
||||
return w;
|
||||
});
|
||||
const eavesPoly = [toRing(eaves)];
|
||||
const planes: Vec3[][] = [];
|
||||
const lineKeys = new Set<string>();
|
||||
const ridges: [Vec2, Vec2][] = [];
|
||||
const hips: [Vec2, Vec2][] = [];
|
||||
const breaks: [Vec2, Vec2][] = [];
|
||||
let ridgeHeight = 0;
|
||||
// Liegt die Strecke p–q auf einer Traufkante (Gerade UND innerhalb der Strecke)?
|
||||
const onSeg = (k: number, p: Vec2) => {
|
||||
const { a, b } = edges[k];
|
||||
const len2 = (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
|
||||
const t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / (len2 || 1);
|
||||
return Math.abs(dist(k, p)) < 1e-5 && t > -1e-6 && t < 1 + 1e-6;
|
||||
};
|
||||
const onEaves = (p: Vec2, q: Vec2) => edges.some((_, k) => onSeg(k, p) && onSeg(k, q));
|
||||
|
||||
edges.forEach((_, k) => {
|
||||
if (isGable[k] || wedge[k].length < 3) return;
|
||||
let face: MultiPolygon = polygonClipping.intersection(eavesPoly, [toRing(wedge[k])]);
|
||||
// Bereiche, in denen eine andere Kante tiefer liegt, abziehen.
|
||||
const subtract: Ring[][] = [];
|
||||
for (let f = 0; f < n; f++) {
|
||||
if (f === k || isGable[f] || wedge[f].length < 3) continue;
|
||||
// Deckungsgleiche Ebenen (gleiche Gerade/Normale, z. B. zwei Traufkanten einer Flucht
|
||||
// mit Versatz dazwischen): g ≡ 0 — nur EINE der beiden Flächen darf die andere
|
||||
// abziehen, sonst fällt der überlappende Teil aus beiden heraus (Lücke im Dach).
|
||||
const coplanar =
|
||||
Math.abs(edges[k].n.x - edges[f].n.x) < 1e-9 &&
|
||||
Math.abs(edges[k].n.y - edges[f].n.y) < 1e-9 &&
|
||||
Math.abs(dist(f, edges[k].a)) < 1e-9;
|
||||
if (coplanar && f > k) continue;
|
||||
// dist_f(p) < dist_k(p) ⇔ g(p) = dist_k(p) − dist_f(p) > 0
|
||||
const lower = clipHalf(wedge[f], (p) => dist(k, p) - dist(f, p));
|
||||
if (lower.length >= 3 && Math.abs(signedArea(lower)) > 1e-9) subtract.push([toRing(lower)]);
|
||||
}
|
||||
if (subtract.length > 0 && face.length > 0) face = polygonClipping.difference(face, ...subtract);
|
||||
for (const poly of face) {
|
||||
const outer = cleanRing(poly[0].slice(0, -1).map(([x, y]) => ({ x: snap(x), y: snap(y) })));
|
||||
if (outer.length < 3 || Math.abs(signedArea(outer)) < 1e-6) continue;
|
||||
const z = (p: Vec2) => {
|
||||
const d = Math.max(0, dist(k, p));
|
||||
return knee ? e + tan * Math.min(d, knee.d) + knee.tanUp * Math.max(0, d - knee.d) : e + tan * d;
|
||||
};
|
||||
for (const piece of convexPieces(outer)) {
|
||||
// Mansarde: Teilfläche an der Knicklinie (Traufabstand = knee.d) teilen.
|
||||
const parts = knee
|
||||
? [clipHalf(piece, (p) => knee.d - dist(k, p)), clipHalf(piece, (p) => dist(k, p) - knee.d)]
|
||||
: [piece];
|
||||
for (const part of parts) {
|
||||
if (part.length < 3 || Math.abs(signedArea(part)) < 1e-9) continue;
|
||||
planes.push(part.map((p) => [p.x, p.y, z(p)] as Vec3));
|
||||
}
|
||||
if (knee) {
|
||||
const low = clipHalf(piece, (p) => knee.d - dist(k, p));
|
||||
for (let i = 0; i < low.length; i++) {
|
||||
const p = low[i];
|
||||
const q = low[(i + 1) % low.length];
|
||||
if (Math.abs(dist(k, p) - knee.d) < 1e-6 && Math.abs(dist(k, q) - knee.d) < 1e-6) breaks.push([p, q]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Grat-/Kehl-/Firstlinien: Flächenränder, die nicht auf der Traufe liegen.
|
||||
for (let i = 0; i < outer.length; i++) {
|
||||
const p = outer[i];
|
||||
const q = outer[(i + 1) % outer.length];
|
||||
if (onEaves(p, q)) continue;
|
||||
const r = (v: number) => Math.round(v * 1e5);
|
||||
const kp = `${r(p.x)},${r(p.y)}`;
|
||||
const kq = `${r(q.x)},${r(q.y)}`;
|
||||
const key = kp < kq ? `${kp}|${kq}` : `${kq}|${kp}`;
|
||||
if (lineKeys.has(key)) continue;
|
||||
lineKeys.add(key);
|
||||
const zp = z(p);
|
||||
const zq = z(q);
|
||||
ridgeHeight = Math.max(ridgeHeight, zp - e, zq - e);
|
||||
if (Math.abs(zp - zq) < 1e-6) ridges.push([p, q]);
|
||||
else hips.push([p, q]);
|
||||
}
|
||||
}
|
||||
});
|
||||
// Giebelflächen: Profil = alle Flächenecken auf der Giebelkante, nach Lage sortiert.
|
||||
const gables: Vec3[][] = [];
|
||||
edges.forEach((ed, k) => {
|
||||
if (!isGable[k]) return;
|
||||
const len2 = (ed.b.x - ed.a.x) ** 2 + (ed.b.y - ed.a.y) ** 2;
|
||||
const top: { t: number; v: Vec3 }[] = [];
|
||||
for (const pl of planes) {
|
||||
for (const v of pl) {
|
||||
const t = ((v[0] - ed.a.x) * (ed.b.x - ed.a.x) + (v[1] - ed.a.y) * (ed.b.y - ed.a.y)) / len2;
|
||||
if (Math.abs(dist(k, { x: v[0], y: v[1] })) < 1e-5 && t > -1e-6 && t < 1 + 1e-6) top.push({ t, v });
|
||||
}
|
||||
}
|
||||
top.sort((p, q) => p.t - q.t);
|
||||
const prof = top.filter((p, i) => i === 0 || Math.abs(p.t - top[i - 1].t) > 1e-6);
|
||||
if (prof.length < 2) return;
|
||||
const poly: Vec3[] = [
|
||||
[ed.a.x, ed.a.y, e],
|
||||
[ed.b.x, ed.b.y, e],
|
||||
...prof.reverse().map((p) => p.v),
|
||||
];
|
||||
gables.push(poly);
|
||||
});
|
||||
return { planes, ridges, hips, breaks, gables, ridgeHeight };
|
||||
}
|
||||
|
||||
/**
|
||||
* Walm-/Satteldach-Flächen über dem Traufring (s. {@link buildHipRoof}). Die Polygon-
|
||||
* Booleans scheitern bei schiefen Winkeln gelegentlich an Rundungsrauschen ("Unable to
|
||||
* complete output ring") — dann mit gröberem Raster erneut versuchen.
|
||||
*/
|
||||
export function rectilinearHipRoof(
|
||||
eavesIn: Vec2[],
|
||||
tan: number,
|
||||
e: number,
|
||||
ridgeAxis?: "x" | "y",
|
||||
knee?: { d: number; tanUp: number },
|
||||
): SkeletonRoof {
|
||||
let lastError: unknown;
|
||||
for (const step of [1e-9, 1e-7, 1e-6, 1e-5]) {
|
||||
ROUND = step;
|
||||
try {
|
||||
return buildHipRoof(eavesIn, tan, e, ridgeAxis, knee);
|
||||
} catch (err) {
|
||||
lastError = err;
|
||||
}
|
||||
}
|
||||
ROUND = 1e-9;
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
// ── Konvexe Zerlegung ───────────────────────────────────────────────────────
|
||||
|
||||
const cross = (o: Vec2, a: Vec2, b: Vec2) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
|
||||
|
||||
function isConvex(poly: Vec2[]): boolean {
|
||||
for (let i = 0; i < poly.length; i++) {
|
||||
if (cross(poly[i], poly[(i + 1) % poly.length], poly[(i + 2) % poly.length]) < -1e-12) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Ohr-Schnitt eines einfachen CCW-Polygons → Dreiecke (Indizes). */
|
||||
function earClip(poly: Vec2[]): number[][] {
|
||||
const idx = poly.map((_, i) => i);
|
||||
const tris: number[][] = [];
|
||||
const inTri = (p: Vec2, a: Vec2, b: Vec2, c: Vec2) =>
|
||||
cross(a, b, p) >= -1e-12 && cross(b, c, p) >= -1e-12 && cross(c, a, p) >= -1e-12;
|
||||
let guard = 0;
|
||||
while (idx.length > 3 && guard++ < 10000) {
|
||||
let cut = false;
|
||||
for (let i = 0; i < idx.length; i++) {
|
||||
const ia = idx[(i + idx.length - 1) % idx.length];
|
||||
const ib = idx[i];
|
||||
const ic = idx[(i + 1) % idx.length];
|
||||
const a = poly[ia], b = poly[ib], c = poly[ic];
|
||||
if (cross(a, b, c) <= 1e-12) continue; // einspringend/entartet
|
||||
const blocked = idx.some((j) => j !== ia && j !== ib && j !== ic && inTri(poly[j], a, b, c));
|
||||
if (blocked) continue;
|
||||
tris.push([ia, ib, ic]);
|
||||
idx.splice(i, 1);
|
||||
cut = true;
|
||||
break;
|
||||
}
|
||||
if (!cut) break; // numerisch entartet: Rest als Fächer
|
||||
}
|
||||
for (let i = 1; i + 1 < idx.length; i++) tris.push([idx[0], idx[i], idx[i + 1]]);
|
||||
return tris;
|
||||
}
|
||||
|
||||
/** Konvexe Teilpolygone (CCW-Eingabe): Ohr-Schnitt, dann Hertel–Mehlhorn-Verschmelzen. */
|
||||
export function convexPieces(polyIn: Vec2[]): Vec2[][] {
|
||||
const poly = signedArea(polyIn) < 0 ? [...polyIn].reverse() : polyIn;
|
||||
if (isConvex(poly)) return [poly];
|
||||
let pieces: number[][] = earClip(poly);
|
||||
let merged = true;
|
||||
while (merged) {
|
||||
merged = false;
|
||||
outer: for (let i = 0; i < pieces.length; i++) {
|
||||
for (let j = i + 1; j < pieces.length; j++) {
|
||||
const A = pieces[i];
|
||||
const B = pieces[j];
|
||||
// Gemeinsame Kante (u→v in A, v→u in B) suchen.
|
||||
for (let s = 0; s < A.length; s++) {
|
||||
const u = A[s];
|
||||
const v = A[(s + 1) % A.length];
|
||||
const t = B.findIndex((x, k) => x === v && B[(k + 1) % B.length] === u);
|
||||
if (t < 0) continue;
|
||||
// A ab v rundum bis u, dann B ab u (ohne u) bis vor v.
|
||||
const rotA: number[] = [];
|
||||
for (let k = 0; k < A.length; k++) rotA.push(A[(s + 1 + k) % A.length]); // v … u
|
||||
const rotB: number[] = [];
|
||||
for (let k = 2; k < B.length; k++) rotB.push(B[(t + k) % B.length]); // nach u … vor v
|
||||
const cand = [...rotA, ...rotB];
|
||||
if (isConvex(cand.map((q) => poly[q]))) {
|
||||
pieces = pieces.filter((_, k) => k !== i && k !== j);
|
||||
pieces.push(cand);
|
||||
merged = true;
|
||||
break outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return pieces.map((pc) => pc.map((q) => poly[q]));
|
||||
}
|
||||
Reference in new issue
Block a user