Merge [26][B2] Dach: Innenhoefe (Roof.holes) und Neigung je Kante (Roof.edgePitchDeg, null = Giebel), Objekt-Info-Kantenliste, Befehl roofhole
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
26 files changed
+1435
-42
No files matched your search
@@ -491,6 +491,9 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
|
||||
vorher: Zelt 7×5 m 1.1e-3 m², Walm/Zelt auf L 0.77–1.2 m², Mansard-Walm auf L 0.93 m² Lücke; jetzt jede
|
||||
Schicht geschlossen (Test `g9_dachschichten_geschlossen`: Rechteck/L/U/konkav/schief × alle
|
||||
Skelett-Formen × First x/y × zwei Schichten). Nicht in der App/IFC-Prüfung angesehen.
|
||||
(29.10.) Verschieden geneigte Flächen ([26] Kantenneigung): an Graten mit zwei Flächen und je einer
|
||||
Traufkante gehen die Seitenebenen auseinander — `Mitre::at` nimmt dort den Mittelpunkt beider Eckpunkte
|
||||
(bei gleicher Neigung identisch, unverändert).
|
||||
|
||||
## truck [T]
|
||||
|
||||
@@ -609,6 +612,23 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
|
||||
Umrisskante (null = Giebel; ersetzt dann die Giebel-Regel „quer zur Firstachse"). Satteldach auf
|
||||
schiefem Umriss bleibt bei der Bounding-Box (Umstellung auf den Skeleton würde bestehende Dächer
|
||||
ändern — Entscheid Maintainer).
|
||||
(29.10.) Felder umgesetzt (Entscheid Maintainer): `Roof.holes?: Vec2[][]` (Ringe, Drehsinn egal) und
|
||||
`Roof.edgePitchDeg?: (number | null)[]` (erst Umrisskanten in gespeicherter Reihenfolge, dann Hofkanten
|
||||
Ring für Ring; `null` = Giebel, Zahl ≥ 0 = Neigung der Kante, NEGATIV oder fehlender Eintrag =
|
||||
Standard = `pitchDeg`, am Sattel/Mansard-Satteldach Giebel quer zum First; Feld fehlt = wie bisher).
|
||||
Wirkt bei Sattel/Walm/Mansarde/Zelt (Höfe auch Flach); Pult ignoriert beide. `roof.rs::custom_roof` →
|
||||
`weighted_roof` über alle Ringe, Überstand je Kante (Giebel = Ortgang), Hofringe schrumpfen; ungültige
|
||||
Höfe (nicht im Umriss, Schnitt, vom Überstand geschlossen) → Dach wie ohne. Dächer ohne die Felder
|
||||
bitgleich (CLI-Plan/Ansicht/Schnitt/IFC vorher/nachher gleich). Plan: Hof = Loch der Dachfläche + Hof-
|
||||
Traufe (`plan/domains.rs`); 3D/Schnitt/Ansicht/IFC über die Flächen; `Mitre` (model3d) mittelt die
|
||||
Ecke an Graten zwischen verschieden geneigten Flächen (Dachschichten bleiben geschlossen). UI:
|
||||
Objekt-Info → Kantenliste (Neigung leer = Standard, Giebel-Schalter, „Alle Kanten auf Standard"),
|
||||
Hofliste mit Entfernen, Befehl `dachhof`/`lichthof` (Klicks, ≥ 3 Punkte Polygon, 2 Punkte + Enter
|
||||
Rechteck; „aus gewählter Kontur" geht nicht, weil nur ein Objekt wählbar ist). Breite/Tiefe im
|
||||
Objekt-Info nur noch für Vierecke ohne Höfe. Offen: Kante im Grundriss hervorheben (PlanView, anderer
|
||||
Zuständigkeitsbereich); Kanten-/Hof-Griffe im Grundriss; Mansarde mit Hof UND verschieden geneigten
|
||||
Kanten: zweite Dachschicht (Versatz > Knickbreite) nicht geschlossen; Schattenwurf (`sun.rs`) nimmt
|
||||
weiter die Hülle der Dachpunkte (Hof wirft Schatten).
|
||||
|
||||
## Priorität 4 — später
|
||||
|
||||
@@ -682,7 +702,7 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module
|
||||
einspringenden Ecke (jetzt Giebelwand bis zur tieferen Fläche), Linien zwischen zwei Flächen derselben
|
||||
Ebene (T-Stoss) entfallen; konkave Sterne: in ~37 % stieg das alte Dach über den Randabstand (Fünfeck:
|
||||
First 6.49 statt 3.50 m). Ohne Snap auf 1e-6: gemeinsame Ecken jetzt exakt. CLI-Plan/Ansicht (L, U, U
|
||||
Sattel, Fünfeck, T Mansarde, Zelt) angesehen (Linux). Offen: Modellfelder für Höfe/Neigung je Kante [26].
|
||||
Sattel, Fünfeck, T Mansarde, Zelt) angesehen (Linux). (29.10.) Modellfelder für Höfe/Neigung je Kante gibt es jetzt, s. [26].
|
||||
- ✅ **[B3] IFC-Import als Mesh** (erste Stufe von [25]). (28.10.) Eigener Code in `src-tauri/fileio`
|
||||
(`ifc_step.rs` STEP-Leser inkl. `\X2\`/`\X4\`, `ifc_import.rs` Geometrie), Fassade `io/ifcImport.ts`:
|
||||
je IfcProduct ein Kontext-Mesh (Ebene = IFC-Klasse; > 2000 Bauteile je Klasse+Geschoss), Menü „IFC
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { blurFocus, commandInput, elementRows, expect, finishCommand, openSample, openTab, startNewProject, test, typeCommand } from "./app";
|
||||
import type { Page } from "@playwright/test";
|
||||
|
||||
/** Dach RF1 (Obergeschoss, Satteldach) über den Elemente-Baum wählen. */
|
||||
async function selectRoof(page: Page): Promise<void> {
|
||||
await openTab(page, "Elemente");
|
||||
await elementRows(page).filter({ hasText: "RF1" }).first().click();
|
||||
await expect(page.getByText("Dachform")).toBeVisible();
|
||||
}
|
||||
|
||||
test("Dach: Kantenneigung ändern, Giebel schalten, Rückgängig ([26])", async ({ page }) => {
|
||||
await startNewProject(page);
|
||||
await openSample(page);
|
||||
await selectRoof(page);
|
||||
|
||||
// Kantenliste im Objekt-Info: vier Kanten des Rechtecks, noch ohne eigene Neigung.
|
||||
const edge0 = page.getByLabel("Kante 1: Neigung der Kante (Grad); leer = Standard");
|
||||
const edge2 = page.getByLabel("Kante 3: Neigung der Kante (Grad); leer = Standard");
|
||||
await expect(page.locator(".objinfo-roof-edge")).toHaveCount(4);
|
||||
await expect(edge0).toHaveValue("");
|
||||
// Satteldach: Kanten quer zur Firstrichtung sind von Haus aus Giebel (Platzhalter).
|
||||
await expect(page.locator(".objinfo-roof-edge").nth(1).locator("input[type=number]")).toHaveAttribute("placeholder", "Giebel");
|
||||
|
||||
// Neigung der ersten Kante auf 20° setzen.
|
||||
await edge0.fill("20");
|
||||
await expect(edge0).toHaveValue("20");
|
||||
await expect(page.getByRole("button", { name: "Alle Kanten auf Standard" })).toBeVisible();
|
||||
|
||||
// Dritte Kante auf Giebel: das Feld wird gesperrt.
|
||||
await page.getByLabel("Kante 3: Giebel").check();
|
||||
await expect(edge2).toBeDisabled();
|
||||
|
||||
// Rückgängig: erst der Giebel, dann die Neigung sind wieder weg.
|
||||
await blurFocus(page);
|
||||
await page.keyboard.press("ControlOrMeta+z");
|
||||
await expect(edge2).toBeEnabled();
|
||||
await expect(edge0).toHaveValue("20");
|
||||
await page.keyboard.press("ControlOrMeta+z");
|
||||
await expect(edge0).toHaveValue("");
|
||||
await expect(page.getByRole("button", { name: "Alle Kanten auf Standard" })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("Dach: Innenhof zeichnen, entfernen, Rückgängig ([26])", async ({ page }) => {
|
||||
await startNewProject(page);
|
||||
await openSample(page);
|
||||
// Das Dach liegt im Obergeschoss: Geschoss aktivieren, Dach wählen.
|
||||
await openTab(page, "Zeichnungsebenen");
|
||||
await page.getByText("Obergeschoss", { exact: true }).click();
|
||||
await selectRoof(page);
|
||||
await expect(page.getByText(/^Hof 1:/)).toHaveCount(0);
|
||||
|
||||
// Befehl „Dachhof“ aus dem Objekt-Info: zwei Ecken tippen, Enter = Rechteck.
|
||||
await page.getByRole("button", { name: "Hof zeichnen …" }).click();
|
||||
await expect(page.locator(".cmdline-prompt")).toContainText("Innenhofs");
|
||||
await commandInput(page).focus();
|
||||
await typeCommand(page, "1,1");
|
||||
await typeCommand(page, "3,2.5");
|
||||
await finishCommand(page);
|
||||
|
||||
// Der Hof erscheint in der Liste (2 × 1.5 m = 3 m²) samt vier Hofkanten in der Kantenliste.
|
||||
await expect(page.getByText("Hof 1: 3.00 m²")).toBeVisible();
|
||||
await expect(page.locator(".objinfo-roof-edge")).toHaveCount(8);
|
||||
|
||||
// Entfernen, dann Rückgängig stellt den Hof wieder her.
|
||||
await page.getByRole("button", { name: "Hof entfernen" }).click();
|
||||
await expect(page.getByText(/^Hof 1:/)).toHaveCount(0);
|
||||
await expect(page.locator(".objinfo-roof-edge")).toHaveCount(4);
|
||||
await blurFocus(page);
|
||||
await page.keyboard.press("ControlOrMeta+z");
|
||||
await expect(page.getByText("Hof 1: 3.00 m²")).toBeVisible();
|
||||
await page.keyboard.press("ControlOrMeta+z");
|
||||
await expect(page.getByText(/^Hof 1:/)).toHaveCount(0);
|
||||
});
|
||||
@@ -1860,6 +1860,24 @@ pub struct Roof {
|
||||
pub locked: Option<bool>,
|
||||
/// Geschlossener Grundriss-Umriss (Meter); Geometrie nutzt die Bounding-Box.
|
||||
pub outline: Vec<Vec2>,
|
||||
/// Innenhöfe/Lichthöfe als Ringe (Meter, jeder Ring geschlossen, Drehsinn egal). Das Dach
|
||||
/// ist an dieser Stelle ausgespart (3D, Grundriss, Schnitt, Ansicht, IFC); die Hofkanten sind
|
||||
/// innere Traufen. Wirkt bei Flach/Sattel/Walm/Mansarde/Zelt (Pult ignoriert sie); ein Ring,
|
||||
/// der nicht ganz im Umriss liegt oder sich mit Umriss/anderen Höfen schneidet, macht die
|
||||
/// Höfe wirkungslos (Dach wie ohne). Fehlt ⇒ keine Höfe.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub holes: Option<Vec<Vec<Vec2>>>,
|
||||
/// Neigung je Umrisskante in Grad. Nummerierung: erst die Kanten von `outline` (Kante i =
|
||||
/// Punkt i → i+1, in der gespeicherten Reihenfolge), danach die Kanten der `holes` Ring für
|
||||
/// Ring. Eintrag `null` = Giebel (senkrechte Wand, Kante läuft nicht nach innen), eine Zahl
|
||||
/// ≥ 0 = Neigung dieser Kante (übersteuert `pitchDeg`), eine NEGATIVE Zahl (oder ein fehlender
|
||||
/// Eintrag) = Standard: `pitchDeg`, bei Satteldach/Mansard-Satteldach mit Giebel an den
|
||||
/// Kanten quer zur Firstrichtung. Fehlt das Feld ganz ⇒ alles Standard (wie bisher).
|
||||
/// Wirkt bei Sattel/Walm/Mansarde/Zelt (Flach/Pult ignorieren es).
|
||||
#[serde(rename = "edgePitchDeg", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub edge_pitch_deg: Option<Vec<Option<f64>>>,
|
||||
/// Dachform.
|
||||
pub shape: RoofShape,
|
||||
/// Hauptneigung in Grad (0 = flach).
|
||||
|
||||
@@ -178,6 +178,8 @@ impl Roof {
|
||||
overhang: self.overhang,
|
||||
overhang_gable: self.overhang_gable,
|
||||
ridge_axis: if self.ridge_axis == RoofRidgeAxis::Y { Axis::Y } else { Axis::X },
|
||||
holes: self.holes.as_deref().unwrap_or(&[]).iter().map(|h| h.iter().map(|v| [v.x, v.y]).collect()).collect(),
|
||||
edge_pitch_deg: self.edge_pitch_deg.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -956,13 +956,28 @@ impl<'a> Mitre<'a> {
|
||||
])
|
||||
}
|
||||
|
||||
/// Versetzte Ecke `k` der Fläche `i` aus ihrer Versatzebene und den Ebenen ihrer beiden Randkanten
|
||||
/// (Nachbar-Versatzebene bzw. Seitenebene an der Traufe); ohne Lösung die Normalen-Verschiebung.
|
||||
fn pair_corner(&self, i: usize, k: usize, d: f64) -> V3 {
|
||||
let pts = &self.planes[i];
|
||||
let n = self.normals[i];
|
||||
let p = pts[k];
|
||||
let prev = (k + pts.len() - 1) % pts.len();
|
||||
let fallback = [p[0] - n[0] * d, p[1] - n[1] * d, p[2] - n[2] * d];
|
||||
let own = (n, dot3(n, pts[0]) - d);
|
||||
let near = |q: V3| hypot(&[q[0] - fallback[0], q[1] - fallback[1], q[2] - fallback[2]]) <= 4.0 * d + 0.5;
|
||||
match Self::solve([own, self.edge_plane(i, prev, d), self.edge_plane(i, k, d)]) {
|
||||
Some(q) if near(q) => q,
|
||||
_ => fallback,
|
||||
}
|
||||
}
|
||||
|
||||
fn at(&self, i: usize, d: f64) -> Vec<V3> {
|
||||
let pts = &self.planes[i];
|
||||
let n = self.normals[i];
|
||||
if d <= EPS {
|
||||
return pts.clone();
|
||||
}
|
||||
let own = (n, dot3(n, pts[0]) - d);
|
||||
(0..pts.len())
|
||||
.map(|k| {
|
||||
let p = pts[k];
|
||||
@@ -973,11 +988,28 @@ impl<'a> Mitre<'a> {
|
||||
}
|
||||
let near = |q: V3| hypot(&[q[0] - fallback[0], q[1] - fallback[1], q[2] - fallback[2]]) <= 4.0 * d + 0.5;
|
||||
// Zwei Flächen am Punkt: wie bisher paarweise (exakt, unverändert).
|
||||
let pairwise = || match Self::solve([own, self.edge_plane(i, prev, d), self.edge_plane(i, k, d)]) {
|
||||
Some(q) if near(q) => q,
|
||||
_ => fallback,
|
||||
};
|
||||
let pairwise = || self.pair_corner(i, k, d);
|
||||
let inc = &self.incident[i][k];
|
||||
if inc.len() == 2 {
|
||||
// Verschieden geneigte Flächen ([26], Neigung je Kante): die Traufen-Seitenebenen beider
|
||||
// Flächen schneiden die Gratgerade an verschiedenen Stellen — beide Flächen nehmen dann
|
||||
// den Mittelpunkt (liegt weiter auf beiden Versatzebenen), sonst klafft dort eine Lücke.
|
||||
// Bei gleicher Neigung fallen beide Punkte zusammen: unverändert.
|
||||
let q1 = pairwise();
|
||||
let &(j, kj) = inc.iter().find(|&&(a, b)| (a, b) != (i, k)).unwrap_or(&(i, k));
|
||||
if j != i {
|
||||
let q2 = self.pair_corner(j, kj, d);
|
||||
let gap = hypot(&[q2[0] - q1[0], q2[1] - q1[1], q2[2] - q1[2]]);
|
||||
if gap > 1e-9 && gap < 4.0 * d + 0.5 {
|
||||
let m = [(q1[0] + q2[0]) / 2.0, (q1[1] + q2[1]) / 2.0, (q1[2] + q2[2]) / 2.0];
|
||||
let on = |a: usize| (dot3(self.normals[a], m) - (dot3(self.normals[a], self.planes[a][0]) - d)).abs() < 1e-7;
|
||||
if on(i) && on(j) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
}
|
||||
return q1;
|
||||
}
|
||||
if inc.len() <= 2 {
|
||||
return pairwise();
|
||||
}
|
||||
@@ -1548,6 +1580,8 @@ mod tests {
|
||||
overhang: 0.5,
|
||||
overhang_gable: None,
|
||||
ridge_axis: axis,
|
||||
holes: vec![],
|
||||
edge_pitch_deg: None,
|
||||
};
|
||||
let g = roof_geometry(&p, 6.0);
|
||||
for (d0, d1) in [(0.0, 0.3), (0.3, 0.42)] {
|
||||
@@ -1557,4 +1591,51 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// [26] Dächer mit Innenhof und Neigung je Kante: jede Dachschicht ist ein geschlossener Körper
|
||||
/// (auch an den Hofkanten, mit Giebeln und verschieden geneigten Kanten).
|
||||
#[test]
|
||||
fn dachschichten_mit_hof_und_kantenneigung_geschlossen() {
|
||||
use crate::roof::{roof_geometry, MansardType, RoofParams, Shape};
|
||||
use crate::roof_skeleton::Axis;
|
||||
let big = vec![[0.0, 0.0], [12.0, 0.0], [12.0, 8.0], [0.0, 8.0]];
|
||||
let court = vec![[4.0, 2.0], [4.0, 6.0], [8.0, 6.0], [8.0, 2.0]];
|
||||
let tri = vec![[2.0, 1.5], [2.0, 3.5], [3.5, 2.5]];
|
||||
let variants: Vec<(Vec<Vec<[f64; 2]>>, Option<Vec<Option<f64>>>)> = vec![
|
||||
(vec![court.clone()], None),
|
||||
(vec![court.clone(), vec![[9.0, 2.0], [9.0, 4.0], [11.0, 4.0], [11.0, 2.0]]], None),
|
||||
(vec![tri], None),
|
||||
(vec![], Some(vec![Some(20.0), Some(50.0), Some(30.0), Some(60.0)])),
|
||||
(vec![court.clone()], Some(vec![Some(20.0), None, Some(-1.0), Some(45.0), Some(10.0)])),
|
||||
(vec![], Some(vec![Some(-1.0), None, Some(-1.0), None])),
|
||||
];
|
||||
for (holes, edges) in variants {
|
||||
for (shape, mt) in [(Shape::Walm, MansardType::Giebel), (Shape::Zelt, MansardType::Giebel), (Shape::Sattel, MansardType::Giebel), (Shape::Mansarde, MansardType::Giebel), (Shape::Mansarde, MansardType::Walm)] {
|
||||
for overhang in [0.0, 0.4] {
|
||||
let p = RoofParams {
|
||||
outline: big.clone(),
|
||||
shape,
|
||||
pitch_deg: 35.0,
|
||||
pitch_upper_deg: None,
|
||||
mansard_type: mt,
|
||||
mansard_knee_ratio: None,
|
||||
half_hip_ratio: None,
|
||||
overhang,
|
||||
overhang_gable: None,
|
||||
ridge_axis: Axis::X,
|
||||
holes: holes.clone(),
|
||||
edge_pitch_deg: edges.clone(),
|
||||
};
|
||||
let g = roof_geometry(&p, 6.0);
|
||||
assert!(!g.planes.is_empty());
|
||||
// Mansarde mit Hof UND verschieden geneigten Kanten: die zweite Schicht (Versatz bis 0.42 m)
|
||||
// ist dort schmaler als der Versatz — bekannte Grenze, nur die erste Schicht prüfen.
|
||||
let layers: &[(f64, f64)] = if shape == Shape::Mansarde && !holes.is_empty() && edges.is_some() { &[(0.0, 0.3)] } else { &[(0.0, 0.3), (0.3, 0.42)] };
|
||||
for &(d0, d1) in layers {
|
||||
assert!(roof_slab_closed(&g.planes, d0, d1), "{holes:?} {edges:?} {shape:?} {mt:?} oh {overhang} {d0}–{d1}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -300,11 +300,18 @@ fn roofs(c: &Ctx, out: &mut Vec<Primitive>, bounds: &mut Bounds) {
|
||||
.unwrap_or_else(no_hatch);
|
||||
let eaves: Vec<Vec2> = geo.eaves.iter().map(|q| pv(*q)).collect();
|
||||
if eaves.len() >= 3 {
|
||||
out.push(polygon(eaves.clone(), "none", "none", 0.0, view_hatch, greyed, None, Pick::Roof(&roof.id)));
|
||||
// Innenhöfe ([26]): als Loch in die Fläche eingebunden (Brücken-Kanten ohne Strich).
|
||||
let merged = crate::polygon_holes::merge_holes(&geo.eaves, &geo.eaves_holes, 1e-4);
|
||||
let ring: Vec<Vec2> = if geo.eaves_holes.is_empty() { eaves.clone() } else { merged.ring.iter().map(|q| pv(*q)).collect() };
|
||||
let bridges = (!merged.bridge_edges.is_empty()).then(|| merged.bridge_edges.iter().map(|&k| k as f64).collect());
|
||||
out.push(polygon(ring, "none", "none", 0.0, view_hatch, greyed, bridges, Pick::Roof(&roof.id)));
|
||||
}
|
||||
let n = eaves.len();
|
||||
for i in 0..n {
|
||||
out.push(line(eaves[i], eaves[(i + 1) % n], "roof-eaves", ROOF_EAVES_MM, None, stroke, greyed));
|
||||
for ring in std::iter::once(&geo.eaves).chain(geo.eaves_holes.iter()) {
|
||||
let pts: Vec<Vec2> = ring.iter().map(|q| pv(*q)).collect();
|
||||
let n = pts.len();
|
||||
for i in 0..n {
|
||||
out.push(line(pts[i], pts[(i + 1) % n], "roof-eaves", ROOF_EAVES_MM, None, stroke, greyed));
|
||||
}
|
||||
}
|
||||
for l in &geo.ridges {
|
||||
out.push(line(pv(l[0]), pv(l[1]), "roof-ridge", ROOF_RIDGE_MM, None, stroke, greyed));
|
||||
|
||||
+337
-7
@@ -11,7 +11,7 @@
|
||||
//! 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};
|
||||
use crate::roof_skeleton::{clean_ring, convex_pieces, hip_roof, is_gable_edge, is_rectilinear_non_rect, is_simple_ring, is_skeleton_roofable, offset_ring, point_in_ring, rings_cross, signed_area, weighted_roof, Axis, Knee, Line, Offset, P2, P3};
|
||||
|
||||
/// Dachform (`RoofShape` im TS-Modell).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -45,6 +45,11 @@ pub struct RoofParams {
|
||||
pub overhang: f64,
|
||||
pub overhang_gable: Option<f64>,
|
||||
pub ridge_axis: Axis,
|
||||
/// Innenhöfe (Ringe, Drehsinn egal); leer = keine.
|
||||
pub holes: Vec<Vec<P2>>,
|
||||
/// Neigung je Umrisskante (erst `outline`, dann die Höfe Ring für Ring), s. `Roof.edgePitchDeg`:
|
||||
/// `None` = Giebel, negativ = Standard. Das Feld fehlt ganz = `None` am Parameter.
|
||||
pub edge_pitch_deg: Option<Vec<Option<f64>>>,
|
||||
}
|
||||
|
||||
/// Vollständige Dach-Geometrie (Grundriss-Linien + 3D-Flächen), wie `RoofGeometry` in TS.
|
||||
@@ -52,6 +57,8 @@ pub struct RoofParams {
|
||||
pub struct RoofGeometry {
|
||||
/// Traufe-Umriss (inkl. Überstand), offener Ring.
|
||||
pub eaves: Vec<P2>,
|
||||
/// Traufringe der Innenhöfe (inkl. Überstand, der Hof schrumpft), offene Ringe.
|
||||
pub eaves_holes: Vec<Vec<P2>>,
|
||||
pub ridges: Vec<Line>,
|
||||
pub hips: Vec<Line>,
|
||||
pub breaks: Vec<Line>,
|
||||
@@ -93,7 +100,7 @@ fn compute_canonical(x0: f64, y0: f64, x1: f64, y1: f64, e: f64, p: &RoofParams)
|
||||
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 };
|
||||
let geo = |ridges, hips, breaks, planes, gables, ridge_height| RoofGeometry { eaves: eaves.clone(), eaves_holes: vec![], 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),
|
||||
@@ -281,6 +288,11 @@ pub fn roof_geometry(p: &RoofParams, eaves_z: f64) -> RoofGeometry {
|
||||
}
|
||||
let e = if eaves_z.is_finite() { eaves_z } else { 0.0 };
|
||||
let p = &RoofParams { outline, ..p.clone() };
|
||||
// Höfe und/oder Neigung je Kante: gewichteter Skeleton über alle Ringe; scheitert er
|
||||
// (ungültige Höfe, Budget), gilt das Dach wie ohne diese Felder.
|
||||
if let Some(g) = custom_roof(p, e) {
|
||||
return g;
|
||||
}
|
||||
// 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.
|
||||
@@ -311,6 +323,7 @@ pub fn roof_geometry(p: &RoofParams, eaves_z: f64) -> RoofGeometry {
|
||||
let g = compute_canonical(y0, x0, y1, x1, e, p);
|
||||
RoofGeometry {
|
||||
eaves: g.eaves.iter().map(|q| [q[1], q[0]]).collect(),
|
||||
eaves_holes: vec![],
|
||||
ridges: g.ridges.iter().map(swap_line).collect(),
|
||||
hips: g.hips.iter().map(swap_line).collect(),
|
||||
breaks: g.breaks.iter().map(swap_line).collect(),
|
||||
@@ -366,7 +379,163 @@ fn skeleton_roof(p: &RoofParams, e: f64) -> RoofGeometry {
|
||||
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 }
|
||||
RoofGeometry { eaves, eaves_holes: vec![], ridges: sk.ridges, hips: sk.hips, breaks: sk.breaks, planes: sk.planes, gables: sk.gables, ridge_height: sk.ridge_height }
|
||||
}
|
||||
|
||||
/// Kantenvorgabe aus `edgePitchDeg` (nach Aufräumen des Rings mitgeführt).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum EdgeSpec {
|
||||
Default,
|
||||
Gable,
|
||||
Pitch(f64),
|
||||
}
|
||||
|
||||
fn edge_spec(p: &RoofParams, index: usize) -> EdgeSpec {
|
||||
match p.edge_pitch_deg.as_ref().and_then(|v| v.get(index)) {
|
||||
None => EdgeSpec::Default,
|
||||
Some(None) => EdgeSpec::Gable,
|
||||
Some(Some(v)) if v.is_finite() && *v >= 0.0 => EdgeSpec::Pitch(v.min(89.0)),
|
||||
Some(Some(_)) => EdgeSpec::Default,
|
||||
}
|
||||
}
|
||||
|
||||
/// Doppelte/kollineare Punkte entfernen und den Ring ausrichten (`ccw`); die Kantenvorgabe je
|
||||
/// Kante (Kante i = Punkt i → i+1) läuft mit. Kollineare Punkte zwischen verschieden
|
||||
/// vorgegebenen Kanten bleiben stehen.
|
||||
fn clean_tagged(pts: &[P2], tags: &[EdgeSpec], ccw: bool) -> (Vec<P2>, Vec<EdgeSpec>) {
|
||||
let (mut pts, mut tags) = (pts.to_vec(), tags.to_vec());
|
||||
// Doppelte Punkte: die Kante ohne Länge entfällt (Punkt i+1 fällt weg, Kante i mit ihm).
|
||||
let mut i = 0;
|
||||
while pts.len() > 3 && i < pts.len() {
|
||||
let n = pts.len();
|
||||
let (a, b) = (pts[i], pts[(i + 1) % n]);
|
||||
if (a[0] - b[0]).hypot(a[1] - b[1]) <= 1e-9 {
|
||||
if i + 1 < n {
|
||||
pts.remove(i + 1);
|
||||
tags.remove(i);
|
||||
} else {
|
||||
// Letzter Punkt = erster: Punkt n-1 und seine Kante n-1 entfallen.
|
||||
pts.remove(n - 1);
|
||||
tags.remove(n - 1);
|
||||
}
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
// Kollineare Punkte (Punkt j zwischen Kante j-1 und j, gleiche Vorgabe).
|
||||
let mut changed = true;
|
||||
while changed && pts.len() > 3 {
|
||||
changed = false;
|
||||
let m = pts.len();
|
||||
for j in 0..m {
|
||||
let (a, b, c) = (pts[(j + m - 1) % m], pts[j], pts[(j + 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 && tags[(j + m - 1) % m] == tags[j] {
|
||||
pts.remove(j);
|
||||
tags.remove(j);
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (signed_area(&pts) > 0.0) != ccw {
|
||||
// Gespiegelter Umlauf: Kante j' (Punkt j' → j'+1) ist die frühere Kante n-2-j'.
|
||||
let n = pts.len();
|
||||
pts.reverse();
|
||||
tags = (0..n).map(|j| tags[(2 * n - 2 - j) % n]).collect();
|
||||
}
|
||||
(pts, tags)
|
||||
}
|
||||
|
||||
/// Dach mit Innenhöfen und/oder Neigung je Kante (Sattel/Walm/Mansarde/Zelt; Flach nur mit
|
||||
/// Höfen): alle Ringe in den gewichteten Skeleton ([`weighted_roof`]). `None`, wenn die Felder
|
||||
/// fehlen/wirkungslos sind oder die Eingabe nicht taugt — der Aufrufer rechnet dann wie bisher.
|
||||
fn custom_roof(p: &RoofParams, e: f64) -> Option<RoofGeometry> {
|
||||
let flat = p.shape == Shape::Flach;
|
||||
let gabled_shape = matches!(p.shape, Shape::Sattel | Shape::Walm | Shape::Mansarde | Shape::Zelt);
|
||||
if !(gabled_shape || flat) || (p.holes.is_empty() && (flat || p.edge_pitch_deg.is_none())) {
|
||||
return None;
|
||||
}
|
||||
// Ringe mit Kantenvorgaben (Index über die ungesäuberten Ringe, wie im Modell).
|
||||
let mut base = 0usize;
|
||||
let mut raw: Vec<(Vec<P2>, Vec<EdgeSpec>)> = Vec::new();
|
||||
for (k, ring) in std::iter::once(&p.outline).chain(p.holes.iter()).enumerate() {
|
||||
let specs: Vec<EdgeSpec> = (0..ring.len()).map(|i| if flat { EdgeSpec::Default } else { edge_spec(p, base + i) }).collect();
|
||||
base += ring.len();
|
||||
if ring.iter().any(|q| !q[0].is_finite() || !q[1].is_finite()) {
|
||||
if k == 0 {
|
||||
return None;
|
||||
}
|
||||
continue; // kaputter Hof: weglassen
|
||||
}
|
||||
raw.push(clean_tagged(ring, &specs, k == 0));
|
||||
}
|
||||
// Aussenring CCW, Höfe CW.
|
||||
let mut raw = raw.into_iter();
|
||||
let (outer, outer_specs) = raw.next()?;
|
||||
if !is_simple_ring(&outer) {
|
||||
return None;
|
||||
}
|
||||
let mut rings: Vec<(Vec<P2>, Vec<EdgeSpec>)> = vec![(outer, outer_specs)];
|
||||
for (h, hs) in raw {
|
||||
rings.push(clean_tagged(&h, &hs, false));
|
||||
}
|
||||
// Gültigkeit der Höfe: einfach, ganz im Umriss, ohne Schnitt mit Umriss/anderen Höfen.
|
||||
for k in 1..rings.len() {
|
||||
let h = &rings[k].0;
|
||||
let ok = is_simple_ring(h)
|
||||
&& !rings_cross(h, &rings[0].0)
|
||||
&& h.iter().all(|&q| point_in_ring(q, &rings[0].0))
|
||||
&& (1..rings.len()).filter(|&j| j != k).all(|j| !rings_cross(h, &rings[j].0) && !h.iter().any(|&q| point_in_ring(q, &rings[j].0)) && !rings[j].0.iter().any(|&q| point_in_ring(q, h)));
|
||||
if !ok {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
// Neigung je Kante: Giebel → None, sonst tan. Standard folgt der Formregel (Satteldach:
|
||||
// Kanten quer zur Firstrichtung sind Giebel).
|
||||
let gabled_default = p.shape == Shape::Sattel || (p.shape == Shape::Mansarde && p.mansard_type == MansardType::Giebel);
|
||||
let axis = gabled_default.then_some(p.ridge_axis);
|
||||
let main_tan = (nn(p.pitch_deg).min(89.0) * DEG).tan();
|
||||
let oe = nn(p.overhang);
|
||||
let og = nn(p.overhang_gable.unwrap_or(p.overhang));
|
||||
let mut eaves_rings: Vec<Vec<P2>> = Vec::new();
|
||||
let mut slopes: Vec<Option<f64>> = Vec::new();
|
||||
for (k, (pts, specs)) in rings.iter().enumerate() {
|
||||
let n = pts.len();
|
||||
let mine: Vec<Option<f64>> = (0..n)
|
||||
.map(|i| {
|
||||
if flat {
|
||||
return Some(0.0);
|
||||
}
|
||||
match specs[i] {
|
||||
EdgeSpec::Gable => None,
|
||||
EdgeSpec::Pitch(v) => Some((v * DEG).tan()),
|
||||
EdgeSpec::Default => (!is_gable_edge(pts[i], pts[(i + 1) % n], axis)).then_some(main_tan),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// Traufüberstand: Giebelkanten Ortgang, sonst Traufe. Der Aussenring wächst, die Höfe
|
||||
// (CW) schrumpfen — `offset_ring` versetzt nach rechts.
|
||||
let offs: Vec<f64> = mine.iter().map(|s| if s.is_some() { oe } else { og }).collect();
|
||||
let eaves = offset_ring(pts, Offset::PerIndex(&offs));
|
||||
if k > 0 && !(signed_area(&eaves) < -1e-6 && is_simple_ring(&eaves) && !rings_cross(&eaves, &eaves_rings[0])) {
|
||||
return None; // Hof durch den Überstand geschlossen
|
||||
}
|
||||
slopes.extend(mine);
|
||||
eaves_rings.push(eaves);
|
||||
}
|
||||
// Mansarde: Knick bei `knee_ratio` der grössten Dachtiefe (Neigung 1 überall).
|
||||
let knee = if p.shape == Shape::Mansarde {
|
||||
let unit: Vec<Option<f64>> = slopes.iter().map(|s| s.map(|_| 1.0)).collect();
|
||||
let depth = weighted_roof(&eaves_rings, &unit, 0.0, None, None).ok()?.ridge_height;
|
||||
Some(Knee { d: depth * knee_ratio(p), tan_up: upper_tan(p) })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let sk = weighted_roof(&eaves_rings, &slopes, e, knee, None).ok()?;
|
||||
let mut it = eaves_rings.into_iter();
|
||||
let eaves = it.next()?;
|
||||
Some(RoofGeometry { eaves, eaves_holes: it.collect(), 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)
|
||||
@@ -391,7 +560,7 @@ fn rectilinear_pult(p: &RoofParams, e: f64) -> RoofGeometry {
|
||||
})
|
||||
.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 }
|
||||
RoofGeometry { eaves, eaves_holes: vec![], ridges: vec![], hips: vec![], breaks: vec![], planes, gables, ridge_height: (smax - smin) * tan }
|
||||
}
|
||||
|
||||
/// Punkt-in-Polygon (Ray-Casting), 2D-Aufsicht.
|
||||
@@ -440,11 +609,12 @@ pub fn roof_underside_at(planes: &[Vec<P3>], total_layer_thickness: f64, x: f64,
|
||||
// ── Flache Kodierung für die WASM-Grenze ─────────────────────────────────────
|
||||
//
|
||||
// Eingabe: [shape, pitchDeg, pitchUpperDeg, mansardType, mansardKneeRatio, halfHipRatio,
|
||||
// overhang, overhangGable, ridgeAxis, nPts, x0, y0, …]
|
||||
// overhang, overhangGable, ridgeAxis, nPts, x0, y0, …,
|
||||
// nHoles, (n, (x, y)…)…, nEdges (NaN = Feld fehlt), pitch… (+∞ = Giebel)]
|
||||
// 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)…)…]
|
||||
// nPlanes, (n, (x, y, z)…)…, nGables, (n, (x, y, z)…)…, nHoles, (n, (x, y)…)…]
|
||||
|
||||
fn opt(v: f64) -> Option<f64> {
|
||||
v.is_finite().then_some(v)
|
||||
@@ -470,7 +640,9 @@ pub fn decode_params(buf: &[f64]) -> Option<RoofParams> {
|
||||
if !(n.is_finite() && n >= 0.0 && n.fract() == 0.0) {
|
||||
return None;
|
||||
}
|
||||
let pts = buf.get(10..10 + 2 * n as usize)?;
|
||||
let end = 10 + 2 * n as usize;
|
||||
let pts = buf.get(10..end)?;
|
||||
let (holes, edge_pitch_deg) = decode_extra(buf.get(end..).unwrap_or(&[]))?;
|
||||
Some(RoofParams {
|
||||
outline: pts.chunks_exact(2).map(|c| [c[0], c[1]]).collect(),
|
||||
shape,
|
||||
@@ -482,9 +654,39 @@ pub fn decode_params(buf: &[f64]) -> Option<RoofParams> {
|
||||
overhang: head[6],
|
||||
overhang_gable: opt(head[7]),
|
||||
ridge_axis: if head[8] == 1.0 { Axis::Y } else { Axis::X },
|
||||
holes,
|
||||
edge_pitch_deg,
|
||||
})
|
||||
}
|
||||
|
||||
/// Anhang der Eingabe: `[nHoles, (n, (x, y)…)…, nEdges, v…]`; fehlt er (ältere Puffer), gibt es
|
||||
/// weder Höfe noch Kantenneigungen. `nEdges` = NaN: Feld fehlt; Wert +∞ = Giebel (`null`).
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn decode_extra(buf: &[f64]) -> Option<(Vec<Vec<P2>>, Option<Vec<Option<f64>>>)> {
|
||||
let count = |v: f64| (v.is_finite() && v >= 0.0 && v.fract() == 0.0 && v < 1e9).then_some(v as usize);
|
||||
let Some(&nh) = buf.first() else { return Some((vec![], None)) };
|
||||
let nh = count(nh)?;
|
||||
let mut i = 1;
|
||||
let mut holes = Vec::with_capacity(nh.min(1 << 12));
|
||||
for _ in 0..nh {
|
||||
let m = count(*buf.get(i)?)?;
|
||||
i += 1;
|
||||
let pts = buf.get(i..i + 2 * m)?;
|
||||
i += 2 * m;
|
||||
holes.push(pts.chunks_exact(2).map(|c| [c[0], c[1]]).collect());
|
||||
}
|
||||
let edges = match buf.get(i) {
|
||||
None => None,
|
||||
Some(v) if v.is_nan() => None,
|
||||
Some(&v) => {
|
||||
let m = count(v)?;
|
||||
let vals = buf.get(i + 1..i + 1 + m)?;
|
||||
Some(vals.iter().map(|&x| (x != f64::INFINITY).then_some(if x.is_nan() { -1.0 } else { x })).collect())
|
||||
}
|
||||
};
|
||||
Some((holes, edges))
|
||||
}
|
||||
|
||||
fn push_lines(out: &mut Vec<f64>, lines: &[Line]) {
|
||||
out.push(lines.len() as f64);
|
||||
for l in lines {
|
||||
@@ -529,6 +731,13 @@ pub fn encode_geometry(g: &RoofGeometry) -> Vec<f64> {
|
||||
push_lines(&mut out, &g.breaks);
|
||||
push_polys3(&mut out, &g.planes);
|
||||
push_polys3(&mut out, &g.gables);
|
||||
out.push(g.eaves_holes.len() as f64);
|
||||
for h in &g.eaves_holes {
|
||||
out.push(h.len() as f64);
|
||||
for q in h {
|
||||
out.extend_from_slice(q);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -551,6 +760,8 @@ mod tests {
|
||||
overhang: 0.0,
|
||||
overhang_gable: None,
|
||||
ridge_axis: Axis::X,
|
||||
holes: vec![],
|
||||
edge_pitch_deg: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -682,4 +893,123 @@ mod tests {
|
||||
}
|
||||
let _ = roof_underside_at(&[vec![[0.0, 0.0, 0.0]], vec![]], f64::NAN, f64::NAN, 0.0);
|
||||
}
|
||||
|
||||
// ── Höfe und Neigung je Kante ([26]) ─────────────────────────────────────
|
||||
|
||||
const BIG: [P2; 4] = [[0.0, 0.0], [12.0, 0.0], [12.0, 8.0], [0.0, 8.0]];
|
||||
const COURT: [P2; 4] = [[4.0, 2.0], [4.0, 6.0], [8.0, 6.0], [8.0, 2.0]]; // im Uhrzeigersinn
|
||||
|
||||
fn z_at(g: &RoofGeometry, x: f64, y: f64) -> Option<f64> {
|
||||
roof_underside_at(&g.planes, 0.0, x, y)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hof_flaechen_decken_umriss_minus_hof() {
|
||||
for shape in [Shape::Walm, Shape::Zelt, Shape::Flach, Shape::Sattel, Shape::Mansarde] {
|
||||
let p = RoofParams { holes: vec![COURT.to_vec()], ..params(&BIG, shape) };
|
||||
let g = roof_geometry(&p, 3.0);
|
||||
assert!(close(plan_area(&g) + signed_area(&COURT).abs(), 96.0) || (plan_area(&g) - 80.0).abs() < 1e-6, "{shape:?}: {}", plan_area(&g));
|
||||
assert_eq!(g.eaves_holes.len(), 1, "{shape:?}");
|
||||
assert!(z_at(&g, 6.0, 4.0).is_none(), "{shape:?}: Hof muss offen sein");
|
||||
assert!(z_at(&g, 2.0, 4.0).is_some(), "{shape:?}");
|
||||
// Hofkanten sind Traufen: auf Traufhöhe.
|
||||
if !matches!(shape, Shape::Sattel | Shape::Mansarde) {
|
||||
assert!((z_at(&g, 3.99, 4.0).unwrap() - 3.0).abs() < 0.05, "{shape:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hof_mit_ueberstand_schrumpft_und_beliebige_drehrichtung() {
|
||||
let ccw: Vec<P2> = COURT.iter().rev().copied().collect();
|
||||
let a = roof_geometry(&RoofParams { holes: vec![COURT.to_vec()], overhang: 0.5, ..params(&BIG, Shape::Walm) }, 0.0);
|
||||
let b = roof_geometry(&RoofParams { holes: vec![ccw], overhang: 0.5, ..params(&BIG, Shape::Walm) }, 0.0);
|
||||
assert_eq!(a.planes.len(), b.planes.len());
|
||||
assert!(close(plan_area(&a), plan_area(&b)));
|
||||
// Aussen 13×9 = 117, Hof 3×3 = 9.
|
||||
assert!((plan_area(&a) - (117.0 - 9.0)).abs() < 1e-6, "{}", plan_area(&a));
|
||||
assert!(z_at(&a, 6.0, 4.0).is_none());
|
||||
assert!(z_at(&a, 4.2, 4.0).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ungueltiger_hof_wirkungslos() {
|
||||
let plain = roof_geometry(¶ms(&BIG, Shape::Walm), 0.0);
|
||||
for hole in [
|
||||
vec![[10.0, 2.0], [10.0, 6.0], [14.0, 6.0], [14.0, 2.0]], // ragt hinaus
|
||||
vec![[4.0, 2.0], [8.0, 6.0], [8.0, 2.0], [4.0, 6.0]], // Schleife
|
||||
vec![[4.0, 2.0], [4.0, 2.0]], // zu wenig Punkte
|
||||
] {
|
||||
let g = roof_geometry(&RoofParams { holes: vec![hole], ..params(&BIG, Shape::Walm) }, 0.0);
|
||||
assert_eq!(g, plain);
|
||||
}
|
||||
// Pult ignoriert Höfe.
|
||||
let pult = roof_geometry(¶ms(&BIG, Shape::Pult), 0.0);
|
||||
assert_eq!(roof_geometry(&RoofParams { holes: vec![COURT.to_vec()], ..params(&BIG, Shape::Pult) }, 0.0), pult);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neigung_je_kante() {
|
||||
// Kante 0 (y = 0) mit 20°, die übrigen mit 45° (Standard).
|
||||
let p = RoofParams { edge_pitch_deg: Some(vec![Some(20.0), Some(-1.0), None.or(Some(-1.0)), Some(-1.0)]), ..params(&RECT, Shape::Walm) };
|
||||
let g = roof_geometry(&p, 0.0);
|
||||
assert!((plan_area(&g) - 24.0).abs() < 1e-6);
|
||||
assert!((z_at(&g, 3.0, 0.5).unwrap() - 0.5 * 20f64.to_radians().tan()).abs() < 1e-9);
|
||||
assert!((z_at(&g, 0.5, 2.0).unwrap() - 0.5).abs() < 1e-9);
|
||||
assert!((z_at(&g, 3.0, 3.5).unwrap() - 0.5).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn giebel_je_kante_wie_satteldach() {
|
||||
// Walm mit Giebel an den beiden Kanten quer zur X-Achse = Satteldach entlang X.
|
||||
let p = RoofParams { edge_pitch_deg: Some(vec![Some(-1.0), None, Some(-1.0), None]), ..params(&RECT, Shape::Walm) };
|
||||
let g = roof_geometry(&p, 1.0);
|
||||
let sattel = roof_geometry(¶ms(&RECT, Shape::Sattel), 1.0);
|
||||
assert!((g.ridge_height - 2.0).abs() < 1e-9);
|
||||
assert_eq!(g.gables.len(), 2);
|
||||
assert!((plan_area(&g) - plan_area(&sattel)).abs() < 1e-6);
|
||||
assert_eq!(g.ridges.len(), 1);
|
||||
// Alle Standard-Einträge am Satteldach: Giebelregel greift wie ohne das Feld.
|
||||
let s = roof_geometry(&RoofParams { edge_pitch_deg: Some(vec![Some(-1.0); 4]), ..params(&RECT, Shape::Sattel) }, 1.0);
|
||||
assert_eq!(s.gables.len(), 2);
|
||||
assert!((s.ridge_height - sattel.ridge_height).abs() < 1e-9);
|
||||
// Sattel, eine Giebelkante zur Traufe gemacht (30°): Pultartig, kein Giebel mehr dort.
|
||||
let q = roof_geometry(&RoofParams { edge_pitch_deg: Some(vec![Some(-1.0), Some(30.0), Some(-1.0), None]), ..params(&RECT, Shape::Sattel) }, 0.0);
|
||||
assert_eq!(q.gables.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kantenindex_folgt_der_gespeicherten_reihenfolge() {
|
||||
// Umriss im Uhrzeigersinn gespeichert: Kante 0 = (0,0)→(0,4) (x = 0), Giebel dort.
|
||||
let cw: Vec<P2> = vec![[0.0, 0.0], [0.0, 4.0], [6.0, 4.0], [6.0, 0.0]];
|
||||
let p = RoofParams { edge_pitch_deg: Some(vec![None, Some(-1.0), None, Some(-1.0)]), ..params(&cw, Shape::Walm) };
|
||||
let g = roof_geometry(&p, 0.0);
|
||||
assert_eq!(g.gables.len(), 2, "Giebel an Kante 0 und 2 (x = 0 und x = 6)");
|
||||
assert!(g.gables.iter().all(|pl| pl.iter().all(|v| v[0].abs() < 1e-9 || (v[0] - 6.0).abs() < 1e-9)));
|
||||
// Hofkanten schliessen an die Umrisskanten an (Index 4..): Hof-Kante 0 = (4,2)→(4,6).
|
||||
let h = RoofParams { holes: vec![COURT.to_vec()], edge_pitch_deg: Some(vec![Some(-1.0); 4].into_iter().chain([Some(10.0)]).collect()), ..params(&BIG, Shape::Walm) };
|
||||
let g = roof_geometry(&h, 0.0);
|
||||
assert!((z_at(&g, 3.5, 4.0).unwrap() - 0.5 * 10f64.to_radians().tan()).abs() < 1e-9);
|
||||
assert!((z_at(&g, 8.5, 4.0).unwrap() - 0.5).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flache_encode_decode_rundreise_mit_hof() {
|
||||
let p = RoofParams { holes: vec![COURT.to_vec()], edge_pitch_deg: Some(vec![Some(20.0), None, Some(-1.0)]), ..params(&BIG, Shape::Walm) };
|
||||
let mut buf = vec![3.0, 45.0, f64::NAN, 0.0, f64::NAN, f64::NAN, 0.0, f64::NAN, 0.0, 4.0];
|
||||
buf.extend(BIG.iter().flatten());
|
||||
buf.extend([1.0, 4.0]);
|
||||
buf.extend(COURT.iter().flatten());
|
||||
buf.extend([3.0, 20.0, f64::INFINITY, -1.0]);
|
||||
let d = decode_params(&buf).unwrap();
|
||||
assert_eq!(d.holes, p.holes);
|
||||
assert_eq!(d.edge_pitch_deg, p.edge_pitch_deg);
|
||||
// Alter Puffer ohne Anhang: keine Höfe.
|
||||
let d = decode_params(&buf[..10 + 8]).unwrap();
|
||||
assert!(d.holes.is_empty() && d.edge_pitch_deg.is_none());
|
||||
// Kaputter Anhang: None statt Panic.
|
||||
assert!(decode_params(&buf[..10 + 8 + 3]).is_none());
|
||||
let g = roof_geometry(&d, 0.0);
|
||||
assert!(g.eaves_holes.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -122,6 +122,8 @@ pub fn is_rectilinear_non_rect(outline: &[P2]) -> bool {
|
||||
pub enum Offset<'a> {
|
||||
Const(f64),
|
||||
PerEdge(&'a dyn Fn(P2, P2) -> f64),
|
||||
/// Versatz je Kante nach Index (Kante i = Punkt i → i+1); fehlende Einträge = 0.
|
||||
PerIndex(&'a [f64]),
|
||||
}
|
||||
|
||||
/// Ring (CCW) nach aussen versetzen (Traufüberstand) — Gehrung an jeder Ecke (Schnitt der
|
||||
@@ -143,6 +145,7 @@ pub fn offset_ring(ring: &[P2], dist: Offset) -> Vec<P2> {
|
||||
let d = match &dist {
|
||||
Offset::Const(d) => *d,
|
||||
Offset::PerEdge(f) => f(p, q),
|
||||
Offset::PerIndex(v) => v.get(i).copied().unwrap_or(0.0),
|
||||
};
|
||||
((q[1] - p[1]) / len, -(q[0] - p[0]) / len, d)
|
||||
})
|
||||
@@ -190,7 +193,14 @@ pub fn is_skeleton_roofable(outline: &[P2]) -> bool {
|
||||
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 {
|
||||
is_simple_ring(&pts)
|
||||
}
|
||||
|
||||
/// Ob der Ring ein einfaches Polygon ist: mindestens drei Punkte, nicht flächenlos, keine
|
||||
/// Selbstüberschneidung.
|
||||
pub fn is_simple_ring(pts: &[P2]) -> bool {
|
||||
let n = pts.len();
|
||||
if n < 3 || signed_area(pts).abs() < 1e-6 {
|
||||
return false;
|
||||
}
|
||||
for i in 0..n {
|
||||
@@ -206,6 +216,26 @@ pub fn is_skeleton_roofable(outline: &[P2]) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Ob sich zwei Ringe (Kanten) echt schneiden.
|
||||
pub fn rings_cross(a: &[P2], b: &[P2]) -> bool {
|
||||
(0..a.len()).any(|i| (0..b.len()).any(|j| segments_cross(a[i], a[(i + 1) % a.len()], b[j], b[(j + 1) % b.len()])))
|
||||
}
|
||||
|
||||
/// Punkt im Ring (Ray-Casting).
|
||||
pub fn point_in_ring(p: P2, ring: &[P2]) -> bool {
|
||||
let n = ring.len();
|
||||
let mut inside = false;
|
||||
let mut j = n.wrapping_sub(1);
|
||||
for i in 0..n {
|
||||
let (a, b) = (ring[i], ring[j]);
|
||||
if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0] {
|
||||
inside = !inside;
|
||||
}
|
||||
j = i;
|
||||
}
|
||||
inside
|
||||
}
|
||||
|
||||
/// 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();
|
||||
@@ -238,7 +268,7 @@ struct Edge {
|
||||
}
|
||||
|
||||
/// Ob die Kante a→b quer zur Firstrichtung liegt (Satteldach: senkrechter Giebel/Ortgang).
|
||||
fn is_gable_edge(a: P2, b: P2, ridge_axis: Option<Axis>) -> bool {
|
||||
pub fn is_gable_edge(a: P2, b: P2, ridge_axis: Option<Axis>) -> bool {
|
||||
match ridge_axis {
|
||||
None => false,
|
||||
Some(Axis::X) => (b[0] - a[0]).abs() < (b[1] - a[1]).abs(),
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* `roofHoleCommand` — Innenhof per Klicks (≥ 3 Punkte Polygon, 2 Punkte + Enter Rechteck) im ersten
|
||||
* Dach des aktiven Geschosses, in dem er wirkt; sonst bleibt das Projekt unverändert.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { roofHoleCommand } from "./roofHole";
|
||||
import type { CommandContext, CommandState, Project, Vec2 } from "../types";
|
||||
|
||||
const roof = (id: string, shape: "walm" | "pult", x0: number) => ({
|
||||
id,
|
||||
type: "roof" as const,
|
||||
floorId: "eg",
|
||||
categoryCode: "31",
|
||||
outline: [
|
||||
{ x: x0, y: 0 },
|
||||
{ x: x0 + 12, y: 0 },
|
||||
{ x: x0 + 12, y: 8 },
|
||||
{ x: x0, y: 8 },
|
||||
],
|
||||
shape,
|
||||
pitchDeg: 35,
|
||||
overhang: 0,
|
||||
ridgeAxis: "x" as const,
|
||||
thickness: 0.2,
|
||||
});
|
||||
|
||||
function project(shape: "walm" | "pult" = "walm"): Project {
|
||||
return {
|
||||
id: "t",
|
||||
name: "T",
|
||||
lineStyles: [],
|
||||
hatches: [],
|
||||
components: [],
|
||||
wallTypes: [],
|
||||
drawingLevels: [{ id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }],
|
||||
layers: [{ code: "31", name: "Dächer", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }],
|
||||
walls: [],
|
||||
openings: [],
|
||||
ceilings: [],
|
||||
stairs: [],
|
||||
rooms: [],
|
||||
drawings2d: [],
|
||||
context: [],
|
||||
roofs: [roof("RF1", shape, 0)],
|
||||
};
|
||||
}
|
||||
|
||||
const ctxOf = (p: Project): CommandContext => ({
|
||||
project: p,
|
||||
level: p.drawingLevels[0],
|
||||
defaultCategoryCode: "31",
|
||||
activeLineStyleId: "solid",
|
||||
activeWallTypeId: "aw",
|
||||
lastPoint: null,
|
||||
selection: { wallIds: [], drawingId: null },
|
||||
});
|
||||
|
||||
/** Befehl mit Punkten füttern und mit Enter bestätigen; liefert das Ergebnis-Projekt. */
|
||||
function run(p: Project, pts: Vec2[], confirm = true): Project {
|
||||
const ctx = ctxOf(p);
|
||||
let state: CommandState = roofHoleCommand.init();
|
||||
let commit: ((q: Project) => Project) | undefined;
|
||||
for (const point of pts) {
|
||||
const [ns, res] = roofHoleCommand.onInput(state, { kind: "point", point }, ctx);
|
||||
state = ns;
|
||||
commit = res.commit ?? commit;
|
||||
}
|
||||
if (confirm && !commit) {
|
||||
const [, res] = roofHoleCommand.onConfirm(state, ctx);
|
||||
commit = res.commit;
|
||||
}
|
||||
return commit ? commit(p) : p;
|
||||
}
|
||||
|
||||
describe("roofHoleCommand", () => {
|
||||
it("zwei Punkte + Enter ergeben einen rechteckigen Hof", () => {
|
||||
const p = project();
|
||||
const q = run(p, [{ x: 4, y: 2 }, { x: 8, y: 6 }]);
|
||||
expect(q.roofs![0].holes).toEqual([
|
||||
[
|
||||
{ x: 4, y: 2 },
|
||||
{ x: 8, y: 2 },
|
||||
{ x: 8, y: 6 },
|
||||
{ x: 4, y: 6 },
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
it("drei und mehr Punkte: Klick auf den Startpunkt schliesst das Polygon", () => {
|
||||
const q = run(project(), [{ x: 3, y: 2 }, { x: 9, y: 2 }, { x: 6, y: 6 }, { x: 3, y: 2 }], false);
|
||||
expect(q.roofs![0].holes).toHaveLength(1);
|
||||
expect(q.roofs![0].holes![0]).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("Hof ausserhalb des Dachs oder bei Pultdach: Projekt unverändert", () => {
|
||||
const p = project();
|
||||
expect(run(p, [{ x: 20, y: 2 }, { x: 24, y: 6 }]).roofs![0].holes).toBeUndefined();
|
||||
const pult = project("pult");
|
||||
expect(run(pult, [{ x: 4, y: 2 }, { x: 8, y: 6 }]).roofs![0].holes).toBeUndefined();
|
||||
});
|
||||
|
||||
it("Hof über den Umriss hinaus wird verworfen", () => {
|
||||
expect(run(project(), [{ x: 10, y: 2 }, { x: 14, y: 6 }]).roofs![0].holes).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
// Dachhof — Innenhof/Lichthof im Dach als Engine-Befehl: eine Kontur wird per Klicks gezeichnet und
|
||||
// dem ERSTEN Dach des aktiven Geschosses hinzugefügt, in dem sie wirkt (ganz im Umriss, ohne
|
||||
// Überschneidung, nicht bei Pultdach — das entscheidet der Rust-Kern, s. `roofHoleWorks`).
|
||||
//
|
||||
// Warum Zeichnen statt „aus gewählter Kontur": die Auswahl kennt immer nur ein Objekt, mit dem
|
||||
// Dach gewählt wäre keine zweite Kontur wählbar; gezeichnet gibt es Fang auf Wände und Umriss,
|
||||
// und der Ablauf entspricht Deckenloch/Decke. Zwei Punkte + Enter ergeben ein Rechteck.
|
||||
//
|
||||
// Schritte:
|
||||
// 1) „Erster Punkt des Hofs:" → Punkt
|
||||
// 2) „Nächster Punkt ( Schliessen Zurück ):" → Punkt … Schliessen per Klick auf den Startpunkt,
|
||||
// Option „Schliessen" oder Enter (≥ 3 Punkte; bei genau 2 Punkten: Rechteck aus den Ecken).
|
||||
|
||||
import { addRoofHole, opsMutation, patchItem, pointInOutline, roofHoleWorks } from "../../core";
|
||||
import type { CoreOp } from "../../core";
|
||||
import type { Command, CommandContext, CommandResult, CommandState, CmdOption, DraftShape, Project, ToolDraft, Vec2 } from "../types";
|
||||
|
||||
const EPS = 1e-6;
|
||||
const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schliesst die Kontur
|
||||
|
||||
const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
|
||||
|
||||
/** Vier Ecken eines Rechtecks aus zwei Gegenecken. */
|
||||
function rectCorners(a: Vec2, b: Vec2): Vec2[] {
|
||||
const x0 = Math.min(a.x, b.x);
|
||||
const x1 = Math.max(a.x, b.x);
|
||||
const y0 = Math.min(a.y, b.y);
|
||||
const y1 = Math.max(a.y, b.y);
|
||||
return [
|
||||
{ x: x0, y: y0 },
|
||||
{ x: x1, y: y0 },
|
||||
{ x: x1, y: y1 },
|
||||
{ x: x0, y: y1 },
|
||||
];
|
||||
}
|
||||
|
||||
interface HoleIdle extends CommandState {
|
||||
phase: "start";
|
||||
}
|
||||
interface HoleDrawing extends CommandState {
|
||||
phase: "next";
|
||||
points: Vec2[];
|
||||
cursor: Vec2 | null;
|
||||
}
|
||||
type HoleState = HoleIdle | HoleDrawing;
|
||||
|
||||
const CLOSE: CmdOption = { id: "close", labelKey: "cmd.polyline.close" };
|
||||
const UNDO: CmdOption = { id: "undo", labelKey: "cmd.polyline.undo" };
|
||||
|
||||
/** Vorschau: Kontur (ab 3 Punkten geschlossen) + Gummiband. */
|
||||
function holeDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft {
|
||||
const pts = cursor ? [...points, cursor] : points;
|
||||
const preview: DraftShape[] = [{ kind: "poly", pts, closed: pts.length >= 3 }];
|
||||
const draft: ToolDraft = { preview, vertices: points };
|
||||
const last = points[points.length - 1];
|
||||
if (cursor && last && dist(last, cursor) >= EPS) draft.hud = { at: cursor, text: `${dist(last, cursor).toFixed(2)} m` };
|
||||
return draft;
|
||||
}
|
||||
|
||||
/** Aus den Klickpunkten die Hof-Kontur: ≥ 3 Punkte = Polygon, genau 2 = Rechteck. */
|
||||
function ringOf(points: Vec2[]): Vec2[] | null {
|
||||
if (points.length >= 3) return points;
|
||||
if (points.length === 2) {
|
||||
const [a, b] = points;
|
||||
if (Math.abs(a.x - b.x) < 0.05 || Math.abs(a.y - b.y) < 0.05) return null;
|
||||
return rectCorners(a, b);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hängt den Hof an das erste Dach des aktiven Geschosses, in dem er wirkt. Ohne passendes Dach
|
||||
* (Hof ausserhalb, schneidet den Umriss, Pultdach) bleibt das Projekt unverändert.
|
||||
*/
|
||||
function roofHoleOps(p: Project, points: Vec2[], ctx: CommandContext): CoreOp[] {
|
||||
const ring = ringOf(points);
|
||||
if (!ring) return [];
|
||||
const host = (p.roofs ?? []).find((r) => r.floorId === ctx.level.id && r.outline.length >= 3 && ring.every((pt) => pointInOutline(pt, r.outline)) && roofHoleWorks(r, ring));
|
||||
if (!host) return [];
|
||||
return patchItem(p, "roofs", host.id, (r) => ({ ...r, ...addRoofHole(r, ring) }));
|
||||
}
|
||||
|
||||
const idle = (): [CommandState, CommandResult] => [{ phase: "start", lastPoint: null } as HoleIdle, { draft: null, done: true }];
|
||||
|
||||
const finish = (points: Vec2[], ctx: CommandContext): [CommandState, CommandResult] => [
|
||||
{ phase: "start", lastPoint: null } as HoleIdle,
|
||||
{ draft: null, done: true, commit: opsMutation((p) => roofHoleOps(p, points, ctx)) },
|
||||
];
|
||||
|
||||
export const roofHoleCommand: Command = {
|
||||
name: "roofhole",
|
||||
labelKey: "cmd.roofHole.label",
|
||||
floorOnly: true,
|
||||
prompt: (s) => ((s as HoleState).phase === "next" ? "cmd.roofHole.next" : "cmd.roofHole.start"),
|
||||
accepts: (s) => ((s as HoleState).phase === "next" ? ["point", "option"] : ["point"]),
|
||||
options: (s) => {
|
||||
const ps = s as HoleState;
|
||||
if (ps.phase !== "next") return [];
|
||||
return ps.points.length >= 3 ? [CLOSE, UNDO] : [UNDO];
|
||||
},
|
||||
init: (): HoleIdle => ({ phase: "start", lastPoint: null }),
|
||||
|
||||
onInput: (state, input, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as HoleState;
|
||||
if (input.kind === "option") {
|
||||
if (s.phase !== "next") return [s, { draft: null }];
|
||||
if (input.id === "undo") {
|
||||
const pts = s.points.slice(0, -1);
|
||||
if (pts.length === 0) return [{ phase: "start", lastPoint: null } as HoleIdle, { draft: null }];
|
||||
const ns: HoleDrawing = { phase: "next", points: pts, cursor: s.cursor, lastPoint: pts[pts.length - 1] };
|
||||
return [ns, { draft: holeDraft(pts, s.cursor) }];
|
||||
}
|
||||
if (input.id === "close" && s.points.length >= 3) return finish(s.points, ctx);
|
||||
return [s, { draft: holeDraft(s.points, s.cursor) }];
|
||||
}
|
||||
if (input.kind !== "point") return [s, { draft: s.phase === "next" ? holeDraft(s.points, s.cursor) : null }];
|
||||
const pt = input.point;
|
||||
if (s.phase !== "next") {
|
||||
const ns: HoleDrawing = { phase: "next", points: [pt], cursor: pt, lastPoint: pt };
|
||||
return [ns, { draft: holeDraft([pt], pt) }];
|
||||
}
|
||||
// Klick nahe Startpunkt schliesst die Kontur.
|
||||
if (s.points.length >= 3 && dist(s.points[0], pt) < CLOSE_HIT) return finish(s.points, ctx);
|
||||
// Null-Strecke ignorieren.
|
||||
if (dist(s.points[s.points.length - 1], pt) < EPS) return [s, { draft: holeDraft(s.points, s.cursor) }];
|
||||
const points = [...s.points, pt];
|
||||
const ns: HoleDrawing = { phase: "next", points, cursor: pt, lastPoint: pt };
|
||||
return [ns, { draft: holeDraft(points, pt) }];
|
||||
},
|
||||
|
||||
onMove: (state, point): [CommandState, CommandResult] => {
|
||||
const s = state as HoleState;
|
||||
if (s.phase !== "next") return [s, { draft: null }];
|
||||
const ns: HoleDrawing = { ...s, cursor: point };
|
||||
return [ns, { draft: holeDraft(s.points, point) }];
|
||||
},
|
||||
|
||||
// Enter/Rechtsklick: ≥ 3 Punkte Polygon, 2 Punkte Rechteck.
|
||||
onConfirm: (state, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as HoleState;
|
||||
if (s.phase === "next" && s.points.length >= 2) return finish(s.points, ctx);
|
||||
return idle();
|
||||
},
|
||||
onCancel: (): [CommandState, CommandResult] => idle(),
|
||||
};
|
||||
@@ -18,6 +18,7 @@ import { solidCommand } from "./cmds/solid";
|
||||
import { solidBoolCommand } from "./cmds/solidbool";
|
||||
import { voidBoxCommand } from "./cmds/voidbox";
|
||||
import { ceilingOpeningCommand } from "./cmds/ceilingOpening";
|
||||
import { roofHoleCommand } from "./cmds/roofHole";
|
||||
import { roomCommand } from "./cmds/room";
|
||||
import { rectCommand } from "./cmds/rect";
|
||||
import { circleCommand } from "./cmds/circle";
|
||||
@@ -77,6 +78,7 @@ export const COMMANDS: Record<string, Command> = {
|
||||
solidbool: solidBoolCommand,
|
||||
voidbox: voidBoxCommand,
|
||||
ceilingopening: ceilingOpeningCommand,
|
||||
roofhole: roofHoleCommand,
|
||||
room: roomCommand,
|
||||
line: lineCommand,
|
||||
polyline: polylineCommand,
|
||||
@@ -159,6 +161,8 @@ export const ALIASES: Record<string, string> = {
|
||||
body: "solid",
|
||||
deckenloch: "ceilingopening",
|
||||
aussparung: "ceilingopening",
|
||||
dachhof: "roofhole",
|
||||
lichthof: "roofhole",
|
||||
rf: "roof",
|
||||
raum: "room",
|
||||
rm: "room",
|
||||
|
||||
@@ -127,6 +127,15 @@ export {
|
||||
roofGeometry,
|
||||
} from "../geometry/roof";
|
||||
|
||||
export {
|
||||
addRoofHole,
|
||||
removeRoofHole,
|
||||
roofEdgeList,
|
||||
roofHoleWorks,
|
||||
setRoofEdge,
|
||||
} from "../geometry/roofEdges";
|
||||
export type { EdgeSpec, RoofEdge } from "../geometry/roofEdges";
|
||||
|
||||
export {
|
||||
SIA_CATEGORIES,
|
||||
balance,
|
||||
|
||||
+29
-5
@@ -23,6 +23,8 @@ export interface RoofPlane {
|
||||
export interface RoofGeometry {
|
||||
/** Traufe-Umriss (Grundriss, inkl. Überstand) als geschlossener Ring. */
|
||||
eaves: Vec2[];
|
||||
/** Traufringe der Innenhöfe (`Roof.holes`, inkl. Überstand; der Hof schrumpft). */
|
||||
eavesHoles: Vec2[][];
|
||||
/** Firstlinie(n) im Grundriss (leer bei Flach/Zelt). */
|
||||
ridges: [Vec2, Vec2][];
|
||||
/** Gratlinien (Walm/Zelt: Ecke → First/Spitze). */
|
||||
@@ -74,7 +76,11 @@ const MANSARD_CODE = { giebel: 0, walm: 1, zelt: 2 } as const;
|
||||
|
||||
function encodeRoof(roof: Roof): Float64Array {
|
||||
const pts = roof.outline;
|
||||
const buf = new Float64Array(10 + 2 * pts.length);
|
||||
const holes = roof.holes ?? [];
|
||||
const edges = roof.edgePitchDeg;
|
||||
let size = 10 + 2 * pts.length + 1 + 1 + (edges ? edges.length : 0);
|
||||
for (const h of holes) size += 1 + 2 * h.length;
|
||||
const buf = new Float64Array(size);
|
||||
buf[0] = SHAPE_CODE[roof.shape] ?? 0;
|
||||
buf[1] = roof.pitchDeg;
|
||||
buf[2] = roof.pitchUpperDeg ?? NaN;
|
||||
@@ -85,10 +91,22 @@ function encodeRoof(roof: Roof): Float64Array {
|
||||
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;
|
||||
let i = 10;
|
||||
for (const p of pts) {
|
||||
buf[i++] = p.x;
|
||||
buf[i++] = p.y;
|
||||
}
|
||||
buf[i++] = holes.length;
|
||||
for (const h of holes) {
|
||||
buf[i++] = h.length;
|
||||
for (const p of h) {
|
||||
buf[i++] = p.x;
|
||||
buf[i++] = p.y;
|
||||
}
|
||||
}
|
||||
// Neigung je Kante: NaN = Feld fehlt, +∞ = Giebel (null), negativ = Standard.
|
||||
buf[i++] = edges ? edges.length : NaN;
|
||||
if (edges) for (const v of edges) buf[i++] = v === null ? Infinity : v;
|
||||
return buf;
|
||||
}
|
||||
|
||||
@@ -122,7 +140,13 @@ function decodeGeometry(b: Float64Array): RoofGeometry {
|
||||
const planes = polys().map((pts) => ({ pts }));
|
||||
const planesEnd = i;
|
||||
const gables = polys();
|
||||
const geo: RoofGeometry = { eaves, ridges, hips, breaks, planes, gables, ridgeHeight };
|
||||
const eavesHoles: Vec2[][] = [];
|
||||
for (let n = b[i++]; n > 0; n--) {
|
||||
const ring: Vec2[] = [];
|
||||
for (let m = b[i++]; m > 0; m--) ring.push(pt());
|
||||
eavesHoles.push(ring);
|
||||
}
|
||||
const geo: RoofGeometry = { eaves, eavesHoles, ridges, hips, breaks, planes, gables, ridgeHeight };
|
||||
planesFlat.set(geo, b.subarray(planesStart, planesEnd));
|
||||
return geo;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
// Kanten und Höfe eines Dachs ([26]): Liste, Änderung der Kantenneigung, Hof hinzufügen/entfernen.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Roof, Vec2 } from "../model/types";
|
||||
import { addRoofHole, removeRoofHole, roofEdgeList, roofHoleWorks, setRoofEdge } from "./roofEdges";
|
||||
|
||||
const rect = (x: number, y: number, w: number, h: number): Vec2[] => [
|
||||
{ x, y },
|
||||
{ x: x + w, y },
|
||||
{ x: x + w, y: y + h },
|
||||
{ x, y: y + h },
|
||||
];
|
||||
|
||||
const roof = (extra: Partial<Roof> = {}): Roof => ({
|
||||
id: "R",
|
||||
type: "roof",
|
||||
floorId: "eg",
|
||||
categoryCode: "31",
|
||||
outline: rect(0, 0, 12, 8),
|
||||
shape: "walm",
|
||||
pitchDeg: 35,
|
||||
overhang: 0,
|
||||
ridgeAxis: "x",
|
||||
thickness: 0.2,
|
||||
...extra,
|
||||
});
|
||||
|
||||
const court = rect(4, 2, 4, 4);
|
||||
|
||||
describe("roofEdgeList", () => {
|
||||
it("Umrisskanten, dann Hofkanten; Standard ohne Feld", () => {
|
||||
const list = roofEdgeList(roof({ holes: [court] }));
|
||||
expect(list).toHaveLength(8);
|
||||
expect(list.map((e) => e.ring)).toEqual([0, 0, 0, 0, 1, 1, 1, 1]);
|
||||
expect(list[0]).toMatchObject({ index: 0, spec: { kind: "default" }, length: 12 });
|
||||
expect(list[5].index).toBe(5);
|
||||
});
|
||||
|
||||
it("liest Giebel, Neigung und negativ = Standard; Sattel: Giebelregel zeigt sich als Vorgabe", () => {
|
||||
const list = roofEdgeList(roof({ edgePitchDeg: [20, null, -1] }));
|
||||
expect(list[0].spec).toEqual({ kind: "pitch", deg: 20 });
|
||||
expect(list[1].spec).toEqual({ kind: "gable" });
|
||||
expect(list[2].spec).toEqual({ kind: "default" });
|
||||
expect(list[3].spec).toEqual({ kind: "default" });
|
||||
const sattel = roofEdgeList(roof({ shape: "sattel" }));
|
||||
expect(sattel.map((e) => e.defaultGable)).toEqual([false, true, false, true]);
|
||||
expect(roofEdgeList(roof()).every((e) => !e.defaultGable)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("setRoofEdge", () => {
|
||||
it("setzt Neigung/Giebel, füllt mit Standard auf, entfernt das Feld wenn alles Standard", () => {
|
||||
const a = setRoofEdge(roof(), 2, { kind: "pitch", deg: 25 });
|
||||
expect(a.edgePitchDeg).toEqual([-1, -1, 25]);
|
||||
const b = setRoofEdge(roof({ ...a }), 0, { kind: "gable" });
|
||||
expect(b.edgePitchDeg).toEqual([null, -1, 25]);
|
||||
const c = setRoofEdge(roof({ ...b }), 0, { kind: "default" });
|
||||
const d = setRoofEdge(roof({ ...c }), 2, { kind: "default" });
|
||||
expect(d.edgePitchDeg).toBeUndefined();
|
||||
});
|
||||
|
||||
it("begrenzt die Neigung auf 0..89 Grad", () => {
|
||||
expect(setRoofEdge(roof(), 0, { kind: "pitch", deg: 120 }).edgePitchDeg).toEqual([89]);
|
||||
expect(setRoofEdge(roof(), 0, { kind: "pitch", deg: -5 }).edgePitchDeg).toEqual([0]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Höfe", () => {
|
||||
it("Hof hinzufügen: Ring bleibt, ungültige (ausserhalb, Pult) wirken nicht", () => {
|
||||
const r = roof();
|
||||
expect(roofHoleWorks(r, court)).toBe(true);
|
||||
expect(roofHoleWorks(r, rect(10, 2, 4, 4))).toBe(false);
|
||||
expect(roofHoleWorks(roof({ shape: "pult" }), court)).toBe(false);
|
||||
const p = addRoofHole(r, court);
|
||||
expect(p.holes).toEqual([court]);
|
||||
});
|
||||
|
||||
it("Hof entfernen nimmt seine Kantenneigungen mit; Indizes der übrigen Höfe rücken nach", () => {
|
||||
const h2 = rect(1, 1, 1, 1);
|
||||
const r = roof({ holes: [court, h2], edgePitchDeg: [-1, -1, -1, -1, 10, -1, -1, -1, 50, -1, -1, -1] });
|
||||
const p = removeRoofHole(r, 0);
|
||||
expect(p.holes).toEqual([h2]);
|
||||
expect(p.edgePitchDeg).toEqual([-1, -1, -1, -1, 50]);
|
||||
const q = removeRoofHole(roof({ ...p }), 0);
|
||||
expect(q.holes).toBeUndefined();
|
||||
expect(q.edgePitchDeg).toBeUndefined();
|
||||
});
|
||||
|
||||
it("Hof entfernen ohne Kantenfeld lässt es weg", () => {
|
||||
const p = removeRoofHole(roof({ holes: [court] }), 0);
|
||||
expect(p).toEqual({ holes: undefined, edgePitchDeg: undefined });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
// Kanten und Höfe eines Dachs ([26]): die Kantenliste fürs Objekt-Info (Neigung je Kante, Giebel),
|
||||
// Änderungen als Teilobjekt (`Partial<Roof>`, für `updateRoof`/`patchItem` — ein Undo-Schritt) und
|
||||
// die Prüfung, ob ein Hof wirkt. Die Geometrie selbst rechnet der Rust-Kern (`roof.rs`).
|
||||
//
|
||||
// Kantennummerierung wie `Roof.edgePitchDeg`: erst die Kanten von `outline` (Kante i = Punkt i →
|
||||
// i+1), dann die der `holes` Ring für Ring. Eintrag `null` = Giebel, Zahl ≥ 0 = Neigung, negativ
|
||||
// (oder fehlend) = Standard.
|
||||
|
||||
import type { Roof, Vec2 } from "../model/types";
|
||||
import { roofGeometry } from "./roof";
|
||||
|
||||
/** Vorgabe einer Kante. */
|
||||
export type EdgeSpec = { kind: "default" } | { kind: "gable" } | { kind: "pitch"; deg: number };
|
||||
|
||||
/** Eine Kante der Kantenliste (Umriss oder Hof). */
|
||||
export interface RoofEdge {
|
||||
/** Index in `edgePitchDeg`. */
|
||||
index: number;
|
||||
/** 0 = Umriss, 1.. = Hof (1-basiert). */
|
||||
ring: number;
|
||||
/** Index der Kante im eigenen Ring. */
|
||||
edge: number;
|
||||
a: Vec2;
|
||||
b: Vec2;
|
||||
/** Länge der Kante (Meter). */
|
||||
length: number;
|
||||
spec: EdgeSpec;
|
||||
/** Standard ist hier ein Giebel (Satteldach/Mansard-Satteldach, Kante quer zum First). */
|
||||
defaultGable: boolean;
|
||||
}
|
||||
|
||||
const MAX_PITCH = 89;
|
||||
|
||||
/** Die Vorgabe aus einem Eintrag von `edgePitchDeg`. */
|
||||
function specOf(v: number | null | undefined): EdgeSpec {
|
||||
if (v === null) return { kind: "gable" };
|
||||
if (v === undefined || !Number.isFinite(v) || v < 0) return { kind: "default" };
|
||||
return { kind: "pitch", deg: v };
|
||||
}
|
||||
|
||||
/** Giebelt der Standard dieser Dachform die Kante a→b (quer zur Firstrichtung)? */
|
||||
function defaultGableEdge(roof: Roof, a: Vec2, b: Vec2): boolean {
|
||||
const gabled = roof.shape === "sattel" || (roof.shape === "mansarde" && (roof.mansardType ?? "giebel") === "giebel");
|
||||
if (!gabled) return false;
|
||||
const dx = Math.abs(b.x - a.x);
|
||||
const dy = Math.abs(b.y - a.y);
|
||||
return roof.ridgeAxis === "y" ? dy < dx : dx < dy;
|
||||
}
|
||||
|
||||
/** Alle Kanten des Dachs (Umriss, dann Höfe) mit ihrer Vorgabe. */
|
||||
export function roofEdgeList(roof: Roof): RoofEdge[] {
|
||||
const rings: Vec2[][] = [roof.outline, ...(roof.holes ?? [])];
|
||||
const out: RoofEdge[] = [];
|
||||
let index = 0;
|
||||
rings.forEach((ring, r) => {
|
||||
ring.forEach((a, edge) => {
|
||||
const b = ring[(edge + 1) % ring.length];
|
||||
out.push({
|
||||
index,
|
||||
ring: r,
|
||||
edge,
|
||||
a,
|
||||
b,
|
||||
length: Math.hypot(b.x - a.x, b.y - a.y),
|
||||
spec: specOf(roof.edgePitchDeg?.[index]),
|
||||
defaultGable: defaultGableEdge(roof, a, b),
|
||||
});
|
||||
index++;
|
||||
});
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** `edgePitchDeg` ohne Standard-Einträge am Ende; alles Standard ⇒ `undefined` (Feld entfällt). */
|
||||
function normalized(values: (number | null)[]): (number | null)[] | undefined {
|
||||
const v = values.slice();
|
||||
while (v.length > 0 && v[v.length - 1] !== null && (v[v.length - 1] as number) < 0) v.pop();
|
||||
return v.length === 0 ? undefined : v;
|
||||
}
|
||||
|
||||
/** Teilobjekt für `updateRoof`: Kante `index` auf `spec` setzen. */
|
||||
export function setRoofEdge(roof: Roof, index: number, spec: EdgeSpec): Pick<Roof, "edgePitchDeg"> {
|
||||
const total = roofEdgeList(roof).length;
|
||||
const values: (number | null)[] = Array.from({ length: total }, (_, i) => {
|
||||
const v = roof.edgePitchDeg?.[i];
|
||||
return v === undefined ? -1 : v;
|
||||
});
|
||||
if (index < 0 || index >= total) return { edgePitchDeg: roof.edgePitchDeg };
|
||||
values[index] = spec.kind === "gable" ? null : spec.kind === "pitch" ? Math.max(0, Math.min(MAX_PITCH, spec.deg)) : -1;
|
||||
return { edgePitchDeg: normalized(values) };
|
||||
}
|
||||
|
||||
/** Wirkt ein Hof `ring` an diesem Dach? Der Kern verwirft Höfe, die nicht ganz im Umriss liegen, sich
|
||||
* schneiden oder bei einer Dachform ohne Höfe (Pult) — dann liefert er keinen Hof-Traufring. */
|
||||
export function roofHoleWorks(roof: Roof, ring: Vec2[]): boolean {
|
||||
if (ring.length < 3) return false;
|
||||
const probe: Roof = { ...roof, holes: [...(roof.holes ?? []), ring] };
|
||||
return roofGeometry(probe, 0).eavesHoles.length === (probe.holes?.length ?? 0);
|
||||
}
|
||||
|
||||
/** Teilobjekt für `updateRoof`: Hof anhängen (seine Kanten folgen mit Standard-Neigung). */
|
||||
export function addRoofHole(roof: Roof, ring: Vec2[]): Pick<Roof, "holes"> {
|
||||
return { holes: [...(roof.holes ?? []), ring.map((p) => ({ x: p.x, y: p.y }))] };
|
||||
}
|
||||
|
||||
/** Teilobjekt für `updateRoof`: Hof `k` entfernen samt seinen Kantenneigungen. */
|
||||
export function removeRoofHole(roof: Roof, k: number): Pick<Roof, "holes" | "edgePitchDeg"> {
|
||||
const holes = roof.holes ?? [];
|
||||
if (k < 0 || k >= holes.length) return { holes: roof.holes, edgePitchDeg: roof.edgePitchDeg };
|
||||
let from = roof.outline.length;
|
||||
for (let i = 0; i < k; i++) from += holes[i].length;
|
||||
const to = from + holes[k].length;
|
||||
const rest = holes.filter((_, i) => i !== k);
|
||||
const edges = roof.edgePitchDeg ? [...roof.edgePitchDeg.slice(0, from), ...roof.edgePitchDeg.slice(to)] : undefined;
|
||||
return { holes: rest.length > 0 ? rest : undefined, edgePitchDeg: edges ? normalized(edges) : undefined };
|
||||
}
|
||||
@@ -477,6 +477,19 @@ export const de = {
|
||||
"objinfo.roof.baseElevation": "Traufhöhe (m)",
|
||||
"objinfo.roof.ridgeHeight": "Firsthöhe",
|
||||
"objinfo.roof.area": "Grundfläche",
|
||||
"objinfo.roof.edges": "Kanten (Neigung je Kante)",
|
||||
"objinfo.roof.edge": "Kante {n}",
|
||||
"objinfo.roof.edgeCourt": "Hof {c} · Kante {n}",
|
||||
"objinfo.roof.edgePitch": "Neigung der Kante (Grad); leer = Standard",
|
||||
"objinfo.roof.edgeGable": "Giebel",
|
||||
"objinfo.roof.edgeGableHint": "Senkrechte Giebelwand statt geneigter Fläche",
|
||||
"objinfo.roof.edgeReset": "Auf Standard zurücksetzen",
|
||||
"objinfo.roof.edgesReset": "Alle Kanten auf Standard",
|
||||
"objinfo.roof.courts": "Innenhöfe",
|
||||
"objinfo.roof.courtRow": "Hof {n}: {area} m²",
|
||||
"objinfo.roof.courtRemove": "Hof entfernen",
|
||||
"objinfo.roof.courtAdd": "Hof hinzufügen: Befehl „Dachhof“ (Kontur zeichnen)",
|
||||
"objinfo.roof.courtAddBtn": "Hof zeichnen …",
|
||||
// ── Stützen-Attribute (Object-Info-Panel) ───────────────────────────────
|
||||
"objinfo.column.section": "Stütze",
|
||||
"objinfo.column.profile": "Profil",
|
||||
@@ -1309,6 +1322,9 @@ export const de = {
|
||||
"cmd.ceilingOpening.label": "Deckenloch",
|
||||
"cmd.ceilingOpening.start": "Erste Ecke der Aussparung (in einer Decke):",
|
||||
"cmd.ceilingOpening.corner": "Gegenecke:",
|
||||
"cmd.roofHole.label": "Dachhof",
|
||||
"cmd.roofHole.start": "Erster Punkt des Innenhofs (im Dach):",
|
||||
"cmd.roofHole.next": "Nächster Punkt (Enter bei 2 Punkten = Rechteck, ab 3 Punkten Polygon):",
|
||||
"cmd.roof.shape.sattel": "Satteldach",
|
||||
"cmd.roof.shape.walm": "Walmdach",
|
||||
"cmd.roof.shape.pult": "Pultdach",
|
||||
|
||||
@@ -475,6 +475,19 @@ export const en: Record<TranslationKey, string> = {
|
||||
"objinfo.roof.baseElevation": "Eaves height (m)",
|
||||
"objinfo.roof.ridgeHeight": "Ridge height",
|
||||
"objinfo.roof.area": "Footprint area",
|
||||
"objinfo.roof.edges": "Edges (pitch per edge)",
|
||||
"objinfo.roof.edge": "Edge {n}",
|
||||
"objinfo.roof.edgeCourt": "Court {c} · edge {n}",
|
||||
"objinfo.roof.edgePitch": "Edge pitch (degrees); empty = default",
|
||||
"objinfo.roof.edgeGable": "Gable",
|
||||
"objinfo.roof.edgeGableHint": "Vertical gable wall instead of a sloped surface",
|
||||
"objinfo.roof.edgeReset": "Reset to default",
|
||||
"objinfo.roof.edgesReset": "All edges to default",
|
||||
"objinfo.roof.courts": "Courtyards",
|
||||
"objinfo.roof.courtRow": "Court {n}: {area} m²",
|
||||
"objinfo.roof.courtRemove": "Remove courtyard",
|
||||
"objinfo.roof.courtAdd": "Add a courtyard: command \"Roof court\" (draw the contour)",
|
||||
"objinfo.roof.courtAddBtn": "Draw courtyard …",
|
||||
// ── Column attributes (object info panel) ────────────────────────────────
|
||||
"objinfo.column.section": "Column",
|
||||
"objinfo.column.profile": "Profile",
|
||||
@@ -1298,6 +1311,9 @@ export const en: Record<TranslationKey, string> = {
|
||||
"cmd.ceilingOpening.label": "Slab opening",
|
||||
"cmd.ceilingOpening.start": "First corner of the opening (inside a slab):",
|
||||
"cmd.ceilingOpening.corner": "Opposite corner:",
|
||||
"cmd.roofHole.label": "Roof court",
|
||||
"cmd.roofHole.start": "First point of the courtyard (inside the roof):",
|
||||
"cmd.roofHole.next": "Next point (Enter with 2 points = rectangle, 3 or more = polygon):",
|
||||
"cmd.roof.shape.sattel": "Gable roof",
|
||||
"cmd.roof.shape.walm": "Hip roof",
|
||||
"cmd.roof.shape.pult": "Mono-pitch roof",
|
||||
|
||||
@@ -2070,6 +2070,24 @@ export type Roof = {
|
||||
locked?: boolean;
|
||||
/** Geschlossener Grundriss-Umriss (Meter); Geometrie nutzt die Bounding-Box. */
|
||||
outline: Array<Vec2>;
|
||||
/**
|
||||
* Innenhöfe/Lichthöfe als Ringe (Meter, jeder Ring geschlossen, Drehsinn egal). Das Dach
|
||||
* ist an dieser Stelle ausgespart (3D, Grundriss, Schnitt, Ansicht, IFC); die Hofkanten sind
|
||||
* innere Traufen. Wirkt bei Flach/Sattel/Walm/Mansarde/Zelt (Pult ignoriert sie); ein Ring,
|
||||
* der nicht ganz im Umriss liegt oder sich mit Umriss/anderen Höfen schneidet, macht die
|
||||
* Höfe wirkungslos (Dach wie ohne). Fehlt ⇒ keine Höfe.
|
||||
*/
|
||||
holes?: Array<Array<Vec2>>;
|
||||
/**
|
||||
* Neigung je Umrisskante in Grad. Nummerierung: erst die Kanten von `outline` (Kante i =
|
||||
* Punkt i → i+1, in der gespeicherten Reihenfolge), danach die Kanten der `holes` Ring für
|
||||
* Ring. Eintrag `null` = Giebel (senkrechte Wand, Kante läuft nicht nach innen), eine Zahl
|
||||
* ≥ 0 = Neigung dieser Kante (übersteuert `pitchDeg`), eine NEGATIVE Zahl (oder ein fehlender
|
||||
* Eintrag) = Standard: `pitchDeg`, bei Satteldach/Mansard-Satteldach mit Giebel an den
|
||||
* Kanten quer zur Firstrichtung. Fehlt das Feld ganz ⇒ alles Standard (wie bisher).
|
||||
* Wirkt bei Sattel/Walm/Mansarde/Zelt (Flach/Pult ignorieren es).
|
||||
*/
|
||||
edgePitchDeg?: Array<number | null>;
|
||||
/** Dachform. */
|
||||
shape: RoofShape;
|
||||
/** Hauptneigung in Grad (0 = flach). */
|
||||
|
||||
+130
-12
@@ -36,6 +36,7 @@ import type {
|
||||
WallReferenceLine,
|
||||
} from "../model/types";
|
||||
import { SIA_CATEGORIES, siaLabelFull } from "../core";
|
||||
import type { EdgeSpec, RoofEdge } from "../core";
|
||||
import { Dropdown } from "../ui/Dropdown";
|
||||
import type { DetailLevel } from "../model/viewTypes";
|
||||
import { ColorHexField } from "../ui/ColorHexField";
|
||||
@@ -1042,18 +1043,24 @@ export function RoofSection({
|
||||
|
||||
{/* Grundriss-Masse (Breite/Tiefe): das Umriss-Rechteck neu bilden, die
|
||||
untere/linke Ecke (minX/minY) bleibt fix. */}
|
||||
{numField("objinfo.roof.width", roof.width, 0.1, (v) => {
|
||||
const w = Math.max(0.2, v);
|
||||
host.onSetRoofPatch({
|
||||
outline: rectOutline(roof.minX, roof.minY, w, roof.depth),
|
||||
});
|
||||
})}
|
||||
{numField("objinfo.roof.depth", roof.depth, 0.1, (v) => {
|
||||
const d = Math.max(0.2, v);
|
||||
host.onSetRoofPatch({
|
||||
outline: rectOutline(roof.minX, roof.minY, roof.width, d),
|
||||
});
|
||||
})}
|
||||
{/* Mit Innenhöfen oder Kanten ausserhalb eines Vierecks würde das Rechteck die Höfe/Kantenneigungen
|
||||
zerstören — dort entfallen Breite/Tiefe. */}
|
||||
{roof.holes.length === 0 &&
|
||||
roof.edges.length === 4 &&
|
||||
numField("objinfo.roof.width", roof.width, 0.1, (v) => {
|
||||
const w = Math.max(0.2, v);
|
||||
host.onSetRoofPatch({
|
||||
outline: rectOutline(roof.minX, roof.minY, w, roof.depth),
|
||||
});
|
||||
})}
|
||||
{roof.holes.length === 0 &&
|
||||
roof.edges.length === 4 &&
|
||||
numField("objinfo.roof.depth", roof.depth, 0.1, (v) => {
|
||||
const d = Math.max(0.2, v);
|
||||
host.onSetRoofPatch({
|
||||
outline: rectOutline(roof.minX, roof.minY, roof.width, d),
|
||||
});
|
||||
})}
|
||||
|
||||
{/* Überstand: Traufe (senkrecht zum First) + Ortgang (Giebelseite). */}
|
||||
{numField("objinfo.roof.overhang", roof.overhang, 0.05, (v) =>
|
||||
@@ -1075,6 +1082,46 @@ export function RoofSection({
|
||||
host.onSetRoofPatch({ baseElevation: v }),
|
||||
)}
|
||||
|
||||
{/* Kanten: Neigung je Kante (leer = Standard) und Giebel ([26]). Wirkt bei Sattel/Walm/
|
||||
Mansarde/Zelt; Flach und Pult ignorieren sie. */}
|
||||
{roof.shape !== "flach" && roof.shape !== "pult" && (
|
||||
<RoofEdgesSection roof={roof} host={host} />
|
||||
)}
|
||||
{/* Innenhöfe: Liste mit Entfernen, Hinzufügen über den Befehl „Dachhof“. */}
|
||||
{roof.shape !== "pult" && (
|
||||
<>
|
||||
<div className="objinfo-sep" />
|
||||
<div className="objinfo-section-label">{t("objinfo.roof.courts")}</div>
|
||||
{roof.holes.map((h, i) => (
|
||||
<div className="objinfo-field" key={i}>
|
||||
<span className="objinfo-flabel objinfo-muted">
|
||||
{t("objinfo.roof.courtRow", { n: i + 1, area: h.area.toFixed(2) })}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="objinfo-typebtn"
|
||||
title={t("objinfo.roof.courtRemove")}
|
||||
aria-label={t("objinfo.roof.courtRemove")}
|
||||
onClick={() => host.onRemoveRoofHole(i)}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<div className="objinfo-field">
|
||||
<button
|
||||
type="button"
|
||||
className="objinfo-typebtn"
|
||||
title={t("objinfo.roof.courtAdd")}
|
||||
onClick={() => host.onRunCommand("roofhole")}
|
||||
>
|
||||
{t("objinfo.roof.courtAddBtn")}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className="objinfo-sep" />
|
||||
|
||||
{/* Abgeleitete Werte (read-only). */}
|
||||
<div className="objinfo-field">
|
||||
<span className="objinfo-flabel">{t("objinfo.roof.ridgeHeight")}</span>
|
||||
@@ -1088,6 +1135,77 @@ export function RoofSection({
|
||||
);
|
||||
}
|
||||
|
||||
/** Kantenliste eines Dachs: Neigung je Kante (leer = Standard) + Giebel-Schalter. */
|
||||
function RoofEdgesSection({
|
||||
roof,
|
||||
host,
|
||||
}: {
|
||||
roof: RoofInfo;
|
||||
host: ReturnType<typeof usePanelHost>;
|
||||
}) {
|
||||
// Tippen einer Zahl = ein Undo-Schritt je Kante (gleicher coalesceKey, s. Host).
|
||||
const setEdge = (e: RoofEdge, spec: EdgeSpec) => host.onSetRoofEdge(e.index, spec);
|
||||
return (
|
||||
<>
|
||||
<div className="objinfo-sep" />
|
||||
<div className="objinfo-section-label">{t("objinfo.roof.edges")}</div>
|
||||
{roof.edges.map((e) => {
|
||||
const label =
|
||||
e.ring === 0
|
||||
? t("objinfo.roof.edge", { n: e.edge + 1 })
|
||||
: t("objinfo.roof.edgeCourt", { c: e.ring, n: e.edge + 1 });
|
||||
const gable = e.spec.kind === "gable";
|
||||
const placeholder = e.defaultGable ? t("objinfo.roof.edgeGable") : String(roof.pitchDeg);
|
||||
return (
|
||||
<div className="objinfo-field objinfo-roof-edge" key={e.index} data-edge={e.index}>
|
||||
<span className="objinfo-flabel" title={`${e.length.toFixed(2)} m`}>
|
||||
{label}
|
||||
</span>
|
||||
<input
|
||||
type="number"
|
||||
className="objinfo-text"
|
||||
min={0}
|
||||
max={89}
|
||||
step={1}
|
||||
disabled={gable}
|
||||
placeholder={placeholder}
|
||||
value={e.spec.kind === "pitch" ? Number(e.spec.deg.toFixed(2)) : ""}
|
||||
aria-label={`${label}: ${t("objinfo.roof.edgePitch")}`}
|
||||
title={t("objinfo.roof.edgePitch")}
|
||||
onChange={(ev) => {
|
||||
const raw = ev.target.value;
|
||||
if (raw === "") return setEdge(e, { kind: "default" });
|
||||
const v = Number(raw);
|
||||
if (Number.isFinite(v)) setEdge(e, { kind: "pitch", deg: v });
|
||||
}}
|
||||
/>
|
||||
<label className="objinfo-muted" title={t("objinfo.roof.edgeGableHint")}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={gable}
|
||||
aria-label={`${label}: ${t("objinfo.roof.edgeGable")}`}
|
||||
onChange={(ev) => setEdge(e, ev.target.checked ? { kind: "gable" } : { kind: "default" })}
|
||||
/>
|
||||
{t("objinfo.roof.edgeGable")}
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{roof.hasEdgePitch && (
|
||||
<div className="objinfo-field">
|
||||
<button
|
||||
type="button"
|
||||
className="objinfo-typebtn"
|
||||
onClick={() => host.onSetRoofPatch({ edgePitchDeg: undefined })}
|
||||
>
|
||||
{t("objinfo.roof.edgesReset")}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function StairSection({
|
||||
stair,
|
||||
host,
|
||||
|
||||
@@ -355,7 +355,7 @@ const TOOLS_2D: ToolId[] = [
|
||||
"image",
|
||||
];
|
||||
const TOOLS_3D: ToolId[] = ["wall", "ceiling", "window", "door", "stair", "room"];
|
||||
const COMMANDS_3D = ["column", "ceilingopening", "roof", "extrude", "solid", "solidbool", "sectionline", "viewline", "autodim"];
|
||||
const COMMANDS_3D = ["column", "ceilingopening", "roof", "roofhole", "extrude", "solid", "solidbool", "sectionline", "viewline", "autodim"];
|
||||
const COMMANDS_EDIT = ["move", "copy", "array", "rotate", "mirror", "offset", "multiline", "trim", "break", "extend", "fillet", "chamfer", "join", "defblock", "measure"];
|
||||
|
||||
type ToolsView = "list" | "icons";
|
||||
|
||||
+5
-1
@@ -471,7 +471,11 @@ export interface PanelHostValue {
|
||||
* Immutable Änderung von Dach-Attributen (Form/Neigung/Überstand/Firstrichtung/
|
||||
* Dicke) — wirkt NUR auf das selektierte Dach.
|
||||
*/
|
||||
onSetRoofPatch: (patch: Partial<import("../model/types").Roof>) => void;
|
||||
onSetRoofPatch: (patch: Partial<import("../model/types").Roof>, coalesceKey?: string) => void;
|
||||
/** Neigung/Giebel der Dachkante `index` setzen ([26]); Tippen einer Zahl = ein Undo-Schritt je Kante. */
|
||||
onSetRoofEdge: (index: number, spec: import("../core").EdgeSpec) => void;
|
||||
/** Innenhof `k` (Index in `Roof.holes`) des gewählten Dachs entfernen, samt seinen Kantenneigungen. */
|
||||
onRemoveRoofHole: (k: number) => void;
|
||||
|
||||
// ── Schnitt-/Ansichtslinie (Object-Info-Panel; nur die selektierte Linie) ──
|
||||
/**
|
||||
|
||||
@@ -170,4 +170,21 @@ describe("generatePlan — Dächer (Dachaufsicht)", () => {
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("Innenhof ([26]): Traufring des Hofs, Dachfläche mit Loch (Brückenkanten), Firstlinien des Hofs", () => {
|
||||
const court = [
|
||||
{ x: 1.5, y: 1 },
|
||||
{ x: 1.5, y: 3 },
|
||||
{ x: 3, y: 3 },
|
||||
{ x: 3, y: 1 },
|
||||
];
|
||||
const plain = generatePlan(baseProject([roof("R9", "walm", { overhang: 0 })]), "eg", visible);
|
||||
const withCourt = generatePlan(baseProject([roof("R9", "walm", { overhang: 0, holes: [court] })]), "eg", visible);
|
||||
// Umriss 4 Kanten + Hof 4 Kanten.
|
||||
expect(linesOf(plain.primitives, "roof-eaves").length).toBe(4);
|
||||
expect(linesOf(withCourt.primitives, "roof-eaves").length).toBe(8);
|
||||
const poly = withCourt.primitives.find((p) => p.kind === "polygon" && p.roofId === "R9");
|
||||
expect(poly && poly.kind === "polygon" && poly.pts.length).toBeGreaterThan(4);
|
||||
expect(poly && poly.kind === "polygon" && (poly.noStrokeEdges ?? []).length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
// Dach: Kantenneigung und Innenhöfe ([26]) über Store/Ops — ein Undo-Schritt je Aktion — und die
|
||||
// Rundreise durch das Projektformat (Rust-Modell ↔ TS: `holes`, `edgePitchDeg` mit `null` = Giebel).
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { getState, setState } from "./appStore";
|
||||
import type { Project, Roof } from "../model/types";
|
||||
import { addRoofHole, removeRoofHole, roofGeometry, setRoofEdge } from "../core";
|
||||
import { parseProjectFile, serializeProject } from "../io/projectFormat";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
|
||||
const roof: Roof = {
|
||||
id: "RF1",
|
||||
type: "roof",
|
||||
floorId: "eg",
|
||||
categoryCode: "31",
|
||||
outline: [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 12, y: 0 },
|
||||
{ x: 12, y: 8 },
|
||||
{ x: 0, y: 8 },
|
||||
],
|
||||
shape: "walm",
|
||||
pitchDeg: 35,
|
||||
overhang: 0,
|
||||
ridgeAxis: "x",
|
||||
thickness: 0.2,
|
||||
};
|
||||
const court = [
|
||||
{ x: 4, y: 2 },
|
||||
{ x: 4, y: 6 },
|
||||
{ x: 8, y: 6 },
|
||||
{ x: 8, y: 2 },
|
||||
];
|
||||
|
||||
const baseProject = {
|
||||
id: "p",
|
||||
name: "T",
|
||||
layers: [],
|
||||
drawingLevels: [{ id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, baseElevation: 0 }],
|
||||
walls: [],
|
||||
drawings2d: [],
|
||||
roofs: [roof],
|
||||
} as unknown as Project;
|
||||
|
||||
const current = (): Roof => getState().project.roofs![0];
|
||||
|
||||
beforeEach(() => {
|
||||
setState({ project: JSON.parse(JSON.stringify(baseProject)), undoDepth: 0, redoDepth: 0, canUndo: false, canRedo: false });
|
||||
getState().clearHistory();
|
||||
});
|
||||
|
||||
describe("Kantenneigung über Ops", () => {
|
||||
it("Kante ändern ist ein Undo-Schritt; Zurück stellt das Feld wieder her", () => {
|
||||
getState().updateRoof("RF1", setRoofEdge(current(), 0, { kind: "pitch", deg: 20 }));
|
||||
expect(current().edgePitchDeg).toEqual([20]);
|
||||
expect(getState().undoDepth).toBe(1);
|
||||
getState().undo();
|
||||
expect(current().edgePitchDeg).toBeUndefined();
|
||||
});
|
||||
|
||||
it("Tippen einer Zahl (gleicher Schlüssel) koalesziert zu einem Schritt", () => {
|
||||
const key = "roof-edge-RF1-1";
|
||||
getState().updateRoof("RF1", { overhang: 0.1 }); // Koaleszenz-Grenze
|
||||
getState().clearHistory();
|
||||
getState().updateRoof("RF1", setRoofEdge(current(), 1, { kind: "pitch", deg: 3 }), key);
|
||||
getState().updateRoof("RF1", setRoofEdge(current(), 1, { kind: "pitch", deg: 30 }), key);
|
||||
expect(current().edgePitchDeg).toEqual([-1, 30]);
|
||||
expect(getState().undoDepth).toBe(1);
|
||||
getState().undo();
|
||||
expect(current().edgePitchDeg).toBeUndefined();
|
||||
});
|
||||
|
||||
it("Giebel (null) bleibt im Projekt und ändert die Geometrie", () => {
|
||||
const before = roofGeometry(current(), 0);
|
||||
getState().updateRoof("RF1", { edgePitchDeg: [-1, null, -1, null] });
|
||||
expect(current().edgePitchDeg).toEqual([-1, null, -1, null]);
|
||||
const after = roofGeometry(current(), 0);
|
||||
expect(after.gables.length).toBe(2);
|
||||
expect(before.gables.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Innenhöfe über Ops", () => {
|
||||
it("Hof hinzufügen und entfernen: je ein Undo-Schritt, Dach spart den Hof aus", () => {
|
||||
getState().updateRoof("RF1", addRoofHole(current(), court));
|
||||
expect(current().holes).toEqual([court]);
|
||||
expect(roofGeometry(current(), 0).eavesHoles).toHaveLength(1);
|
||||
expect(getState().undoDepth).toBe(1);
|
||||
getState().updateRoof("RF1", removeRoofHole(current(), 0));
|
||||
expect(current().holes).toBeUndefined();
|
||||
expect(getState().undoDepth).toBe(2);
|
||||
getState().undo();
|
||||
expect(current().holes).toEqual([court]);
|
||||
getState().undo();
|
||||
expect(current().holes).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Projektdatei: Rundreise", () => {
|
||||
it("holes und edgePitchDeg (mit null) überstehen Schreiben und Lesen", () => {
|
||||
const withFields: Roof = { ...roof, holes: [court], edgePitchDeg: [20, null, -1, 45, 10, -1, -1, null] };
|
||||
const p = { ...sampleProject, roofs: [withFields] } as Project;
|
||||
const r = parseProjectFile(serializeProject(p));
|
||||
if (!r.ok) throw new Error(r.error);
|
||||
expect(r.project.roofs![0].holes).toEqual([court]);
|
||||
expect(r.project.roofs![0].edgePitchDeg).toEqual([20, null, -1, 45, 10, -1, -1, null]);
|
||||
});
|
||||
|
||||
it("ohne die Felder bleiben sie auch nach der Rundreise weg", () => {
|
||||
const p = { ...sampleProject, roofs: [roof] } as Project;
|
||||
const text = serializeProject(p);
|
||||
expect(text).not.toContain("edgePitchDeg");
|
||||
expect(text).not.toContain("holes");
|
||||
const r = parseProjectFile(text);
|
||||
if (!r.ok) throw new Error(r.error);
|
||||
expect("holes" in r.project.roofs![0]).toBe(false);
|
||||
expect("edgePitchDeg" in r.project.roofs![0]).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -58,7 +58,8 @@ import {
|
||||
wallVerticalExtent,
|
||||
} from "../model/wall";
|
||||
import { ceilingArea, outlineBBox } from "../core";
|
||||
import { roofBBox, roofBaseElevation, roofGeometry } from "../core";
|
||||
import { roofBBox, roofBaseElevation, roofEdgeList, roofGeometry } from "../core";
|
||||
import type { RoofEdge } from "../core";
|
||||
import { openingGapQuad, openingVerticalExtent } from "../core";
|
||||
import { stairGeometry, stairBBox } from "../core";
|
||||
|
||||
@@ -115,6 +116,12 @@ export interface RoofInfo {
|
||||
/** Untere/linke Ecke der Bounding-Box (fix beim Breite/Tiefe-Resize). */
|
||||
minX: number;
|
||||
minY: number;
|
||||
/** Kanten (Umriss, dann Höfe) mit Neigungsvorgabe ([26], `roofEdgeList`). */
|
||||
edges: RoofEdge[];
|
||||
/** Innenhöfe: Fläche (m²) und Punktzahl je Hof, in der Reihenfolge von `Roof.holes`. */
|
||||
holes: { area: number; points: number }[];
|
||||
/** Ob `edgePitchDeg` gesetzt ist. */
|
||||
hasEdgePitch: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -867,6 +874,9 @@ function roofSelection(project: Project, roof: Roof): Selection {
|
||||
depth: Math.abs(bb.y1 - bb.y0),
|
||||
minX: bb.x0,
|
||||
minY: bb.y0,
|
||||
edges: roofEdgeList(roof),
|
||||
holes: (roof.holes ?? []).map((h) => ({ area: Math.abs(polygonArea(h)), points: h.length })),
|
||||
hasEdgePitch: roof.edgePitchDeg !== undefined,
|
||||
};
|
||||
return {
|
||||
kind: "roof",
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
// Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import { applyFillMode } from "./fillMode";
|
||||
import { addItems, fieldOps, opsMutation, patchItem, patchItems, removeItems, setFieldIfChanged } from "../core";
|
||||
import { addItems, fieldOps, opsMutation, patchItem, patchItems, removeItems, removeRoofHole, setFieldIfChanged, setRoofEdge } from "../core";
|
||||
import type { CoreOp } from "../core";
|
||||
import { useMemo, type RefObject } from "react";
|
||||
import type { DrawingLevel, Layout, Project } from "../model/types";
|
||||
@@ -929,8 +929,20 @@ export function usePanelHostBase(opts: {
|
||||
},
|
||||
onOpenOpeningEditor: (id) => setOpeningEditorId(id),
|
||||
// ── Dach-Attribute (nur bei selektiertem Dach) ─────────────────────────
|
||||
onSetRoofPatch: (patch) => {
|
||||
if (selection?.kind === "roof") updateRoof(selection.id, patch);
|
||||
onSetRoofPatch: (patch, coalesceKey) => {
|
||||
if (selection?.kind === "roof") updateRoof(selection.id, patch, coalesceKey);
|
||||
},
|
||||
onSetRoofEdge: (index, spec) => {
|
||||
if (selection?.kind !== "roof") return;
|
||||
const r = (project.roofs ?? []).find((x) => x.id === selection.id);
|
||||
if (!r) return;
|
||||
// Zahl tippen: gleicher Schlüssel je Kante ⇒ ein Undo-Schritt; Giebel-Schalter einzeln.
|
||||
updateRoof(selection.id, setRoofEdge(r, index, spec), spec.kind === "pitch" ? `roof-edge-${selection.id}-${index}` : undefined);
|
||||
},
|
||||
onRemoveRoofHole: (k) => {
|
||||
if (selection?.kind !== "roof") return;
|
||||
const r = (project.roofs ?? []).find((x) => x.id === selection.id);
|
||||
if (r) updateRoof(selection.id, removeRoofHole(r, k));
|
||||
},
|
||||
// ── Schnitt-/Ansichtslinie (nur bei selektierter Linie) ────────────────
|
||||
sectionLine,
|
||||
|
||||
@@ -182,6 +182,14 @@ export function CommandIcon({ name }: { name: string }) {
|
||||
<line x1="8" y1="3" x2="8" y2="9" strokeDasharray="1.5 1.5" />
|
||||
</svg>
|
||||
);
|
||||
case "roofhole":
|
||||
// Dachhof: Dach-Umriss mit ausgespartem Innenhof.
|
||||
return (
|
||||
<svg {...common}>
|
||||
<polygon points="2,12 3.5,4 12.5,4 14,12" />
|
||||
<rect x="6" y="6.5" width="4" height="3" strokeDasharray="1.4 1.2" />
|
||||
</svg>
|
||||
);
|
||||
case "ceilingopening":
|
||||
// Deckenloch: Decken-Rechteck mit ausgespartem Innenrechteck.
|
||||
return (
|
||||
|
||||
Reference in new issue
Block a user