diff --git a/src/geometry/roof.ts b/src/geometry/roof.ts index 39f4fc7a..db7c87ff 100644 --- a/src/geometry/roof.ts +++ b/src/geometry/roof.ts @@ -11,6 +11,7 @@ import type { Project, Roof, Vec2 } from "../model/types"; import { getFloor } from "../model/types"; +import { cleanRing, isRectilinearNonRect, offsetRectilinear, rectilinearHipRoof } from "./roofSkeleton"; /** 3D-Punkt [x, y, z=Höhe] in Modell-Metern. */ export type Vec3 = [number, number, number]; @@ -335,6 +336,11 @@ const swapLine = (l: [Vec2, Vec2]): [Vec2, Vec2] => [swap2(l[0]), swap2(l[1])]; * transponiert. */ export function roofGeometry(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). + if (roof.shape === "walm" && isRectilinearNonRect(roof.outline)) { + return rectilinearWalm(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) @@ -363,6 +369,34 @@ export function roofGeometry(roof: Roof, eavesZ: number): RoofGeometry { }; } +/** + * 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 eaves = offsetRectilinear(ring, Math.max(0, roof.overhang)); + const tan = Math.tan(Math.max(0, roof.pitchDeg) * DEG); + const sk = rectilinearHipRoof(eaves, tan, eavesZ); + return { + eaves, + ridges: sk.ridges, + hips: sk.hips, + breaks: [], + planes: sk.planes.map((pts) => ({ pts })), + gables: [], + ridgeHeight: sk.ridgeHeight, + }; +} + /** Punkt-in-Polygon (Ray-Casting), 2D-Aufsicht. */ function pointInPolygon2D(p: Vec2, poly: Vec2[]): boolean { let inside = false; diff --git a/src/geometry/roofSkeleton.test.ts b/src/geometry/roofSkeleton.test.ts new file mode 100644 index 00000000..61759371 --- /dev/null +++ b/src/geometry/roofSkeleton.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest"; +import type { Roof, Vec2 } from "../model/types"; +import { roofGeometry } from "./roof"; +import { convexPieces, isRectilinearNonRect, rectilinearHipRoof } from "./roofSkeleton"; + +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 }]; + +const planArea = (pts: number[][]) => { + let a = 0; + for (let i = 0; i < pts.length; i++) { + const p = pts[i], q = pts[(i + 1) % pts.length]; + a += p[0] * q[1] - q[0] * p[1]; + } + return Math.abs(a) / 2; +}; + +describe("rectilinearHipRoof (L-Grundriss)", () => { + const r = rectilinearHipRoof(L, 1, 0); + 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); + expect(r.ridgeHeight).toBeCloseTo(3, 6); + }); + it("Kehle: einspringende Ecke (8,4) steigt zum Kehlpunkt (6,2)", () => { + expect(r.hips.some(([a, b]) => (a.x === 8 && a.y === 4 && b.x === 6 && b.y === 2) || (b.x === 8 && b.y === 4 && a.x === 6 && a.y === 2))).toBe(true); + }); +}); + +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); + expect(roofGeometry(base, 0).planes.length).toBe(8); + const rect = { ...base, outline: L.slice(0, 1).concat([{ x: 11, y: 0 }, { x: 11, y: 6 }, { x: 0, y: 6 }]) }; + expect(roofGeometry(rect, 0).planes.length).toBe(4); + }); +}); diff --git a/src/geometry/roofSkeleton.ts b/src/geometry/roofSkeleton.ts new file mode 100644 index 00000000..0d727dd3 --- /dev/null +++ b/src/geometry/roofSkeleton.ts @@ -0,0 +1,298 @@ +// 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 `polygon-clipping` +// (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 polygonClipping from "polygon-clipping"; +import type { MultiPolygon, Ring } from "polygon-clipping"; +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; + }); +} + +/** Rechtwinkligen Ring (CCW) um `d` nach aussen versetzen (Traufüberstand). */ +export function offsetRectilinear(ring: Vec2[], d: number): Vec2[] { + if (d <= 0) return ring.map((p) => ({ ...p })); + const n = ring.length; + // Aussen-Normale je Kante (CCW → rechte Normale). + const off = ring.map((p, i) => { + const q = ring[(i + 1) % n]; + const len = Math.hypot(q.x - p.x, q.y - p.y) || 1; + return { x: ((q.y - p.y) / len) * d, y: (-(q.x - p.x) / len) * d }; + }); + // Ecke i = Schnitt der versetzten Kanten (i−1) und i; bei rechten Winkeln + // einfach die Summe beider Versätze. + return ring.map((p, i) => { + const a = off[(i + n - 1) % n]; + const b = off[i]; + return { x: p.x + a.x + b.x, y: p.y + a.y + b.y }; + }); +} + +/** 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; +} + +const toRing = (pts: Vec2[]): Ring => pts.map((p) => [p.x, 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][]; + ridgeHeight: number; +} + +/** + * Walmdach-Flächen über dem rechtwinkligen Traufring `eaves` (beliebige + * Orientierung) bei Neigung `tan` und Traufhöhe `e`. + */ +export function rectilinearHipRoof(eavesIn: Vec2[], tan: number, e: 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 } }; + }); + 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]; + const bisA = { x: ed.n.x + prev.n.x, y: ed.n.y + prev.n.y }; + const bisB = { 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)); + w = clipHalf(w, side(ed.a, bisA, ed.b)); + w = clipHalf(w, side(ed.b, bisB, ed.a)); + return w; + }); + const eavesPoly = [toRing(eaves)]; + const planes: Vec3[][] = []; + const lineKeys = new Set(); + const ridges: [Vec2, Vec2][] = []; + const hips: [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 (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 || wedge[f].length < 3) 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) => e + tan * Math.max(0, dist(k, p)); + for (const piece of convexPieces(outer)) { + planes.push(piece.map((p) => [p.x, p.y, z(p)] as Vec3)); + } + // 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]); + } + } + }); + return { planes, ridges, hips, ridgeHeight }; +} + +// ── 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])); +}