From 8be0ceda905f35af98e175af15e4e26ac2a8866c Mon Sep 17 00:00:00 2001 From: karim Date: Tue, 27 Oct 2026 20:20:09 +0100 Subject: [PATCH] [64][59] Sonnenstand (NOAA) und Boden-Schatten von Waenden/Koerpern/Daechern als Polygon-Vereinigung; CLI sun; Tests --- src/analysis/sun.test.ts | 38 ++++++++++ src/analysis/sun.ts | 145 +++++++++++++++++++++++++++++++++++++++ src/cli/main.ts | 16 ++++- src/core/extra.ts | 2 + 4 files changed, 199 insertions(+), 2 deletions(-) create mode 100644 src/analysis/sun.test.ts create mode 100644 src/analysis/sun.ts diff --git a/src/analysis/sun.test.ts b/src/analysis/sun.test.ts new file mode 100644 index 00000000..18c13eb7 --- /dev/null +++ b/src/analysis/sun.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vitest"; +import { sunPosition, shadowOfPrism, shadowPolygons } from "./sun"; +import { sampleProject } from "../model/sampleProject"; + +describe("sunPosition", () => { + it("Zürich, Sommersonnenwende, Sonnenhöchststand ≈ 66°, Süden", () => { + const s = sunPosition(47.37, 8.54, new Date(Date.UTC(2026, 5, 21, 11, 26))); + expect(s.elevation).toBeGreaterThan(65.5); + expect(s.elevation).toBeLessThan(66.6); + expect(Math.abs(s.azimuth - 180)).toBeLessThan(3); + }); + it("Wintersonnenwende mittags ≈ 19°, nachts unter dem Horizont", () => { + const noon = sunPosition(47.37, 8.54, new Date(Date.UTC(2026, 11, 21, 11, 20))); + expect(noon.elevation).toBeGreaterThan(18.5); + expect(noon.elevation).toBeLessThan(19.8); + expect(sunPosition(47.37, 8.54, new Date(Date.UTC(2026, 5, 21, 23, 0))).elevation).toBeLessThan(0); + }); + it("Vormittags steht die Sonne im Osten", () => { + const s = sunPosition(47.37, 8.54, new Date(Date.UTC(2026, 2, 21, 6, 0))); + expect(s.azimuth).toBeGreaterThan(60); + expect(s.azimuth).toBeLessThan(120); + }); +}); + +describe("Schatten", () => { + const sq = [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 2 }, { x: 0, y: 2 }]; + it("Prisma 4 m hoch, Sonne im Süden auf 45° → Schatten 4 m nach Norden", () => { + const sh = shadowOfPrism(sq, 0, 4, { azimuth: 180, elevation: 45 }); + const ys = sh.map((p) => p.y); + expect(Math.max(...ys)).toBeCloseTo(6, 6); + expect(Math.min(...ys)).toBeCloseTo(0, 6); + }); + it("Sonne unter dem Horizont → kein Schatten, Projekt liefert Polygone am Tag", () => { + expect(shadowOfPrism(sq, 0, 4, { azimuth: 0, elevation: -3 })).toEqual([]); + expect(shadowPolygons(sampleProject, { azimuth: 200, elevation: 30 }).length).toBeGreaterThan(0); + expect(shadowPolygons(sampleProject, { azimuth: 200, elevation: -3 })).toEqual([]); + }); +}); diff --git a/src/analysis/sun.ts b/src/analysis/sun.ts new file mode 100644 index 00000000..8bc035bc --- /dev/null +++ b/src/analysis/sun.ts @@ -0,0 +1,145 @@ +// Sonnenstand und Schattenwurf im Grundriss (Lageplan-Schattenstudie, [64]/[59]). +// +// • `sunPosition`: Azimut (° von Nord im Uhrzeigersinn) und Höhe (°) nach dem vereinfachten +// NOAA-Verfahren (Genauigkeit ~0.1°, ohne Refraktion). +// • `shadowOfPrism`/`shadowPolygons`: Boden-Schatten (z = 0) von Wänden, freien Körpern und +// Dächern als Vereinigung konvexer Hüllen (Prisma ∪ verschobenes Prisma). Modell: x = Ost, +// y = Nord, Höhen über dem Geländenullpunkt (Meter). + +import polygonClipping from "polygon-clipping"; +import type { Pair, Polygon as PcPolygon } from "polygon-clipping"; +import type { Project, Vec2 } from "../model/types"; +import { wallVerticalExtent } from "../model/wall"; +import { roofBaseElevation, roofGeometry } from "../geometry/roof"; +import { lv95ToWgs84 } from "../io/lv95"; +import { getFloor, getWallType, wallTypeThickness } from "../model/types"; + +export interface SunPosition { + /** Grad von Nord im Uhrzeigersinn (Ost = 90, Süd = 180). */ + azimuth: number; + /** Grad über dem Horizont (negativ = Nacht). */ + elevation: number; +} + +const RAD = Math.PI / 180; + +export function sunPosition(latDeg: number, lonDeg: number, when: Date): SunPosition { + const jd = when.getTime() / 86400000 + 2440587.5; + const n = jd - 2451545.0; + const L = (280.46 + 0.9856474 * n) % 360; + const g = ((357.528 + 0.9856003 * n) % 360) * RAD; + const lambda = (L + 1.915 * Math.sin(g) + 0.02 * Math.sin(2 * g)) * RAD; + const eps = (23.439 - 0.0000004 * n) * RAD; + const ra = Math.atan2(Math.cos(eps) * Math.sin(lambda), Math.cos(lambda)); + const dec = Math.asin(Math.sin(eps) * Math.sin(lambda)); + // Greenwich-Sternzeit → Stundenwinkel. + const gmst = (280.46061837 + 360.98564736629 * n) % 360; + const ha = (((gmst + lonDeg) * RAD - ra) % (2 * Math.PI) + 3 * Math.PI) % (2 * Math.PI) - Math.PI; + const lat = latDeg * RAD; + const sinEl = Math.sin(lat) * Math.sin(dec) + Math.cos(lat) * Math.cos(dec) * Math.cos(ha); + const el = Math.asin(sinEl); + const az = Math.atan2(-Math.sin(ha) * Math.cos(dec), Math.sin(dec) * Math.cos(lat) - Math.cos(dec) * Math.sin(lat) * Math.cos(ha)); + return { azimuth: (((az / RAD) % 360) + 360) % 360, elevation: el / RAD }; +} + +/** Breite/Länge des Projekts aus `geoAnchor` (LV95), sonst Zürich als Platzhalter. */ +export function projectLatLon(project: Project): { lat: number; lon: number } { + const a = project.geoAnchor; + if (a) { + const p = lv95ToWgs84(a.lv95.e, a.lv95.n); + return { lat: p.lat, lon: p.lon }; + } + return { lat: 47.3769, lon: 8.5417 }; +} + +function hull(points: Vec2[]): Vec2[] { + const p = points.slice().sort((a, b) => a.x - b.x || a.y - b.y); + if (p.length < 3) return p; + const cross = (o: Vec2, a: Vec2, b: Vec2) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x); + const lower: Vec2[] = []; + for (const q of p) { + while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], q) <= 0) lower.pop(); + lower.push(q); + } + const upper: Vec2[] = []; + for (const q of p.slice().reverse()) { + while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], q) <= 0) upper.pop(); + upper.push(q); + } + return lower.slice(0, -1).concat(upper.slice(0, -1)); +} + +/** Verschiebung des Schattens je Meter Höhe (Richtung von der Sonne weg). */ +function shadowShift(sun: SunPosition): Vec2 | null { + if (sun.elevation <= 0.5) return null; + const k = 1 / Math.tan(sun.elevation * RAD); + const az = sun.azimuth * RAD; + return { x: -Math.sin(az) * k, y: -Math.cos(az) * k }; +} + +/** Boden-Schatten eines Prismas `footprint` von `zBottom` bis `zTop` (leer bei Nacht). */ +export function shadowOfPrism(footprint: Vec2[], zBottom: number, zTop: number, sun: SunPosition): Vec2[] { + const k = shadowShift(sun); + if (!k || zTop <= zBottom || footprint.length < 3) return []; + const pts: Vec2[] = []; + for (const p of footprint) { + pts.push({ x: p.x + k.x * zBottom, y: p.y + k.y * zBottom }); + pts.push({ x: p.x + k.x * zTop, y: p.y + k.y * zTop }); + } + return hull(pts); +} + +/** Vereinigter Schatten aller Wände, Körper und Dächer als Polygone (Aussenring + Löcher je Eintrag). */ +export function shadowPolygons(project: Project, sun: SunPosition): Vec2[][] { + if (shadowShift(sun) === null) return []; + const parts: Vec2[][] = []; + for (const w of project.walls) { + const { zBottom, zTop } = wallVerticalExtent(project, w); + const dx = w.end.x - w.start.x; + const dy = w.end.y - w.start.y; + const len = Math.hypot(dx, dy); + if (len < 1e-9) continue; + const t = wallTypeThickness(getWallType(project, w)) / 2; + const nx = (-dy / len) * t; + const ny = (dx / len) * t; + const fp = [ + { x: w.start.x + nx, y: w.start.y + ny }, + { x: w.end.x + nx, y: w.end.y + ny }, + { x: w.end.x - nx, y: w.end.y - ny }, + { x: w.start.x - nx, y: w.start.y - ny }, + ]; + parts.push(shadowOfPrism(fp, zBottom, zTop, sun)); + } + for (const s of project.extrudedSolids ?? []) { + if (s.operation === "subtract") continue; + let base = 0; + try { + base = getFloor(project, s.levelId).baseElevation ?? 0; + } catch { + /* Geschoss fehlt → 0 */ + } + const z0 = base + (s.baseOffset ?? 0); + parts.push(shadowOfPrism(s.points, z0, z0 + s.height, sun)); + } + for (const r of project.roofs ?? []) { + const eavesZ = roofBaseElevation(project, r); + const geo = roofGeometry(r, eavesZ); + const k = shadowShift(sun)!; + const pts: Vec2[] = geo.eaves.map((p) => ({ x: p.x + k.x * eavesZ, y: p.y + k.y * eavesZ })); + const top = eavesZ + geo.ridgeHeight; + for (const [a, b] of geo.ridges) for (const p of [a, b]) pts.push({ x: p.x + k.x * top, y: p.y + k.y * top }); + for (const [, b] of geo.hips) pts.push({ x: b.x + k.x * top, y: b.y + k.y * top }); + // Traufkante auf Traufhöhe + Firstpunkte → Hülle (Dach ist konvex genug für die Studie). + for (const p of geo.eaves) pts.push({ x: p.x + k.x * top, y: p.y + k.y * top }); + parts.push(hull(pts)); + } + const polys: PcPolygon[] = parts + .filter((p) => p.length >= 3) + .map((p) => [[...p.map((q): Pair => [q.x, q.y]), [p[0].x, p[0].y] as Pair]]); + if (polys.length === 0) return []; + const union = polygonClipping.union(polys[0], ...polys.slice(1)); + // Pro Teilpolygon nur der Aussenring (Löcher eines Schattens sind Hofflächen: bewusst mitgeben). + const out: Vec2[][] = []; + for (const poly of union) for (const ring of poly) out.push(ring.slice(0, -1).map(([x, y]) => ({ x, y }))); + return out; +} diff --git a/src/cli/main.ts b/src/cli/main.ts index 04aa611a..503ce7d9 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -8,7 +8,7 @@ // dossier-cli plan [--level EG] [--scale 100] [--out eg.svg] // dossier-cli section [--out schnitt.svg] (braucht render3d-WASM) // dossier-cli elevation [--out ansicht.svg] -// dossier-cli dxf|ifc|step|obj|stl|schedule|kennzahlen [--level EG] [--out datei] +// dossier-cli dxf|ifc|step|obj|stl|schedule|kennzahlen|sun [--level EG] [--out datei] // dossier-cli model3d [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png) // dossier-cli mcp MCP-Server (stdio): project_info, query, render_svg, apply_ops, validate // dossier-cli bench [--runs 10] Zeitprofil der Ableitungen (ms je Aufruf) @@ -26,6 +26,9 @@ import { exportProjectStep, exportScheduleCsv, computeKennzahlen, + sunPosition, + shadowPolygons, + projectLatLon, checkRoomProgram, exportStl, generateElevationPlan, @@ -113,7 +116,7 @@ export async function run(argv: string[]): Promise { const [file, command, ...rest] = args.positional; if (!file || !command) { process.stderr.write( - "Aufruf: dossier-cli [Optionen]\n", + "Aufruf: dossier-cli [Optionen]\n", ); return 2; } @@ -207,6 +210,15 @@ export async function run(argv: string[]): Promise { out(args, JSON.stringify({ kennzahlen: k, raumprogramm: prog }, null, 2), `${project.name || "projekt"}-kennzahlen.json`); return 0; } + case "sun": { + // Sonnenstand + Schatten-Polygone (Boden, Meter) für Datum/Uhrzeit (UTC), z. B. --when 2026-06-21T10:00Z + const when = new Date(String(args.flags.get("when") ?? "2026-06-21T10:00:00Z")); + if (Number.isNaN(when.getTime())) throw new Error("--when: ungültiges Datum"); + const { lat, lon } = projectLatLon(project); + const sun = sunPosition(lat, lon, when); + out(args, JSON.stringify({ when: when.toISOString(), lat, lon, sun, shadows: shadowPolygons(project, sun) }, null, 2), `${project.name || "projekt"}-sonne.json`); + return 0; + } case "schedule": out(args, exportScheduleCsv(project), `${project.name || "projekt"}-liste.csv`); return 0; diff --git a/src/core/extra.ts b/src/core/extra.ts index 8da0b1ed..c7a0f7be 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -14,3 +14,5 @@ export type { CoreOp } from "./ops"; export type { Project, DrawingLevel } from "../model/types"; export { computeKennzahlen, checkRoomProgram, solidVolume } from "../analysis/kennzahlen"; export type { Kennzahlen, ProgramCheck } from "../analysis/kennzahlen"; +export { sunPosition, shadowPolygons, shadowOfPrism, projectLatLon } from "../analysis/sun"; +export type { SunPosition } from "../analysis/sun";