Merge remote-tracking branch 'origin/master' into worktree-agent-a0f13906a9829e7a3
# Conflicts: # src-tauri/core/src/plan/elevation.rs # src-tauri/core/src/plan/section.rs
This commit is contained in:
101 files changed
+8304
-374
No files matched your search
@@ -1183,6 +1183,32 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
|
||||
Treppenuntersicht, Abzugskörper beliebiger Form im Schnitt. · L
|
||||
- ◐ **[G2] Wand an Dach.** 27.10.: schräge Oberkante (`topDrop`) in render3d statt 15-cm-Treppung. Offen:
|
||||
Schnitt, exakte Lösung über [B6]. · M–L
|
||||
- (30.10.) **Exakt je Schicht, analytisch** (ohne Booleans, `wall_bands.rs`): Dach-Unterkante als Facetten
|
||||
(`RoofFacet`: Dachfläche um die Schichtdicke senkrecht gesenkt, Gaubeninneres mit der Gaubendach-Unterkante,
|
||||
`DormerGeom::under_facets`); über einem Punkt gilt die obere Hülle (Kehlen verschnittener Dächer, Gaube).
|
||||
Jedes Band wird an den Bereichsgrenzen geteilt — längs mit der exakten Grenzlinie als Schnittlinie (First,
|
||||
Grat, Kehle, Höhenlinie Dach = Krone/Fuss), seitlich über die Dicke, wo eine Grenze längs durchläuft
|
||||
(Traufwand, deren Krone die Dachfläche schneidet) — und bekommt eine **ebene Oberkante** (`Piece.top_plane`,
|
||||
`RWall.topPlane` = `[z am Anfang, dz/dx, dz/dy]`): jede Ecke exakt auf der Unterkante, auch quer über die
|
||||
Dicke. Öffnungen unter dem Dach: Pfeiler/Brüstung/Sturz je mit eigener ebener Oberkante statt Treppung;
|
||||
innere Teilungen als Stossfugen (`joint`, keine Stirn in Ansicht/Schnitt-Projektion). **Option je Wand**
|
||||
`Wall.roofAttach` („An Dach anschliessen", Objekt-Info): fehlt = automatisch (nur kürzen, wo die Krone über
|
||||
der Unterkante liegt), `true` = bis unter das Dach verlängern, `false` = Dächer schneiden nicht. Verbraucher:
|
||||
render3d (Mesh, Deckel-Schraffur, Schnitt-Prisma mit schräger Deckelkante), Kern-Schnitt und -Ansicht
|
||||
(Schnitt-Eingabe jetzt mit den Dächern des Geschosses), OBJ/STL/glTF und IFC (Prisma bis zur Dachunterkante,
|
||||
`model3d::wall_piece_mesh`), Mengen (Brutto-/Nettovolumen exakt über die Grundfläche,
|
||||
`wall_piece_volume`). Ansicht: Wandflächen unter Dächern gegen die Dachscheiben (Oberfläche, Trauf-/Ortgang-
|
||||
Stirn, Gaubenstirn/-wangen) verdeckt bzw. auf die Verdeckungsgrenze gekappt, Giebeldreiecke entfallen, wenn
|
||||
Wände ans Dach reichen (dafür Stirnflächen der Dachscheibe). Bogenwände ([T2]) laufen über die Sehnen-
|
||||
Teilwände mit. Geprüft: Rust-Tests (Giebel beidseitig je Schicht exakt, Traufwand schräg + seitlich geteilt,
|
||||
Fenster unter der Schräge Volumen exakt, An-Dach-Option, Kehle = obere Hülle, Schnitt-Pfad, Körper dicht und
|
||||
Volumen = Analytik, Schnitt nie über der Unterkante, Ansicht Traufe/Giebel), render3d-Test (Mesh-Ecken auf der
|
||||
Ebene, Schnitt schräg), CLI-Schnitte/-Ansichten eines Testhauses (Satteldach mit Trauf-/Giebelwänden,
|
||||
Fenster unter der Schräge, T-Dach mit Kehlen, Gaube, Bogenwand, Innenwand „bis unters Dach") als PNG
|
||||
angesehen (Linux). Offen: Ansicht bleibt Painter + Verdeckungstest gegen Dächer (keine HLR, [G4]); Grenzen,
|
||||
die fast parallel zur Achse schräg durchs Band laufen, nur genähert (seitliche Teilung an der Mitte);
|
||||
Fenster, das ins Dach ragt, verliert seinen Sturz; Dachgeometrie im 3D-Live-Schnitt unverändert; nicht in
|
||||
der Tauri-App/Metal geprüft.
|
||||
- ◐ **[G3] Öffnungen beliebiger Form** (29.10.) `Opening.shape` (rundbogen, segmentbogen, spitzbogen, rund/oval,
|
||||
schraeg, giebel) + `shapeRise` (Stich). Kern `opening_shape.rs`: konvexer Umriss im Öffnungsrechteck; die Wand
|
||||
behält das Rechteck-Loch, der Rest zwischen Rechteck und Umriss kommt als Füllkörper (senkrechte Streifen =
|
||||
@@ -1255,6 +1281,16 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
|
||||
statt `RWall` gehen), 3D-Live-Schnitt-Deckel verschnittener Dächer (zeigen noch die unverschnittenen
|
||||
Schichten), IFC-Mengen der Gaube, Kehlen symmetrisch je Schicht (heute „überlappt" das frühere Dach),
|
||||
Gauben über First/Grat hinaus nicht abgefangen, nicht in der Tauri-App/Metal geprüft.
|
||||
- (30.10.) Restpunkte: **Gauben über den First** werden abgefangen (`dormer::geometry`): Stirnhöhe (bzw. Tiefe
|
||||
der Schleppgaube) so gekappt, dass die Gaubendach-Oberkante spätestens am First auf die Hauptdach-Oberkante
|
||||
trifft (`DormerGeom.clamped`), das Gaubendach endet am Rand seiner Dachfläche (vorher ragte es jenseits des
|
||||
Firsts als Splitter heraus). **IFC-Mengen der Gaube**: `Qto_DossierDormerQuantities` am IfcRoof (Breiten,
|
||||
Stirnhöhe, geneigter Ausschnitt, Wand- und Dachvolumen aus den Körpern), NetArea des Dachs ohne den
|
||||
Ausschnitt. **Haarfugen** der Dachfläche in der Ansicht: Kontur in Füllfarbe 0.15 mm statt 0.05 mm. Wand ↔
|
||||
Dach: [G2]. Wand ↔ Decke: bestehende Schicht-Dominanz (3D je Band nach Rang, Schnitt
|
||||
`subtract_dominant_bands`) im CLI-Schnitt des Beispielprojekts angesehen, nicht geändert. Offen:
|
||||
3D-Live-Schnitt-Deckel verschnittener Dächer, Kehlen symmetrisch je Schicht, Warnung bei gekappter Gaube in
|
||||
der UI, Wand ↔ Decke für beliebige Polygone im Schnitt ([G6]).
|
||||
- (30.10.) Boolean-Werkzeug dafür: Manifold-Port `manifold-rust`, nicht truck — truck scheitert an Gaube und
|
||||
L-Ecke (bündige Unterseiten), `manifold-rust` rechnet beide exakt und dicht. Details und Plan: [107].
|
||||
- ○ **[G6] Allgemeine Polygon-Dominanz im Schnitt** (nicht nur Rechtecke). · M
|
||||
@@ -1380,12 +1416,31 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
|
||||
der Tauri-App. Offen: Schichteinzug [106], Formöffnungen [G3] und Ansichtsschraffur im 3D ([100]) in Bogenwänden; Wände teilen/trimmen (fehlt
|
||||
auch für gerade); echte Polar-Schraffur; IFC-Körper als extrudiertes Bogenprofil statt Netz; Griff-Vorschau
|
||||
zeigt nur die Achse; automatische Aussenbemassung misst Bogenwände als Sehne.
|
||||
- ○ **[T3] Wendeltreppe/Wendelfläche** + Handlauf-Sweep. · M
|
||||
- ○ **[T4] Import-Meshes glätten oder kantig** (`add_smooth_normals`). · S
|
||||
- ○ **[T5] Import reparieren** (`put_together_same_attrs`, Healing). · S
|
||||
- ○ **[T6] Glattes Gelände aus Höhenlinien** + Gelände-Prisma für Aushub (= [68]). · L
|
||||
- ○ **[T7] Rotationskörper/Loft im UI** (API besteht). · S–M
|
||||
- ○ **[T8] Kollisionsprüfung im 3D zeigen** (heute nur Marker im Grundriss). · S
|
||||
- ◐ **[T3] Wendeltreppe/Wendelfläche** + Handlauf-Sweep. · M — 30.10.: Ortbeton-Wendeltreppe mit echter Wendelfläche (Schraubenuntersicht, ebene Tritte, `stairs3d::spiral_mesh`), Handlauf als Schraubensweep samt Pfosten (links/rechts/beide nach Drehsinn), Mittelsäule `Stair.centerColumn` (Radius, Objekt-Info; als Block in 3D/Schnitt). Tests Rust (Volumen, Punkte auf der Schraube, Sweep-Radius, Säule). Plansymbol (Bögen, Schnittlinie, Pfeil) war schon da und im CLI-SVG geprüft; nicht in der Tauri-App. Offen: Säule im Grundriss, IFC/Mengen der Wendelfläche, Handlauf-Profil rund.
|
||||
- ○ **[T4] Import-Meshes glätten oder kantig** (`add_smooth_normals`). · S — Stand 30.10.: nicht begonnen. Braucht Renderer-Änderung (`render3d::append_context_mesh` rechnet nur Flächennormalen) + Feld an `ImportedMesh`/`RMesh`/`MeshInput` + WASM/Metal-Neubau; Verschweissen ([T5]) als Voraussetzung ist da.
|
||||
- ✅ **[T5] Import reparieren** (`put_together_same_attrs`, Healing). · S — 30.10.: `mesh_repair.rs` im Mesh-Import (`decode_mesh`): Ecken verschweissen (0.01 mm), entartete Dreiecke entfernen, Löcher bis 8 Randkanten in fast geschlossenen Netzen (Randanteil ≤ 5 %) per Fächer schliessen, Orientierung nach aussen; Zähler im Importbericht (`repaired`, Meldung). Tests Rust (Suppe, Entartete, Loch/Orientierung, offene Fläche bleibt, Bericht). Gilt für OBJ/STL/glTF/PLY, nicht für IFC/DXF/STEP. Nicht in der App getestet. Offen: Verschweissen über Zellgrenzen, Schalter/Schwellen im Import-Dialog, Normalen-Ausrichtung widersprüchlich orientierter Flächen.
|
||||
- ◐ **[T6] Glattes Gelände aus Höhenlinien** + Gelände-Prisma für Aushub (= [68]). (30.10.) Kern `terrain.rs`:
|
||||
Konturen verdichtet und als Bruchkanten erzwungen (constrained Delaunay: Sloan-Kantentausch auf `delaunay.rs`,
|
||||
danach Lawson nur an freien Kanten; konkave Ränder: lange Randsplitter weg), flache Dreiecke (Kuppen/Mulden/
|
||||
Talböden) mit Schwerpunkt aus Eckgradienten, begrenzt auf ±0.45·Äquidistanz (keine neuen Höhenlinien); Glättung
|
||||
durch adaptive Kantenteilung (rissfrei 1→2/3/4) mit Hermite-Mittelpunkt aus 1-Ring-Gradienten, ohne Überschwingen
|
||||
(Mittelpunkt streng zwischen den Endhöhen, Kontur-Kanten exakt). Optionen `smooth`/`maxEdge`/`breaklines`
|
||||
(`terrain_from_contours_opts_json`, Panel „Glätten"); Befehl `terrain` und Panel nutzen es (Standard: 2 Stufen).
|
||||
Neue Felder `TerrainMesh.contourInterval`/`contourIndexEvery`: Grundriss zeichnet Höhenlinien aus dem Netz
|
||||
(samt Baugruben) neu, Zähllinien dicker und beschriftet (2 mm Papier, lesbar gedreht); Rahmen wie bisher.
|
||||
Schnitt: gestaltetes Terrain (Baugruben) ausgezogen, gewachsenes gestrichelt, SIA-Erdreich-Band 1.5 m darunter
|
||||
([109] `std-h-erdreich`) ohne Gebäude-Inneres; Grundlinie entfällt mit Gelände. Ansicht: Silhouette des Geländes
|
||||
vor dem Gebäude (obere Hüllkurve), darunter verdeckt (Papierfläche). 3D/Export/Pick: geändertes Netz. Höhenbezug:
|
||||
ist `referenceElevationMasl` gesetzt und liegt das Gelände in m ü. M., gilt Modell = roh − Referenz (3D, Schnitt,
|
||||
Baurecht; Höhenlinien-Beschriftung roh). Gelände-Prisma (`terrain::prism`, dicht, Volumen per Divergenzsatz).
|
||||
Tests: Rust (Bruchkanten, Kegelhügel ohne Überschwingen/flache Dreiecke, Prisma dicht, Unsinn), vitest.
|
||||
Geprüft im Linux-Container (CLI-Grundriss/-Schnitt/-Ansicht eines Hügels mit Baugrube angesehen; Erdreich-Schraffur
|
||||
über den Kern-Generator gerendert, das CLI-SVG zeigt keine Schraffuren), nicht in der Tauri-App.
|
||||
Offen: swissALTI3D-Raster wird nicht geglättet (nur Äquidistanz 1 m gesetzt); Natural-Neighbour/Clough-Tocher statt
|
||||
Hermite-Teilung; Höhenlinien unter der Beschriftung nicht unterbrochen; Luftbild-Farben fallen auf geändertem
|
||||
Gelände weg; Erdreich-Band fest 1.5 m (nicht bis zur Planunterkante). · L
|
||||
- ✅ **[T7] Rotationskörper/Loft im UI** (API besteht). · S–M — 30.10.: Befehle `revolve` (Profil + Achse aus 2 Plan-Punkten + Winkel; Achse waagrecht auf Höhe r_max, Profil auf einer Seite) und `loft` (≥ 2 Profile der Reihe nach, gleichmässig über die Höhe; Punktzahl durch Kantenteilung angeglichen) in `cmd_solid.rs`/`cmds/{revolve,loft}.ts`, Körper als `ExtrudedSolid.brep` (Objekt-Info, STEP, Kennwerte wie die Grundkörper); Kürzel `rev`/`lf`, Werkzeugpalette 3D. Tests Rust (Spezifikation, Ops, truck-Volumen/STEP), vitest (Befehlsablauf). Nicht in der Tauri-App getestet. Offen: Achse senkrecht/beliebig im Raum, Loft mit Führungskurve, Profil-Startpunkt-Ausrichtung beim Loft.
|
||||
- ✅ **[T8] Kollisionsprüfung im 3D zeigen** (heute nur Marker im Grundriss). · S — 30.10.: Treffer in Sitzung (`panels/clashSession.ts`), Panel „Kollisionen" (`ClashPanel`: Liste, Klick wählt beide Bauteile und fährt die 3D-Kamera auf die Durchdringung, `cameraBridge.focusCamera`), im 3D rote Hüllquader aller Treffer (`clashHighlightLines` in `viewportContent`); Prüflauf öffnet das Panel, Marker im Grundriss bleiben. Tests vitest (Linien, Auswahl, Kamera-Fokus). Nicht im echten WebGPU-Viewport/Tauri geprüft. Offen: Hüllquader statt exakter Durchdringungsgeometrie, Panel-Name zeigt Ids statt Bauteilnamen, Wiederholung/Ignorieren einzelner Treffer.
|
||||
|
||||
---
|
||||
|
||||
@@ -1471,8 +1526,15 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
|
||||
(Befehl `dimdetach`, Kürzel `bml`, Kontextmenü, Objekt-Info). Autodim [81] hängt an Ecken/Leibungen.
|
||||
Transformieren: Bezüge bleiben bei Verschieben/Drehen zusammen mit den Elementen, sonst (allein, Spiegeln,
|
||||
Skalieren) gelöst; Kopien hängen an mitkopierten Elementen; ein von Hand gezogener Punkt ist frei.
|
||||
Offen: Bogenwände/Treppen nicht anhängbar, Achsraster fehlt im Modell; nur Linux/Chromium geprüft (Marke
|
||||
am Bildschirm nicht auf macOS/Metal angesehen). · L
|
||||
Nachtrag (30.10.): auch Bogenwände (Enden, Punkt auf Achse/Fläche als Anteil der Bogenlänge, Mittelpunkt, Rand-
|
||||
Bezug `rim` mit Winkel), Treppen (Umriss-Ecken/-Kanten, bei L-Treppen auch Podest-Ecken/-Kanten; Wendel: die vier
|
||||
Ecken der Schliesslinien, Mittelpunkt), Rasterachsen und Achsschnittpunkte [112] sind anhängbar. **Radius-,
|
||||
Durchmesser- und Bogenlängen-Bemassung** (`Dimension.kind`, Befehle `dimradius`/`dimdiameter`/`dimarc`, Kürzel
|
||||
`rad`/`dm`/`bogenl`): Klick auf den Rand eines 2D-Kreises/-Bogens oder einer Bogenwand (Achse oder Schichtfläche);
|
||||
Mittelpunkt und Randpunkte hängen an `center`/`rim` und werden einzeln (ohne Kettenprojektion) nachgeführt; DXF als
|
||||
Linien/Bögen/Text (nicht als DIMENSION). Autodim [81] misst nicht mittige Wände (Referenzlinie/-versatz) jetzt an
|
||||
der echten Fläche. Offen: Wendeltreppen-Bögen (nur die Schliesslinien-Ecken), Treppenlauf-Mitten, Rand-Bezug auf
|
||||
Ellipsen/Splines; nur Linux/Chromium geprüft (Marke am Bildschirm nicht auf macOS/Metal angesehen). · L
|
||||
- ○ **[39] Auswahl gehört zum Modell.** · M
|
||||
- ◐ **[40] Ansichten duplizieren.** Ebenen duplizieren vorhanden. · S
|
||||
- ◐ **[76] Vektorfang auf PDF.** (28.10.) Rust `fileio/pdf_object.rs` + `pdf_vector.rs` (eigener Leser:
|
||||
@@ -1618,7 +1680,8 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
|
||||
Einzel-Plan-PDF (`exportPdf.ts`) noch ohne Ebenen.
|
||||
- ◐ **[81] Automatische Aussenbemassung.** (27.10.) Befehl `autodim` (Kürzel `ab`): je Seite Öffnungs-,
|
||||
Vor-/Rücksprung- und Gesamtkette. Offen: schiefe Wände, Massstab aus der Ansicht statt fest 1:100.
|
||||
(30.10.) Ketten assoziativ [38] (Ecken/Leibungen, nur mittige Wände).
|
||||
(30.10.) Ketten assoziativ [38] (Ecken/Leibungen). Nicht mittige Wände
|
||||
(Referenzlinie links/rechts, -versatz): die Kette misst die echte Fläche (`WallIn.shift`). Offen: Bogenwände als Sehne.
|
||||
- ✅ **[82] Grafische Legenden.** (30.10.) `Layout.legends` (`LayoutLegend`: Lage, Titel, Arten Schraffur/Material · Linientyp ·
|
||||
Kategorie, optional Handauswahl `manualKeys`). `analysis/legend.ts`: Einträge automatisch aus den Viewports (Material der
|
||||
Wand-/Decken-/Dach-Aufbauten und Stützen im gezeigten Geschoss, Schraffuren/Linientypen der Zeichnungen, sichtbare
|
||||
@@ -1748,6 +1811,18 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
|
||||
Tabellenbreite nur über das Zahlenfeld (kein Ziehgriff); keine Kopfzeilen-Füllung/Farben; Schrift im PDF nur
|
||||
Helvetica/Times/Courier (jsPDF-Grundschriften); DXF-Beschriftungen in der Sprache der Oberfläche beim Export;
|
||||
nicht in der Tauri-App getestet. · S
|
||||
- ✅ **[112] Achsraster.** (30.10.) Neue 2D-Zeichnungsform `Drawing2DGeom::Grid` (`grid.rs`, Auswahl/Verschieben/Kopieren/
|
||||
Ebenen/DXF wie jede Zeichnung): rechtwinklig (`a` = Achsen 1, 2, 3 …, `b` = A, B, C …, unregelmässige Abstände, gedreht
|
||||
um `angle`) oder radial (Strahlen in Grad, Ringe als Bögen/Kreise), `extend` Überstand, `bubbles` Start/Ende/beide,
|
||||
`bubbleMm` (Papier-mm), `levels` (leer = in allen Geschossen), `show3d` (dünne Spur im 3D). Grundriss: strichpunktierte
|
||||
Achsen, Blasen mit Beschriftung (Massstab folgt `scale`); Schnitt und Ansicht: Achsen quer zur Blickebene als senkrechte
|
||||
Linien mit Blase oben (`plan/grid_view.rs`, eigene Gruppe, Massstab über `scaleDenominator`); Fang auf Achsen,
|
||||
Ringe und Achsschnittpunkte (Endpunkt); Griffe: Ursprung und je Achse das Achsende (zieht die Lage); Bemassung
|
||||
assoziativ [38] an Achse/Achsschnittpunkt. Befehl `grid` (Kürzel `achsraster`, `achsen`, Werkzeug „Achsraster"):
|
||||
Ursprung, dann Feldweiten als Text (`6 4.5 3x5`), Option Radial; Attribute-Panel: Blasenseite, Überstand, Blasen-Ø,
|
||||
Geschosse, 3D. Geprüft im Linux-Container (Rust, vitest, e2e, CLI-SVG Grundriss/Schnitt/Ansicht), nicht in der
|
||||
Tauri-App/Metal. Offen: Achsbeschriftung je Achse im UI ändern, Blasenseite je Achse, Achsen als Autodim-Vorschlag,
|
||||
IFC `IfcGrid`, Raster-Versatz je Geschoss. · M
|
||||
- ◐ **[110] Linientyp ohne Strichstärke.** (30.10., Wunsch Maintainer: „Volllinie 0.5/0.35 soll es nicht
|
||||
geben") Ein Linienstil ist nur Muster (Volllinie, Strich, Punkt, Zickzack, Motiv) + Farbe; die Stärke trägt
|
||||
das Element (`Drawing2D.weightMm`, sonst Ebene), die Schraffur (neu `HatchStyle.lineWeight`, Default 0.13),
|
||||
@@ -1851,12 +1926,30 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
|
||||
## Priorität 4 — später
|
||||
|
||||
Alle ○: [27] Punktwolken (Leser ✅ [B9], Anzeige ◐ s. u., Modell offen) · [28] Phasen · [29] Bauteillisten (◐, Export vorhanden; Fenster-/Türliste ✅ [97]) · [43] Verknüpfte
|
||||
Modelle · [44] Aus Datei einfügen · [45] Favoriten · [68] Gelände mit Baugrube (= [T6]) · [71] U-Werte (✅ s. u.) ·
|
||||
Modelle · [44] Aus Datei einfügen · [45] Favoriten · [68] Gelände mit Baugrube (◐ s. u.) · [71] U-Werte (✅ s. u.) ·
|
||||
[72] Graue Energie KBOB · [73] eBKP-H · [74] SIA 500 · [75] Fluchtwege VKF · [83] Befehlspalette ·
|
||||
[85] Makro-Rekorder · [86] Pipette · [87] Fang mit Begründung · [48] Web-Worker
|
||||
(◐, DXF-Parser, IFC-Import) · [52] Icons (◐, `CommandIcon.tsx`) · [56] Startparameter · [89] Git-freundliches
|
||||
Format · [90] Versionsvergleich · [91] Assistent · [92] Speckle.
|
||||
|
||||
- ◐ **[68] Baugrube / Geländebearbeitung.** (30.10.) Kontext-Objekt `excavation` (Rust-Modell, `ContextObject`):
|
||||
Sohle (`outline`, `bottom` m ±0.00), Böschung `slope` (Standard 45°, je Kante `edgeSlopes`), Schüttung `fillSlope`
|
||||
(33.7°), Bermen `bermWidth`/`bermHeight`. Neues Gelände = clamp(t, b − d·tan β, b + H(d)) mit d = Abstand zum
|
||||
Umriss (Ecken als Kegel) — dasselbe Element schneidet ein (Abtrag) und schüttet auf (Auftrag, Planie am Hang).
|
||||
Kern `excavation.rs`: Netz im Wirkbereich neu trianguliert (Raster mit exakter Höhe, Sohle und Böschungsoberkante
|
||||
als Bruchkanten, aussen Original-TIN samt Kanten), zwischengespeichert je Netz. Mengen (Abfrage
|
||||
`excavationQuantities`): Abtrag/Auftrag als Integral der exakten Funktion (Raster-Mittelpunkte), Hinterfüllung =
|
||||
Abtrag ausserhalb der Gebäude-Grundfläche; Test gegen die analytische Formel (10×10×3 m, 45°: 508.27 m³, < 0.2 %)
|
||||
und gegen die Prisma-Differenz des Netzes (< 2 %). Grundriss: Sohle, Böschungsoberkante, Böschungsschraffur
|
||||
(lang/halb, an Ecken gefächert); Schnitt/Ansicht/3D über das geänderte Gelände. Befehl `excavation`
|
||||
(Alias baugrube/aushub; Sohle = Geschoss − 0.30 m), Panel „Gelände & Kontext" (Sohle, Neigungen, Bermen, Mengen),
|
||||
Layout-Tabelle „Erdarbeiten" ([111], Quelle `earthworks`), CLI `kennzahlen` → `erdarbeiten`.
|
||||
Baurecht ([63]): Geländehöhen an der Fassade (gewachsen/gestaltet, Ecken + alle ≤ 2 m), massgebendes Terrain =
|
||||
tiefster gewachsener Punkt an der Fassade (vereinfacht), Gesamthöhe dagegen geprüft (ohne Gelände wie bisher ±0.00).
|
||||
Offen: Mengen je Baugrube gegen das gewachsene Terrain (Überlagerungen doppelt); Arbeitsraum als Abstand;
|
||||
senkrechter Verbau (Spundwand) nur als 89.5°-Böschung; Griffe/Objekt-Info für den Umriss; IVHB-Terrain nach
|
||||
kantonalem Recht (Lotrechte statt tiefster Fassadenpunkt); nicht in der Tauri-App geprüft.
|
||||
|
||||
- ◐ **[107] Manifold für Körper-Booleans (Schritt 1: trucksolid).** (30.10.) `manifold-rust` `=0.19.1` (Apache-2.0,
|
||||
exakter Modus) ersetzt den csgrs-Fallback in `src-tauri/trucksolid/src/boolean.rs`; csgrs, die Git-Abhängigkeit
|
||||
und nalgebra sind entfernt, `NOTICE` ergänzt. Reihenfolge unverändert: truck-B-Rep zuerst (exakte Flächen/STEP),
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
// [112]/[38] Achsraster: anlegen (Ursprung + Feldweiten), zwischen zwei Achsen bemassen, Achse am Griff
|
||||
// verschieben → die Bemassung folgt; Rückgängig stellt beides her.
|
||||
import { blurFocus, commandInput, expect, openTab, startNewProject, test, typeCommand } from "./app";
|
||||
import type { Page } from "@playwright/test";
|
||||
|
||||
/** Modellpunkt (m) → Client-Pixel (wie `dimAssoc.spec.ts::screenOf`). */
|
||||
async function screenOf(page: Page, x: number, y: number): Promise<{ x: number; y: number }> {
|
||||
return page.locator("svg.plan-svg").evaluate(
|
||||
(el, [mx, my]) => {
|
||||
const [vx, vy, vw, vh] = el.getAttribute("viewBox")!.split(/\s+/).map(Number);
|
||||
const ox = Number(el.getAttribute("data-origin-x") ?? 0);
|
||||
const oy = Number(el.getAttribute("data-origin-y") ?? 0);
|
||||
const r = el.getBoundingClientRect();
|
||||
const s = Math.min(r.width / vw, r.height / vh);
|
||||
return {
|
||||
x: r.left + (r.width - vw * s) / 2 + (mx * 90 - ox - vx) * s,
|
||||
y: r.top + (r.height - vh * s) / 2 + (-my * 90 - oy - vy) * s,
|
||||
};
|
||||
},
|
||||
[x, y],
|
||||
);
|
||||
}
|
||||
|
||||
async function clickModel(page: Page, x: number, y: number): Promise<void> {
|
||||
const p = await screenOf(page, x, y);
|
||||
await page.mouse.move(p.x, p.y);
|
||||
await page.mouse.click(p.x, p.y);
|
||||
}
|
||||
|
||||
const numbers = (page: Page) =>
|
||||
page.locator("svg.plan-svg text").evaluateAll((els) => els.map((e) => e.textContent ?? "").filter((s) => /^\d+\.\d\d$/.test(s)));
|
||||
|
||||
const labels = (page: Page) => page.locator("svg.plan-svg text").evaluateAll((els) => els.map((e) => e.textContent ?? ""));
|
||||
|
||||
test("Achsraster anlegen, zwischen zwei Achsen bemassen, Achse verschieben → Mass folgt", async ({ page }) => {
|
||||
await startNewProject(page);
|
||||
await openTab(page, "Elemente");
|
||||
await commandInput(page).focus();
|
||||
await typeCommand(page, "achsraster");
|
||||
await expect(page.locator(".cmdline-prompt")).toHaveText(/Ursprung des Achsrasters/);
|
||||
await typeCommand(page, "0,0");
|
||||
await expect(page.locator(".cmdline-prompt")).toHaveText(/Feldweiten Achsen 1, 2, 3/);
|
||||
await typeCommand(page, "6 6");
|
||||
await expect(page.locator(".cmdline-prompt")).toHaveText(/Feldweiten Achsen A, B, C/);
|
||||
await typeCommand(page, "5");
|
||||
await blurFocus(page);
|
||||
await page.getByTitle("Auf Plan einpassen").click();
|
||||
// Beschriftungen in den Blasen: 1, 2, 3 und A, B (je an beiden Enden).
|
||||
await expect.poll(() => labels(page)).toEqual(expect.arrayContaining(["1", "2", "3", "A", "B"]));
|
||||
|
||||
// Bemassung der Achsen 1 und 2 (Achsschnittpunkte A/1 und A/2), Abstand 1 m unter dem Raster.
|
||||
await commandInput(page).focus();
|
||||
await typeCommand(page, "dim");
|
||||
await clickModel(page, 0, 0);
|
||||
await clickModel(page, 6, 0);
|
||||
await commandInput(page).press("Enter");
|
||||
await expect(page.locator(".cmdline-prompt")).toHaveText(/Lage der Masslinie/);
|
||||
await typeCommand(page, "-1");
|
||||
await expect.poll(() => numbers(page)).toContain("6.00");
|
||||
|
||||
// Raster wählen (Klick auf Achse 2), Achsgriff am Achsende nach rechts ziehen: Achse 2 von x = 6 auf 7.5.
|
||||
await blurFocus(page);
|
||||
await page.keyboard.press("Escape");
|
||||
await clickModel(page, 6, 2.5);
|
||||
await expect.poll(() => page.locator(".plan-grip").count()).toBeGreaterThan(2);
|
||||
const from = await screenOf(page, 6, 6.5);
|
||||
const to = await screenOf(page, 7.5, 6.5);
|
||||
await page.mouse.move(from.x, from.y);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move((from.x + to.x) / 2, from.y, { steps: 4 });
|
||||
await page.mouse.move(to.x, to.y, { steps: 4 });
|
||||
await page.mouse.up();
|
||||
await page.mouse.click(to.x, to.y);
|
||||
|
||||
await expect.poll(async () => (await numbers(page)).some((v) => Math.abs(Number(v) - 7.5) < 0.1)).toBe(true);
|
||||
// Rückgängig (der Griff-Zug kann je nach Last in zwei Schritten ankommen): bis das alte Mass wieder steht.
|
||||
await blurFocus(page);
|
||||
for (let i = 0; i < 3 && !(await numbers(page)).includes("6.00"); i++) {
|
||||
await page.keyboard.press("ControlOrMeta+z");
|
||||
await page.waitForTimeout(300);
|
||||
}
|
||||
await expect.poll(() => numbers(page)).toContain("6.00");
|
||||
});
|
||||
@@ -20,6 +20,9 @@ pub struct WallIn {
|
||||
pub start: Vec2,
|
||||
pub end: Vec2,
|
||||
pub thickness: f64,
|
||||
/// Versatz der Wandmitte von der Achse (links der Laufrichtung positiv): Wände mit Referenzlinie
|
||||
/// links/rechts oder -versatz liegen nicht mittig auf ihrer Achse.
|
||||
pub shift: f64,
|
||||
}
|
||||
|
||||
/// Öffnung: Index der Wirtswand in der Wandliste, Leibungspunkte auf der Achse.
|
||||
@@ -66,8 +69,9 @@ fn wall_rect(w: &WallIn, t: f64, ext_start: f64, ext_end: f64) -> Ring {
|
||||
let len = dx.hypot(dy);
|
||||
let (ux, uy) = (dx / len, dy / len);
|
||||
let (nx, ny) = (-uy * (t / 2.0), ux * (t / 2.0));
|
||||
let a = [w.start[0] - ux * ext_start, w.start[1] - uy * ext_start];
|
||||
let b = [w.end[0] + ux * ext_end, w.end[1] + uy * ext_end];
|
||||
let sh = if w.shift.is_finite() { w.shift } else { 0.0 };
|
||||
let a = [w.start[0] - ux * ext_start - uy * sh, w.start[1] - uy * ext_start + ux * sh];
|
||||
let b = [w.end[0] + ux * ext_end - uy * sh, w.end[1] + uy * ext_end + ux * sh];
|
||||
vec![[a[0] + nx, a[1] + ny], [b[0] + nx, b[1] + ny], [b[0] - nx, b[1] - ny], [a[0] - nx, a[1] - ny]]
|
||||
}
|
||||
|
||||
@@ -185,7 +189,8 @@ pub fn auto_exterior_dimensions(walls: &[WallIn], openings: &[OpeningIn], scale_
|
||||
continue; // Wand quer zu n
|
||||
}
|
||||
let t = if w.thickness.is_finite() && w.thickness > 0.0 { w.thickness } else { 0.3 };
|
||||
let outer_s = dot(w.start, n) + t / 2.0;
|
||||
let left = [-dy / len, dx / len];
|
||||
let outer_s = dot(w.start, n) + (if w.shift.is_finite() { w.shift } else { 0.0 }) * dot(left, n) + t / 2.0;
|
||||
let (ja, jb) = (dot(o.jamb_start, u), dot(o.jamb_end, u));
|
||||
if !ja.is_finite() || !jb.is_finite() {
|
||||
continue;
|
||||
@@ -239,7 +244,7 @@ mod tests {
|
||||
/// L-förmiger Grundriss aus 0.3-m-Wänden (Achsen).
|
||||
fn l_walls() -> Vec<WallIn> {
|
||||
let axis = [[0.0, 0.0], [10.0, 0.0], [10.0, 6.0], [4.0, 6.0], [4.0, 9.0], [0.0, 9.0]];
|
||||
(0..axis.len()).map(|i| WallIn { start: axis[i], end: axis[(i + 1) % axis.len()], thickness: 0.3 }).collect()
|
||||
(0..axis.len()).map(|i| WallIn { start: axis[i], end: axis[(i + 1) % axis.len()], thickness: 0.3, shift: 0.0 }).collect()
|
||||
}
|
||||
fn lengths(pts: &[Vec2]) -> Vec<f64> {
|
||||
pts.windows(2).map(|w| (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1])).collect()
|
||||
@@ -285,17 +290,36 @@ mod tests {
|
||||
assert!((south.offset - 1.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
/// Wand mit Referenzlinie links: die Achse liegt an der Innenkante, die Aussenmasse stimmen trotzdem.
|
||||
#[test]
|
||||
fn nicht_mittige_wand_misst_die_echte_flaeche() {
|
||||
// Achse y = 0, Körper y 0 … 0.3 (shift +0.15), Öffnung 1 … 2 m.
|
||||
let w = [WallIn { start: [0.0, 0.0], end: [5.0, 0.0], thickness: 0.3, shift: 0.15 }];
|
||||
let o = OpeningIn { wall: 0, jamb_start: [1.0, 0.0], jamb_end: [2.0, 0.0] };
|
||||
let dims = auto_exterior_dimensions(&w, &[o], 100.0);
|
||||
let south = dims.iter().find(|d| d.side == 0 && d.chain == CHAIN_TOTAL).unwrap();
|
||||
let north = dims.iter().find(|d| d.side == 2 && d.chain == CHAIN_TOTAL).unwrap();
|
||||
// Masslinie Süd liegt 1.0 m (1:100) vor der Südfläche y = 0; Nord vor y = 0.3.
|
||||
let south_y = south.pts[0][1] - south.offset * 1.0 * 0.0;
|
||||
assert!((south_y - 0.0).abs() < 1e-6 || (south_y - 0.3).abs() < 1e-6, "{south_y}");
|
||||
assert!((north.pts[0][1] - 0.3).abs() < 1e-6, "{:?}", north.pts);
|
||||
assert!((south.pts[0][1] - 0.0).abs() < 1e-6, "{:?}", south.pts);
|
||||
// Leibungen der Öffnung hängen an der Nordfläche (y = 0.3), nicht an y = 0.15.
|
||||
let op = dims.iter().find(|d| d.side == 2 && d.chain == CHAIN_OPENINGS).unwrap();
|
||||
assert!(op.src.iter().all(|q| (q[1] - 0.3).abs() < 1e-6), "{:?}", op.src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsinn_ohne_panik() {
|
||||
assert!(auto_exterior_dimensions(&[], &[], 100.0).is_empty());
|
||||
let bad = [
|
||||
WallIn { start: [f64::NAN, 0.0], end: [1.0, 0.0], thickness: 0.3 },
|
||||
WallIn { start: [0.0, 0.0], end: [0.0, 0.0], thickness: 0.3 },
|
||||
WallIn { start: [f64::NAN, 0.0], end: [1.0, 0.0], thickness: 0.3, shift: 0.0 },
|
||||
WallIn { start: [0.0, 0.0], end: [0.0, 0.0], thickness: 0.3, shift: 0.0 },
|
||||
];
|
||||
let o = OpeningIn { wall: 7, jamb_start: [0.0, 0.0], jamb_end: [1.0, 0.0] };
|
||||
assert!(auto_exterior_dimensions(&bad, &[o], f64::NAN).is_empty());
|
||||
// Dicke NaN → 0.3; Öffnung mit NaN-Leibung wird übergangen.
|
||||
let w = [WallIn { start: [0.0, 0.0], end: [5.0, 0.0], thickness: f64::NAN }];
|
||||
let w = [WallIn { start: [0.0, 0.0], end: [5.0, 0.0], thickness: f64::NAN, shift: 0.0 }];
|
||||
let o = OpeningIn { wall: 0, jamb_start: [f64::NAN, 0.0], jamb_end: [1.0, 0.0] };
|
||||
let dims = auto_exterior_dimensions(&w, &[o], 0.0);
|
||||
assert!(dims.iter().all(|d| d.chain != CHAIN_OPENINGS));
|
||||
|
||||
@@ -881,7 +881,7 @@ const PROFILE_HIT_TOL: f64 = 0.25;
|
||||
|
||||
/// Extrudierbares Profil einer Zeichnung: geschlossene Polylinie (≥ 3 Punkte), Rechteck, Kreis.
|
||||
/// Punkte als JSON-Werte (Polylinie: die gespeicherten), dazu `circle` beim Kreis.
|
||||
fn profile_of(d: &Value) -> Option<(Vec<Value>, Option<Value>)> {
|
||||
pub(crate) fn profile_of(d: &Value) -> Option<(Vec<Value>, Option<Value>)> {
|
||||
let g = field(d, "geom")?;
|
||||
match field(g, "shape").and_then(Value::as_str)? {
|
||||
"polyline" => {
|
||||
|
||||
@@ -961,6 +961,127 @@ fn dimension_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGe
|
||||
}
|
||||
}
|
||||
|
||||
// ── Achsraster ([112]) und Radius-/Bogenmass ([38]) ─────────────────────────
|
||||
|
||||
/// Geometrie des neuen Rasters: `at` (Ursprung), `xs`/`ys` (Feldweiten als Text), `radial`, `angle`
|
||||
/// (Bogenmass), optional `extend`, `bubbles`, `levels`. `None` bei unlesbaren Feldweiten.
|
||||
fn grid_geom(v: &Value) -> Option<Value> {
|
||||
let radial = b_of(v, "radial");
|
||||
let xs = crate::grid::parse_bays(s_of(v, "xs"))?;
|
||||
let ys = crate::grid::parse_bays(s_of(v, "ys")).or_else(|| (!radial).then(Vec::new).filter(|_| s_of(v, "ys").trim().is_empty()))?;
|
||||
let (a, b) = crate::grid::axes_from_bays(radial, &xs, &ys);
|
||||
let list = |l: &[crate::model::GridAxis]| Value::Array(l.iter().map(|x| obj(vec![("label", s(&x.label)), ("pos", js_num(x.pos))])).collect());
|
||||
let mut f = vec![("shape", s("grid")), ("origin", pt_val(v, "at")), ("angle", js_num(opt_n(v, "angle").unwrap_or(0.0))), ("a", list(&a)), ("b", list(&b))];
|
||||
if radial {
|
||||
f.push(("radial", Value::Bool(true)));
|
||||
}
|
||||
for k in ["extend", "bubbleMm"] {
|
||||
if let Some(x) = opt_n(v, k) {
|
||||
f.push((k, js_num(x)));
|
||||
}
|
||||
}
|
||||
if matches!(s_of(v, "bubbles"), "start" | "end" | "both") {
|
||||
f.push(("bubbles", s(s_of(v, "bubbles"))));
|
||||
}
|
||||
if let Some(l) = v.get("levels").filter(|l| l.as_array().is_some_and(|a| !a.is_empty())) {
|
||||
f.push(("levels", l.clone()));
|
||||
}
|
||||
Some(obj(f))
|
||||
}
|
||||
|
||||
/// Vorschau des Rasters am Cursor: Achsen als Linien, Ringe als Polygonzug.
|
||||
fn grid_preview(v: &Value, pts: &[V], p: &mut Preview) {
|
||||
let Some(at) = pts.first() else { return };
|
||||
let mut v2 = v.clone();
|
||||
v2["at"] = pv(*at);
|
||||
let Some(g) = grid_geom(&v2).and_then(|g| serde_json::from_value::<crate::model::Drawing2DGeom>(g).ok()) else { return };
|
||||
let Some(spec) = crate::grid::Spec::of(&g) else { return };
|
||||
p.ok = true;
|
||||
for ax in spec.axes() {
|
||||
match ax.shape {
|
||||
crate::grid::Shape::Line { a, b } => p.shapes.line(a, b),
|
||||
crate::grid::Shape::Arc { c, r, a0, a1 } => {
|
||||
let n = (((a1 - a0).abs() / (PI / 24.0)).ceil() as usize).clamp(2, 400);
|
||||
let q: Vec<V> = (0..=n).map(|i| a0 + (a1 - a0) * i as f64 / n as f64).map(|t| (c.0 + r * jsnum::cos(t), c.1 + r * jsnum::sin(t))).collect();
|
||||
p.shapes.poly_open(&q);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dim_kind(v: &Value) -> Option<crate::model::DimKind> {
|
||||
use crate::model::DimKind;
|
||||
match s_of(v, "kind") {
|
||||
"radius" => Some(DimKind::Radius),
|
||||
"diameter" => Some(DimKind::Diameter),
|
||||
"arc" => Some(DimKind::Arc),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Toleranz beim Treffen eines Kreises/Bogens (Modell-Meter, `tol` der Anfrage).
|
||||
fn round_tol(v: &Value) -> f64 {
|
||||
opt_n(v, "tol").filter(|t| *t > 0.0).unwrap_or(0.15)
|
||||
}
|
||||
|
||||
/// Radius-/Durchmesser-/Bogenlängen-Mass: Klicks auf dem Rand eines Kreises, Bogens oder einer
|
||||
/// Bogenwand; Mittelpunkt und Randpunkte hängen daran (`refs`). Bogenlänge: `side` (Punkt der
|
||||
/// Masslinie) oder `offset` bestimmt den Abstand vom Bogen.
|
||||
fn dimround_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
use crate::model::DimKind;
|
||||
let Some(kind) = dim_kind(v) else { return Vec::new() };
|
||||
let clicks: Vec<V> = arr(v.get("pts")).iter().map(pair).collect();
|
||||
let lk = crate::document::Lookup::plain(root);
|
||||
let Some((pts, refs)) = crate::dim_assoc::round_dimension(&lk, ctx.level, kind, &clicks, round_tol(v)) else { return Vec::new() };
|
||||
let offset = match (kind, opt_p(v, "side")) {
|
||||
(DimKind::Arc, Some(side)) => hypot2(side.0 - pts[0].0, side.1 - pts[0].1) - hypot2(pts[1].0 - pts[0].0, pts[1].1 - pts[0].1),
|
||||
(DimKind::Arc, None) => opt_n(v, "offset").unwrap_or(0.5),
|
||||
_ => 0.0,
|
||||
};
|
||||
let kind_s = match kind {
|
||||
DimKind::Radius => "radius",
|
||||
DimKind::Diameter => "diameter",
|
||||
DimKind::Arc => "arc",
|
||||
};
|
||||
let geom = obj(vec![
|
||||
("shape", s("dimension")),
|
||||
("pts", pvs(&pts)),
|
||||
("offset", js_num(offset)),
|
||||
("kind", s(kind_s)),
|
||||
("refs", serde_json::to_value(refs).unwrap_or(Value::Null)),
|
||||
]);
|
||||
add_drawing(v, ctx, ids, geom)
|
||||
}
|
||||
|
||||
/// Vorschau: Radius-/Durchmesserlinie bzw. Bogen zwischen den Klicks (Cursor = letzter Punkt).
|
||||
fn dimround_preview(root: &Map<String, Value>, v: &Value, ctx: &Ctx, pts: &[V], p: &mut Preview) {
|
||||
use crate::model::DimKind;
|
||||
let Some(kind) = dim_kind(v) else { return };
|
||||
let lk = crate::document::Lookup::plain(root);
|
||||
let tol = round_tol(v);
|
||||
let arc_phase = kind == DimKind::Arc;
|
||||
// Klickpunkte: bei der Bogenlänge die ersten zwei (Cursor als zweiter, solange er läuft).
|
||||
let clicks: Vec<V> = if arc_phase { pts.iter().take(2).copied().collect() } else { pts.iter().take(1).copied().collect() };
|
||||
let Some((q, _)) = crate::dim_assoc::round_dimension(&lk, ctx.level, kind, &clicks, tol).or_else(|| crate::dim_assoc::round_dimension(&lk, ctx.level, kind, &clicks[..1], tol).filter(|_| arc_phase)) else { return };
|
||||
p.ok = true;
|
||||
let c = q[0];
|
||||
match kind {
|
||||
DimKind::Radius => p.shapes.line(c, q[1]),
|
||||
DimKind::Diameter => p.shapes.line((2.0 * c.0 - q[1].0, 2.0 * c.1 - q[1].1), q[1]),
|
||||
DimKind::Arc => {
|
||||
let r = hypot2(q[1].0 - c.0, q[1].1 - c.1);
|
||||
let a0 = angle(c, q[1]);
|
||||
let a1 = if q.len() > 2 { angle(c, q[2]) } else { a0 };
|
||||
let sweep = (a1 - a0).rem_euclid(TAU);
|
||||
let off = pts.get(2).map_or(0.0, |s| hypot2(s.0 - c.0, s.1 - c.1) - r);
|
||||
let n = ((sweep / (PI / 24.0)).ceil() as usize).clamp(1, 400);
|
||||
let poly: Vec<V> = (0..=n).map(|i| a0 + sweep * i as f64 / n as f64).map(|t| (c.0 + (r + off) * jsnum::cos(t), c.1 + (r + off) * jsnum::sin(t))).collect();
|
||||
p.shapes.poly_open(&poly);
|
||||
p.info.push(r * sweep);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bemassungs-Vorschau. `phase` next: `pts` = Kette + roher Cursor → Kette bis zum (auf die Masslinie
|
||||
/// projizierten) Cursor, `info = [cx, cy]`; offset: `pts` = Kette + Cursor (oder ohne → Abstand 0),
|
||||
/// Hilfs- und Masslinien, `info = [Abstand, Summe]`.
|
||||
@@ -1016,7 +1137,15 @@ fn auto_dims(root: &Map<String, Value>, ctx: &Ctx, prefix: &str, scale: f64) ->
|
||||
let tid = field(w, "wallTypeId").and_then(Value::as_str);
|
||||
let th = types.iter().find(|t| id_of(t) == tid).map_or(0.3, type_thickness);
|
||||
let (a, b) = (p(w, "start"), p(w, "end"));
|
||||
WallIn { start: [a.0, a.1], end: [b.0, b.1], thickness: th }
|
||||
// Wandmitte gegenüber der Achse (Referenzlinie links/rechts bzw. -versatz, wie `dim_assoc`).
|
||||
let half = th / 2.0;
|
||||
let shift = match (field(w, "referenceOffset").and_then(Value::as_f64), field(w, "referenceLine").and_then(Value::as_str)) {
|
||||
(Some(v), _) => v.clamp(-half, half),
|
||||
(None, Some("left")) => half,
|
||||
(None, Some("right")) => -half,
|
||||
_ => 0.0,
|
||||
};
|
||||
WallIn { start: [a.0, a.1], end: [b.0, b.1], thickness: th, shift }
|
||||
})
|
||||
.collect();
|
||||
let mut oin = Vec::new();
|
||||
@@ -1154,6 +1283,11 @@ pub fn ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) ->
|
||||
),
|
||||
"pointmarker" => add_drawing(v, ctx, ids, obj(vec![("shape", s("pointmarker")), ("at", pt_val(v, "at"))])),
|
||||
"block" => block_ops(v, ctx, ids),
|
||||
"grid" => match grid_geom(v) {
|
||||
Some(g) => add_drawing(v, ctx, ids, g),
|
||||
None => Vec::new(),
|
||||
},
|
||||
"dimround" => dimround_ops(root, v, ctx, ids),
|
||||
"dimension" => dimension_ops(root, v, ctx, ids),
|
||||
"autodim" => autodim_ops(root, ctx),
|
||||
_ => return None,
|
||||
@@ -1227,6 +1361,8 @@ pub fn preview(root: &Map<String, Value>, v: &Value, ctx: &Ctx, pts: &[V], p: &m
|
||||
}
|
||||
}
|
||||
"dimension" => dimension_preview(v, pts, p),
|
||||
"grid" => grid_preview(v, pts, p),
|
||||
"dimround" => dimround_preview(root, v, ctx, pts, p),
|
||||
"autodim" => p.ok = !auto_dims(root, ctx, "autodim", 100.0).is_empty(),
|
||||
_ => return false,
|
||||
}
|
||||
@@ -1282,6 +1418,52 @@ mod tests {
|
||||
assert!((at.1 - (0.0 - 0.0035)).abs() < 1e-12);
|
||||
}
|
||||
|
||||
/// [112] Befehl „Achsraster": Feldweiten als Text → Achsen 1, 2, 3 / A, B …; unlesbar → nichts.
|
||||
#[test]
|
||||
fn achsraster_befehl() {
|
||||
let v = json!({"cmd": "grid", "at": {"x": 1, "y": 2}, "xs": "5 3x6", "ys": "4,5 4", "angle": 0, "bubbles": "end", "levels": ["L"]});
|
||||
let o = ops(&Map::new(), &v, &ctx(), &mut IdGen::new("s")).unwrap();
|
||||
let g = &o[0].to_json()["items"][0]["geom"];
|
||||
assert_eq!(g["shape"], "grid");
|
||||
assert_eq!(g["a"].as_array().unwrap().len(), 5);
|
||||
assert_eq!(g["a"][4]["pos"], 23);
|
||||
assert_eq!(g["b"][2]["label"], "C");
|
||||
assert_eq!(g["b"][2]["pos"], 8.5);
|
||||
assert_eq!(g["bubbles"], "end");
|
||||
assert_eq!(g["origin"]["x"], 1);
|
||||
assert!(serde_json::from_value::<crate::model::Drawing2DGeom>(g.clone()).is_ok());
|
||||
// Ohne `angle` (Befehl aus der Hülle) gilt 0; leere Querachsen sind erlaubt.
|
||||
let bare = json!({"cmd": "grid", "at": [0, 0], "xs": "5", "ys": ""});
|
||||
let o2 = ops(&Map::new(), &bare, &ctx(), &mut IdGen::new("s")).unwrap();
|
||||
assert_eq!(o2[0].to_json()["items"][0]["geom"]["angle"], 0);
|
||||
let bad = json!({"cmd": "grid", "at": {"x": 0, "y": 0}, "xs": "x", "ys": ""});
|
||||
assert!(ops(&Map::new(), &bad, &ctx(), &mut IdGen::new("s")).unwrap().is_empty());
|
||||
// Vorschau am Cursor.
|
||||
let mut p = Preview { shapes: Shapes::default(), ok: false, info: vec![] };
|
||||
grid_preview(&v, &[(0.0, 0.0)], &mut p);
|
||||
assert!(p.ok && !p.shapes.buf.is_empty());
|
||||
}
|
||||
|
||||
/// [38] Befehl Radius/Bogenmass: trifft den Kreis, hängt Mittelpunkt und Rand an.
|
||||
#[test]
|
||||
fn rundmass_befehl() {
|
||||
let root = json!({"drawings2d": [{"id": "K", "levelId": "L", "categoryCode": "20", "geom": {"shape": "circle", "center": {"x": 1, "y": 1}, "r": 2}}]});
|
||||
let root = root.as_object().unwrap().clone();
|
||||
let v = json!({"cmd": "dimround", "kind": "diameter", "pts": [[3.01, 1.0]]});
|
||||
let o = ops(&root, &v, &ctx(), &mut IdGen::new("s")).unwrap();
|
||||
let g = &o[0].to_json()["items"][0]["geom"];
|
||||
assert_eq!(g["kind"], "diameter");
|
||||
assert_eq!(g["refs"][0]["feature"], "center");
|
||||
assert_eq!(g["refs"][1]["feature"], "rim");
|
||||
let v = json!({"cmd": "dimround", "kind": "arc", "pts": [[3.0, 1.0], [1.0, 3.0]], "side": [1.0, 4.0]});
|
||||
let g = &ops(&root, &v, &ctx(), &mut IdGen::new("s")).unwrap()[0].to_json()["items"][0]["geom"];
|
||||
assert_eq!(g["pts"].as_array().unwrap().len(), 3);
|
||||
assert!((g["offset"].as_f64().unwrap() - 1.0).abs() < 1e-9);
|
||||
// Kein Kreis in der Nähe → nichts.
|
||||
let far = json!({"cmd": "dimround", "kind": "radius", "pts": [[50.0, 50.0]]});
|
||||
assert!(ops(&root, &far, &ctx(), &mut IdGen::new("s")).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revisionswolke_beulen() {
|
||||
assert!(revision_cloud(&[(0.0, 0.0)], false, 0.3).is_none());
|
||||
|
||||
@@ -733,6 +733,7 @@ fn map_points(g: &Value, f: &dyn Fn(P) -> P) -> Value {
|
||||
"rect" | "image" => with_all(g, vec![("min", m("min")), ("max", m("max"))]),
|
||||
"circle" | "arc" | "ellipse" => with(g, "center", m("center")),
|
||||
"text" | "kote" | "detailref" | "scalebar" | "pointmarker" | "block" => with(g, "at", m("at")),
|
||||
"grid" => with(g, "origin", m("origin")),
|
||||
_ => g.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
+259
-30
@@ -150,6 +150,130 @@ pub fn solid_from_inputs(shape: &str, p0: V, p1: Option<V>, nums: &[f64]) -> Opt
|
||||
}
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// Rotationskörper und Loft aus Plan-Profilen ([T7])
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/// Rotationskörper: das Plan-Profil (geschlossen, in der Zeichenebene) dreht sich um die Achse
|
||||
/// `a → b` (liegt waagrecht im Plan, auf Höhe des grössten Profilabstands, damit ein voller Körper auf
|
||||
/// der Geschoss-UK steht). Das Profil muss ganz auf einer Seite der Achse liegen; es wird als
|
||||
/// (r = Abstand, z = Lage entlang der Achse) an `revolve` von truck gegeben und per `transform` ins
|
||||
/// Modell gesetzt (lokal x → Querrichtung, y → oben, z → Achse). `angle_deg` in (0, 360]; positive
|
||||
/// Drehung hebt das Profil nach oben. Ergebnis: Grundriss-Rechteck, Höhe, B-Rep-Beschreibung, Label.
|
||||
pub fn revolve_from_profile(profile: &[V], a: V, b: V, angle_deg: f64) -> Option<(Vec<V>, f64, Value, String)> {
|
||||
let len = hypot2(b.0 - a.0, b.1 - a.1);
|
||||
if profile.len() < 3 || !(len > 1e-6) || !angle_deg.is_finite() || !(angle_deg > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let mut d = ((b.0 - a.0) / len, (b.1 - a.1) / len);
|
||||
let side = |d: V, p: V| (p.0 - a.0) * -d.1 + (p.1 - a.1) * d.0;
|
||||
let (lo, hi) = profile.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(side(d, *p)), hi.max(side(d, *p))));
|
||||
if !(lo.is_finite() && hi.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
if lo < -1e-6 {
|
||||
if hi > 1e-6 {
|
||||
return None; // Profil überquert die Achse
|
||||
}
|
||||
d = (-d.0, -d.1); // Profil liegt rechts: Achse umdrehen, damit r >= 0
|
||||
}
|
||||
let n = (-d.1, d.0);
|
||||
let ring: Vec<(f64, f64)> = profile.iter().map(|p| (side(d, *p).max(0.0), (p.0 - a.0) * d.0 + (p.1 - a.1) * d.1)).collect();
|
||||
let r_max = ring.iter().fold(0.0_f64, |m, q| m.max(q.0));
|
||||
if !(r_max > 1e-6) {
|
||||
return None;
|
||||
}
|
||||
let (z_min, z_max) = ring.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), q| (lo.min(q.1), hi.max(q.1)));
|
||||
if !(z_max - z_min > 1e-6) {
|
||||
return None;
|
||||
}
|
||||
let angle = angle_deg.min(360.0);
|
||||
let flat: Vec<Value> = ring.iter().flat_map(|q| [js_num(q.0), js_num(q.1)]).collect();
|
||||
let inner = obj(vec![("kind", s("revolve")), ("profile", Value::Array(flat)), ("angleDeg", js_num(angle))]);
|
||||
let m = [n.0, 0.0, d.0, a.0, n.1, 0.0, d.1, a.1, 0.0, 1.0, 0.0, r_max];
|
||||
let spec = obj(vec![("kind", s("transform")), ("m", Value::Array(m.iter().map(|x| js_num(*x)).collect())), ("solid", inner)]);
|
||||
let at = |along: f64, perp: f64| (a.0 + d.0 * along + n.0 * perp, a.1 + d.1 * along + n.1 * perp);
|
||||
let pts = vec![at(z_min, -r_max), at(z_max, -r_max), at(z_max, r_max), at(z_min, r_max)];
|
||||
Some((pts, 2.0 * r_max, spec, format!("Rotationskörper {}°", fixed2(angle))))
|
||||
}
|
||||
|
||||
fn ring_area(r: &[V]) -> f64 {
|
||||
let n = r.len();
|
||||
(0..n).map(|i| r[i].0 * r[(i + 1) % n].1 - r[(i + 1) % n].0 * r[i].1).sum::<f64>() / 2.0
|
||||
}
|
||||
|
||||
/// Gleiche Punktzahl für alle Ringe: kürzere Ringe teilen ihre längste Kante, bis sie so viele Punkte
|
||||
/// haben wie der längste (Ecken bleiben erhalten); alle gegen den Uhrzeigersinn.
|
||||
fn match_rings(rings: &[Vec<V>]) -> Vec<Vec<V>> {
|
||||
let target = rings.iter().map(Vec::len).max().unwrap_or(0);
|
||||
rings
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let mut r = r.clone();
|
||||
if ring_area(&r) < 0.0 {
|
||||
r.reverse();
|
||||
}
|
||||
while r.len() < target {
|
||||
let n = r.len();
|
||||
let len = |k: usize| hypot2(r[(k + 1) % n].0 - r[k].0, r[(k + 1) % n].1 - r[k].1);
|
||||
let Some(i) = (0..n).max_by(|&i, &j| len(i).partial_cmp(&len(j)).unwrap_or(std::cmp::Ordering::Equal)) else { break };
|
||||
let (p, q) = (r[i], r[(i + 1) % n]);
|
||||
r.insert(i + 1, ((p.0 + q.0) / 2.0, (p.1 + q.1) / 2.0));
|
||||
}
|
||||
r
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Loft durch >= 2 Plan-Profile, gleichmässig über `height` verteilt (erstes Profil unten).
|
||||
pub fn loft_from_rings(rings: &[Vec<V>], height: f64) -> Option<(Vec<V>, f64, Value, String)> {
|
||||
if rings.len() < 2 || !(height > 1e-6) || rings.iter().any(|r| r.len() < 3 || r.iter().any(|p| !(p.0.is_finite() && p.1.is_finite()))) {
|
||||
return None;
|
||||
}
|
||||
let rings = match_rings(rings);
|
||||
let last = (rings.len() - 1) as f64;
|
||||
let sections: Vec<Value> = rings
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, r)| obj(vec![("z", js_num(height * i as f64 / last)), ("points", Value::Array(r.iter().flat_map(|p| [js_num(p.0), js_num(p.1)]).collect()))]))
|
||||
.collect();
|
||||
let spec = obj(vec![("kind", s("loft")), ("sections", Value::Array(sections))]);
|
||||
Some((rings[0].clone(), height, spec, format!("Loft {} Profile h={}", rings.len(), fixed2(height))))
|
||||
}
|
||||
|
||||
fn profile_ring(root: &Map<String, Value>, id: &str) -> Option<Vec<V>> {
|
||||
let (pts, _) = find(root, "drawings2d", id).and_then(crate::cmd_create::profile_of)?;
|
||||
Some(pts.iter().map(xy).collect())
|
||||
}
|
||||
|
||||
fn brep_solid_ops(root: &Map<String, Value>, ctx: &Ctx, ids: &mut IdGen, sources: &[&str], made: Option<(Vec<V>, f64, Value, String)>) -> Vec<Op> {
|
||||
let Some((pts, height, spec, label)) = made else { return Vec::new() };
|
||||
let solid = obj(vec![
|
||||
("id", s(&ids.next("body"))),
|
||||
("type", s("extrudedSolid")),
|
||||
("levelId", s(ctx.level)),
|
||||
("points", pvs(&pts)),
|
||||
("height", js_num(height)),
|
||||
("brep", obj(vec![("spec", spec), ("origin", pv(pts[0])), ("label", s(&label))])),
|
||||
]);
|
||||
let mut ops = crate::cmd_create::remove_op(root, "drawings2d", sources);
|
||||
ops.extend(add_op("extrudedSolids", vec![solid]));
|
||||
ops
|
||||
}
|
||||
|
||||
fn revolve_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
let src = s_of(v, "source");
|
||||
let made = profile_ring(root, src).and_then(|ring| revolve_from_profile(&ring, p_of(v, "a"), p_of(v, "b"), num_or(field(v, "angle"), 360.0)));
|
||||
brep_solid_ops(root, ctx, ids, &[src], made)
|
||||
}
|
||||
|
||||
fn loft_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
let sources: Vec<&str> = arr(v.get("sources")).iter().filter_map(Value::as_str).collect();
|
||||
let rings: Option<Vec<Vec<V>>> = sources.iter().map(|id| profile_ring(root, id)).collect();
|
||||
let made = rings.and_then(|r| loft_from_rings(&r, n_of(v, "height")));
|
||||
brep_solid_ops(root, ctx, ids, &sources, made)
|
||||
}
|
||||
|
||||
fn solid_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
let nums: Vec<f64> = arr(v.get("nums")).iter().map(|x| num_of(Some(x))).collect();
|
||||
let Some((pts, height, spec, label)) = solid_from_inputs(s_of(v, "shape"), p_of(v, "p0"), opt_p(v, "p1"), &nums) else {
|
||||
@@ -327,46 +451,70 @@ fn voidbox_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
/// Gelände-TIN aus Höhenlinien (`generateTerrainFromContours`): alle endlichen Stützpunkte, Delaunay
|
||||
/// über (x, y), Höhe der Kontur je Punkt; Null-Flächen-Dreiecke verworfen.
|
||||
pub fn terrain_from_contours(contours: &[Value], id: &str) -> Value {
|
||||
let (mut xs, mut ys, mut zs) = (Vec::new(), Vec::new(), Vec::new());
|
||||
for c in contours {
|
||||
let z = num_of(field(c, "z"));
|
||||
let z = if z.is_finite() { z } else { 0.0 };
|
||||
for p in arr(field(c, "pts")) {
|
||||
let (x, y) = xy(p);
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
continue;
|
||||
terrain_from_contours_with(contours, id, crate::terrain::TerrainOpts::default())
|
||||
}
|
||||
|
||||
/// Gelände aus Höhenlinien ([T6], `terrain.rs`): Konturen als Bruchkanten (constrained Delaunay),
|
||||
/// flache Dreiecke behoben, adaptiv geglättet (ohne Überschwingen). Äquidistanz der Plan-Höhenlinien =
|
||||
/// kleinster Höhenabstand der Konturen. Unter drei Punkten ein leeres Netz.
|
||||
pub fn terrain_from_contours_with(contours: &[Value], id: &str, o: crate::terrain::TerrainOpts) -> Value {
|
||||
let cs: Vec<crate::terrain::ContourIn> = contours
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let z = num_of(field(c, "z"));
|
||||
crate::terrain::ContourIn {
|
||||
z: if z.is_finite() { z } else { 0.0 },
|
||||
pts: arr(field(c, "pts")).iter().map(xy).filter(|p| p.0.is_finite() && p.1.is_finite()).map(|p| [p.0, p.1]).collect(),
|
||||
closed: truthy(field(c, "closed")),
|
||||
}
|
||||
xs.push(x);
|
||||
ys.push(y);
|
||||
zs.push(z);
|
||||
}
|
||||
}
|
||||
if xs.len() < 3 {
|
||||
})
|
||||
.collect();
|
||||
let t = crate::terrain::terrain_from_contours(&cs, &[], o);
|
||||
if t.tris.is_empty() {
|
||||
return json!({ "id": id, "type": "terrainMesh", "name": "Gelände", "categoryCode": "02", "positions": [], "indices": [] });
|
||||
}
|
||||
let coords: Vec<f64> = xs.iter().zip(&ys).flat_map(|(x, y)| [*x, *y]).collect();
|
||||
let tri = crate::delaunay::triangulate(&coords);
|
||||
let positions: Vec<Value> = (0..xs.len()).flat_map(|i| [js_num(xs[i]), js_num(ys[i]), js_num(zs[i])]).collect();
|
||||
let mut indices = Vec::new();
|
||||
for t in tri.chunks_exact(3) {
|
||||
let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize);
|
||||
let area2 = ((xs[b] - xs[a]) * (ys[c] - ys[a]) - (xs[c] - xs[a]) * (ys[b] - ys[a])).abs();
|
||||
if area2 <= 1e-9 {
|
||||
continue;
|
||||
}
|
||||
indices.extend([Value::from(t[0]), Value::from(t[1]), Value::from(t[2])]);
|
||||
}
|
||||
let (pos, idx) = t.to_flat(0.0);
|
||||
let iv = crate::terrain::interval_of(&cs.iter().map(|c| c.z).collect::<Vec<_>>());
|
||||
obj(vec![
|
||||
("id", s(id)),
|
||||
("type", s("terrainMesh")),
|
||||
("name", s("Gelände")),
|
||||
("layer", s("Terrain")),
|
||||
("categoryCode", s("02")),
|
||||
("positions", Value::Array(positions)),
|
||||
("indices", Value::Array(indices)),
|
||||
("positions", Value::Array(pos.into_iter().map(js_num).collect())),
|
||||
("indices", Value::Array(idx.into_iter().map(Value::from).collect())),
|
||||
("contourInterval", js_num(iv)),
|
||||
])
|
||||
}
|
||||
|
||||
/// [68] Baugrube aus dem gezeichneten Umriss (≥ 3 Punkte; 2 Punkte = Rechteck). Sohle = Geschoss-
|
||||
/// Unterkante − 0.30 m (Magerbeton + Bodenplatte), Böschung 45°.
|
||||
fn excavation_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
let mut pts: Vec<V> = pts_of(v, "pts").into_iter().filter(|p| p.0.is_finite() && p.1.is_finite()).collect();
|
||||
if pts.len() == 2 {
|
||||
pts = rect_corners(pts[0], pts[1]).to_vec();
|
||||
}
|
||||
let area2: f64 = (0..pts.len()).map(|i| pts[i].0 * pts[(i + 1) % pts.len()].1 - pts[(i + 1) % pts.len()].0 * pts[i].1).sum();
|
||||
if pts.len() < 3 || area2.abs() < 0.02 {
|
||||
return Vec::new();
|
||||
}
|
||||
let base = arr(root.get("floors")).iter().find(|f| field(f, "id").and_then(Value::as_str) == Some(ctx.level)).map_or(0.0, |f| num_or(field(f, "baseElevation"), 0.0));
|
||||
let n = arr(root.get("context")).iter().filter(|o| field(o, "type").and_then(Value::as_str) == Some("excavation")).count();
|
||||
add_op(
|
||||
"context",
|
||||
vec![obj(vec![
|
||||
("id", s(&ids.next("excavation"))),
|
||||
("type", s("excavation")),
|
||||
("name", s(&format!("Baugrube {}", n + 1))),
|
||||
("layer", s("Terrain")),
|
||||
("categoryCode", s("02")),
|
||||
("outline", pvs(&pts)),
|
||||
("bottom", js_num(base - 0.3)),
|
||||
("slope", js_num(crate::excavation::DEFAULT_SLOPE)),
|
||||
])],
|
||||
)
|
||||
}
|
||||
|
||||
fn terrain_ops(root: &Map<String, Value>, ids: &mut IdGen) -> Vec<Op> {
|
||||
let Some(set) = arr(root.get("context")).iter().find(|o| field(o, "type").and_then(Value::as_str) == Some("contourSet")) else {
|
||||
return Vec::new();
|
||||
@@ -621,9 +769,12 @@ fn direction_arrow(a: V, b: V, sign: f64, out: &mut Shapes) {
|
||||
pub fn ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Option<Vec<Op>> {
|
||||
Some(match s_of(v, "cmd") {
|
||||
"solid" => solid_ops(v, ctx, ids),
|
||||
"revolve" => revolve_ops(root, v, ctx, ids),
|
||||
"loft" => loft_ops(root, v, ctx, ids),
|
||||
"solidbool" => solidbool_ops(root, v, ids),
|
||||
"voidbox" => voidbox_ops(v, ctx, ids),
|
||||
"terrain" => terrain_ops(root, ids),
|
||||
"excavation" => excavation_ops(root, v, ctx, ids),
|
||||
"ceilingOpening" => ceiling_opening_ops(root, v, ctx),
|
||||
"roofHole" => roof_hole_ops(root, v, ctx),
|
||||
"roofWindow" => roof_window_ops(root, v, ctx, ids),
|
||||
@@ -741,11 +892,89 @@ mod tests {
|
||||
assert!(run("eg", 9.0).is_empty());
|
||||
}
|
||||
|
||||
/// [68] Baugrube: Umriss (2 Punkte = Rechteck), Sohle = Geschoss − 0.30, als Kontext-Objekt.
|
||||
#[test]
|
||||
fn baugrube_befehl() {
|
||||
let root = json!({"floors": [{"id": "ug", "baseElevation": -3.0}]});
|
||||
let root = root.as_object().unwrap();
|
||||
let run = |pts: Value| {
|
||||
let mut ids = IdGen::new("s");
|
||||
let ctx = Ctx { level: "ug", floor_height: None, cat: "", wall_type: "", text_height: 0.25, symbol: 1.0 };
|
||||
ops(root, &json!({"cmd": "excavation", "pts": pts}), &ctx, &mut ids).unwrap()
|
||||
};
|
||||
let o = run(json!([{"x": 0, "y": 0}, {"x": 10, "y": 8}]));
|
||||
let Op::Add { collection, items, .. } = &o[0] else { panic!() };
|
||||
assert_eq!(collection, "context");
|
||||
assert_eq!((items[0]["type"].as_str(), items[0]["bottom"].as_f64()), (Some("excavation"), Some(-3.3)));
|
||||
assert_eq!(items[0]["outline"].as_array().unwrap().len(), 4);
|
||||
assert!(run(json!([{"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 2, "y": 0}])).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gelaende_aus_hoehenlinien() {
|
||||
let c = json!([{"z": 1, "pts": [{"x": 0, "y": 0}, {"x": 4, "y": 0}]}, {"z": 2, "pts": [{"x": 0, "y": 3}, {"x": 4, "y": 3}]}]);
|
||||
let raw = terrain_from_contours_with(c.as_array().unwrap(), "t", crate::terrain::TerrainOpts { smooth: 0, max_edge: 100.0, breaklines: true });
|
||||
assert_eq!(raw["indices"].as_array().unwrap().len(), 6);
|
||||
assert_eq!(raw["positions"][2], 1);
|
||||
assert_eq!(raw["contourInterval"], 1);
|
||||
// Standard: verdichtet und geglättet, Höhen bleiben im Bereich der Konturen.
|
||||
let t = terrain_from_contours(c.as_array().unwrap(), "t");
|
||||
assert_eq!(t["indices"].as_array().unwrap().len(), 6);
|
||||
assert_eq!(t["positions"][2], 1);
|
||||
let pos = t["positions"].as_array().unwrap();
|
||||
assert!(t["indices"].as_array().unwrap().len() > 6);
|
||||
assert!(pos.iter().skip(2).step_by(3).all(|z| (1.0..=2.0).contains(&z.as_f64().unwrap())));
|
||||
assert!(terrain_from_contours(&[], "t")["indices"].as_array().unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// [T7] Rotationskörper: Achse waagrecht im Plan, Profil auf einer Seite, Matrix bildet lokal x → Quer, z → Achse ab.
|
||||
#[test]
|
||||
fn rotationskoerper_aus_profil() {
|
||||
let prof = [(0.0, 0.0), (2.0, 0.0), (2.0, 1.0), (0.0, 1.0)];
|
||||
let (pts, h, spec, label) = revolve_from_profile(&prof, (0.0, 0.0), (5.0, 0.0), 360.0).unwrap();
|
||||
assert_eq!(h, 2.0);
|
||||
assert_eq!(label, "Rotationskörper 360.00°");
|
||||
assert_eq!(spec["kind"], "transform");
|
||||
assert_eq!(spec["solid"]["profile"], json!([0, 0, 0, 2, 1, 2, 1, 0]));
|
||||
let m: Vec<f64> = spec["m"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
|
||||
let w = |l: [f64; 3]| [m[0] * l[0] + m[1] * l[1] + m[2] * l[2] + m[3], m[4] * l[0] + m[5] * l[1] + m[6] * l[2] + m[7], m[8] * l[0] + m[9] * l[1] + m[10] * l[2] + m[11]];
|
||||
assert_eq!(w([1.0, 0.0, 2.0]), [2.0, 1.0, 1.0]);
|
||||
assert_eq!(w([0.0, 1.0, 0.0]), [0.0, 0.0, 2.0]);
|
||||
assert_eq!(pts.len(), 4);
|
||||
let rechts = [(0.0, 0.0), (2.0, 0.0), (2.0, -1.0), (0.0, -1.0)];
|
||||
let (_, _, spec2, _) = revolve_from_profile(&rechts, (0.0, 0.0), (5.0, 0.0), 90.0).unwrap();
|
||||
assert_eq!(spec2["solid"]["angleDeg"], 90.0);
|
||||
assert!(revolve_from_profile(&[(0.0, -1.0), (2.0, -1.0), (2.0, 1.0), (0.0, 1.0)], (0.0, 0.0), (5.0, 0.0), 360.0).is_none());
|
||||
assert!(revolve_from_profile(&prof, (0.0, 0.0), (0.0, 0.0), 360.0).is_none());
|
||||
assert!(revolve_from_profile(&prof, (0.0, 0.0), (5.0, 0.0), f64::NAN).is_none());
|
||||
}
|
||||
|
||||
/// [T7] Loft: gleiche Punktzahl (Kante teilen), Höhen gleichmässig, Ringe gegen den Uhrzeigersinn.
|
||||
#[test]
|
||||
fn loft_aus_profilen() {
|
||||
let quad = vec![(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)];
|
||||
let tri_cw = vec![(0.5, 0.5), (0.5, 1.5), (1.5, 0.5)];
|
||||
let (pts, h, spec, label) = loft_from_rings(&[quad.clone(), tri_cw, quad.clone()], 3.0).unwrap();
|
||||
assert_eq!((pts.len(), h), (4, 3.0));
|
||||
assert_eq!(label, "Loft 3 Profile h=3.00");
|
||||
let secs = spec["sections"].as_array().unwrap();
|
||||
assert_eq!(secs.len(), 3);
|
||||
assert_eq!(secs[1]["z"], 1.5);
|
||||
assert!(secs.iter().all(|s| s["points"].as_array().unwrap().len() == 8));
|
||||
assert!(loft_from_rings(&[quad.clone()], 3.0).is_none());
|
||||
assert!(loft_from_rings(&[quad.clone(), quad], 0.0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_und_loft_befehle_legen_koerper_an_und_entfernen_quellen() {
|
||||
let d = |id: &str, pts: Value| json!({"id": id, "type": "drawing2d", "levelId": "eg", "geom": {"shape": "polyline", "closed": true, "pts": pts}});
|
||||
let sq = |x: f64, s: f64| json!([{"x": x, "y": 0}, {"x": x + s, "y": 0}, {"x": x + s, "y": s}, {"x": x, "y": s}]);
|
||||
let root = json!({"drawings2d": [d("A", sq(0.0, 2.0)), d("B", sq(10.0, 1.0))]});
|
||||
let root = root.as_object().unwrap();
|
||||
let ctx = Ctx { level: "eg", floor_height: None, cat: "", wall_type: "", text_height: 0.25, symbol: 1.0 };
|
||||
let mut ids = IdGen::new("t");
|
||||
let ops = loft_ops(root, &json!({"sources": ["A", "B"], "height": 2.0}), &ctx, &mut ids);
|
||||
assert_eq!(ops.len(), 2);
|
||||
let ops = revolve_ops(root, &json!({"source": "A", "a": {"x": -1, "y": -1}, "b": {"x": 5, "y": -1}, "angle": 180}), &ctx, &mut ids);
|
||||
assert_eq!(ops.len(), 2);
|
||||
assert!(revolve_ops(root, &json!({"source": "ZZ", "a": {"x": 0, "y": 0}, "b": {"x": 1, "y": 0}}), &ctx, &mut ids).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -166,6 +166,21 @@ pub fn mv_geom(g: &Value, xf: &Xf) -> Option<Value> {
|
||||
"circle" | "arc" | "ellipse" => with(g, "center", p("center")),
|
||||
"bezier" | "spline" | "dimension" => with(g, "pts", ps("pts")),
|
||||
"kote" | "detailref" | "scalebar" | "pointmarker" => with(g, "at", p("at")),
|
||||
"grid" => {
|
||||
// Ursprung und Richtung über einen mit abgebildeten Richtungspunkt; eine Spiegelung kehrt die
|
||||
// Querachsen um (rechtwinklig: Y-Lagen, radial: Strahlwinkel).
|
||||
let (ox, oy) = xy(field(g, "origin").unwrap_or(&Value::Null));
|
||||
let ang = num_of(field(g, "angle"));
|
||||
let no = xf.apply(ox, oy);
|
||||
let nt = xf.apply(ox + jsnum::cos(ang), oy + jsnum::sin(ang));
|
||||
let mut f = vec![("origin", pt(no.0, no.1)), ("angle", js_num(jsnum::atan2(nt.1 - no.1, nt.0 - no.0)))];
|
||||
if xf.reverses() {
|
||||
let key = if field(g, "radial").and_then(Value::as_bool) == Some(true) { "a" } else { "b" };
|
||||
let neg = Value::Array(arr(field(g, key)).iter().map(|x| with(x, "pos", js_num(-num_of(field(x, "pos"))))).collect());
|
||||
f.push((key, neg));
|
||||
}
|
||||
with_all(g, f)
|
||||
}
|
||||
"text" => {
|
||||
// Hinweis-Ziel, Knicke und Pfadpunkte wandern mit.
|
||||
let mut f = vec![("at", Some(p("at")))];
|
||||
@@ -205,6 +220,18 @@ pub fn scale_geom(g: &Value, xf: &Xf, k: f64) -> Option<Value> {
|
||||
"circle" | "arc" => with(&g, "r", times("r")),
|
||||
"ellipse" => with_all(&g, vec![("rx", times("rx")), ("ry", times("ry"))]),
|
||||
"dimension" => with(&g, "offset", times("offset")),
|
||||
"grid" => {
|
||||
let scaled = |key: &str| Value::Array(arr(field(&g, key)).iter().map(|x| with(x, "pos", js_num(num_of(field(x, "pos")) * k))).collect());
|
||||
let radial = field(&g, "radial").and_then(Value::as_bool) == Some(true);
|
||||
let mut f = vec![("b", scaled("b"))];
|
||||
if !radial {
|
||||
f.push(("a", scaled("a")));
|
||||
}
|
||||
if field(&g, "extend").is_some() {
|
||||
f.push(("extend", times("extend")));
|
||||
}
|
||||
with_all(&g, f)
|
||||
}
|
||||
"text" => {
|
||||
let mut f = vec![("height", times("height"))];
|
||||
if field(&g, "width").is_some() {
|
||||
|
||||
+402
-34
@@ -4,8 +4,12 @@
|
||||
//! - **Anhängen** ([`attach`]): ein gefangener Punkt wird über Deckungsgleichheit (Toleranz [`TOL`])
|
||||
//! einem Merkmal zugeordnet — Öffnungs-Leibung/-Mitte, Wandende, Wandecke (Schnitt zweier
|
||||
//! Wandlinien), Punkt auf Wandachse/Schichtgrenze, Stütze (Mitte, Ecken, Kanten), Decken-/Dach-/
|
||||
//! Raum-Umriss (Ecken, Kanten), 2D-Zeichnung (Eckpunkte, Mittelpunkte, Kanten). Bogenwände
|
||||
//! werden nicht angehängt. Freie Klicks decken sich praktisch nie und bleiben frei.
|
||||
//! Raum-Umriss (Ecken, Kanten), 2D-Zeichnung (Eckpunkte, Mittelpunkte, Kanten), Treppe (Umriss
|
||||
//! und Podest: Ecken, Kanten), Bogenwand (Enden, Punkt auf Achse/Fläche, Mittelpunkt), Rasterachse
|
||||
//! und Achsschnittpunkt ([112]). Freie Klicks decken sich praktisch nie und bleiben frei.
|
||||
//! - **Radius/Durchmesser/Bogenlänge** ([`refs_for_round`]): Mittelpunkt und Punkte auf dem Rand
|
||||
//! (`DimFeature::Rim`, Winkel) von 2D-Kreis, -Bogen oder Bogenwand; sie werden einzeln (ohne
|
||||
//! Kettenprojektion) nachgeführt.
|
||||
//! - **Nachführen** ([`sync_ops`]): nach jeder Benutzer-Änderung (`Document::commit`) löst der Kern
|
||||
//! die Bezüge auf und schreibt die Lage in `pts` zurück (dieselbe Undo-Stufe). Damit lesen alle
|
||||
//! Ableitungen (Plan, DXF, Griffe, Auswahl-Info) einfach `pts`, und `pts` ist immer die zuletzt
|
||||
@@ -78,6 +82,7 @@ struct WallGeo {
|
||||
offs: Vec<f64>,
|
||||
total: f64,
|
||||
arc: bool,
|
||||
warc: Option<crate::wall_arc::WallArc>,
|
||||
}
|
||||
|
||||
fn wall_geo(lk: &Lookup, w: &Value) -> Option<WallGeo> {
|
||||
@@ -106,16 +111,40 @@ fn wall_geo(lk: &Lookup, w: &Value) -> Option<WallGeo> {
|
||||
}
|
||||
}
|
||||
let arc = crate::wall_arc::is_arc_bulge(num(w.get("bulge")));
|
||||
Some(WallGeo { a, b, offs, total, arc })
|
||||
let warc = if arc { crate::wall_arc::WallArc::of(kernel2d::Vec2 { x: a.0, y: a.1 }, kernel2d::Vec2 { x: b.0, y: b.1 }, num(w.get("bulge"))) } else { None };
|
||||
Some(WallGeo { a, b, offs, total, arc, warc })
|
||||
}
|
||||
|
||||
impl WallGeo {
|
||||
/// Linie `index` (fehlt = Achse): Anfang und Ende.
|
||||
fn offset(&self, index: Option<u32>) -> Option<f64> {
|
||||
match index {
|
||||
None => Some(0.0),
|
||||
Some(k) => self.offs.get(k as usize).copied(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Punkt auf Linie `index` beim Anteil `t` (Bogenwand: entlang der Bogenlänge auf dem Versatzbogen).
|
||||
fn point(&self, index: Option<u32>, t: f64) -> Option<P> {
|
||||
let o = self.offset(index)?;
|
||||
match &self.warc {
|
||||
Some(w) => {
|
||||
let q = w.point(t * w.length(), o);
|
||||
Some((q.x, q.y))
|
||||
}
|
||||
None => {
|
||||
let (a, b) = self.line(index)?;
|
||||
Some(lerp(a, b, t))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Linie `index` (fehlt = Achse): Anfang und Ende (Bogenwand: Sehne zwischen den Bogenenden).
|
||||
fn line(&self, index: Option<u32>) -> Option<(P, P)> {
|
||||
let o = match index {
|
||||
None => 0.0,
|
||||
Some(k) => *self.offs.get(k as usize)?,
|
||||
};
|
||||
let o = self.offset(index)?;
|
||||
if let Some(w) = &self.warc {
|
||||
let (p0, p1) = (w.point(0.0, o), w.point(w.length(), o));
|
||||
return Some(((p0.x, p0.y), (p1.x, p1.y)));
|
||||
}
|
||||
let n = left(unit(self.a, self.b)?);
|
||||
Some((add(self.a, n, o), add(self.b, n, o)))
|
||||
}
|
||||
@@ -149,6 +178,32 @@ struct Shape {
|
||||
pts: Vec<P>,
|
||||
closed: bool,
|
||||
center: Option<P>,
|
||||
/// Weitere geschlossene Umrisse (Treppenpodest): Ecken/Kanten zählen nach denen von `pts` weiter.
|
||||
more: Vec<Vec<P>>,
|
||||
}
|
||||
|
||||
impl Shape {
|
||||
fn new(pts: Vec<P>, closed: bool, center: Option<P>) -> Shape {
|
||||
Shape { pts, closed, center, more: Vec::new() }
|
||||
}
|
||||
|
||||
fn vertex(&self, mut i: usize) -> Option<P> {
|
||||
if i < self.pts.len() {
|
||||
return Some(self.pts[i]);
|
||||
}
|
||||
i -= self.pts.len();
|
||||
for m in &self.more {
|
||||
if i < m.len() {
|
||||
return Some(m[i]);
|
||||
}
|
||||
i -= m.len();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn vertex_count(&self) -> usize {
|
||||
self.pts.len() + self.more.iter().map(Vec::len).sum::<usize>()
|
||||
}
|
||||
}
|
||||
|
||||
fn pts_list(v: Option<&Value>) -> Vec<P> {
|
||||
@@ -163,35 +218,55 @@ fn column_shape(c: &Value) -> Option<Shape> {
|
||||
let rot = num(c.get("rotation")).unwrap_or(0.0);
|
||||
let (co, si) = (crate::jsnum::cos(rot), crate::jsnum::sin(rot));
|
||||
let pts = [(-hw, -hd), (hw, -hd), (hw, hd), (-hw, hd)].iter().map(|&(x, y)| (at.0 + x * co - y * si, at.1 + x * si + y * co)).collect();
|
||||
return Some(Shape { pts, closed: true, center: Some(at) });
|
||||
return Some(Shape::new(pts, true, Some(at)));
|
||||
}
|
||||
Some(Shape { pts: Vec::new(), closed: false, center: Some(at) })
|
||||
Some(Shape::new(Vec::new(), false, Some(at)))
|
||||
}
|
||||
|
||||
fn drawing_shape(d: &Value) -> Option<Shape> {
|
||||
let g = d.get("geom")?;
|
||||
let p = |k: &str| pt(g.get(k));
|
||||
Some(match str_of(g, "shape")? {
|
||||
"line" => Shape { pts: vec![p("a")?, p("b")?], closed: false, center: None },
|
||||
"polyline" => Shape { pts: pts_list(g.get("pts")), closed: g.get("closed").and_then(Value::as_bool).unwrap_or(false), center: None },
|
||||
"line" => Shape::new(vec![p("a")?, p("b")?], false, None),
|
||||
"polyline" => Shape::new(pts_list(g.get("pts")), g.get("closed").and_then(Value::as_bool).unwrap_or(false), None),
|
||||
"rect" => {
|
||||
let (lo, hi) = (p("min")?, p("max")?);
|
||||
Shape { pts: vec![lo, (hi.0, lo.1), hi, (lo.0, hi.1)], closed: true, center: None }
|
||||
Shape::new(vec![lo, (hi.0, lo.1), hi, (lo.0, hi.1)], true, None)
|
||||
}
|
||||
"circle" | "arc" | "ellipse" => Shape { pts: Vec::new(), closed: false, center: Some(p("center")?) },
|
||||
"circle" | "arc" | "ellipse" => Shape::new(Vec::new(), false, Some(p("center")?)),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Listen, in denen Ecke/Kante/Mitte ihr Element suchen (in dieser Reihenfolge).
|
||||
const SHAPE_LISTS: [&str; 5] = ["columns", "ceilings", "roofs", "rooms", "drawings2d"];
|
||||
const SHAPE_LISTS: [&str; 6] = ["columns", "ceilings", "roofs", "rooms", "drawings2d", "stairs"];
|
||||
|
||||
/// Treppe: Umriss (gerade/L: Aussenlinie; Wendel: die vier Ecken der Schliesslinien), Podest als
|
||||
/// weiterer Umriss, Mittelpunkt nur bei der Wendel.
|
||||
fn stair_shape(e: &Value) -> Option<Shape> {
|
||||
let s: crate::model::Stair = serde_json::from_value(e.clone()).ok()?;
|
||||
let sp = crate::stair::decode_params(&s.encode())?;
|
||||
let o = kernel2d::stair_outline(&sp);
|
||||
let t = |q: &kernel2d::Vec2| (q.x, q.y);
|
||||
if let Some(poly) = o.polygon {
|
||||
let mut sh = Shape::new(poly.iter().map(t).collect(), true, None);
|
||||
if let Some(l) = kernel2d::stair_geometry(&sp, 3.0).landing {
|
||||
sh.more.push(l.iter().map(t).collect());
|
||||
}
|
||||
return Some(sh);
|
||||
}
|
||||
let sp2 = o.spiral?;
|
||||
let [(i0, o0), (i1, o1)] = sp2.lines;
|
||||
Some(Shape::new(vec![t(&i0), t(&o0), t(&o1), t(&i1)], true, Some((sp2.arcs[0].0.x, sp2.arcs[0].0.y))))
|
||||
}
|
||||
|
||||
fn shape_of(coll: &str, e: &Value) -> Option<Shape> {
|
||||
match coll {
|
||||
"columns" => column_shape(e),
|
||||
"ceilings" | "roofs" => Some(Shape { pts: pts_list(e.get("outline")), closed: true, center: None }),
|
||||
"rooms" => Some(Shape { pts: pts_list(e.get("boundary")), closed: true, center: None }),
|
||||
"ceilings" | "roofs" => Some(Shape::new(pts_list(e.get("outline")), true, None)),
|
||||
"rooms" => Some(Shape::new(pts_list(e.get("boundary")), true, None)),
|
||||
"drawings2d" => drawing_shape(e),
|
||||
"stairs" => stair_shape(e),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -200,17 +275,66 @@ fn find_shape(lk: &Lookup, id: &str) -> Option<Shape> {
|
||||
SHAPE_LISTS.iter().find_map(|c| lk.find(c, id).map(|e| (*c, e))).and_then(|(c, e)| shape_of(c, e))
|
||||
}
|
||||
|
||||
fn edge(s: &Shape, i: usize) -> Option<(P, P)> {
|
||||
let n = s.pts.len();
|
||||
fn ring_edge(pts: &[P], closed: bool, i: usize) -> Option<(P, P)> {
|
||||
let n = pts.len();
|
||||
if i + 1 < n {
|
||||
Some((s.pts[i], s.pts[i + 1]))
|
||||
} else if s.closed && n > 2 && i + 1 == n {
|
||||
Some((s.pts[i], s.pts[0]))
|
||||
Some((pts[i], pts[i + 1]))
|
||||
} else if closed && n > 2 && i + 1 == n {
|
||||
Some((pts[i], pts[0]))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn ring_edges(pts: &[P], closed: bool) -> usize {
|
||||
if closed && pts.len() > 2 {
|
||||
pts.len()
|
||||
} else {
|
||||
pts.len().saturating_sub(1)
|
||||
}
|
||||
}
|
||||
|
||||
fn edge(s: &Shape, mut i: usize) -> Option<(P, P)> {
|
||||
let n = ring_edges(&s.pts, s.closed);
|
||||
if i < n {
|
||||
return ring_edge(&s.pts, s.closed, i);
|
||||
}
|
||||
i -= n;
|
||||
for m in &s.more {
|
||||
let k = ring_edges(m, true);
|
||||
if i < k {
|
||||
return ring_edge(m, true, i);
|
||||
}
|
||||
i -= k;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn edge_count(s: &Shape) -> usize {
|
||||
ring_edges(&s.pts, s.closed) + s.more.iter().map(|m| ring_edges(m, true)).sum::<usize>()
|
||||
}
|
||||
|
||||
/// Rasterachse `index` des Rasters `id` und das Raster selbst.
|
||||
fn with_grid<T>(lk: &Lookup, id: &str, f: impl FnOnce(&crate::grid::Spec) -> Option<T>) -> Option<T> {
|
||||
let d = lk.find("drawings2d", id)?;
|
||||
let g: crate::model::Drawing2DGeom = serde_json::from_value(d.get("geom")?.clone()).ok()?;
|
||||
f(&crate::grid::Spec::of(&g)?)
|
||||
}
|
||||
|
||||
/// Kreis/Bogen (2D-Zeichnung) oder Bogenwand-Schicht: Mittelpunkt, Radius.
|
||||
fn round_of(lk: &Lookup, id: &str, index: Option<u32>) -> Option<(P, f64)> {
|
||||
if let Some(d) = lk.find("drawings2d", id) {
|
||||
let g = d.get("geom")?;
|
||||
if matches!(str_of(g, "shape"), Some("circle" | "arc")) {
|
||||
return Some((pt(g.get("center"))?, num(g.get("r"))?));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
let g = wall_geo(lk, lk.find("walls", id)?)?;
|
||||
let w = g.warc?;
|
||||
Some(((w.center.x, w.center.y), w.radius_at(g.offset(index)?)))
|
||||
}
|
||||
|
||||
/// Schnitt zweier unendlicher Geraden (parallel → `None`).
|
||||
fn intersect(a: (P, P), b: (P, P)) -> Option<P> {
|
||||
let r = sub(a.1, a.0);
|
||||
@@ -229,17 +353,27 @@ fn intersect(a: (P, P), b: (P, P)) -> Option<P> {
|
||||
pub fn resolve(lk: &Lookup, r: &DimRef) -> Option<P> {
|
||||
let wall_line = |id: &str, idx: Option<u32>| -> Option<(P, P)> { wall_geo(lk, lk.find("walls", id)?)?.line(idx) };
|
||||
let p = match r.feature {
|
||||
DimFeature::Wall => {
|
||||
let (a, b) = wall_line(&r.id, r.index)?;
|
||||
lerp(a, b, r.t?)
|
||||
}
|
||||
DimFeature::Wall => wall_geo(lk, lk.find("walls", &r.id)?)?.point(r.index, r.t?)?,
|
||||
DimFeature::Opening => opening_point(lk, lk.find("openings", &r.id)?, r.index?, r.index2)?,
|
||||
DimFeature::Vertex => *find_shape(lk, &r.id)?.pts.get(r.index? as usize)?,
|
||||
DimFeature::Vertex => find_shape(lk, &r.id)?.vertex(r.index? as usize)?,
|
||||
DimFeature::Edge => {
|
||||
let (a, b) = edge(&find_shape(lk, &r.id)?, r.index? as usize)?;
|
||||
lerp(a, b, r.t?)
|
||||
}
|
||||
DimFeature::Center => find_shape(lk, &r.id)?.center?,
|
||||
DimFeature::Center => match find_shape(lk, &r.id) {
|
||||
Some(sh) => sh.center?,
|
||||
None => {
|
||||
let w = wall_geo(lk, lk.find("walls", &r.id)?)?.warc?;
|
||||
(w.center.x, w.center.y)
|
||||
}
|
||||
},
|
||||
DimFeature::Axis => with_grid(lk, &r.id, |g| g.point_at(r.index?, r.t?))?,
|
||||
DimFeature::AxisCross => with_grid(lk, &r.id, |g| g.cross(r.index?, r.index2?))?,
|
||||
DimFeature::Rim => {
|
||||
let (c, rad) = round_of(lk, &r.id, r.index)?;
|
||||
let a = r.t?;
|
||||
(c.0 + rad * a.cos(), c.1 + rad * a.sin())
|
||||
}
|
||||
DimFeature::Intersection => intersect(wall_line(&r.id, r.index)?, wall_line(r.id2.as_deref()?, r.index2)?)?,
|
||||
};
|
||||
finite(p).then_some(p)
|
||||
@@ -276,7 +410,6 @@ pub fn attach(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<DimRef> {
|
||||
.iter()
|
||||
.filter(|w| on_level(w, "floorId", level))
|
||||
.filter_map(|w| Some((str_of(w, "id")?, wall_geo(lk, w)?)))
|
||||
.filter(|(_, g)| !g.arc)
|
||||
.collect();
|
||||
// 1) Öffnungen: Leibungen und Mitte auf jeder Linie der Wirtswand.
|
||||
for o in list(lk, "openings") {
|
||||
@@ -300,9 +433,24 @@ pub fn attach(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<DimRef> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// 2b) Bogenwände: Mittelpunkt, Punkt auf Achse/Schichtgrenze (Anteil der Bogenlänge).
|
||||
for (id, g) in walls.iter().filter(|(_, g)| g.warc.is_some()) {
|
||||
let Some(w) = &g.warc else { continue };
|
||||
if dist((w.center.x, w.center.y), s) <= tol {
|
||||
return Some(rf(id, DimFeature::Center));
|
||||
}
|
||||
let (ls, ln) = w.local(kernel2d::Vec2 { x: s.0, y: s.1 });
|
||||
let len = w.length();
|
||||
for (k, _, _) in g.lines() {
|
||||
let Some(o) = g.offset(k) else { continue };
|
||||
if (ln - o).abs() <= tol && ls >= -tol && ls <= len + tol {
|
||||
return Some(DimRef { index: k, t: Some((ls / len).clamp(0.0, 1.0)), ..rf(id, DimFeature::Wall) });
|
||||
}
|
||||
}
|
||||
}
|
||||
// 3) Wandecken: auf den Linien zweier Wände (Verlängerung bis zur Wanddicke über das Ende).
|
||||
let mut hits: Vec<(&str, Option<u32>, P, P, f64)> = Vec::new();
|
||||
for (id, g) in &walls {
|
||||
for (id, g) in walls.iter().filter(|(_, g)| !g.arc) {
|
||||
let len = dist(g.a, g.b);
|
||||
let m = (g.total.max(0.3) + tol) / len;
|
||||
for (k, a, b) in g.lines() {
|
||||
@@ -324,7 +472,7 @@ pub fn attach(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<DimRef> {
|
||||
if let Some(h) = hits.iter().find(|h| (0.0..=1.0).contains(&h.4)) {
|
||||
return Some(DimRef { index: h.1, t: Some(h.4), ..rf(h.0, DimFeature::Wall) });
|
||||
}
|
||||
// 5) Stützen, Decken, Dächer, Räume, 2D-Zeichnungen: Mitte, Ecken, Kanten.
|
||||
// 5) Stützen, Decken, Dächer, Räume, 2D-Zeichnungen, Treppen: Mitte, Ecken, Kanten.
|
||||
for coll in SHAPE_LISTS {
|
||||
let key = if coll == "drawings2d" { "levelId" } else { "floorId" };
|
||||
for e in list(lk, coll).iter().filter(|e| on_level(e, key, level)) {
|
||||
@@ -332,10 +480,10 @@ pub fn attach(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<DimRef> {
|
||||
if sh.center.is_some_and(|c| dist(c, s) <= tol) {
|
||||
return Some(rf(id, DimFeature::Center));
|
||||
}
|
||||
if let Some(i) = sh.pts.iter().position(|p| dist(*p, s) <= tol) {
|
||||
if let Some(i) = (0..sh.vertex_count()).find(|&i| sh.vertex(i).is_some_and(|p| dist(p, s) <= tol)) {
|
||||
return Some(DimRef { index: Some(i as u32), ..rf(id, DimFeature::Vertex) });
|
||||
}
|
||||
for i in 0..sh.pts.len() {
|
||||
for i in 0..edge_count(&sh) {
|
||||
let Some((a, b)) = edge(&sh, i) else { continue };
|
||||
if let Some((t, d)) = param(a, b, s) {
|
||||
if d <= tol && (0.0..=1.0).contains(&t) {
|
||||
@@ -345,9 +493,93 @@ pub fn attach(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<DimRef> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// 6) Achsraster ([112]): Achsschnittpunkt, sonst Punkt auf einer Achse.
|
||||
for d in list(lk, "drawings2d") {
|
||||
let Some(id) = str_of(d, "id") else { continue };
|
||||
let Some(g) = d.get("geom").filter(|g| str_of(g, "shape") == Some("grid")) else { continue };
|
||||
let Ok(geom) = serde_json::from_value::<crate::model::Drawing2DGeom>(g.clone()) else { continue };
|
||||
let Some(spec) = crate::grid::Spec::of(&geom) else { continue };
|
||||
let visible = serde_json::from_value::<crate::model::Drawing2D>(d.clone()).map(|dd| crate::grid::visible_on(&dd, level)).unwrap_or(false);
|
||||
if !visible {
|
||||
continue;
|
||||
}
|
||||
let n = (spec.a.len() + spec.b.len()) as u32;
|
||||
for i in 0..spec.a.len() as u32 {
|
||||
for j in spec.a.len() as u32..n {
|
||||
if spec.cross(i, j).is_some_and(|p| dist(p, s) <= tol) {
|
||||
return Some(DimRef { index: Some(i), index2: Some(j), ..rf(id, DimFeature::AxisCross) });
|
||||
}
|
||||
}
|
||||
}
|
||||
for i in 0..n {
|
||||
if let Some((t, d)) = spec.project(i, s) {
|
||||
if d <= tol && (-1e-9..=1.0 + 1e-9).contains(&t) {
|
||||
return Some(DimRef { index: Some(i), t: Some(t.clamp(0.0, 1.0)), ..rf(id, DimFeature::Axis) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Rand-Bezug (Winkel `a`) auf dem Kreis/Bogen `id` ([38]).
|
||||
fn rim(id: &str, index: Option<u32>, a: f64) -> DimRef {
|
||||
DimRef { index, t: Some(a), ..rf(id, DimFeature::Rim) }
|
||||
}
|
||||
|
||||
/// Kreis/Bogen (2D-Zeichnung des Geschosses) oder Bogenwand-Schicht, auf deren Rand `s` liegt
|
||||
/// (Toleranz `tol`): Kennung, Schichtgrenze, Mittelpunkt, Radius.
|
||||
pub fn find_round(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<(String, Option<u32>, P, f64)> {
|
||||
// Nächster Rand innerhalb der Toleranz (bei konzentrischen Kreisen/Schichten der genaueste).
|
||||
let mut best: Option<(f64, (String, Option<u32>, P, f64))> = None;
|
||||
let mut offer = |err: f64, hit: (String, Option<u32>, P, f64)| {
|
||||
if err <= tol && best.as_ref().is_none_or(|(e, _)| err < *e) {
|
||||
best = Some((err, hit));
|
||||
}
|
||||
};
|
||||
for d in list(lk, "drawings2d").iter().filter(|d| on_level(d, "levelId", level)) {
|
||||
let (Some(id), Some(g)) = (str_of(d, "id"), d.get("geom")) else { continue };
|
||||
if !matches!(str_of(g, "shape"), Some("circle" | "arc")) {
|
||||
continue;
|
||||
}
|
||||
let (Some(c), Some(r)) = (pt(g.get("center")), num(g.get("r"))) else { continue };
|
||||
offer((dist(c, s) - r).abs(), (id.to_owned(), None, c, r));
|
||||
}
|
||||
for w in list(lk, "walls").iter().filter(|w| on_level(w, "floorId", level)) {
|
||||
let (Some(id), Some(g)) = (str_of(w, "id"), wall_geo(lk, w)) else { continue };
|
||||
let Some(arc) = g.warc else { continue };
|
||||
let c = (arc.center.x, arc.center.y);
|
||||
let mut ks: Vec<Option<u32>> = vec![None];
|
||||
ks.extend((0..g.offs.len() as u32).map(Some));
|
||||
for k in ks {
|
||||
let Some(o) = g.offset(k) else { continue };
|
||||
let r = arc.radius_at(o);
|
||||
offer((dist(c, s) - r).abs(), (id.to_owned(), k, c, r));
|
||||
}
|
||||
}
|
||||
best.map(|(_, h)| h)
|
||||
}
|
||||
|
||||
/// Radius-/Durchmesser-/Bogenlängen-Bemassung ([38]): aus den Klickpunkten `clicks` (ein Punkt auf
|
||||
/// dem Rand; bei der Bogenlänge Anfang und Ende) die Punkte `pts` (Mittelpunkt, Randpunkt[e]) und
|
||||
/// ihre Bezüge. `None`, wenn kein Kreis/Bogen/Bogenwand getroffen wird.
|
||||
pub fn round_dimension(lk: &Lookup, level: &str, kind: crate::model::DimKind, clicks: &[P], tol: f64) -> Option<(Vec<P>, Vec<Option<DimRef>>)> {
|
||||
use crate::model::DimKind;
|
||||
let first = *clicks.first()?;
|
||||
let (id, idx, c, r) = find_round(lk, level, first, tol)?;
|
||||
let ang = |p: P| (p.1 - c.1).atan2(p.0 - c.0);
|
||||
let on_rim = |a: f64| (c.0 + r * a.cos(), c.1 + r * a.sin());
|
||||
let a0 = ang(first);
|
||||
let mut pts = vec![c, on_rim(a0)];
|
||||
let mut refs = vec![Some(rf(&id, DimFeature::Center)), Some(rim(&id, idx, a0))];
|
||||
if kind == DimKind::Arc {
|
||||
let a1 = ang(*clicks.get(1)?);
|
||||
pts.push(on_rim(a1));
|
||||
refs.push(Some(rim(&id, idx, a1)));
|
||||
}
|
||||
Some((pts, refs))
|
||||
}
|
||||
|
||||
/// Bezüge einer neuen Kette `pts`: je Punkt der erste Fangpunkt aus `snaps`, der auf ihn projiziert
|
||||
/// (Kette = Gerade pts[0]→pts[1]) und an einem Merkmal hängt; `d` = Normalabstand Fangpunkt → Punkt.
|
||||
/// `keep(i)` liefert einen schon bekannten Bezug (Ergänzen einer Kette). Kein Bezug → `None`.
|
||||
@@ -411,6 +643,13 @@ pub fn resolve_chain(lk: &Lookup, pts: &[P], refs: &[Option<DimRef>]) -> (Vec<P>
|
||||
(out, lost)
|
||||
}
|
||||
|
||||
/// Punkte ohne Kettenprojektion (Radius-/Bogenmass): jeder hängende Punkt an seiner Lage.
|
||||
fn resolve_each(lk: &Lookup, pts: &[P], refs: &[Option<DimRef>]) -> (Vec<P>, Vec<bool>) {
|
||||
let q: Vec<Option<P>> = (0..pts.len()).map(|i| refs.get(i).and_then(Option::as_ref).and_then(|r| resolve(lk, r))).collect();
|
||||
let lost = (0..refs.len()).map(|i| refs[i].is_some() && q.get(i).copied().flatten().is_none()).collect();
|
||||
(pts.iter().zip(&q).map(|(p, n)| n.unwrap_or(*p)).collect(), lost)
|
||||
}
|
||||
|
||||
fn refs_of(g: &Value) -> Option<Vec<Option<DimRef>>> {
|
||||
let r = g.get("refs")?;
|
||||
let refs: Vec<Option<DimRef>> = serde_json::from_value(r.clone()).ok()?;
|
||||
@@ -441,7 +680,8 @@ pub fn sync_ops(lk: &Lookup) -> Vec<Op> {
|
||||
if pts.len() != g.get("pts").and_then(Value::as_array).map_or(0, Vec::len) {
|
||||
continue;
|
||||
}
|
||||
let (np, lost) = resolve_chain(lk, &pts, &refs);
|
||||
let round = str_of(g, "kind").is_some();
|
||||
let (np, lost) = if round { resolve_each(lk, &pts, &refs) } else { resolve_chain(lk, &pts, &refs) };
|
||||
let moved = np.iter().zip(&pts).any(|(a, b)| dist(*a, *b) > MOVE_EPS);
|
||||
let flags_changed = refs.iter().zip(&lost).any(|(r, l)| r.as_ref().is_some_and(|r| r.lost.unwrap_or(false) != *l));
|
||||
if !moved && !flags_changed {
|
||||
@@ -690,6 +930,134 @@ mod tests {
|
||||
assert!(d.last_extra().is_empty());
|
||||
}
|
||||
|
||||
fn grid_project() -> Map<String, Value> {
|
||||
root(json!({
|
||||
"drawings2d": [
|
||||
{"id": "G", "type": "drawing2d", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0,
|
||||
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 6}], "b": [{"label": "A", "pos": 0}, {"label": "B", "pos": 4}], "extend": 1}}
|
||||
]
|
||||
}))
|
||||
}
|
||||
|
||||
/// [112] Rasterachsen: Punkt auf Achse, Achsschnittpunkt; die Bemassung folgt der verschobenen Achse.
|
||||
#[test]
|
||||
fn rasterachsen_bezuege_folgen_der_achse() {
|
||||
let mut r = grid_project();
|
||||
let lk = Lookup::plain(&r);
|
||||
// Achsschnittpunkt 2/B (index 1 × index 3), Punkt auf Achse 1.
|
||||
let cross = attach(&lk, "eg", (6.0, 4.0), TOL).unwrap();
|
||||
assert_eq!((cross.feature, cross.index, cross.index2), (DimFeature::AxisCross, Some(1), Some(3)));
|
||||
let on1 = attach(&lk, "eg", (0.0, 2.5), TOL).unwrap();
|
||||
assert_eq!((on1.feature, on1.index), (DimFeature::Axis, Some(0)));
|
||||
close(resolve(&lk, &on1).unwrap(), (0.0, 2.5));
|
||||
// Bemassung zwischen Achse 1 und Achse 2 (Kette bei y = 1): Länge 6; Achse 2 nach x = 7.5 → 7.5.
|
||||
let pts = [(0.0, 1.0), (6.0, 1.0)];
|
||||
let refs = vec![attach(&lk, "eg", (0.0, 1.0), TOL), attach(&lk, "eg", (6.0, 1.0), TOL)];
|
||||
assert!(refs.iter().all(|x| x.as_ref().is_some_and(|x| x.feature == DimFeature::Axis)));
|
||||
set(&mut r, "drawings2d", "G", "geom", json!({"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0,
|
||||
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 7.5}], "b": [{"label": "A", "pos": 0}, {"label": "B", "pos": 4}], "extend": 1}));
|
||||
let (np, lost) = resolve_chain(&Lookup::plain(&r), &pts, &refs);
|
||||
assert_eq!(lost, vec![false, false]);
|
||||
close(np[0], (0.0, 1.0));
|
||||
close(np[1], (7.5, 1.0));
|
||||
// Raster gelöscht → ungültig.
|
||||
r.insert("drawings2d".into(), json!([]));
|
||||
assert!(resolve(&Lookup::plain(&r), refs[1].as_ref().unwrap()).is_none());
|
||||
}
|
||||
|
||||
fn arc_project() -> Map<String, Value> {
|
||||
root(json!({
|
||||
"wallTypes": [{"id": "T", "layers": [{"thickness": 0.1}, {"thickness": 0.2}]}],
|
||||
// Halbkreis: Mittelpunkt (5, 0), Achsradius 5, Scheitel (5, 5).
|
||||
"walls": [{"id": "A", "floorId": "eg", "wallTypeId": "T", "start": {"x": 0, "y": 0}, "end": {"x": 10, "y": 0}, "bulge": 1}],
|
||||
"drawings2d": [{"id": "K", "levelId": "eg", "geom": {"shape": "circle", "center": {"x": 30, "y": 0}, "r": 2}}]
|
||||
}))
|
||||
}
|
||||
|
||||
/// [38] Bogenwand: Enden, Punkt auf Achse/Fläche (Anteil der Bogenlänge), Mittelpunkt, Rand-Bezug.
|
||||
#[test]
|
||||
fn bogenwand_bezuege() {
|
||||
let mut r = arc_project();
|
||||
let lk = Lookup::plain(&r);
|
||||
let apex = attach(&lk, "eg", (5.0, 5.0), TOL).unwrap();
|
||||
assert_eq!((apex.feature, apex.index), (DimFeature::Wall, None));
|
||||
assert!((apex.t.unwrap() - 0.5).abs() < 1e-9);
|
||||
let face = attach(&lk, "eg", (5.0, 5.15), TOL).unwrap();
|
||||
assert_eq!((face.feature, face.index), (DimFeature::Wall, Some(2)));
|
||||
let end = attach(&lk, "eg", (10.0, 0.0), TOL).unwrap();
|
||||
assert_eq!((end.feature, end.t), (DimFeature::Wall, Some(1.0)));
|
||||
let centre = attach(&lk, "eg", (5.0, 0.0), TOL).unwrap();
|
||||
assert_eq!(centre.feature, DimFeature::Center);
|
||||
close(resolve(&lk, ¢re).unwrap(), (5.0, 0.0));
|
||||
close(resolve(&lk, &face).unwrap(), (5.0, 5.15));
|
||||
// Rand-Bezug (Winkel 90°) auf der Fläche 2: Radius 5.15; Mittelpunkt und Winkel bleiben beim Strecken.
|
||||
let rim_ref = DimRef { index: Some(2), t: Some(std::f64::consts::FRAC_PI_2), ..rf("A", DimFeature::Rim) };
|
||||
close(resolve(&lk, &rim_ref).unwrap(), (5.0, 5.15));
|
||||
// Wand verlängern (Ende x = 12 → Mittelpunkt (6, 0), Radius 6): Scheitel folgt.
|
||||
set(&mut r, "walls", "A", "end", json!({"x": 12, "y": 0}));
|
||||
let lk = Lookup::plain(&r);
|
||||
close(resolve(&lk, &apex).unwrap(), (6.0, 6.0));
|
||||
close(resolve(&lk, ¢re).unwrap(), (6.0, 0.0));
|
||||
}
|
||||
|
||||
/// [38] Radius-, Durchmesser- und Bogenlängen-Bemassung hängen an Kreis und Bogenwand.
|
||||
#[test]
|
||||
fn radius_und_bogenmass_assoziativ() {
|
||||
use crate::model::DimKind;
|
||||
let mut r = arc_project();
|
||||
let lk = Lookup::plain(&r);
|
||||
let (pts, refs) = round_dimension(&lk, "eg", DimKind::Radius, &[(30.0, 2.0)], 0.1).unwrap();
|
||||
close(pts[0], (30.0, 0.0));
|
||||
close(pts[1], (30.0, 2.0));
|
||||
assert_eq!(refs[0].as_ref().unwrap().feature, DimFeature::Center);
|
||||
// Kreis verschieben und vergrössern → Mittelpunkt und Randpunkt folgen (ohne Kettenprojektion).
|
||||
set(&mut r, "drawings2d", "K", "geom", json!({"shape": "circle", "center": {"x": 40, "y": 5}, "r": 3}));
|
||||
let (np, lost) = resolve_each(&Lookup::plain(&r), &pts, &refs);
|
||||
assert_eq!(lost, vec![false, false]);
|
||||
close(np[0], (40.0, 5.0));
|
||||
close(np[1], (40.0, 8.0));
|
||||
// Bogenlänge auf der Aussenfläche der Bogenwand (Radius 5.15): Viertelkreis von 90° bis 0°.
|
||||
let lk = Lookup::plain(&r);
|
||||
let (pts, refs) = round_dimension(&lk, "eg", DimKind::Arc, &[(5.0, 5.15), (5.15, 0.0)], 0.04).unwrap();
|
||||
assert_eq!(pts.len(), 3);
|
||||
close(pts[0], (5.0, 0.0));
|
||||
assert_eq!(refs[1].as_ref().unwrap().index, Some(2));
|
||||
// Nichts getroffen.
|
||||
assert!(round_dimension(&lk, "eg", DimKind::Radius, &[(100.0, 100.0)], 0.1).is_none());
|
||||
}
|
||||
|
||||
/// [38] Treppe: Umriss-Ecken/-Kanten und Podest-Kanten der L-Treppe sind anhängbar.
|
||||
#[test]
|
||||
fn treppe_bezuege() {
|
||||
let stair = |shape: &str| json!({"id": "S", "type": "stair", "floorId": "eg", "categoryCode": "20", "shape": shape,
|
||||
"start": {"x": 0, "y": 0}, "dir": {"x": 1, "y": 0}, "runLength": 3, "run2Length": 2, "turn": 1, "width": 1, "stepCount": 16});
|
||||
let r = root(json!({"stairs": [stair("straight")]}));
|
||||
let lk = Lookup::plain(&r);
|
||||
let sh = find_shape(&lk, "S").unwrap();
|
||||
assert_eq!(sh.pts.len(), 4);
|
||||
// Eck 0 und Mitte der Kante 1 (Auftrittsende) hängen an und lösen auf.
|
||||
let v0 = sh.pts[0];
|
||||
let rv = attach(&lk, "eg", v0, TOL).unwrap();
|
||||
assert_eq!((rv.feature, rv.id.as_str(), rv.index), (DimFeature::Vertex, "S", Some(0)));
|
||||
let (a, b) = edge(&sh, 1).unwrap();
|
||||
let mid = lerp(a, b, 0.5);
|
||||
let re = attach(&lk, "eg", mid, TOL).unwrap();
|
||||
assert_eq!((re.feature, re.index), (DimFeature::Edge, Some(1)));
|
||||
close(resolve(&lk, &re).unwrap(), mid);
|
||||
// L-Treppe: zusätzlich Podest-Ecken und -Kanten (Indizes nach dem Umriss).
|
||||
let r = root(json!({"stairs": [stair("L")]}));
|
||||
let lk = Lookup::plain(&r);
|
||||
let sh = find_shape(&lk, "S").unwrap();
|
||||
assert_eq!(sh.pts.len(), 6);
|
||||
assert_eq!(sh.more.len(), 1);
|
||||
let n = sh.pts.len();
|
||||
let landing_corner = sh.vertex(n).unwrap();
|
||||
let rl = attach(&lk, "eg", landing_corner, TOL).unwrap();
|
||||
assert_eq!(rl.feature, DimFeature::Vertex);
|
||||
close(resolve(&lk, &rl).unwrap(), landing_corner);
|
||||
assert!(edge_count(&sh) > n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn befehl_bemassung_haengt_gefangene_punkte_an() {
|
||||
let r = project();
|
||||
|
||||
@@ -76,6 +76,8 @@ pub struct DormerGeom {
|
||||
pub main_thickness: f64,
|
||||
/// Ende der Gaubendach-Flächen hinten (lokal v).
|
||||
pub v_end: f64,
|
||||
/// Über den First hinaus und darum gekappt ([G5]).
|
||||
pub clamped: bool,
|
||||
}
|
||||
|
||||
/// Fläche des Gaubendachs: Grundriss-Polygon (lokal, Gegenuhrzeigersinn) und Ebene `z = a + bu·u + bv·v`
|
||||
@@ -157,8 +159,62 @@ pub fn roof_layers(p: &Project, roof: &Roof, d: &Dormer) -> Vec<Layer> {
|
||||
}
|
||||
|
||||
/// Gaubengeometrie; `None` bei unsinnigen Parametern (zu schmal, zu niedrig, Gaubendach steiler als das
|
||||
/// Hauptdach bei der Schleppgaube, Punkt nicht in einer geneigten Fläche).
|
||||
/// Hauptdach bei der Schleppgaube, Punkt nicht in einer geneigten Fläche). Reicht die Gaube über den
|
||||
/// First/Grat ihrer Dachfläche hinaus (zu hoch), wird sie abgefangen: Stirnhöhe (bzw. Tiefe der
|
||||
/// Schleppgaube) so gekappt, dass die Gaubendach-Oberkante spätestens am First auf die Hauptdach-Oberkante
|
||||
/// trifft (`clamped`); das Gaubendach endet am Rand der Dachfläche.
|
||||
pub fn geometry(p: &Project, roof: &Roof, d: &Dormer) -> Option<DormerGeom> {
|
||||
let g = geometry_raw(p, roof, d)?;
|
||||
let pts = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof)).planes.into_iter().nth(g.frame.plane)?;
|
||||
let f = g.frame.clone();
|
||||
let inside = |v: f64| point_in_xy(f.plan(0.0, v)[0], f.plan(0.0, v)[1], &pts);
|
||||
// Tiefe bis zum Rand der Dachfläche (First/Grat) längs der Gaubenmitte.
|
||||
let (mut lo, mut hi) = (0.0, 60.0);
|
||||
if inside(hi) {
|
||||
return Some(g);
|
||||
}
|
||||
let mut g = g;
|
||||
for _ in 0..60 {
|
||||
let m = (lo + hi) / 2.0;
|
||||
if inside(m) {
|
||||
lo = m;
|
||||
} else {
|
||||
hi = m;
|
||||
}
|
||||
}
|
||||
let v_edge = lo;
|
||||
// Wo die Gaubendach-OBERKANTE die Hauptdach-Oberkante trifft (hinter dem Lochrand).
|
||||
let (tm, t, hw, rv) = (f.tan_main, g.tan_p, g.width / 2.0, g.roof_vertical());
|
||||
let meet = match g.kind {
|
||||
DormerKind::Schlepp => (g.front_height + rv) / (tm - t),
|
||||
DormerKind::Flach => (g.front_height + rv) / tm,
|
||||
_ => (g.front_height + hw * t + rv) / tm,
|
||||
};
|
||||
let v_r = v_edge - 1e-3;
|
||||
// Gaubendach nicht über den Rand der Dachfläche hinaus verlängern (sonst ragt es jenseits des Firsts);
|
||||
// 1 cm davor endet es unter der Hauptdach-Oberkante (nicht bündig mit dem First: keine Splitter).
|
||||
let cap = |g: &mut DormerGeom, meet: f64| g.v_end = g.v_end.min((v_edge - 0.01).max(meet.min(v_edge)));
|
||||
if meet <= v_r + 1e-9 {
|
||||
cap(&mut g, meet);
|
||||
return Some(g);
|
||||
}
|
||||
let mut d2 = d.clone();
|
||||
match g.kind {
|
||||
DormerKind::Schlepp if d.depth.is_some_and(|x| x.is_finite() && x > 0.1) => d2.depth = Some(d2.depth.unwrap_or(0.0) - (meet - v_r)),
|
||||
DormerKind::Schlepp => d2.front_height = v_r * (tm - t) - rv,
|
||||
DormerKind::Flach => d2.front_height = v_r * tm - rv,
|
||||
_ => d2.front_height = v_r * tm - hw * t - rv,
|
||||
}
|
||||
if !(d2.front_height >= 0.3) || d2.depth.is_some_and(|x| !(x > 0.1)) {
|
||||
return None;
|
||||
}
|
||||
let mut g2 = geometry_raw(p, roof, &d2)?;
|
||||
cap(&mut g2, v_r);
|
||||
g2.clamped = true;
|
||||
Some(g2)
|
||||
}
|
||||
|
||||
fn geometry_raw(p: &Project, roof: &Roof, d: &Dormer) -> Option<DormerGeom> {
|
||||
let frame = frame(p, roof, d)?;
|
||||
if !(finite_pos(d.width) && d.width >= 0.4 && d.width <= 30.0 && finite_pos(d.front_height) && d.front_height <= 10.0) {
|
||||
return None;
|
||||
@@ -186,7 +242,7 @@ pub fn geometry(p: &Project, roof: &Roof, d: &Dormer) -> Option<DormerGeom> {
|
||||
return None;
|
||||
}
|
||||
let z_e = frame.z_m0 + d.front_height;
|
||||
let mut g = DormerGeom { frame, kind: d.kind, width: d.width, front_height: d.front_height, overhang, tan_p, z_e, roof_layers, wall_layers, roof_thickness, wall_thickness, main_thickness, v_end: 0.0 };
|
||||
let mut g = DormerGeom { frame, kind: d.kind, width: d.width, front_height: d.front_height, overhang, tan_p, z_e, roof_layers, wall_layers, roof_thickness, wall_thickness, main_thickness, v_end: 0.0, clamped: false };
|
||||
// Hinten weit genug, dass die ganze Gaubendach-Unterkante unter der Hauptdach-Unterkante endet.
|
||||
let main_v = main_thickness * (1.0 + tm * tm).sqrt();
|
||||
let top_extra = roof_thickness * (1.0 + tan_p * tan_p).sqrt();
|
||||
@@ -214,6 +270,49 @@ impl DormerGeom {
|
||||
}
|
||||
}
|
||||
|
||||
/// Unterkante des Gaubeninneren als Facetten für Wände darunter ([G2]): Bereich zwischen Stirn und
|
||||
/// Wangen bis zum Lochrand, je Gaubendach-Fläche eine Ebene (Welt).
|
||||
pub fn under_facets(&self) -> Vec<crate::wall_bands::RoofFacet> {
|
||||
let (hw, tw, t, ze) = (self.width / 2.0, self.wall_thickness, self.tan_p, self.z_e);
|
||||
let hi = hw - tw;
|
||||
if !(hi > 1e-3) {
|
||||
return Vec::new();
|
||||
}
|
||||
let ring: Vec<P> = match self.kind {
|
||||
DormerKind::Flach | DormerKind::Schlepp => vec![[-hi, tw], [hi, tw], [hi, self.hole_v(hi)], [-hi, self.hole_v(-hi)]],
|
||||
_ => vec![[-hi, tw], [hi, tw], [hi, self.hole_v(hi)], [0.0, self.hole_v(0.0)], [-hi, self.hole_v(-hi)]],
|
||||
};
|
||||
// (Ring lokal, z = a + bu·u + bv·v), Bereiche überdeckungsfrei.
|
||||
let mut parts: Vec<(Vec<P>, f64, f64, f64)> = Vec::new();
|
||||
match self.kind {
|
||||
DormerKind::Flach => parts.push((ring, ze, 0.0, 0.0)),
|
||||
DormerKind::Schlepp => parts.push((ring, ze, 0.0, t)),
|
||||
DormerKind::Sattel | DormerKind::Unknown => {
|
||||
parts.push((clip_half(&ring, [-1.0, 0.0, 0.0]), ze + hw * t, t, 0.0));
|
||||
parts.push((clip_half(&ring, [1.0, 0.0, 0.0]), ze + hw * t, -t, 0.0));
|
||||
}
|
||||
DormerKind::Walm => {
|
||||
// Stirn-Walm: v ≤ hw − |u|; Seiten: darüber, links/rechts.
|
||||
let front = clip_half(&clip_half(&ring, [-1.0, -1.0, hw]), [1.0, -1.0, hw]);
|
||||
parts.push((front, ze, 0.0, t));
|
||||
parts.push((clip_half(&clip_half(&ring, [-1.0, 0.0, 0.0]), [-1.0, 1.0, -hw]), ze + hw * t, t, 0.0));
|
||||
parts.push((clip_half(&clip_half(&ring, [1.0, 0.0, 0.0]), [1.0, 1.0, -hw]), ze + hw * t, -t, 0.0));
|
||||
}
|
||||
}
|
||||
let f = &self.frame;
|
||||
parts
|
||||
.into_iter()
|
||||
.filter(|(r, ..)| r.len() >= 3)
|
||||
.filter_map(|(r, a, bu, bv)| {
|
||||
// u = (q − p)·ew, v = −(q − p)·h.
|
||||
let gx = bu * f.ew[0] - bv * f.h[0];
|
||||
let gy = bu * f.ew[1] - bv * f.h[1];
|
||||
let c = a - gx * f.p[0] - gy * f.p[1];
|
||||
crate::wall_bands::RoofFacet::new(r.iter().map(|q| f.plan(q[0], q[1])).collect(), [c, gx, gy])
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Lotrechter Abstand Oberkante − Unterkante (Gaubendach).
|
||||
pub fn roof_vertical(&self) -> f64 {
|
||||
self.roof_thickness * (1.0 + self.tan_p * self.tan_p).sqrt()
|
||||
@@ -319,6 +418,24 @@ impl DormerGeom {
|
||||
}
|
||||
}
|
||||
|
||||
/// Konvexer Ring, beschnitten auf die Halbebene `a·u + b·v + c ≥ 0` (Sutherland-Hodgman).
|
||||
fn clip_half(ring: &[P], [a, b, c]: [f64; 3]) -> Vec<P> {
|
||||
let f = |q: P| a * q[0] + b * q[1] + c;
|
||||
let mut out = Vec::new();
|
||||
for i in 0..ring.len() {
|
||||
let (p, q) = (ring[i], ring[(i + 1) % ring.len()]);
|
||||
let (fp, fq) = (f(p), f(q));
|
||||
if fp >= 0.0 {
|
||||
out.push(p);
|
||||
}
|
||||
if (fp >= 0.0) != (fq >= 0.0) {
|
||||
let t = fp / (fp - fq);
|
||||
out.push([p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Gaube `dormer_id` im Dach `roof_id` (Index des Dachs, Gaube).
|
||||
pub fn find<'a>(p: &'a Project, roof_id: &str, dormer_id: &str) -> Option<(usize, &'a Roof, &'a Dormer)> {
|
||||
let (ri, roof) = p.roofs.as_deref()?.iter().enumerate().find(|(_, r)| r.id == roof_id)?;
|
||||
@@ -345,7 +462,7 @@ pub fn dormer_openings(p: &Project, roof_index: usize) -> Vec<(&Opening, &Dormer
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
|
||||
pub(crate) fn gable_project() -> Project {
|
||||
@@ -362,6 +479,25 @@ mod tests {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zu_hohe_gaube_wird_vor_dem_first_gekappt() {
|
||||
let mut p = gable_project();
|
||||
let roof = &mut p.roofs.as_mut().unwrap()[0];
|
||||
roof.dormers.as_mut().unwrap()[0].front_height = 6.0;
|
||||
let roof = &p.roofs.as_ref().unwrap()[0];
|
||||
let g = geometry(&p, roof, &roof.dormers.as_ref().unwrap()[0]).expect("gekappt statt verworfen");
|
||||
assert!(g.clamped && g.front_height < 6.0);
|
||||
// Gaubendach trifft die Hauptdach-Oberkante 1 mm vor dem First (y = 4; Stirn bei y = 1 ⇒ 3 m),
|
||||
// nichts reicht über den First.
|
||||
let reach = g.hole().iter().map(|q| q[1]).fold(0.0, f64::max);
|
||||
let meet = (g.front_height + 1.2 * g.tan_p + g.roof_vertical()) / g.frame.tan_main;
|
||||
assert!(reach < 2.999 && (meet - 2.999).abs() < 1e-6 && g.v_end <= 3.0 + 1e-9, "{reach} {meet} {}", g.v_end);
|
||||
let q = gable_project();
|
||||
let r0 = &q.roofs.as_ref().unwrap()[0];
|
||||
let ok = geometry(&q, r0, &r0.dormers.as_ref().unwrap()[0]).unwrap();
|
||||
assert!(!ok.clamped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_and_hole_on_gable_roof() {
|
||||
let p = gable_project();
|
||||
|
||||
@@ -0,0 +1,711 @@
|
||||
//! Baugrube / Geländebearbeitung ([68], [T6]): ein Umriss (Sohle) auf fester Höhe, Böschungen bis zum
|
||||
//! Gelände (Abtrag) bzw. Schüttungen bis zum Gelände (Auftrag), optional mit Bermen.
|
||||
//!
|
||||
//! Neue Geländehöhe am Punkt p: clamp(t(p), b − d·tan β, b + H(d)) mit d = Abstand zum Umriss (innen 0),
|
||||
//! H(d) = Böschungsprofil (Neigung α der nächsten Kante, je `bermHeight` eine Berme der Breite
|
||||
//! `bermWidth`), β = Schüttungswinkel. Innen gilt damit überall die Sohle b; die Ecken der Böschung sind
|
||||
//! Kegel (wie beim Aushub mit dem Bagger).
|
||||
//!
|
||||
//! • Netz: das Gelände wird im Wirkbereich neu trianguliert — Rasterpunkte (exakte neue Höhe), Umriss
|
||||
//! und Böschungsoberkante (Schnitt Böschung/Gelände) als Bruchkanten, ausserhalb das Original-TIN
|
||||
//! samt seinen Kanten. Ergebnis je Gelände-Netz zwischengespeichert ([`site_terrain`]).
|
||||
//! • Mengen: Abtrag/Auftrag als Integral von (t − neu) über ein feines Raster (Mittelpunktregel auf der
|
||||
//! exakten Funktion, nicht auf dem Netz); Hinterfüllung = Abtrag ausserhalb der Gebäude-Grundfläche.
|
||||
//! Jede Baugrube wird gegen das gewachsene Terrain gerechnet.
|
||||
|
||||
use crate::model::{ContextObject, Excavation, Project, TerrainMesh};
|
||||
use crate::terrain::{constrained_tin, datum, isolines, P2, Tin, TinIndex};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::rc::Rc;
|
||||
|
||||
pub const DEFAULT_SLOPE: f64 = 45.0;
|
||||
pub const DEFAULT_FILL_SLOPE: f64 = 33.7;
|
||||
|
||||
fn tan_deg(a: f64) -> f64 {
|
||||
a.clamp(5.0, 89.5).to_radians().tan()
|
||||
}
|
||||
|
||||
/// Baugrube im Höhenbezug des Netzes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ExSpec {
|
||||
/// Umriss gegen den Uhrzeigersinn.
|
||||
pub ring: Vec<P2>,
|
||||
pub bottom: f64,
|
||||
pub cut_tan: Vec<f64>,
|
||||
pub fill_tan: f64,
|
||||
pub berm_w: f64,
|
||||
pub berm_h: f64,
|
||||
}
|
||||
|
||||
fn seg_dist(p: P2, a: P2, b: P2) -> f64 {
|
||||
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
|
||||
let l2 = dx * dx + dy * dy;
|
||||
let t = if l2 > 0.0 { (((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(p[0] - a[0] - t * dx).hypot(p[1] - a[1] - t * dy)
|
||||
}
|
||||
|
||||
pub fn point_in_ring(p: P2, r: &[P2]) -> bool {
|
||||
let mut inside = false;
|
||||
let n = r.len();
|
||||
let mut j = n.wrapping_sub(1);
|
||||
for i in 0..n {
|
||||
let (a, b) = (r[i], r[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
|
||||
}
|
||||
|
||||
fn signed_area(r: &[P2]) -> f64 {
|
||||
let n = r.len();
|
||||
(0..n).map(|i| r[i][0] * r[(i + 1) % n][1] - r[(i + 1) % n][0] * r[i][1]).sum::<f64>() / 2.0
|
||||
}
|
||||
|
||||
impl ExSpec {
|
||||
/// Aus dem Modell; `dz` = Höhenbezug des Netzes ([`datum`]). `None` bei kaputtem Umriss.
|
||||
pub fn of(e: &Excavation, dz: f64) -> Option<ExSpec> {
|
||||
let mut ring: Vec<P2> = e.outline.iter().map(|v| [v.x, v.y]).filter(|p| p[0].is_finite() && p[1].is_finite()).collect();
|
||||
ring.dedup_by(|a, b| (a[0] - b[0]).hypot(a[1] - b[1]) < 1e-9);
|
||||
if ring.len() > 2 && (ring[0][0] - ring[ring.len() - 1][0]).hypot(ring[0][1] - ring[ring.len() - 1][1]) < 1e-9 {
|
||||
ring.pop();
|
||||
}
|
||||
if ring.len() < 3 || !e.bottom.is_finite() || signed_area(&ring).abs() < 1e-6 {
|
||||
return None;
|
||||
}
|
||||
let n = ring.len();
|
||||
let slope = e.slope.filter(|s| s.is_finite() && *s > 0.0).unwrap_or(DEFAULT_SLOPE);
|
||||
let mut cut_tan: Vec<f64> = (0..n).map(|i| tan_deg(e.edge_slopes.as_ref().and_then(|v| v.get(i)).copied().filter(|s| s.is_finite() && *s > 0.0).unwrap_or(slope))).collect();
|
||||
if signed_area(&ring) < 0.0 {
|
||||
// Kante i (p_i → p_i+1) wird nach dem Umdrehen Kante n−2−i (mod n).
|
||||
ring.reverse();
|
||||
let old = cut_tan.clone();
|
||||
for i in 0..n {
|
||||
cut_tan[(2 * n - 2 - i) % n] = old[i];
|
||||
}
|
||||
}
|
||||
let bw = e.berm_width.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(0.0);
|
||||
let bh = e.berm_height.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(0.0);
|
||||
Some(ExSpec {
|
||||
ring,
|
||||
bottom: e.bottom + dz,
|
||||
cut_tan,
|
||||
fill_tan: tan_deg(e.fill_slope.filter(|s| s.is_finite() && *s > 0.0).unwrap_or(DEFAULT_FILL_SLOPE)),
|
||||
berm_w: if bh > 0.0 { bw } else { 0.0 },
|
||||
berm_h: if bw > 0.0 { bh } else { 0.0 },
|
||||
})
|
||||
}
|
||||
|
||||
/// Abstand zum Umriss (innen 0) und Index der nächsten Kante.
|
||||
pub fn dist(&self, p: P2) -> (f64, usize) {
|
||||
if point_in_ring(p, &self.ring) {
|
||||
return (0.0, 0);
|
||||
}
|
||||
let n = self.ring.len();
|
||||
(0..n).map(|i| (seg_dist(p, self.ring[i], self.ring[(i + 1) % n]), i)).fold((f64::INFINITY, 0), |a, b| if b.0 < a.0 { b } else { a })
|
||||
}
|
||||
|
||||
/// Böschungsprofil: Höhe über der Sohle im Abstand d bei Neigung tan.
|
||||
fn profile(&self, d: f64, tan: f64) -> f64 {
|
||||
if self.berm_w > 0.0 {
|
||||
let run = self.berm_h / tan;
|
||||
let period = run + self.berm_w;
|
||||
let k = (d / period).floor();
|
||||
k * self.berm_h + (d - k * period).min(run) * tan
|
||||
} else {
|
||||
d * tan
|
||||
}
|
||||
}
|
||||
|
||||
/// Abstand, bei dem das Profil die Höhe h erreicht (Umkehrung von [`profile`]).
|
||||
fn reach(&self, h: f64, tan: f64) -> f64 {
|
||||
if !(h > 0.0) {
|
||||
return 0.0;
|
||||
}
|
||||
if self.berm_w > 0.0 {
|
||||
let k = (h / self.berm_h).floor();
|
||||
k * (self.berm_h / tan + self.berm_w) + (h - k * self.berm_h) / tan
|
||||
} else {
|
||||
h / tan
|
||||
}
|
||||
}
|
||||
|
||||
/// Neue Geländehöhe zur alten Höhe `t` am Punkt p.
|
||||
pub fn apply(&self, t: f64, p: P2) -> f64 {
|
||||
let (d, i) = self.dist(p);
|
||||
let hi = self.bottom + self.profile(d, self.cut_tan[i]);
|
||||
let lo = self.bottom - d * self.fill_tan;
|
||||
t.max(lo).min(hi)
|
||||
}
|
||||
|
||||
fn bbox(&self) -> [f64; 4] {
|
||||
let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
|
||||
for p in &self.ring {
|
||||
b = [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])];
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Wirkbereich: grösster Abstand vom Umriss, in dem das Gelände geändert wird.
|
||||
pub fn reach_in(&self, orig: &Tin, idx: &TinIndex) -> f64 {
|
||||
let b = self.bbox();
|
||||
let min_tan = self.cut_tan.iter().copied().fold(f64::INFINITY, f64::min);
|
||||
let mut r = 0.0;
|
||||
for _ in 0..6 {
|
||||
let (mut lo, mut hi) = (self.bottom, self.bottom);
|
||||
for (p, z) in orig.xy.iter().zip(&orig.z) {
|
||||
if p[0] >= b[0] - r && p[0] <= b[2] + r && p[1] >= b[1] - r && p[1] <= b[3] + r {
|
||||
lo = lo.min(*z);
|
||||
hi = hi.max(*z);
|
||||
}
|
||||
}
|
||||
// Zwischen den Ecken (grosse Dreiecke): Stichproben im Bereich.
|
||||
for j in 0..=24 {
|
||||
for i in 0..=24 {
|
||||
let (x, y) = (b[0] - r + (b[2] - b[0] + 2.0 * r) * i as f64 / 24.0, b[1] - r + (b[3] - b[1] + 2.0 * r) * j as f64 / 24.0);
|
||||
if let Some(z) = idx.z_at(x, y) {
|
||||
lo = lo.min(z);
|
||||
hi = hi.max(z);
|
||||
}
|
||||
}
|
||||
}
|
||||
let nr = self.reach(hi - self.bottom, min_tan).max((self.bottom - lo) / self.fill_tan).min(2000.0);
|
||||
if nr <= r + 1e-6 {
|
||||
return nr;
|
||||
}
|
||||
r = nr;
|
||||
}
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
/// Regelmässiges Raster über einem Rechteck (Knoten).
|
||||
struct Grid {
|
||||
x0: f64,
|
||||
y0: f64,
|
||||
s: f64,
|
||||
nx: usize,
|
||||
ny: usize,
|
||||
}
|
||||
|
||||
impl Grid {
|
||||
fn new(b: [f64; 4], s: f64, max_nodes: usize) -> Grid {
|
||||
let (w, h) = (b[2] - b[0], b[3] - b[1]);
|
||||
let mut s = s;
|
||||
while ((w / s).ceil() + 1.0) * ((h / s).ceil() + 1.0) > max_nodes as f64 {
|
||||
s *= 1.25;
|
||||
}
|
||||
Grid { x0: b[0], y0: b[1], s, nx: (w / s).ceil() as usize + 1, ny: (h / s).ceil() as usize + 1 }
|
||||
}
|
||||
fn at(&self, i: usize, j: usize) -> P2 {
|
||||
[self.x0 + i as f64 * self.s, self.y0 + j as f64 * self.s]
|
||||
}
|
||||
/// TIN des Rasters mit den Werten `v` (NaN = fehlt; Zellen nur mit vier Werten).
|
||||
fn tin(&self, v: &[f64]) -> Tin {
|
||||
let mut t = Tin { xy: Vec::with_capacity(v.len()), z: v.to_vec(), tris: Vec::new() };
|
||||
for j in 0..self.ny {
|
||||
for i in 0..self.nx {
|
||||
t.xy.push(self.at(i, j));
|
||||
}
|
||||
}
|
||||
for j in 0..self.ny.saturating_sub(1) {
|
||||
for i in 0..self.nx.saturating_sub(1) {
|
||||
let k = (j * self.nx + i) as u32;
|
||||
let q = [k, k + 1, k + 1 + self.nx as u32, k + self.nx as u32];
|
||||
if q.iter().all(|&i| v[i as usize].is_finite()) {
|
||||
t.tris.push([q[0], q[1], q[2]]);
|
||||
t.tris.push([q[0], q[2], q[3]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
}
|
||||
|
||||
/// Ergebnis einer Baugrube auf einem Netz.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Excavated {
|
||||
pub tin: Tin,
|
||||
/// Böschungsoberkante (Abtrag) bzw. Böschungsfuss (Auftrag) im Gelände.
|
||||
pub daylight: Vec<Vec<P2>>,
|
||||
pub reach: f64,
|
||||
pub step: f64,
|
||||
}
|
||||
|
||||
/// Wendet eine Baugrube auf ein Netz an. `None`, wenn sie das Netz nicht trifft.
|
||||
pub fn excavate(orig: &Tin, ex: &ExSpec) -> Option<Excavated> {
|
||||
let idx = TinIndex::new(orig);
|
||||
let c = ex.ring.iter().fold([0.0, 0.0], |a, p| [a[0] + p[0], a[1] + p[1]]);
|
||||
let c = [c[0] / ex.ring.len() as f64, c[1] / ex.ring.len() as f64];
|
||||
if idx.z_at(c[0], c[1]).is_none() && ex.ring.iter().all(|p| idx.z_at(p[0], p[1]).is_none()) {
|
||||
return None;
|
||||
}
|
||||
let r = ex.reach_in(orig, &idx);
|
||||
let b = ex.bbox();
|
||||
let s0 = (((b[2] - b[0] + 2.0 * r) * (b[3] - b[1] + 2.0 * r)).sqrt() / 120.0).clamp(0.15, 2.0);
|
||||
let reg = [b[0] - r - s0, b[1] - r - s0, b[2] + r + s0, b[3] + r + s0];
|
||||
let g = Grid::new(reg, s0, 250_000);
|
||||
let s = g.s;
|
||||
let mut t_val = vec![f64::NAN; g.nx * g.ny];
|
||||
let mut d_val = vec![f64::INFINITY; g.nx * g.ny];
|
||||
let (mut cut_phi, mut fill_phi) = (vec![f64::NAN; g.nx * g.ny], vec![f64::NAN; g.nx * g.ny]);
|
||||
for j in 0..g.ny {
|
||||
for i in 0..g.nx {
|
||||
let p = g.at(i, j);
|
||||
let k = j * g.nx + i;
|
||||
let Some(t) = idx.z_at(p[0], p[1]) else { continue };
|
||||
let (d, e) = ex.dist(p);
|
||||
t_val[k] = t;
|
||||
d_val[k] = d;
|
||||
cut_phi[k] = t - (ex.bottom + ex.profile(d, ex.cut_tan[e]));
|
||||
fill_phi[k] = (ex.bottom - d * ex.fill_tan) - t;
|
||||
}
|
||||
}
|
||||
let mut pts: Vec<[f64; 3]> = Vec::new();
|
||||
let mut cons: Vec<(u32, u32)> = Vec::new();
|
||||
let chain = |line: &[P2], z: &dyn Fn(P2) -> Option<f64>, pts: &mut Vec<[f64; 3]>, cons: &mut Vec<(u32, u32)>| {
|
||||
let mut prev: Option<u32> = None;
|
||||
for &p in line {
|
||||
match z(p) {
|
||||
Some(h) => {
|
||||
pts.push([p[0], p[1], h]);
|
||||
let k = pts.len() as u32 - 1;
|
||||
if let Some(q) = prev {
|
||||
cons.push((q, k));
|
||||
}
|
||||
prev = Some(k);
|
||||
}
|
||||
None => prev = None,
|
||||
}
|
||||
}
|
||||
};
|
||||
// 1. Umriss der Sohle, verdichtet.
|
||||
let n = ex.ring.len();
|
||||
let mut ring_pts: Vec<P2> = Vec::new();
|
||||
for i in 0..n {
|
||||
let (a, q) = (ex.ring[i], ex.ring[(i + 1) % n]);
|
||||
let steps = ((a[0] - q[0]).hypot(a[1] - q[1]) / s).ceil().max(1.0) as usize;
|
||||
for k in 0..steps {
|
||||
let f = k as f64 / steps as f64;
|
||||
ring_pts.push([a[0] + (q[0] - a[0]) * f, a[1] + (q[1] - a[1]) * f]);
|
||||
}
|
||||
}
|
||||
ring_pts.push(ring_pts[0]);
|
||||
let bottom = ex.bottom;
|
||||
chain(&ring_pts, &|p| idx.z_at(p[0], p[1]).map(|t| ex.apply(t, p).min(bottom).max(bottom)), &mut pts, &mut cons);
|
||||
// 2. Böschungsoberkante / -fuss: Nullinien von t − hi bzw. lo − t ausserhalb des Umrisses.
|
||||
let mut daylight = Vec::new();
|
||||
for phi in [&cut_phi, &fill_phi] {
|
||||
let gt = g.tin(phi);
|
||||
for l in isolines(>, 1e12, 0.0) {
|
||||
let mut part: Vec<P2> = Vec::new();
|
||||
let flush = |part: &mut Vec<P2>, daylight: &mut Vec<Vec<P2>>| {
|
||||
if part.len() >= 2 {
|
||||
daylight.push(std::mem::take(part));
|
||||
} else {
|
||||
part.clear();
|
||||
}
|
||||
};
|
||||
let mut pl = l.pts.clone();
|
||||
if l.closed {
|
||||
pl.push(pl[0]);
|
||||
}
|
||||
for p in pl {
|
||||
if ex.dist(p).0 > 1e-6 {
|
||||
part.push(p);
|
||||
} else {
|
||||
flush(&mut part, &mut daylight);
|
||||
}
|
||||
}
|
||||
flush(&mut part, &mut daylight);
|
||||
}
|
||||
}
|
||||
for l in &daylight {
|
||||
chain(l, &|p| idx.z_at(p[0], p[1]), &mut pts, &mut cons);
|
||||
}
|
||||
// 3. Rasterpunkte im Wirkbereich.
|
||||
for j in 0..g.ny {
|
||||
for i in 0..g.nx {
|
||||
let k = j * g.nx + i;
|
||||
if t_val[k].is_finite() && d_val[k] <= r + s {
|
||||
let p = g.at(i, j);
|
||||
pts.push([p[0], p[1], ex.apply(t_val[k], p)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 4. Original ausserhalb samt Kanten.
|
||||
let mut keep = vec![u32::MAX; orig.xy.len()];
|
||||
for (i, p) in orig.xy.iter().enumerate() {
|
||||
if ex.dist(*p).0 > r + 1.5 * s {
|
||||
keep[i] = pts.len() as u32;
|
||||
pts.push([p[0], p[1], orig.z[i]]);
|
||||
}
|
||||
}
|
||||
let mut seen: HashSet<(u32, u32)> = HashSet::new();
|
||||
for tr in &orig.tris {
|
||||
for k in 0..3 {
|
||||
let (a, b) = (keep[tr[k] as usize], keep[tr[(k + 1) % 3] as usize]);
|
||||
if a != u32::MAX && b != u32::MAX && seen.insert((a.min(b), a.max(b))) {
|
||||
cons.push((a, b));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (mut tin, _) = constrained_tin(&pts, &cons, 0.3 * s, 0.0);
|
||||
// Dreiecke ausserhalb des Original-Netzes (konkave Ränder) weg.
|
||||
let xy = tin.xy.clone();
|
||||
tin.tris.retain(|tr| {
|
||||
let c = tr.iter().fold([0.0, 0.0], |a, &i| [a[0] + xy[i as usize][0] / 3.0, a[1] + xy[i as usize][1] / 3.0]);
|
||||
idx.z_at(c[0], c[1]).is_some()
|
||||
});
|
||||
Some(Excavated { tin, daylight, reach: r, step: s })
|
||||
}
|
||||
|
||||
// ── Mengen ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Abtrag, Auftrag, Hinterfüllung (m³) und Sohlenfläche (m²).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct Volumes {
|
||||
pub cut: f64,
|
||||
pub fill: f64,
|
||||
pub backfill: f64,
|
||||
pub bottom_area: f64,
|
||||
}
|
||||
|
||||
/// Integriert (t − neu) über ein Raster der Weite ≤ `h` (Mittelpunkte, höchstens ~1.5 Mio. Proben).
|
||||
/// `footprint`: Gebäude-Grundfläche (Ringe); Abtrag darin zählt nicht zur Hinterfüllung.
|
||||
pub fn volumes(orig: &Tin, ex: &ExSpec, h: f64, footprint: &[Vec<P2>]) -> Volumes {
|
||||
let idx = TinIndex::new(orig);
|
||||
let r = ex.reach_in(orig, &idx);
|
||||
let b = ex.bbox();
|
||||
let reg = [b[0] - r, b[1] - r, b[2] + r, b[3] + r];
|
||||
let (w, hh) = (reg[2] - reg[0], reg[3] - reg[1]);
|
||||
let mut h = h.max(1e-3);
|
||||
while (w / h).ceil() * (hh / h).ceil() > 1.5e6 {
|
||||
h *= 1.2;
|
||||
}
|
||||
let (nx, ny) = ((w / h).ceil() as usize, (hh / h).ceil() as usize);
|
||||
let (hx, hy) = (w / nx as f64, hh / ny as f64);
|
||||
let cell = hx * hy;
|
||||
let mut v = Volumes { bottom_area: signed_area(&ex.ring).abs(), ..Default::default() };
|
||||
for j in 0..ny {
|
||||
for i in 0..nx {
|
||||
let p = [reg[0] + (i as f64 + 0.5) * hx, reg[1] + (j as f64 + 0.5) * hy];
|
||||
let Some(t) = idx.z_at(p[0], p[1]) else { continue };
|
||||
let dz = t - ex.apply(t, p);
|
||||
if dz > 0.0 {
|
||||
v.cut += dz * cell;
|
||||
if !footprint.iter().any(|f| point_in_ring(p, f)) {
|
||||
v.backfill += dz * cell;
|
||||
}
|
||||
} else {
|
||||
v.fill -= dz * cell;
|
||||
}
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
// ── Gelände mit Baugruben, zwischengespeichert ──────────────────────────────
|
||||
|
||||
/// Gelände-Netz samt angewandten Baugruben (Höhen roh, Modell = roh − `datum`).
|
||||
#[derive(Debug)]
|
||||
pub struct SiteTerrain {
|
||||
pub datum: f64,
|
||||
pub orig: Tin,
|
||||
/// Gelände nach allen Baugruben; `None`, wenn keine das Netz trifft.
|
||||
pub modified: Option<Tin>,
|
||||
/// (Baugrube, Spezifikation, Böschungsoberkante)
|
||||
pub items: Vec<(String, ExSpec, Vec<Vec<P2>>)>,
|
||||
}
|
||||
|
||||
impl SiteTerrain {
|
||||
pub fn current(&self) -> &Tin {
|
||||
self.modified.as_ref().unwrap_or(&self.orig)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn excavations(p: &Project) -> Vec<&Excavation> {
|
||||
p.context.as_deref().unwrap_or(&[]).iter().filter_map(|c| if let ContextObject::Excavation(e) = c { Some(e) } else { None }).collect()
|
||||
}
|
||||
|
||||
pub fn terrains(p: &Project) -> Vec<&TerrainMesh> {
|
||||
p.context.as_deref().unwrap_or(&[]).iter().filter_map(|c| if let ContextObject::TerrainMesh(t) = c { Some(t) } else { None }).collect()
|
||||
}
|
||||
|
||||
type Cache = Vec<(u64, Rc<SiteTerrain>)>;
|
||||
thread_local! {
|
||||
static CACHE: RefCell<Cache> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
fn hash_of(p: &Project, t: &TerrainMesh, ex: &[&Excavation]) -> u64 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
for v in t.positions.iter().chain(&t.indices) {
|
||||
v.to_bits().hash(&mut h);
|
||||
}
|
||||
p.reference_elevation_masl.map(f64::to_bits).hash(&mut h);
|
||||
for e in ex {
|
||||
serde_json::to_string(e).unwrap_or_default().hash(&mut h);
|
||||
}
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Gelände-Netz `t` mit allen Baugruben des Projekts (zwischengespeichert, Schlüssel = Inhalt).
|
||||
pub fn site_terrain(p: &Project, t: &TerrainMesh) -> Rc<SiteTerrain> {
|
||||
let ex = excavations(p);
|
||||
let key = hash_of(p, t, &ex);
|
||||
if let Some(hit) = CACHE.with(|c| c.borrow().iter().find(|(k, _)| *k == key).map(|(_, v)| v.clone())) {
|
||||
return hit;
|
||||
}
|
||||
let orig = Tin::from_flat(&t.positions, &t.indices);
|
||||
let dz = datum(p.reference_elevation_masl, &orig.z);
|
||||
let mut cur: Option<Tin> = None;
|
||||
let mut items = Vec::new();
|
||||
for e in ex {
|
||||
let Some(spec) = ExSpec::of(e, dz) else { continue };
|
||||
let base = cur.as_ref().unwrap_or(&orig);
|
||||
if let Some(r) = excavate(base, &spec) {
|
||||
items.push((e.id.clone(), spec, r.daylight));
|
||||
cur = Some(r.tin);
|
||||
}
|
||||
}
|
||||
let st = Rc::new(SiteTerrain { datum: dz, orig, modified: cur, items });
|
||||
CACHE.with(|c| {
|
||||
let mut c = c.borrow_mut();
|
||||
c.insert(0, (key, st.clone()));
|
||||
c.truncate(4);
|
||||
});
|
||||
st
|
||||
}
|
||||
|
||||
/// Gelände-Netz im Modellbezug samt Baugruben (flach: Positionen, Indizes) und ob es geändert wurde.
|
||||
/// Ohne Baugrube und ohne Höhenbezug das Original (ohne Kopie).
|
||||
pub fn terrain_model_mesh<'a>(p: &Project, t: &'a TerrainMesh) -> (std::borrow::Cow<'a, [f64]>, std::borrow::Cow<'a, [f64]>, bool) {
|
||||
use std::borrow::Cow;
|
||||
let st = site_terrain(p, t);
|
||||
if st.modified.is_none() && st.datum == 0.0 {
|
||||
return (Cow::Borrowed(&t.positions), Cow::Borrowed(&t.indices), false);
|
||||
}
|
||||
let (pos, idx) = st.current().to_flat(-st.datum);
|
||||
(Cow::Owned(pos), Cow::Owned(idx), st.modified.is_some())
|
||||
}
|
||||
|
||||
/// Mengen je Baugrube (gegen das gewachsene Terrain des ersten Netzes, das sie trifft).
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExQty {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub bottom: f64,
|
||||
pub bottom_area: f64,
|
||||
pub cut: f64,
|
||||
pub fill: f64,
|
||||
pub backfill: f64,
|
||||
}
|
||||
|
||||
pub fn quantities(p: &Project) -> Vec<ExQty> {
|
||||
let fp: Vec<Vec<P2>> = crate::site_rules::building_footprint(p).iter().flat_map(|poly| poly.first().map(|r| r.iter().map(|v| [v.x, v.y]).collect::<Vec<P2>>())).collect();
|
||||
let mut out = Vec::new();
|
||||
for e in excavations(p) {
|
||||
for t in terrains(p) {
|
||||
let st = site_terrain(p, t);
|
||||
let Some((_, spec, _)) = st.items.iter().find(|(id, ..)| *id == e.id) else { continue };
|
||||
let h = (spec.ring.iter().map(|q| q[0]).fold(f64::NEG_INFINITY, f64::max) - spec.ring.iter().map(|q| q[0]).fold(f64::INFINITY, f64::min)).max(1.0) / 400.0;
|
||||
let v = volumes(&st.orig, spec, h.clamp(0.02, 0.5), &fp);
|
||||
out.push(ExQty { id: e.id.clone(), name: e.name.clone(), bottom: e.bottom, bottom_area: v.bottom_area, cut: v.cut, fill: v.fill, backfill: v.backfill });
|
||||
break;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Höhe des gewachsenen (`designed = false`) bzw. gestalteten Terrains im Modellbezug; `None` ohne Gelände.
|
||||
pub fn terrain_z(p: &Project, x: f64, y: f64, designed: bool) -> Option<f64> {
|
||||
for t in terrains(p) {
|
||||
let st = site_terrain(p, t);
|
||||
let tin = if designed { st.current() } else { &st.orig };
|
||||
if let Some(z) = TinIndex::new(tin).z_at(x, y) {
|
||||
return Some(z - st.datum);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// ── Grundriss: Böschungsschraffur ────────────────────────────────────────────
|
||||
|
||||
/// Böschungsschraffur: Striche von der Oberkante zur Unterkante, abwechselnd lang und halb, im Abstand
|
||||
/// `spacing` entlang des Umrisses (an konvexen Ecken gefächert). `t` = Gelände vor dieser Baugrube.
|
||||
pub fn slope_hatch(t: &Tin, ex: &ExSpec, spacing: f64) -> Vec<(P2, P2)> {
|
||||
let idx = TinIndex::new(t);
|
||||
let r = ex.reach_in(t, &idx).max(spacing);
|
||||
let step = (spacing / 4.0).max(0.02);
|
||||
// Länge des geänderten Bereichs entlang des Strahls q + n·L; Vorzeichen: Abtrag (true) / Auftrag.
|
||||
let ray = |q: P2, n: P2| -> Option<(f64, bool)> {
|
||||
let mut last: Option<(f64, bool)> = None;
|
||||
let mut l = step / 2.0;
|
||||
while l <= r + step {
|
||||
let p = [q[0] + n[0] * l, q[1] + n[1] * l];
|
||||
let tz = idx.z_at(p[0], p[1])?;
|
||||
let dz = tz - ex.apply(tz, p);
|
||||
if dz.abs() < 1e-6 {
|
||||
break;
|
||||
}
|
||||
last = Some((l, dz > 0.0));
|
||||
l += step;
|
||||
}
|
||||
last
|
||||
};
|
||||
let n = ex.ring.len();
|
||||
let normal = |i: usize| {
|
||||
let (a, b) = (ex.ring[i], ex.ring[(i + 1) % n]);
|
||||
let l = (b[0] - a[0]).hypot(b[1] - a[1]).max(1e-12);
|
||||
[(b[1] - a[1]) / l, -(b[0] - a[0]) / l]
|
||||
};
|
||||
let mut rays: Vec<(P2, P2)> = Vec::new();
|
||||
for i in 0..n {
|
||||
let (a, b) = (ex.ring[i], ex.ring[(i + 1) % n]);
|
||||
let len = (b[0] - a[0]).hypot(b[1] - a[1]);
|
||||
let nn = normal(i);
|
||||
let k = (len / spacing).floor() as usize;
|
||||
let off = (len - k as f64 * spacing) / 2.0;
|
||||
for s in 0..=k {
|
||||
let f = (off + s as f64 * spacing) / len.max(1e-12);
|
||||
if f <= 1e-9 || f >= 1.0 - 1e-9 {
|
||||
continue;
|
||||
}
|
||||
rays.push(([a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f], nn));
|
||||
}
|
||||
// Fächer an der konvexen Ecke b.
|
||||
let n2 = normal((i + 1) % n);
|
||||
let cross = nn[0] * n2[1] - nn[1] * n2[0];
|
||||
if cross > 1e-9 {
|
||||
let a0 = nn[1].atan2(nn[0]);
|
||||
let mut a1 = n2[1].atan2(n2[0]);
|
||||
if a1 < a0 {
|
||||
a1 += std::f64::consts::TAU;
|
||||
}
|
||||
let mid = [((a0 + a1) / 2.0).cos(), ((a0 + a1) / 2.0).sin()];
|
||||
let lm = ray(b, mid).map_or(0.0, |r| r.0);
|
||||
let m = ((a1 - a0) * lm / spacing).floor() as usize;
|
||||
for s in 0..=m {
|
||||
let ang = a0 + (a1 - a0) * s as f64 / m.max(1) as f64;
|
||||
rays.push((b, [ang.cos(), ang.sin()]));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for (k, (q, nn)) in rays.into_iter().enumerate() {
|
||||
let Some((l, cut)) = ray(q, nn) else { continue };
|
||||
let far = [q[0] + nn[0] * l, q[1] + nn[1] * l];
|
||||
let (top, bot) = if cut { (far, q) } else { (q, far) };
|
||||
let f = if k % 2 == 0 { 1.0 } else { 0.5 };
|
||||
out.push((top, [top[0] + (bot[0] - top[0]) * f, top[1] + (bot[1] - top[1]) * f]));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Gelände vor der Baugrube `id` (für die Schraffur); `None`, wenn sie das Netz nicht trifft.
|
||||
pub fn terrain_before(st: &SiteTerrain, id: &str) -> Option<Tin> {
|
||||
let pos = st.items.iter().position(|(i, ..)| i == id)?;
|
||||
if pos == 0 {
|
||||
return Some(st.orig.clone());
|
||||
}
|
||||
let mut cur = st.orig.clone();
|
||||
for (_, spec, _) in &st.items[..pos] {
|
||||
cur = excavate(&cur, spec)?.tin;
|
||||
}
|
||||
Some(cur)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::Vec2;
|
||||
use crate::terrain::{mesh_volume, prism, watertight};
|
||||
|
||||
fn flat(z: f64, half: f64) -> Tin {
|
||||
Tin { xy: vec![[-half, -half], [half, -half], [half, half], [-half, half]], z: vec![z; 4], tris: vec![[0, 1, 2], [0, 2, 3]] }
|
||||
}
|
||||
|
||||
fn square(e: f64, bottom: f64) -> Excavation {
|
||||
Excavation {
|
||||
id: "bg".into(),
|
||||
outline: vec![Vec2 { x: -e, y: -e }, Vec2 { x: e, y: -e }, Vec2 { x: e, y: e }, Vec2 { x: -e, y: e }],
|
||||
bottom,
|
||||
slope: Some(45.0),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aushub_wie_analytisch() {
|
||||
// 10 × 10 m, 3 m tief, 45°: V = A·h + U·h²/(2 tan α) + π h³/(3 tan² α).
|
||||
let ex = ExSpec::of(&square(5.0, -3.0), 0.0).unwrap();
|
||||
let t = flat(0.0, 50.0);
|
||||
let exact = 100.0 * 3.0 + 40.0 * 9.0 / 2.0 + std::f64::consts::PI * 27.0 / 3.0;
|
||||
let v = volumes(&t, &ex, 0.02, &[]);
|
||||
assert!((v.cut - exact).abs() < 2e-3 * exact, "{} vs {exact}", v.cut);
|
||||
assert!(v.fill.abs() < 1e-9 && (v.bottom_area - 100.0).abs() < 1e-9);
|
||||
// Hinterfüllung: ohne Gebäude = Abtrag; mit Gebäude 10 × 10 = Abtrag − 300.
|
||||
assert!((v.backfill - v.cut).abs() < 1e-9);
|
||||
let fp = vec![vec![[-5.0, -5.0], [5.0, -5.0], [5.0, 5.0], [-5.0, 5.0]]];
|
||||
let v2 = volumes(&t, &ex, 0.02, &fp);
|
||||
assert!((v.cut - v2.backfill - 300.0).abs() < 1.0, "{}", v2.backfill);
|
||||
// Netz: dicht als Prisma, Volumen-Differenz ≈ Aushub.
|
||||
let r = excavate(&t, &ex).unwrap();
|
||||
let (v0, f0) = prism(&t, -10.0);
|
||||
let (v1, f1) = prism(&r.tin, -10.0);
|
||||
assert!(watertight(&f1));
|
||||
let dv = mesh_volume(&v0, &f0) - mesh_volume(&v1, &f1);
|
||||
assert!((dv - exact).abs() < 0.02 * exact, "{dv} vs {exact}");
|
||||
// Sohle und Böschungsoberkante: Oberkante als geschlossener Ring bei d = 3.
|
||||
let z = TinIndex::new(&r.tin).z_at(0.0, 0.0).unwrap();
|
||||
assert!((z + 3.0).abs() < 1e-9);
|
||||
assert!(!r.daylight.is_empty());
|
||||
for l in &r.daylight {
|
||||
for q in l {
|
||||
assert!((ex.dist(*q).0 - 3.0).abs() < 0.1, "{q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auftrag_am_hang_und_bermen() {
|
||||
// Hang 10 %: Plattform auf ±0 schneidet bergseits ein und wird talseits geschüttet.
|
||||
let t = Tin { xy: vec![[-50.0, -50.0], [50.0, -50.0], [50.0, 50.0], [-50.0, 50.0]], z: vec![-5.0, -5.0, 5.0, 5.0], tris: vec![[0, 1, 2], [0, 2, 3]] };
|
||||
let ex = ExSpec::of(&square(5.0, 0.0), 0.0).unwrap();
|
||||
let v = volumes(&t, &ex, 0.05, &[]);
|
||||
assert!(v.cut > 10.0 && v.fill > 10.0, "{v:?}");
|
||||
// Bermen verlängern die Böschung: mehr Aushub als ohne.
|
||||
let mut e = square(5.0, -6.0);
|
||||
let base = volumes(&flat(0.0, 60.0), &ExSpec::of(&e, 0.0).unwrap(), 0.05, &[]).cut;
|
||||
e.berm_width = Some(1.0);
|
||||
e.berm_height = Some(2.0);
|
||||
let sp = ExSpec::of(&e, 0.0).unwrap();
|
||||
assert!((sp.profile(2.0, 1.0) - 2.0).abs() < 1e-12 && (sp.profile(2.5, 1.0) - 2.0).abs() < 1e-12 && (sp.profile(3.5, 1.0) - 2.5).abs() < 1e-12);
|
||||
assert!((sp.reach(2.5, 1.0) - 3.5).abs() < 1e-12);
|
||||
assert!(volumes(&flat(0.0, 60.0), &sp, 0.05, &[]).cut > base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schraffur_und_unsinn() {
|
||||
let t = flat(0.0, 50.0);
|
||||
let mut e = square(5.0, -3.0);
|
||||
// Umlaufsinn im Uhrzeigersinn: Kantenneigungen wandern mit.
|
||||
e.outline.reverse();
|
||||
e.edge_slopes = Some(vec![60.0, 45.0, 45.0, 45.0]);
|
||||
let ex = ExSpec::of(&e, 0.0).unwrap();
|
||||
// Kante 0 war (−5,5)→(5,5) (oben); dort steiler: Böschung kürzer.
|
||||
let h = slope_hatch(&t, &ex, 0.5);
|
||||
assert!(h.len() > 40);
|
||||
let top: Vec<_> = h.iter().filter(|(a, _)| a[1] > 5.0 + 1e-6 && a[0].abs() < 4.0).collect();
|
||||
assert!(!top.is_empty() && top.iter().all(|(a, _)| a[1] < 5.0 + 3.0 / 60f64.to_radians().tan() + 0.2));
|
||||
assert!(ExSpec::of(&Excavation { outline: vec![Vec2 { x: 0.0, y: 0.0 }], ..Default::default() }, 0.0).is_none());
|
||||
assert!(ExSpec::of(&Excavation { bottom: f64::NAN, ..square(1.0, 0.0) }, 0.0).is_none());
|
||||
// Ausserhalb des Netzes: nichts.
|
||||
let far = ExSpec::of(&Excavation { outline: square(1.0, 0.0).outline.iter().map(|v| Vec2 { x: v.x + 500.0, y: v.y }).collect(), ..square(1.0, 0.0) }, 0.0).unwrap();
|
||||
assert!(excavate(&t, &far).is_none());
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ fn shift_geom(g: &mut Drawing2DGeom, dx: f64, dy: f64) {
|
||||
*max = shift(*max, dx, dy);
|
||||
}
|
||||
Circle { center, .. } | Arc { center, .. } | Ellipse { center, .. } => *center = shift(*center, dx, dy),
|
||||
Kote { at, .. } | Detailref { at, .. } | Scalebar { at, .. } | Pointmarker { at } | Block { at, .. } => *at = shift(*at, dx, dy),
|
||||
Grid { origin: at, .. } | Kote { at, .. } | Detailref { at, .. } | Scalebar { at, .. } | Pointmarker { at } | Block { at, .. } => *at = shift(*at, dx, dy),
|
||||
Text { at, leader_target, leader_bend_points, path_pts, .. } => {
|
||||
*at = shift(*at, dx, dy);
|
||||
if let Some(t) = leader_target {
|
||||
@@ -63,6 +63,7 @@ fn shift_context(o: &mut ContextObject, dx: f64, dy: f64) {
|
||||
}
|
||||
ContextObject::ImportedMesh(m) => shift_positions(&mut m.positions, dx, dy),
|
||||
ContextObject::TerrainMesh(m) => shift_positions(&mut m.positions, dx, dy),
|
||||
ContextObject::Excavation(e) => shift_all(&mut e.outline, dx, dy),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -63,6 +63,7 @@ fn shift_geom(g: &Value, dx: f64, dy: f64) -> Value {
|
||||
"rect" | "image" => shift_pts_fields(&mut m, &["min", "max"], dx, dy, &[]),
|
||||
"circle" | "arc" | "ellipse" => shift_pts_fields(&mut m, &["center"], dx, dy, &[]),
|
||||
"kote" | "detailref" | "scalebar" | "pointmarker" | "block" => shift_pts_fields(&mut m, &["at"], dx, dy, &[]),
|
||||
"grid" => shift_pts_fields(&mut m, &["origin"], dx, dy, &[]),
|
||||
"text" => {
|
||||
shift_pts_fields(&mut m, &["at"], dx, dy, &[]);
|
||||
if truthy(g.get("leaderTarget")) {
|
||||
|
||||
@@ -0,0 +1,466 @@
|
||||
//! Achsraster ([112]): Geometrie der Rasterachsen, Achsblasen, Fangpunkte und Schnitt-/Ansichtslinien.
|
||||
//!
|
||||
//! Das Raster ist eine 2D-Zeichnung (`Drawing2DGeom::Grid`, Auswahl/Verschieben/Kopieren/Ebenen wie
|
||||
//! jede Zeichnung). Rechtwinklig: `a` = Achsen parallel zur lokalen Y-Achse (X = `pos`), `b` = Achsen
|
||||
//! parallel zur lokalen X-Achse (Y = `pos`). Radial: `a` = Strahlen (`pos` = Grad gegen `angle`),
|
||||
//! `b` = Ringe (`pos` = Radius). Die Achsen tragen fortlaufende Indizes: erst `a`, dann `b`.
|
||||
|
||||
use crate::model::{Drawing2D, Drawing2DGeom, GridAxis, GridBubbles};
|
||||
|
||||
pub type P = (f64, f64);
|
||||
|
||||
/// Überstand der Achsen über die äusserste Querachse (Meter).
|
||||
pub const DEFAULT_EXTEND: f64 = 1.5;
|
||||
/// Blasen-Durchmesser (Papier-mm).
|
||||
pub const DEFAULT_BUBBLE_MM: f64 = 8.0;
|
||||
|
||||
/// Verlauf einer Achse: Strecke oder Kreisbogen (gegen den Uhrzeigersinn von `a0` nach `a1`).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Shape {
|
||||
Line { a: P, b: P },
|
||||
Arc { c: P, r: f64, a0: f64, a1: f64 },
|
||||
}
|
||||
|
||||
/// Eine Rasterachse.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Axis {
|
||||
pub index: u32,
|
||||
pub label: String,
|
||||
pub shape: Shape,
|
||||
/// Blasen an Anfang/Ende: Endpunkt der Achse und Richtung nach aussen.
|
||||
pub bubbles: [Option<(P, P)>; 2],
|
||||
}
|
||||
|
||||
/// Parameter eines Rasters.
|
||||
pub struct Spec<'a> {
|
||||
pub origin: P,
|
||||
pub angle: f64,
|
||||
pub radial: bool,
|
||||
pub a: &'a [GridAxis],
|
||||
pub b: &'a [GridAxis],
|
||||
pub extend: f64,
|
||||
pub bubbles: GridBubbles,
|
||||
}
|
||||
|
||||
impl<'a> Spec<'a> {
|
||||
/// Raster einer Zeichnung (`None`, wenn sie keines ist).
|
||||
pub fn of(g: &'a Drawing2DGeom) -> Option<Spec<'a>> {
|
||||
let Drawing2DGeom::Grid { origin, angle, radial, a, b, extend, bubbles, .. } = g else { return None };
|
||||
Some(Spec {
|
||||
origin: (origin.x, origin.y),
|
||||
angle: *angle,
|
||||
radial: *radial == Some(true),
|
||||
a,
|
||||
b,
|
||||
extend: extend.filter(|e| e.is_finite() && *e >= 0.0).unwrap_or(DEFAULT_EXTEND),
|
||||
bubbles: bubbles.unwrap_or(GridBubbles::Both),
|
||||
})
|
||||
}
|
||||
|
||||
fn world(&self, x: f64, y: f64) -> P {
|
||||
let (s, c) = self.angle.sin_cos();
|
||||
(self.origin.0 + x * c - y * s, self.origin.1 + x * s + y * c)
|
||||
}
|
||||
|
||||
fn dir(&self, x: f64, y: f64) -> P {
|
||||
let (s, c) = self.angle.sin_cos();
|
||||
(x * c - y * s, x * s + y * c)
|
||||
}
|
||||
|
||||
fn span(list: &[GridAxis]) -> (f64, f64) {
|
||||
let it = list.iter().map(|g| g.pos).filter(|p| p.is_finite());
|
||||
let lo = it.clone().fold(f64::INFINITY, f64::min);
|
||||
let hi = it.fold(f64::NEG_INFINITY, f64::max);
|
||||
if lo > hi {
|
||||
(0.0, 0.0)
|
||||
} else {
|
||||
(lo, hi)
|
||||
}
|
||||
}
|
||||
|
||||
fn ray_angle(&self, pos: f64) -> f64 {
|
||||
self.angle + pos.to_radians()
|
||||
}
|
||||
|
||||
/// Alle Achsen (Index: `a` zuerst, dann `b`).
|
||||
pub fn axes(&self) -> Vec<Axis> {
|
||||
let want = |start: bool| match self.bubbles {
|
||||
GridBubbles::Both => true,
|
||||
GridBubbles::Start => start,
|
||||
GridBubbles::End => !start,
|
||||
};
|
||||
let mut out = Vec::with_capacity(self.a.len() + self.b.len());
|
||||
let ext = self.extend;
|
||||
if !self.radial {
|
||||
let (y0, y1) = Self::span(self.b);
|
||||
let (x0, x1) = Self::span(self.a);
|
||||
for (i, g) in self.a.iter().enumerate() {
|
||||
let (p0, p1) = (self.world(g.pos, y0 - ext), self.world(g.pos, y1 + ext));
|
||||
let (d0, d1) = (self.dir(0.0, -1.0), self.dir(0.0, 1.0));
|
||||
out.push(Axis {
|
||||
index: i as u32,
|
||||
label: g.label.clone(),
|
||||
shape: Shape::Line { a: p0, b: p1 },
|
||||
bubbles: [want(true).then_some((p0, d0)), want(false).then_some((p1, d1))],
|
||||
});
|
||||
}
|
||||
for (j, g) in self.b.iter().enumerate() {
|
||||
let (p0, p1) = (self.world(x0 - ext, g.pos), self.world(x1 + ext, g.pos));
|
||||
let (d0, d1) = (self.dir(-1.0, 0.0), self.dir(1.0, 0.0));
|
||||
out.push(Axis {
|
||||
index: (self.a.len() + j) as u32,
|
||||
label: g.label.clone(),
|
||||
shape: Shape::Line { a: p0, b: p1 },
|
||||
bubbles: [want(true).then_some((p0, d0)), want(false).then_some((p1, d1))],
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// Radial: Strahlen vom Mittelpunkt bis zum grössten Ring + Überstand, Ringe zwischen den Strahlen.
|
||||
let (_, rmax) = Self::span(self.b);
|
||||
for (i, g) in self.a.iter().enumerate() {
|
||||
let th = self.ray_angle(g.pos);
|
||||
let u = (th.cos(), th.sin());
|
||||
let end = (self.origin.0 + u.0 * (rmax + ext), self.origin.1 + u.1 * (rmax + ext));
|
||||
out.push(Axis {
|
||||
index: i as u32,
|
||||
label: g.label.clone(),
|
||||
shape: Shape::Line { a: self.origin, b: end },
|
||||
bubbles: [None, (self.bubbles != GridBubbles::Start).then_some((end, u))],
|
||||
});
|
||||
}
|
||||
let (t0, t1) = Self::span(self.a);
|
||||
let (t0, t1) = (self.ray_angle(t0), self.ray_angle(t1));
|
||||
for (j, g) in self.b.iter().enumerate() {
|
||||
let r = g.pos;
|
||||
let full = self.a.len() < 2 || t1 - t0 >= std::f64::consts::TAU - 1e-9 || r <= 1e-9;
|
||||
let (a0, a1) = if full {
|
||||
(self.angle, self.angle + std::f64::consts::TAU)
|
||||
} else {
|
||||
let da = (ext / r).min((std::f64::consts::TAU - (t1 - t0)) / 2.0);
|
||||
(t0 - da, t1 + da)
|
||||
};
|
||||
let at = |t: f64| (self.origin.0 + r * t.cos(), self.origin.1 + r * t.sin());
|
||||
let tan = |t: f64, s: f64| (-t.sin() * s, t.cos() * s);
|
||||
out.push(Axis {
|
||||
index: (self.a.len() + j) as u32,
|
||||
label: g.label.clone(),
|
||||
shape: Shape::Arc { c: self.origin, r, a0, a1 },
|
||||
bubbles: [
|
||||
(!full && want(true)).then(|| (at(a0), tan(a0, -1.0))),
|
||||
(if full { self.bubbles != GridBubbles::Start } else { want(false) }).then(|| (at(a1), tan(a1, 1.0))),
|
||||
],
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Schnittpunkte der Achsen: rechtwinklig `a` × `b`, radial Strahl × Ring.
|
||||
pub fn crossings(&self) -> Vec<P> {
|
||||
let mut out = Vec::new();
|
||||
for i in 0..self.a.len() {
|
||||
for j in 0..self.b.len() {
|
||||
if let Some(p) = self.cross(i as u32, (self.a.len() + j) as u32) {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Schnittpunkt zweier Achsen (Reihenfolge egal); gleiche Familie → `None`.
|
||||
pub fn cross(&self, i: u32, j: u32) -> Option<P> {
|
||||
let na = self.a.len() as u32;
|
||||
let (i, j) = if i < na && j >= na { (i, j) } else if j < na && i >= na { (j, i) } else { return None };
|
||||
let (ga, gb) = (self.a.get(i as usize)?, self.b.get((j - na) as usize)?);
|
||||
let p = if self.radial {
|
||||
let th = self.ray_angle(ga.pos);
|
||||
(self.origin.0 + gb.pos * th.cos(), self.origin.1 + gb.pos * th.sin())
|
||||
} else {
|
||||
self.world(ga.pos, gb.pos)
|
||||
};
|
||||
(p.0.is_finite() && p.1.is_finite()).then_some(p)
|
||||
}
|
||||
|
||||
/// Punkt auf Achse `index` beim Anteil `t` (0 = Anfang, 1 = Ende).
|
||||
pub fn point_at(&self, index: u32, t: f64) -> Option<P> {
|
||||
let ax = self.axes().into_iter().find(|a| a.index == index)?;
|
||||
let p = match ax.shape {
|
||||
Shape::Line { a, b } => (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t),
|
||||
Shape::Arc { c, r, a0, a1 } => {
|
||||
let th = a0 + (a1 - a0) * t;
|
||||
(c.0 + r * th.cos(), c.1 + r * th.sin())
|
||||
}
|
||||
};
|
||||
(p.0.is_finite() && p.1.is_finite()).then_some(p)
|
||||
}
|
||||
|
||||
/// Anteil `t` des Punkts `s` auf der Achse und sein Abstand zu ihr (nächster Punkt der Achse).
|
||||
pub fn project(&self, index: u32, s: P) -> Option<(f64, f64)> {
|
||||
let ax = self.axes().into_iter().find(|a| a.index == index)?;
|
||||
match ax.shape {
|
||||
Shape::Line { a, b } => {
|
||||
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
|
||||
let l2 = dx * dx + dy * dy;
|
||||
(l2 > 1e-18).then(|| {
|
||||
let t = ((s.0 - a.0) * dx + (s.1 - a.1) * dy) / l2;
|
||||
let q = (a.0 + dx * t, a.1 + dy * t);
|
||||
(t, (s.0 - q.0).hypot(s.1 - q.1))
|
||||
})
|
||||
}
|
||||
Shape::Arc { c, r, a0, a1 } => {
|
||||
let th = (s.1 - c.1).atan2(s.0 - c.0);
|
||||
let sweep = a1 - a0;
|
||||
let mut rel = (th - a0).rem_euclid(std::f64::consts::TAU);
|
||||
if rel > sweep.abs() + 1e-9 {
|
||||
// ausserhalb des Bogens: zum näheren Ende
|
||||
rel = if rel - sweep.abs() < std::f64::consts::TAU - rel { sweep.abs() } else { 0.0 };
|
||||
}
|
||||
(sweep.abs() > 1e-12).then(|| (rel / sweep.abs(), ((s.0 - c.0).hypot(s.1 - c.1) - r).abs()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Feldweiten aus Text: Zahlen, getrennt durch Leerzeichen/`;` (Komma als Dezimalzeichen), `N*W` oder
|
||||
/// `NxW` = N Felder zu W. Nur endliche Werte > 0, höchstens 200 Felder.
|
||||
pub fn parse_bays(text: &str) -> Option<Vec<f64>> {
|
||||
let mut out = Vec::new();
|
||||
for tok in text.split(|c: char| c.is_whitespace() || c == ';').filter(|t| !t.is_empty()) {
|
||||
let tok = tok.replace(',', ".");
|
||||
let (n, w) = match tok.split_once(['x', 'X', '*']) {
|
||||
Some((n, w)) => (n.parse::<usize>().ok()?, w.parse::<f64>().ok()?),
|
||||
None => (1, tok.parse::<f64>().ok()?),
|
||||
};
|
||||
if !(w.is_finite() && w > 0.0) || n == 0 || out.len() + n > 200 {
|
||||
return None;
|
||||
}
|
||||
out.extend(std::iter::repeat(w).take(n));
|
||||
}
|
||||
(!out.is_empty()).then_some(out)
|
||||
}
|
||||
|
||||
/// Beschriftung `i` (0-basiert) als Buchstaben A … Z, AA, AB … (ohne I und O wie im Hochbau üblich).
|
||||
pub fn letter_label(mut i: usize) -> String {
|
||||
const L: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||
let mut s = Vec::new();
|
||||
loop {
|
||||
s.push(L[i % L.len()]);
|
||||
if i < L.len() {
|
||||
break;
|
||||
}
|
||||
i = i / L.len() - 1;
|
||||
}
|
||||
s.reverse();
|
||||
String::from_utf8(s).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Achsen aus Feldweiten: rechtwinklig a = 1, 2, 3 … bei 0, Σ…; b = A, B, C … ebenso. Radial: a =
|
||||
/// Strahlen (Winkel in Grad ab 0), b = Ringe (Radien = laufende Summe, der erste Ring beim ersten Mass).
|
||||
pub fn axes_from_bays(radial: bool, xs: &[f64], ys: &[f64]) -> (Vec<GridAxis>, Vec<GridAxis>) {
|
||||
let cum = |w: &[f64], zero: bool| {
|
||||
let mut acc = 0.0;
|
||||
let mut out = Vec::new();
|
||||
if zero {
|
||||
out.push(0.0);
|
||||
}
|
||||
for v in w {
|
||||
acc += v;
|
||||
out.push(acc);
|
||||
}
|
||||
out
|
||||
};
|
||||
let a = cum(xs, true).iter().enumerate().map(|(i, p)| GridAxis { label: (i + 1).to_string(), pos: *p }).collect();
|
||||
let b = cum(ys, !radial).iter().enumerate().map(|(i, p)| GridAxis { label: letter_label(i), pos: *p }).collect();
|
||||
(a, b)
|
||||
}
|
||||
|
||||
/// Achsen als Punktfolgen für die 3D-Spur (Bögen in 7.5°-Schritten).
|
||||
pub fn polylines_3d(spec: &Spec) -> Vec<Vec<P>> {
|
||||
spec.axes()
|
||||
.into_iter()
|
||||
.map(|ax| match ax.shape {
|
||||
Shape::Line { a, b } => vec![a, b],
|
||||
Shape::Arc { c, r, a0, a1 } => {
|
||||
let n = (((a1 - a0).abs() / (std::f64::consts::PI / 24.0)).ceil() as usize).clamp(2, 400);
|
||||
(0..=n).map(|i| a0 + (a1 - a0) * i as f64 / n as f64).map(|t| (c.0 + r * t.cos(), c.1 + r * t.sin())).collect()
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Wird das Raster `d` im Geschoss `level` gezeigt? (`levels` fehlt/leer = in allen Geschossen.)
|
||||
pub fn visible_on(d: &Drawing2D, level: &str) -> bool {
|
||||
match &d.geom {
|
||||
Drawing2DGeom::Grid { levels: Some(l), .. } if !l.is_empty() => l.iter().any(|x| x == level),
|
||||
Drawing2DGeom::Grid { .. } => true,
|
||||
_ => d.level_id == level,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bildmass der Blase (Durchmesser, Modell-Meter) aus Papier-mm und Massstab.
|
||||
pub fn bubble_diameter(mm: Option<f64>, scale: f64) -> f64 {
|
||||
mm.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(DEFAULT_BUBBLE_MM) * scale / 1000.0
|
||||
}
|
||||
|
||||
/// Senkrechte Achsen eines Schnitts/einer Ansicht: Raster-Achsen (nur Strecken) als (Beschriftung,
|
||||
/// Lage entlang der Schnittlinien-Achse u). `origin`/`dir` = Schnittlinie (Einheitsvektor `dir`).
|
||||
/// Schnitt (`projected` false): die Achse muss die Schnittebene innerhalb ihrer Länge schneiden.
|
||||
/// Ansicht (`projected` true): Achsen, die (bis 5°) senkrecht auf der Ansichtsebene stehen, erscheinen
|
||||
/// unabhängig von ihrer Länge an der Stelle, an der ihre Verlängerung die Ebene trifft.
|
||||
pub fn section_axes(spec: &Spec, origin: P, dir: P, projected: bool) -> Vec<(String, f64)> {
|
||||
let mut out = Vec::new();
|
||||
for ax in spec.axes() {
|
||||
let Shape::Line { a, b } = ax.shape else { continue };
|
||||
let (rx, ry) = (b.0 - a.0, b.1 - a.1);
|
||||
let den = dir.0 * ry - dir.1 * rx;
|
||||
let slope = if projected { 0.996 } else { 1e-9 };
|
||||
if den.abs() < slope * rx.hypot(ry).max(1e-12) {
|
||||
continue;
|
||||
}
|
||||
// Schnitt Gerade origin+u*dir mit der Achsstrecke a+t*r.
|
||||
let (qx, qy) = (a.0 - origin.0, a.1 - origin.1);
|
||||
let t = (qx * dir.1 - qy * dir.0) / den;
|
||||
if !projected && !(-1e-9..=1.0 + 1e-9).contains(&t) {
|
||||
continue;
|
||||
}
|
||||
let u = (qx * ry - qy * rx) / den;
|
||||
out.push((ax.label.clone(), u));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::Vec2;
|
||||
|
||||
fn ax(l: &str, p: f64) -> GridAxis {
|
||||
GridAxis { label: l.into(), pos: p }
|
||||
}
|
||||
|
||||
fn ortho() -> Drawing2DGeom {
|
||||
Drawing2DGeom::Grid {
|
||||
origin: Vec2 { x: 10.0, y: 20.0 },
|
||||
angle: 0.0,
|
||||
radial: None,
|
||||
a: vec![ax("1", 0.0), ax("2", 4.0), ax("3", 10.0)],
|
||||
b: vec![ax("A", 0.0), ax("B", 5.0)],
|
||||
extend: Some(2.0),
|
||||
bubbles: None,
|
||||
bubble_mm: None,
|
||||
levels: None,
|
||||
show_3d: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unregelmaessiger_raster_achsen_und_ueberstand() {
|
||||
let g = ortho();
|
||||
let s = Spec::of(&g).unwrap();
|
||||
let axes = s.axes();
|
||||
assert_eq!(axes.len(), 5);
|
||||
// Achse "2": senkrecht bei x = 14, von y = 18 bis 27.
|
||||
assert_eq!(axes[1].shape, Shape::Line { a: (14.0, 18.0), b: (14.0, 27.0) });
|
||||
// Achse "B": waagrecht bei y = 25, von x = 8 bis 22.
|
||||
assert_eq!(axes[4].shape, Shape::Line { a: (8.0, 25.0), b: (22.0, 25.0) });
|
||||
// Blasen an beiden Enden, Richtung nach aussen.
|
||||
assert_eq!(axes[1].bubbles[0], Some(((14.0, 18.0), (0.0, -1.0))));
|
||||
assert_eq!(axes[1].bubbles[1], Some(((14.0, 27.0), (0.0, 1.0))));
|
||||
assert_eq!(s.crossings().len(), 6);
|
||||
assert_eq!(s.cross(4, 1), Some((14.0, 25.0)));
|
||||
assert_eq!(s.cross(0, 1), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gedrehtes_raster_und_blasenseite() {
|
||||
let mut g = ortho();
|
||||
if let Drawing2DGeom::Grid { angle, bubbles, .. } = &mut g {
|
||||
*angle = std::f64::consts::FRAC_PI_2;
|
||||
*bubbles = Some(GridBubbles::End);
|
||||
}
|
||||
let s = Spec::of(&g).unwrap();
|
||||
let p = s.cross(1, 4).unwrap(); // Achse 2 x B: lokal (4, 5) -> (10 - 5, 20 + 4)
|
||||
assert!((p.0 - 5.0).abs() < 1e-12 && (p.1 - 24.0).abs() < 1e-12);
|
||||
let a = &s.axes()[0];
|
||||
assert!(a.bubbles[0].is_none() && a.bubbles[1].is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_strahlen_ringe() {
|
||||
let g = Drawing2DGeom::Grid {
|
||||
origin: Vec2 { x: 0.0, y: 0.0 },
|
||||
angle: 0.0,
|
||||
radial: Some(true),
|
||||
a: vec![ax("1", 0.0), ax("2", 90.0)],
|
||||
b: vec![ax("A", 3.0), ax("B", 6.0)],
|
||||
extend: Some(1.0),
|
||||
bubbles: None,
|
||||
bubble_mm: None,
|
||||
levels: None,
|
||||
show_3d: None,
|
||||
};
|
||||
let s = Spec::of(&g).unwrap();
|
||||
let axes = s.axes();
|
||||
assert_eq!(axes.len(), 4);
|
||||
match axes[0].shape {
|
||||
Shape::Line { b, .. } => assert!((b.0 - 7.0).abs() < 1e-12 && b.1.abs() < 1e-12),
|
||||
_ => panic!(),
|
||||
}
|
||||
let p = s.cross(1, 3).unwrap();
|
||||
assert!(p.0.abs() < 1e-12 && (p.1 - 6.0).abs() < 1e-12);
|
||||
match axes[2].shape {
|
||||
Shape::Arc { a0, a1, r, .. } => {
|
||||
assert_eq!(r, 3.0);
|
||||
assert!(a0 < 0.0 && a1 > std::f64::consts::FRAC_PI_2);
|
||||
}
|
||||
_ => panic!(),
|
||||
}
|
||||
// Projektion auf den Ring.
|
||||
let (t, d) = s.project(2, (0.0, 3.5)).unwrap();
|
||||
assert!((d - 0.5).abs() < 1e-9 && t > 0.0 && t < 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feldweiten_und_beschriftung() {
|
||||
assert_eq!(parse_bays("5 4,5 3x6"), Some(vec![5.0, 4.5, 6.0, 6.0, 6.0]));
|
||||
assert_eq!(parse_bays("2*3.2; 4"), Some(vec![3.2, 3.2, 4.0]));
|
||||
assert_eq!(parse_bays(""), None);
|
||||
assert_eq!(parse_bays("5 -1"), None);
|
||||
assert_eq!(parse_bays("abc"), None);
|
||||
assert_eq!(parse_bays("0x5"), None);
|
||||
assert_eq!((letter_label(0), letter_label(7), letter_label(8), letter_label(23), letter_label(24)), ("A".into(), "H".into(), "J".into(), "Z".into(), "AA".into()));
|
||||
let (a, b) = axes_from_bays(false, &[5.0, 3.0], &[4.0]);
|
||||
assert_eq!(a.iter().map(|x| (x.label.as_str(), x.pos)).collect::<Vec<_>>(), [("1", 0.0), ("2", 5.0), ("3", 8.0)]);
|
||||
assert_eq!(b.iter().map(|x| (x.label.as_str(), x.pos)).collect::<Vec<_>>(), [("A", 0.0), ("B", 4.0)]);
|
||||
// Radial: Ringe ohne Radius 0.
|
||||
let (_, rings) = axes_from_bays(true, &[45.0], &[2.0, 3.0]);
|
||||
assert_eq!(rings.iter().map(|x| x.pos).collect::<Vec<_>>(), [2.0, 5.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sichtbarkeit_je_geschoss() {
|
||||
let mut d = Drawing2D { level_id: "eg".into(), geom: ortho(), ..Default::default() };
|
||||
assert!(visible_on(&d, "og") && visible_on(&d, "eg"));
|
||||
if let Drawing2DGeom::Grid { levels, .. } = &mut d.geom {
|
||||
*levels = Some(vec!["eg".into()]);
|
||||
}
|
||||
assert!(visible_on(&d, "eg") && !visible_on(&d, "og"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schnittachsen_quer_zur_schnittlinie() {
|
||||
let g = ortho();
|
||||
let s = Spec::of(&g).unwrap();
|
||||
// Schnitt entlang +x bei y = 22: schneidet die senkrechten Achsen 1, 2, 3 bei u = 0, 4, 10 (ab x = 10).
|
||||
let r = section_axes(&s, (10.0, 22.0), (1.0, 0.0), false);
|
||||
let us: Vec<f64> = r.iter().map(|x| x.1).collect();
|
||||
assert_eq!(r.len(), 3);
|
||||
assert!((us[0]).abs() < 1e-9 && (us[1] - 4.0).abs() < 1e-9 && (us[2] - 10.0).abs() < 1e-9);
|
||||
// Ausserhalb der Achslänge: nichts.
|
||||
assert!(section_axes(&s, (10.0, 40.0), (1.0, 0.0), false).is_empty());
|
||||
// Ansicht von aussen (Ebene bei y = 40): die senkrechten Achsen erscheinen trotzdem, die waagrechten nicht.
|
||||
let v = section_axes(&s, (10.0, 40.0), (1.0, 0.0), true);
|
||||
assert_eq!(v.iter().map(|x| x.0.as_str()).collect::<Vec<_>>(), ["1", "2", "3"]);
|
||||
}
|
||||
}
|
||||
@@ -613,6 +613,11 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option<Val
|
||||
let ng = with(g, "pts", replace_at(pts, index, &p));
|
||||
return Some(with_geom(d, crate::dim_assoc::without_ref(&ng, index_in(index, n))));
|
||||
}
|
||||
if index == n as f64 && field(g, "kind").and_then(Value::as_str) == Some("arc") && n >= 2 {
|
||||
// Bogenlängen-Mass: Abstand der Masslinie vom Bogen (radial).
|
||||
let (c, p0) = (xy(&pts[0]), xy(&pts[1]));
|
||||
return set("offset", js_num(hypot2(x - c.0, y - c.1) - hypot2(p0.0 - c.0, p0.1 - c.1)));
|
||||
}
|
||||
if index == n as f64 {
|
||||
// Griff auf der Masslinie: nur `offset` (Normalabstand zur Punktreihe).
|
||||
let (a, b) = (xy(pts.first()?), xy(pts.last()?));
|
||||
@@ -698,6 +703,33 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option<Val
|
||||
set("at", p)
|
||||
}
|
||||
"kote" | "detailref" | "scalebar" | "pointmarker" | "block" => set("at", p),
|
||||
"grid" => {
|
||||
// Griff 0 = Ursprung, danach je Achse (a, dann b) das Achsende: zieht die Achse auf die neue Lage.
|
||||
if index == 0.0 {
|
||||
return set("origin", p);
|
||||
}
|
||||
let (na, nb) = (arr(field(g, "a")).len(), arr(field(g, "b")).len());
|
||||
let k = index_in(index - 1.0, na + nb)?;
|
||||
let (ox, oy) = xy(field(g, "origin").unwrap_or(&Value::Null));
|
||||
let ang = num_of(field(g, "angle"));
|
||||
let (dx, dy) = (x - ox, y - oy);
|
||||
let radial = field(g, "radial").and_then(Value::as_bool) == Some(true);
|
||||
let (key, i) = if k < na { ("a", k) } else { ("b", k - na) };
|
||||
let pos = match (radial, key) {
|
||||
(false, "a") => dx * jsnum::cos(ang) + dy * jsnum::sin(ang),
|
||||
(false, _) => -dx * jsnum::sin(ang) + dy * jsnum::cos(ang),
|
||||
(true, "a") => {
|
||||
let d = (jsnum::atan2(dy, dx) - ang).to_degrees();
|
||||
let old = num_of(field(&arr(field(g, "a"))[i], "pos"));
|
||||
// auf den Winkel nächst dem alten legen (kein Sprung um 360°)
|
||||
old + (d - old + 180.0).rem_euclid(360.0) - 180.0
|
||||
}
|
||||
(true, _) => hypot2(dx, dy),
|
||||
};
|
||||
let list = arr(field(g, key));
|
||||
let nl = Value::Array(list.iter().enumerate().map(|(j, e)| if j == i { with(e, "pos", js_num(pos)) } else { e.clone() }).collect());
|
||||
set(key, nl)
|
||||
}
|
||||
"circle" => {
|
||||
let (cx, cy) = xy(field(g, "center").unwrap_or(&Value::Null));
|
||||
let r = pass(field(g, "r"));
|
||||
@@ -758,6 +790,7 @@ fn drawing_moved(d: &Value, dx: f64, dy: f64) -> Option<Value> {
|
||||
"rect" | "image" => with_all(g, vec![("min", mv("min")), ("max", mv("max"))]),
|
||||
"circle" | "arc" | "ellipse" => with(g, "center", mv("center")),
|
||||
"kote" | "detailref" | "scalebar" | "pointmarker" | "text" => with(g, "at", mv("at")),
|
||||
"grid" => with(g, "origin", mv("origin")),
|
||||
_ => return None,
|
||||
};
|
||||
Some(with_geom(d, ng))
|
||||
@@ -1229,6 +1262,18 @@ pub fn drawing_vertices(g: &Value, scale: f64) -> Option<Vec<(f64, f64)>> {
|
||||
out
|
||||
}
|
||||
"kote" | "detailref" | "scalebar" | "pointmarker" | "block" => vec![p("at")],
|
||||
"grid" => {
|
||||
let geom: crate::model::Drawing2DGeom = serde_json::from_value(g.clone()).ok()?;
|
||||
let spec = crate::grid::Spec::of(&geom)?;
|
||||
let mut out = vec![p("origin")];
|
||||
for ax in spec.axes() {
|
||||
out.push(match ax.shape {
|
||||
crate::grid::Shape::Line { b, .. } => b,
|
||||
crate::grid::Shape::Arc { c, r, a1, .. } => (c.0 + r * jsnum::cos(a1), c.1 + r * jsnum::sin(a1)),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
"text" => {
|
||||
if truthy(field(g, "pathPts")) {
|
||||
pts("pathPts")
|
||||
|
||||
@@ -269,7 +269,7 @@ fn by_from(p: &[f64; 4], q: &[f64; 4]) -> std::cmp::Ordering {
|
||||
fn bands_match_openings(wall: &Wall, bands: &[&RWall], cutouts: &[Cutout]) -> bool {
|
||||
let u = normalize(sub(wall.end, wall.start));
|
||||
for b in bands {
|
||||
if b.top_drop.is_some_and(|d| d[0].abs() > 1e-9 || d[1].abs() > 1e-9) {
|
||||
if b.top_plane.is_some() || b.top_drop.is_some_and(|d| d[0].abs() > 1e-9 || d[1].abs() > 1e-9) {
|
||||
return false;
|
||||
}
|
||||
let a = dot(Vec2 { x: b.start[0] - wall.start.x, y: b.start[1] - wall.start.y }, u);
|
||||
@@ -497,6 +497,33 @@ struct SolidOpening {
|
||||
/// Dreiecke eines 8-Ecken-Quaders wie `model3d::OPENING_BOX_TRIS`.
|
||||
const BOX_TRIS: [u32; 36] = [0, 1, 3, 0, 3, 2, 4, 5, 7, 4, 7, 6, 0, 1, 5, 0, 5, 4, 2, 3, 7, 2, 7, 6, 0, 2, 6, 0, 6, 4, 1, 3, 7, 1, 7, 5];
|
||||
|
||||
/// Gauben eines Dachs (Index) für die Mengen ([G5]): je Gaube Breite, Stirnhöhe, geneigte Fläche des
|
||||
/// Ausschnitts im Hauptdach, Volumen der Wände (Stirn/Wangen) und des Gaubendachs aus den Körpern.
|
||||
fn dormer_parts(p: &Project, ri: usize, roof: &Roof) -> Vec<qty::DormerIn> {
|
||||
let solids = crate::roof_assembly::roof_solids(p, ri);
|
||||
let vol = |id: &str, role: crate::roof_assembly::Role| -> f64 {
|
||||
solids.as_ref().map_or(0.0, |s| s.parts.iter().filter(|x| x.role == role && x.dormer.as_deref() == Some(id)).map(|x| x.mesh.volume().abs()).sum())
|
||||
};
|
||||
roof.dormers
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.filter_map(|d| {
|
||||
let g = crate::dormer::geometry(p, roof, d)?;
|
||||
let hole = g.hole();
|
||||
let n = hole.len();
|
||||
let proj = (0..n).map(|i| hole[i][0] * hole[(i + 1) % n][1] - hole[(i + 1) % n][0] * hole[i][1]).sum::<f64>().abs() / 2.0;
|
||||
Some(qty::DormerIn {
|
||||
width: d.width,
|
||||
front_height: g.front_height,
|
||||
opening_area: proj * (1.0 + g.frame.tan_main * g.frame.tan_main).sqrt(),
|
||||
wall_volume: vol(&d.id, crate::roof_assembly::Role::DormerWall),
|
||||
roof_volume: vol(&d.id, crate::roof_assembly::Role::DormerRoof),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn push_box(positions: &mut Vec<f64>, indices: &mut Vec<u32>, b: &[f64; 24], base: f64) {
|
||||
let at = (positions.len() / 3) as u32;
|
||||
for c in b.chunks_exact(3) {
|
||||
@@ -766,6 +793,17 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result<Flat, String>
|
||||
let bands = bands_by_wall.get(wall.id.as_str()).unwrap_or(&no_bands);
|
||||
let (mut positions, mut indices) = (Vec::<f64>::new(), Vec::<u32>::new());
|
||||
for b in bands {
|
||||
// Ebene Oberkante unter einem Dach ([G2]): Prisma bis an die Dachunterkante.
|
||||
if b.top_plane.is_some() && b.holes.as_ref().is_none_or(|h| h.is_empty()) {
|
||||
if let Some(m) = model3d::wall_piece_mesh(b) {
|
||||
let at = (positions.len() / 3) as u32;
|
||||
for c in m.positions.chunks_exact(3) {
|
||||
positions.extend_from_slice(&[c[0], c[1], c[2] - base]);
|
||||
}
|
||||
indices.extend(m.indices.iter().map(|i| at + i));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let cut = wall_cut_mesh_checked(&CutWall {
|
||||
start: b.start,
|
||||
end: b.end,
|
||||
@@ -1085,7 +1123,16 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result<Flat, String>
|
||||
props.extend(crate::u_value::roof_u_value(&p, roof).and_then(|u| u.u).map(|u| Prop::Thermal("ThermalTransmittance", u)));
|
||||
let planes = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof)).planes;
|
||||
let mut psets = vec![Pset { name: "Pset_RoofCommon", props }];
|
||||
psets.extend(qto("Qto_RoofBaseQuantities", qty::roof_quantities(&planes)));
|
||||
let mut roof_q = qty::roof_quantities(&planes);
|
||||
// Gauben ([G5]): Ausschnitt im Hauptdach (geneigt) von der Nettofläche ab, eigene Mengen der Gauben.
|
||||
let dormer_q = p.roofs.as_deref().unwrap_or(&[]).iter().position(|r| r.id == roof.id).map_or_else(Vec::new, |ri| qty::dormer_quantities(&dormer_parts(&p, ri, roof)));
|
||||
if let Some(cut) = dormer_q.iter().find(|q| q.name == "OpeningArea").map(|q| q.value) {
|
||||
if let Some(net) = roof_q.iter_mut().find(|q| q.name == "NetArea") {
|
||||
net.value = max(0.0, net.value - cut);
|
||||
}
|
||||
}
|
||||
psets.extend(qto("Qto_RoofBaseQuantities", roof_q));
|
||||
psets.extend(qto("Qto_DossierDormerQuantities", dormer_q));
|
||||
let ty = roof_type.map(|t| (t.id.clone(), t.name.clone(), t.layers.iter().map(|l| (l.component_id.clone(), component_name(&p, &l.component_id), l.thickness)).collect::<Vec<_>>()));
|
||||
let (id, name, pre) = (f.str(&roof.id), f.str(roof_type.map_or("Dach", |t| t.name.as_str())), f.str(predefined));
|
||||
f.nums(&[REC_ROOF, structure, id, name, pre]);
|
||||
@@ -1253,6 +1300,20 @@ mod tests {
|
||||
assert_eq!(f.nums.iter().filter(|v| **v == REC_OPENING_SOLID).count() >= 2, true);
|
||||
}
|
||||
|
||||
/// [G5] Gauben-Mengen: Ausschnitt geneigt, Wand- und Dachvolumen aus den Körpern.
|
||||
#[test]
|
||||
fn gauben_mengen() {
|
||||
let p = crate::dormer::tests::gable_project();
|
||||
let roof = &p.roofs.as_ref().unwrap()[0];
|
||||
let d = dormer_parts(&p, 0, roof);
|
||||
assert_eq!(d.len(), 1);
|
||||
assert!(d[0].opening_area > 2.4 * 1.6 * 2f64.sqrt() && d[0].opening_area < 2.4 * 3.0 * 2f64.sqrt(), "{d:?}");
|
||||
assert!(d[0].wall_volume > 0.1 && d[0].roof_volume > 0.1, "{d:?}");
|
||||
let q = qty::dormer_quantities(&d);
|
||||
assert_eq!(q.len(), 5);
|
||||
assert!(qty::dormer_quantities(&[]).is_empty());
|
||||
}
|
||||
|
||||
/// [T2] Bogenwand: Datensatz WALL_ARC mit Kreisachse (Mitte, Radius, Startwinkel, Schwenk).
|
||||
#[test]
|
||||
fn bogenwand_als_netz_mit_kreisachse() {
|
||||
|
||||
@@ -115,9 +115,15 @@ pub fn wall_quantities(start: Vec2, end: Vec2, bands: &[&RWall], cutouts: &[Cuto
|
||||
z_min = min(z_min, b.base_elevation);
|
||||
z_max = max(z_max, b.base_elevation + b.height);
|
||||
let drop = b.top_drop.map_or(0.0, |d| (d[0] + d[1]) / 2.0);
|
||||
if sloped_band(b) {
|
||||
if sloped_band(b) || b.top_plane.is_some() {
|
||||
sloped = true;
|
||||
}
|
||||
if b.top_plane.is_some() {
|
||||
// Ebene Oberkante unter einem Dach ([G2]): exakt über die Grundfläche.
|
||||
gross += crate::model3d::wall_piece_volume(b);
|
||||
tallest = max(tallest, b.height);
|
||||
continue;
|
||||
}
|
||||
gross += l * b.thickness * (b.height - drop);
|
||||
tallest = max(tallest, b.height - drop);
|
||||
}
|
||||
@@ -235,6 +241,33 @@ pub fn roof_quantities(planes: &[Vec<[f64; 3]>]) -> Vec<Qty> {
|
||||
vec![area("GrossArea", sloped), area("NetArea", sloped), area("ProjectedArea", projected)]
|
||||
}
|
||||
|
||||
/// Eine Gaube für die Mengen ([G5]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct DormerIn {
|
||||
pub width: f64,
|
||||
pub front_height: f64,
|
||||
/// Geneigte Fläche des Ausschnitts im Hauptdach.
|
||||
pub opening_area: f64,
|
||||
pub wall_volume: f64,
|
||||
pub roof_volume: f64,
|
||||
}
|
||||
|
||||
/// Gauben eines Dachs, summiert: Anzahl als Länge der Breiten (`Width`), grösste Stirnhöhe, Ausschnitt
|
||||
/// im Hauptdach, Volumen der Gaubenwände und -dächer. Leer ohne Gauben.
|
||||
pub fn dormer_quantities(d: &[DormerIn]) -> Vec<Qty> {
|
||||
if d.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let sum = |f: fn(&DormerIn) -> f64| d.iter().map(f).sum::<f64>();
|
||||
vec![
|
||||
len("Width", sum(|x| x.width)),
|
||||
len("FrontHeight", d.iter().map(|x| x.front_height).fold(0.0, f64::max)),
|
||||
area("OpeningArea", sum(|x| x.opening_area)),
|
||||
vol("WallVolume", sum(|x| x.wall_volume)),
|
||||
vol("RoofVolume", sum(|x| x.roof_volume)),
|
||||
]
|
||||
}
|
||||
|
||||
/// Stützen-Basismengen: Länge, Querschnitt, Mantel, Oberfläche und Volumen.
|
||||
pub fn column_quantities(footprint: &[Vec2], length: f64) -> Vec<Qty> {
|
||||
let cross = ring_area(footprint);
|
||||
@@ -283,6 +316,7 @@ mod tests {
|
||||
height,
|
||||
base_elevation: base,
|
||||
top_drop: None,
|
||||
top_plane: None,
|
||||
color: [0.5, 0.5, 0.5],
|
||||
layers: vec![],
|
||||
wall_id: "w".into(),
|
||||
|
||||
@@ -374,6 +374,7 @@ pub fn decode_mesh(f: &[f64], strings: &[String]) -> Result<(Vec<MeshObject>, Va
|
||||
k += 1.0;
|
||||
}
|
||||
let mut objects = Vec::new();
|
||||
let mut repaired = [0usize; 3];
|
||||
let mut k = 0.0;
|
||||
while k < n_obj {
|
||||
let h = f.get(at..at + 9).ok_or("Mesh-Import: Puffer beschädigt")?;
|
||||
@@ -385,12 +386,17 @@ pub fn decode_mesh(f: &[f64], strings: &[String]) -> Result<(Vec<MeshObject>, Va
|
||||
if !(np.fract() == 0.0 && ni.fract() == 0.0 && np >= 0.0 && ni >= 0.0) || at + np as usize + ni as usize > f.len() {
|
||||
return Err("Mesh-Import: Puffer beschädigt".into());
|
||||
}
|
||||
let positions = f[at..at + np as usize].to_vec();
|
||||
let positions: Vec<f64> = f[at..at + np as usize].to_vec();
|
||||
at += np as usize;
|
||||
// Wie `Uint32Array`: ganzzahlig modulo 2³².
|
||||
let indices = f[at..at + ni as usize].iter().map(|&x| (jsnum::to_int32(x) as u32) as f64).collect();
|
||||
let indices: Vec<f64> = f[at..at + ni as usize].iter().map(|&x| (jsnum::to_int32(x) as u32) as f64).collect();
|
||||
at += ni as usize;
|
||||
objects.push(MeshObject { name, group, color, positions, indices });
|
||||
// Reparatur ([T5]): verschweissen, Entartete raus, kleine Löcher zu; Zähler gehen in den Bericht.
|
||||
let r = crate::mesh_repair::repair(&positions, &indices);
|
||||
repaired[0] += r.welded;
|
||||
repaired[1] += r.degenerate;
|
||||
repaired[2] += r.holes;
|
||||
objects.push(MeshObject { name, group, color, positions: r.pos, indices: r.idx });
|
||||
k += 1.0;
|
||||
}
|
||||
let report = json!({
|
||||
@@ -405,6 +411,7 @@ pub fn decode_mesh(f: &[f64], strings: &[String]) -> Result<(Vec<MeshObject>, Va
|
||||
"truncated": f[9] == 1.0,
|
||||
"warnings": warnings,
|
||||
"objects": objects.len(),
|
||||
"repaired": {"welded": repaired[0], "degenerate": repaired[1], "holes": repaired[2]},
|
||||
});
|
||||
Ok((objects, report))
|
||||
}
|
||||
@@ -593,3 +600,24 @@ mod step_tests {
|
||||
assert!(decode_step(&[1.0, f64::NAN]).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod repair_tests {
|
||||
use super::*;
|
||||
|
||||
/// [T5] Der Import verschweisst Ecken und meldet die Reparatur im Bericht.
|
||||
#[test]
|
||||
fn mesh_import_repariert_und_berichtet() {
|
||||
let mut f = vec![1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0];
|
||||
// Objekt: Name 0, Gruppe -1, keine Farbe, 6 Ecken (Quadrat als zwei Dreiecke, STL-artig) + 1 entartetes Dreieck
|
||||
f.extend([0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 18.0, 9.0]);
|
||||
f.extend([0., 0., 0., 1., 0., 0., 1., 1., 0., 0., 0., 0., 1., 1., 0., 0., 1., 0.]);
|
||||
f.extend([0., 1., 2., 3., 4., 5., 0., 0., 1.]);
|
||||
let (objects, report) = decode_mesh(&f, &["q".to_string()]).unwrap();
|
||||
assert_eq!(objects[0].positions.len(), 12); // 4 statt 6 Ecken
|
||||
assert_eq!(objects[0].indices.len(), 6);
|
||||
assert_eq!(report["repaired"]["welded"], 2);
|
||||
assert_eq!(report["repaired"]["degenerate"], 1);
|
||||
assert_eq!(report["repaired"]["holes"], 0);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ pub mod export_schedule;
|
||||
pub mod opening_schedule;
|
||||
pub mod u_value;
|
||||
pub mod sheet_table;
|
||||
pub mod terrain;
|
||||
pub mod excavation;
|
||||
pub mod flat;
|
||||
pub mod flat_write;
|
||||
pub mod polygon_bool;
|
||||
@@ -28,6 +30,7 @@ pub mod stair;
|
||||
pub mod joins;
|
||||
pub mod wall_bands;
|
||||
pub mod wall_arc;
|
||||
pub mod grid;
|
||||
pub mod room_area;
|
||||
pub mod room_boundary;
|
||||
pub mod polygon_holes;
|
||||
@@ -35,6 +38,7 @@ pub mod js_fmt;
|
||||
pub use dossier_hatch::jsmath;
|
||||
pub mod stairs3d;
|
||||
pub mod mesh3d;
|
||||
pub mod mesh_repair;
|
||||
pub mod ceilings3d;
|
||||
pub mod columns3d;
|
||||
pub mod drawing2d_3d;
|
||||
|
||||
@@ -127,6 +127,19 @@ const BOX_QUADS: [[usize; 4]; 6] = [[4, 6, 7, 5], [1, 3, 2, 0], [2, 3, 7, 6], [4
|
||||
|
||||
/// Voller Wand-Schicht-Quader ohne Öffnungen (lochlose Bänder); entartete Bänder fallen weg.
|
||||
fn push_wall_box(g: &mut Prim, w: &RWall) {
|
||||
// Ebene Oberkante unter einem Dach ([G2]): Prisma, Modell (x, y, z) → Welt (x, Höhe, y), gespiegelt.
|
||||
if w.top_plane.is_some() {
|
||||
if let Some(m) = crate::model3d::wall_piece_mesh(w) {
|
||||
let base = (g.positions.len() / 3) as f64;
|
||||
for c in m.positions.chunks_exact(3) {
|
||||
g.positions.extend_from_slice(&[c[0], c[2], c[1]]);
|
||||
}
|
||||
for t in m.indices.chunks_exact(3) {
|
||||
g.indices.extend_from_slice(&[base + t[0] as f64, base + t[2] as f64, base + t[1] as f64]);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let [sx, sy] = w.start;
|
||||
let [ex, ey] = w.end;
|
||||
let dx = ex - sx;
|
||||
@@ -485,10 +498,14 @@ pub fn mesh_export_data(src: &Project, opt: &MeshOptions) -> Result<Flat, String
|
||||
if opt.context {
|
||||
for obj in p.context.as_deref().unwrap_or(&[]) {
|
||||
let (terrain, id, name, color, positions, indices) = match obj {
|
||||
ContextObject::TerrainMesh(m) => (true, &m.id, &m.name, None, &m.positions, &m.indices),
|
||||
ContextObject::ImportedMesh(m) => (false, &m.id, &m.name, m.color.as_deref(), &m.positions, &m.indices),
|
||||
ContextObject::TerrainMesh(m) => {
|
||||
let (pos, idx, _) = crate::excavation::terrain_model_mesh(&p, m);
|
||||
(true, &m.id, &m.name, None, pos, idx)
|
||||
}
|
||||
ContextObject::ImportedMesh(m) => (false, &m.id, &m.name, m.color.as_deref(), std::borrow::Cow::Borrowed(m.positions.as_slice()), std::borrow::Cow::Borrowed(m.indices.as_slice())),
|
||||
_ => continue,
|
||||
};
|
||||
let (positions, indices) = (&*positions, &*indices);
|
||||
if positions.len() < 9 || indices.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
//! Reparatur importierter Dreiecksnetze ([T5]): Ecken verschweissen (STL liefert jedes Dreieck mit eigenen
|
||||
//! Ecken), entartete Dreiecke entfernen, kleine Löcher in sonst geschlossenen Netzen mit einem Fächer
|
||||
//! schliessen. Reine Funktion über flache Puffer (`pos` = `[x, y, z, …]` in Metern, `idx` = Dreiecks-Indizes
|
||||
//! als `f64`); Unsinn (NaN, Indizes ausserhalb) bleibt unverändert bzw. wird als entartet entfernt.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Verschweiss-Toleranz (Meter): 0.01 mm — fängt Rundungsdifferenzen der Formate, nicht echte Spalte.
|
||||
pub const WELD_TOL: f64 = 1e-5;
|
||||
/// Löcher mit höchstens so vielen Randkanten werden geschlossen.
|
||||
pub const MAX_HOLE_EDGES: usize = 8;
|
||||
/// Löcher nur schliessen, wenn höchstens dieser Anteil der Kanten am Rand liegt (sonst offene Fläche gewollt).
|
||||
const MAX_BOUNDARY_SHARE: f64 = 0.05;
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Repaired {
|
||||
pub pos: Vec<f64>,
|
||||
pub idx: Vec<f64>,
|
||||
/// Zusammengelegte Ecken.
|
||||
pub welded: usize,
|
||||
/// Entfernte entartete Dreiecke (doppelte Ecke, Fläche ≈ 0, ungültiger Index).
|
||||
pub degenerate: usize,
|
||||
/// Geschlossene Löcher.
|
||||
pub holes: usize,
|
||||
}
|
||||
|
||||
fn tri_area2(p: &[[f64; 3]; 3]) -> f64 {
|
||||
let (a, b, c) = (p[0], p[1], p[2]);
|
||||
let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
|
||||
let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
|
||||
let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
|
||||
(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt()
|
||||
}
|
||||
|
||||
pub fn repair(pos: &[f64], idx: &[f64]) -> Repaired {
|
||||
repair_with(pos, idx, MAX_BOUNDARY_SHARE)
|
||||
}
|
||||
|
||||
/// Wie [`repair`], mit frei wählbarem Randanteil-Schutz (Tests, strenge Importe).
|
||||
pub fn repair_with(pos: &[f64], idx: &[f64], max_boundary_share: f64) -> Repaired {
|
||||
let nv = pos.len() / 3;
|
||||
// 1) Verschweissen über ein Raster (Zelle = Toleranz); Nachbarzellen werden nicht geprüft — Ecken, die
|
||||
// knapp über einer Zellgrenze liegen, bleiben getrennt (konservativ, nie falsch verbunden).
|
||||
let mut cell: HashMap<(i64, i64, i64), u32> = HashMap::new();
|
||||
let mut map: Vec<Option<u32>> = vec![None; nv];
|
||||
let mut out_pos: Vec<f64> = Vec::new();
|
||||
for i in 0..nv {
|
||||
let p = [pos[3 * i], pos[3 * i + 1], pos[3 * i + 2]];
|
||||
if !p.iter().all(|x| x.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let key = ((p[0] / WELD_TOL).round() as i64, (p[1] / WELD_TOL).round() as i64, (p[2] / WELD_TOL).round() as i64);
|
||||
let id = *cell.entry(key).or_insert_with(|| {
|
||||
out_pos.extend(p);
|
||||
(out_pos.len() / 3 - 1) as u32
|
||||
});
|
||||
map[i] = Some(id);
|
||||
}
|
||||
let welded = map.iter().flatten().count() - out_pos.len() / 3;
|
||||
// 2) Dreiecke übernehmen, entartete verwerfen
|
||||
let mut tris: Vec<[u32; 3]> = Vec::new();
|
||||
let mut degenerate = 0;
|
||||
for t in idx.chunks_exact(3) {
|
||||
let v: Vec<Option<u32>> = t.iter().map(|&k| if k >= 0.0 && k.fract() == 0.0 && (k as usize) < nv { map[k as usize] } else { None }).collect();
|
||||
let (Some(a), Some(b), Some(c)) = (v[0], v[1], v[2]) else {
|
||||
degenerate += 1;
|
||||
continue;
|
||||
};
|
||||
let p = |i: u32| [out_pos[3 * i as usize], out_pos[3 * i as usize + 1], out_pos[3 * i as usize + 2]];
|
||||
if a == b || b == c || a == c || tri_area2(&[p(a), p(b), p(c)]) < 1e-12 {
|
||||
degenerate += 1;
|
||||
continue;
|
||||
}
|
||||
tris.push([a, b, c]);
|
||||
}
|
||||
// 3) Löcher schliessen
|
||||
let holes = close_holes(&mut tris, max_boundary_share);
|
||||
Repaired { pos: out_pos, idx: tris.iter().flatten().map(|&k| k as f64).collect(), welded, degenerate, holes }
|
||||
}
|
||||
|
||||
/// Kleine Randschleifen eines fast geschlossenen Netzes mit einem Fächer füllen; Anzahl geschlossener Löcher.
|
||||
fn close_holes(tris: &mut Vec<[u32; 3]>, max_boundary_share: f64) -> usize {
|
||||
let mut directed: HashMap<(u32, u32), usize> = HashMap::new();
|
||||
for t in tris.iter() {
|
||||
for k in 0..3 {
|
||||
*directed.entry((t[k], t[(k + 1) % 3])).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
// Randkanten: Kante a→b ohne Gegenkante b→a; Nicht-Mannigfaltigkeit (Kante mehrfach) → nichts anfassen
|
||||
if directed.values().any(|&n| n > 1) {
|
||||
return 0;
|
||||
}
|
||||
let boundary: Vec<(u32, u32)> = directed.keys().filter(|&&(a, b)| !directed.contains_key(&(b, a))).copied().collect();
|
||||
if boundary.is_empty() || boundary.len() as f64 > max_boundary_share * directed.len() as f64 {
|
||||
return 0;
|
||||
}
|
||||
// Der Rand läuft a→b; die fehlenden Dreiecke tragen b→a, der Deckel läuft also gegen die Randrichtung.
|
||||
let mut next: HashMap<u32, Vec<u32>> = HashMap::new();
|
||||
for &(a, b) in &boundary {
|
||||
next.entry(a).or_default().push(b);
|
||||
}
|
||||
if next.values().any(|v| v.len() != 1) {
|
||||
return 0; // Rand verzweigt sich (Schmetterlingsecke) — nicht raten
|
||||
}
|
||||
let mut seen: std::collections::HashSet<u32> = std::collections::HashSet::new();
|
||||
let mut closed = 0;
|
||||
let mut starts: Vec<u32> = next.keys().copied().collect();
|
||||
starts.sort_unstable();
|
||||
for s in starts {
|
||||
if seen.contains(&s) {
|
||||
continue;
|
||||
}
|
||||
let mut ring = vec![s];
|
||||
let mut cur = s;
|
||||
let mut ok = true;
|
||||
loop {
|
||||
let n = next[&cur][0];
|
||||
if n == s {
|
||||
break;
|
||||
}
|
||||
if ring.len() >= MAX_HOLE_EDGES || !next.contains_key(&n) || ring.contains(&n) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
ring.push(n);
|
||||
cur = n;
|
||||
}
|
||||
seen.extend(ring.iter().copied());
|
||||
if !ok || ring.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
ring.reverse();
|
||||
for k in 1..ring.len() - 1 {
|
||||
tris.push([ring[0], ring[k], ring[k + 1]]);
|
||||
}
|
||||
closed += 1;
|
||||
}
|
||||
closed
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Würfel mit eigenen Ecken je Dreieck (wie STL), Kantenlänge 1, nach aussen orientiert.
|
||||
fn soup(skip: &[usize]) -> (Vec<f64>, Vec<f64>) {
|
||||
let v = [[0., 0., 0.], [1., 0., 0.], [1., 1., 0.], [0., 1., 0.], [0., 0., 1.], [1., 0., 1.], [1., 1., 1.], [0., 1., 1.]];
|
||||
let f: [[usize; 3]; 12] = [
|
||||
[0, 2, 1], [0, 3, 2], [4, 5, 6], [4, 6, 7], [0, 1, 5], [0, 5, 4],
|
||||
[1, 2, 6], [1, 6, 5], [2, 3, 7], [2, 7, 6], [3, 0, 4], [3, 4, 7],
|
||||
];
|
||||
let (mut pos, mut idx) = (Vec::new(), Vec::new());
|
||||
for (i, t) in f.iter().enumerate() {
|
||||
if skip.contains(&i) {
|
||||
continue;
|
||||
}
|
||||
for &k in t {
|
||||
idx.push((pos.len() / 3) as f64);
|
||||
pos.extend(v[k]);
|
||||
}
|
||||
}
|
||||
(pos, idx)
|
||||
}
|
||||
|
||||
fn volume(r: &Repaired) -> f64 {
|
||||
r.idx
|
||||
.chunks(3)
|
||||
.map(|t| {
|
||||
let p = |i: f64| [r.pos[3 * i as usize], r.pos[3 * i as usize + 1], r.pos[3 * i as usize + 2]];
|
||||
let (a, b, c) = (p(t[0]), p(t[1]), p(t[2]));
|
||||
(a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stl_suppe_wird_verschweisst() {
|
||||
let (pos, idx) = soup(&[]);
|
||||
let r = repair(&pos, &idx);
|
||||
assert_eq!(r.pos.len() / 3, 8);
|
||||
assert_eq!(r.welded, 36 - 8);
|
||||
assert_eq!((r.degenerate, r.holes), (0, 0));
|
||||
assert!((volume(&r) - 1.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entartete_dreiecke_fliegen_raus() {
|
||||
let (mut pos, mut idx) = soup(&[]);
|
||||
let n = (pos.len() / 3) as f64;
|
||||
pos.extend([5., 5., 5., 6., 6., 6., 7., 7., 7.]); // kollinear
|
||||
idx.extend([n, n + 1., n + 2.]);
|
||||
idx.extend([0., 0., 1.]); // doppelte Ecke
|
||||
idx.extend([0., 1., 9999.]); // Index ausserhalb
|
||||
let r = repair(&pos, &idx);
|
||||
assert_eq!(r.degenerate, 3);
|
||||
assert_eq!(r.idx.len(), 36);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offene_flaeche_bleibt_offen() {
|
||||
// Einzelnes Quadrat: Rand 100 % → gewollt offen
|
||||
let pos = [0., 0., 0., 1., 0., 0., 1., 1., 0., 0., 1., 0.];
|
||||
let idx = [0., 1., 2., 0., 2., 3.];
|
||||
let r = repair(&pos, &idx);
|
||||
assert_eq!((r.holes, r.idx.len()), (0, 6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loch_wird_mit_faecher_geschlossen_und_ist_nach_aussen_orientiert() {
|
||||
// Würfel ohne zwei Dreiecke (Deckel) → 4-Kanten-Loch; der Randanteil-Schutz (5 %) lässt es offen …
|
||||
let (pos, idx) = soup(&[2, 3]);
|
||||
assert_eq!(repair(&pos, &idx).holes, 0);
|
||||
// … ohne Schutz wird es geschlossen und das Netz ist wieder ein Würfel (Volumen 1, richtig herum)
|
||||
let r = repair_with(&pos, &idx, 1.0);
|
||||
assert_eq!(r.holes, 1);
|
||||
assert_eq!(r.idx.len(), 36);
|
||||
assert!((volume(&r) - 1.0).abs() < 1e-12, "Volumen {}", volume(&r));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grosses_loch_bleibt_offen() {
|
||||
// Kegelmantel ohne Boden: Randschleife mit 9 Kanten > MAX_HOLE_EDGES — wird nie geschlossen
|
||||
let n = 9;
|
||||
let mut pos = Vec::new();
|
||||
for k in 0..n {
|
||||
let a = std::f64::consts::TAU * k as f64 / n as f64;
|
||||
pos.extend([a.cos(), a.sin(), 0.0]);
|
||||
}
|
||||
pos.extend([0.0, 0.0, 1.0]);
|
||||
let mut idx = Vec::new();
|
||||
for k in 0..n {
|
||||
idx.extend([k as f64, ((k + 1) % n) as f64, n as f64]);
|
||||
}
|
||||
let r = repair_with(&pos, &idx, 1.0);
|
||||
assert_eq!(r.holes, 0);
|
||||
}
|
||||
}
|
||||
@@ -2212,6 +2212,12 @@ pub struct Wall {
|
||||
#[serde(rename = "sliceTermination", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub slice_termination: Option<SliceTermination>,
|
||||
/// An Dach anschliessen ([G2]): `undefined` = automatisch (die Wand endet an der Dach-Unterkante,
|
||||
/// wo ihre Krone darüber liegt — je Schicht, Giebel/Traufe/Grat/Kehle/Gaube), `true` = zusätzlich bis
|
||||
/// unter das Dach verlängert, `false` = Dächer schneiden die Wand nicht.
|
||||
#[serde(rename = "roofAttach", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub roof_attach: Option<bool>,
|
||||
/// Ansichtsschraffur ([100]): Drehung (Grad) des Oberflächenmusters dieses Elements gegenüber der
|
||||
/// Ausrichtung am Element (Default 0).
|
||||
#[serde(rename = "surfacePatternAngle", default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -3121,6 +3127,11 @@ pub struct Stair {
|
||||
#[serde(rename = "arrowStyle", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional, inline)]
|
||||
pub arrow_style: Option<StairArrowStyle>,
|
||||
/// Nur Wendel: Radius (Meter) der Mittelsäule (Spindel) im Zentrum. Fehlt er oder ist er
|
||||
/// ≤ 0, gibt es keine Säule.
|
||||
#[serde(rename = "centerColumn", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub center_column: Option<f64>,
|
||||
#[serde(flatten)]
|
||||
#[ts(skip)]
|
||||
pub extra: Extra,
|
||||
@@ -4119,6 +4130,9 @@ pub enum LayoutTableSource {
|
||||
/// Bauteilliste mit U-Werten ([71]).
|
||||
#[serde(rename = "elements")]
|
||||
Elements,
|
||||
/// [68] Erdarbeiten: Baugruben mit Abtrag/Auftrag/Hinterfüllung.
|
||||
#[serde(rename = "earthworks")]
|
||||
Earthworks,
|
||||
#[serde(other)]
|
||||
#[ts(skip)]
|
||||
Unknown,
|
||||
@@ -5086,6 +5100,53 @@ pub struct TerrainMesh {
|
||||
#[serde(rename = "vertexColors", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub vertex_colors: Option<Vec<f64>>,
|
||||
/// [T6] Äquidistanz der Höhenlinien im Grundriss in m (aus dem Netz neu erzeugt, inkl. Baugruben).
|
||||
/// Fehlt der Wert oder ist er ≤ 0, zeigt der Grundriss nur den Rahmen.
|
||||
#[serde(rename = "contourInterval", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub contour_interval: Option<f64>,
|
||||
/// [T6] Jede n-te Höhenlinie ist Zähllinie (dicker, beschriftet). Default 5.
|
||||
#[serde(rename = "contourIndexEvery", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub contour_index_every: Option<f64>,
|
||||
#[serde(flatten)]
|
||||
#[ts(skip)]
|
||||
pub extra: Extra,
|
||||
}
|
||||
|
||||
/// [68] Baugrube / Geländebearbeitung: Sohle als Umriss auf der Höhe `bottom` (m, Modell ±0.00).
|
||||
/// Ausserhalb steigt die Böschung mit `slope` (Grad, Default 45; je Kante `edgeSlopes`, 0 = Default)
|
||||
/// bis zum Gelände (Abtrag); liegt das Gelände tiefer, fällt eine Schüttung mit `fillSlope` (Default
|
||||
/// 33.7 ≈ 2:3) bis zum Gelände (Auftrag). Bermen: alle `bermHeight` m Höhe eine waagrechte Berme der
|
||||
/// Breite `bermWidth`. Schneidet jedes Gelände-Netz, das den Umriss enthält.
|
||||
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
|
||||
#[serde(default)]
|
||||
pub struct Excavation {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub layer: Option<String>,
|
||||
#[serde(rename = "categoryCode", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub category_code: Option<String>,
|
||||
pub outline: Vec<Vec2>,
|
||||
pub bottom: f64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub slope: Option<f64>,
|
||||
#[serde(rename = "fillSlope", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub fill_slope: Option<f64>,
|
||||
#[serde(rename = "edgeSlopes", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub edge_slopes: Option<Vec<f64>>,
|
||||
#[serde(rename = "bermWidth", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub berm_width: Option<f64>,
|
||||
#[serde(rename = "bermHeight", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub berm_height: Option<f64>,
|
||||
#[serde(flatten)]
|
||||
#[ts(skip)]
|
||||
pub extra: Extra,
|
||||
|
||||
@@ -125,6 +125,26 @@ pub enum DimFeature {
|
||||
/// Schnittpunkt der Wandlinie (`id`, `index`) mit der Wandlinie (`id2`, `index2`) — Ecken.
|
||||
#[serde(rename = "intersection")]
|
||||
Intersection,
|
||||
/// Punkt auf Rasterachse `index` des Achsrasters `id` beim Anteil `t` entlang der Achse ([112]).
|
||||
#[serde(rename = "axis")]
|
||||
Axis,
|
||||
/// Schnittpunkt der Rasterachsen `index` und `index2` des Achsrasters `id` ([112]).
|
||||
#[serde(rename = "axiscross")]
|
||||
AxisCross,
|
||||
/// Punkt auf dem Kreis/Bogen (2D-Kreis, -Bogen, Bogenwand) `id` beim Winkel `t` (Bogenmass);
|
||||
/// bei Bogenwänden `index` = Schichtgrenze (fehlt = Achse). Für Radius-, Durchmesser- und
|
||||
/// Bogenlängen-Bemassung ([38]).
|
||||
#[serde(rename = "rim")]
|
||||
Rim,
|
||||
}
|
||||
|
||||
/// Art einer Bemassung ([38]).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum DimKind {
|
||||
Radius,
|
||||
Diameter,
|
||||
Arc,
|
||||
}
|
||||
|
||||
/// Bezug eines Bemassungspunkts auf ein Element ([38]).
|
||||
@@ -180,6 +200,23 @@ pub enum SplineMode {
|
||||
Control,
|
||||
}
|
||||
|
||||
/// Eine Achse des Achsrasters: Beschriftung und Lage (Abstand bzw. Winkel/Radius, s. `Grid`).
|
||||
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
|
||||
#[serde(default)]
|
||||
pub struct GridAxis {
|
||||
pub label: String,
|
||||
pub pos: f64,
|
||||
}
|
||||
|
||||
/// Welche Achsenden eine Blase tragen.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum GridBubbles {
|
||||
Start,
|
||||
End,
|
||||
Both,
|
||||
}
|
||||
|
||||
/// Geometrie eines 2D-Zeichenelements (Tag `shape`).
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
#[serde(tag = "shape")]
|
||||
@@ -332,6 +369,11 @@ pub enum Drawing2DGeom {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
refs: Option<Vec<Option<DimRef>>>,
|
||||
/// Art der Bemassung (fehlt = linear): Radius/Durchmesser (`pts` = Mittelpunkt, Punkt auf dem
|
||||
/// Kreis) und Bogenlänge (`pts` = Mittelpunkt, Bogenanfang, Bogenende).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional, inline)]
|
||||
kind: Option<DimKind>,
|
||||
},
|
||||
/// Höhenkote (SIA 400 B.5.4, Figur 18): Dreieck-Symbol + Höhenwert (Meter,
|
||||
/// ±0.00-Referenz frei wählbar, s. Norm) an einem Punkt. `kind` bestimmt
|
||||
@@ -404,6 +446,41 @@ pub enum Drawing2DGeom {
|
||||
/// gleichbleibende Lesbarkeit im Plan.
|
||||
#[serde(rename = "pointmarker")]
|
||||
Pointmarker { at: Vec2 },
|
||||
/// Achsraster ([112], `grid.rs`): rechtwinklig (`a` = Achsen parallel zur lokalen Y-Achse bei
|
||||
/// X = `pos`, Beschriftung 1, 2, 3 …; `b` = Achsen parallel zur lokalen X-Achse bei Y = `pos`,
|
||||
/// A, B, C …) oder radial (`radial`: `a` = Strahlen unter `pos` Grad, `b` = Ringe mit Radius
|
||||
/// `pos`). `origin`/`angle` (Bogenmass) legen das lokale System fest.
|
||||
#[serde(rename = "grid")]
|
||||
Grid {
|
||||
origin: Vec2,
|
||||
#[serde(default)]
|
||||
angle: f64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
radial: Option<bool>,
|
||||
a: Vec<GridAxis>,
|
||||
b: Vec<GridAxis>,
|
||||
/// Überstand der Achsen über die äusserste Querachse (Meter, Standard 1.5).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
extend: Option<f64>,
|
||||
/// Enden mit Achsblase (Standard Anfang und Ende).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional, inline)]
|
||||
bubbles: Option<GridBubbles>,
|
||||
/// Blasen-Durchmesser in Papier-mm (Standard 8).
|
||||
#[serde(rename = "bubbleMm", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
bubble_mm: Option<f64>,
|
||||
/// Geschosse, in denen das Raster gezeigt wird; fehlt oder leer = in allen.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
levels: Option<Vec<String>>,
|
||||
/// Im 3D-Modell als dünne Linien zeigen.
|
||||
#[serde(rename = "show3d", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
show_3d: Option<bool>,
|
||||
},
|
||||
#[serde(rename = "text")]
|
||||
Text {
|
||||
at: Vec2,
|
||||
@@ -527,6 +604,8 @@ pub enum ContextObject {
|
||||
TerrainMesh(TerrainMesh),
|
||||
#[serde(rename = "image")]
|
||||
Image(ContextImage),
|
||||
#[serde(rename = "excavation")]
|
||||
Excavation(Excavation),
|
||||
}
|
||||
|
||||
impl Default for Drawing2DGeom {
|
||||
|
||||
+146
-40
@@ -255,6 +255,10 @@ pub struct RWall {
|
||||
pub base_elevation: f64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub top_drop: Option<[f64; 2]>,
|
||||
/// Ebene Oberkante unter einer Dachfläche ([G2]): `[z am Anfang (Mittellinie), dz/dx, dz/dy]`
|
||||
/// (Grundriss-Meter). Übersteuert `topDrop`; `height` ist dann der höchste Eckwert über der UK.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub top_plane: Option<[f64; 3]>,
|
||||
pub color: Rgb,
|
||||
pub layers: Vec<()>,
|
||||
pub wall_id: String,
|
||||
@@ -525,13 +529,13 @@ fn compute_joins_by_floor(p: &Project) -> Result<HashMap<String, WallCuts>, Stri
|
||||
Ok(merged)
|
||||
}
|
||||
|
||||
fn floor_context(p: &Project, floor_id: &str) -> FloorContext {
|
||||
fn floor_context(p: &Project, floor_id: &str, with_ceilings: bool) -> FloorContext {
|
||||
let ceilings: Vec<CeilingIn> = p
|
||||
.ceilings
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.filter(|c| c.floor_id == floor_id && c.outline.len() >= 3)
|
||||
.filter(|c| with_ceilings && c.floor_id == floor_id && c.outline.len() >= 3)
|
||||
.map(|c| {
|
||||
let (z_bottom, z_top) = p.ceiling_vertical_extent(c);
|
||||
CeilingIn {
|
||||
@@ -552,7 +556,14 @@ fn floor_context(p: &Project, floor_id: &str) -> FloorContext {
|
||||
let eaves_z = p.roof_base_elevation(r);
|
||||
let geo = crate::roof::roof_geometry(&r.params(), eaves_z);
|
||||
let total: f64 = p.roof_layers(r).iter().fold(0.0, |s, l| s + l.thickness.max(0.0));
|
||||
RoofIn { eaves_z, total_thickness: total, eaves: geo.eaves, planes: geo.planes }
|
||||
let mut ri = RoofIn::new(eaves_z, total, geo.eaves, geo.planes);
|
||||
// Gauben ([G2]): unter dem Gaubeninneren endet die Wand an der Gaubendach-Unterkante.
|
||||
for d in r.dormers.as_deref().unwrap_or(&[]) {
|
||||
if let Some(g) = crate::dormer::geometry(p, r, d) {
|
||||
ri.facets.extend(g.under_facets());
|
||||
}
|
||||
}
|
||||
ri
|
||||
})
|
||||
.collect();
|
||||
FloorContext::new(ceilings, roofs)
|
||||
@@ -571,17 +582,13 @@ pub fn emit_walls(p: &Project, layered: bool) -> Result<Vec<RWall>, String> {
|
||||
let joins = if layered { Some(compute_joins_by_floor(p)?) } else { None };
|
||||
let maps = wall_material_color_maps(p);
|
||||
let mut contexts: HashMap<&str, FloorContext> = HashMap::new();
|
||||
let empty = FloorContext::default();
|
||||
let mut out = Vec::new();
|
||||
let by_wall = p.openings_by_wall();
|
||||
for wall in &p.walls {
|
||||
let (bands, stacked) = resolve_wall_bands(p, &maps, wall, layered);
|
||||
let (z_bottom, z_top) = p.wall_vertical_extent(wall);
|
||||
let ctx = if layered {
|
||||
contexts.entry(wall.floor_id.as_str()).or_insert_with(|| floor_context(p, &wall.floor_id))
|
||||
} else {
|
||||
&empty
|
||||
};
|
||||
// Schnitt-Eingabe: nur die Dächer ([G2]); Decken rechnet der Schnitt selbst (Dominanz).
|
||||
let ctx = contexts.entry(wall.floor_id.as_str()).or_insert_with(|| floor_context(p, &wall.floor_id, layered));
|
||||
let win = wall_bands::WallIn {
|
||||
start: kv(wall.start),
|
||||
end: kv(wall.end),
|
||||
@@ -599,6 +606,7 @@ pub fn emit_walls(p: &Project, layered: bool) -> Result<Vec<RWall>, String> {
|
||||
bands: bands.iter().map(|b| BandIn { thickness: b.thickness, priority: b.priority }).collect(),
|
||||
openings: wall_openings(p, wall, by_wall.get(wall.id.as_str()).map_or(&[][..], |v| v.as_slice()), true),
|
||||
cuts: if layered { joins.as_ref().and_then(|j| j.get(&wall.id)).cloned().unwrap_or_default() } else { WallCuts::default() },
|
||||
roof_attach: wall.roof_attach,
|
||||
reveals: if layered && stacked { wall_reveals(p, wall, by_wall.get(wall.id.as_str()).map_or(&[][..], |v| v.as_slice()), bands.len()) } else { Vec::new() },
|
||||
};
|
||||
// Bogenwand ([T2]): Sehnen-Teilwände mit radialen Gehrungen.
|
||||
@@ -618,8 +626,8 @@ pub fn emit_walls(p: &Project, layered: bool) -> Result<Vec<RWall>, String> {
|
||||
let Some(b) = bands.get(piece.band) else { continue };
|
||||
// Schnitt-Eingabe der Bogen-Teilwände: radiale Gehrungen auch ohne Schichtband-Pfad.
|
||||
if arc.is_some() && !layered {
|
||||
piece.start_cut = win.cuts.start_cut;
|
||||
piece.end_cut = win.cuts.end_cut;
|
||||
piece.start_cut = piece.start_cut.or(win.cuts.start_cut);
|
||||
piece.end_cut = piece.end_cut.or(win.cuts.end_cut);
|
||||
}
|
||||
out.push(RWall {
|
||||
start: [piece.start.x, piece.start.y],
|
||||
@@ -628,6 +636,7 @@ pub fn emit_walls(p: &Project, layered: bool) -> Result<Vec<RWall>, String> {
|
||||
height: piece.z_top - piece.z_bottom,
|
||||
base_elevation: piece.z_bottom,
|
||||
top_drop: piece.top_drop,
|
||||
top_plane: piece.top_plane.map(|c| [c[0] + c[1] * piece.start.x + c[2] * piece.start.y, c[1], c[2]]),
|
||||
color: b.color,
|
||||
layers: vec![],
|
||||
wall_id: wall.id.clone(),
|
||||
@@ -637,7 +646,10 @@ pub fn emit_walls(p: &Project, layered: bool) -> Result<Vec<RWall>, String> {
|
||||
cut: band_cut_meta(b),
|
||||
start_cut: piece.start_cut.map(|l| [l.point.x, l.point.y, l.dir.x, l.dir.y]),
|
||||
end_cut: piece.end_cut.map(|l| [l.point.x, l.point.y, l.dir.x, l.dir.y]),
|
||||
joint: arc.map_or([false; 2], |a| [inner_joint(&a, wall, &keep, piece.start), inner_joint(&a, wall, &keep, piece.end)]),
|
||||
joint: {
|
||||
let j = arc.map_or([false; 2], |a| [inner_joint(&a, wall, &keep, piece.start), inner_joint(&a, wall, &keep, piece.end)]);
|
||||
[j[0] || piece.joint[0], j[1] || piece.joint[1]]
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -646,6 +658,68 @@ pub fn emit_walls(p: &Project, layered: bool) -> Result<Vec<RWall>, String> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Grundriss-Ecken eines Wandkörpers an seinen Schnittlinien: Anfang +n, Ende +n, Ende −n, Anfang −n
|
||||
/// (+n = linke Normale). `None` bei entarteter Achse.
|
||||
pub(crate) fn wall_footprint(w: &RWall) -> Option<[[f64; 2]; 4]> {
|
||||
let (dx, dy) = (w.end[0] - w.start[0], w.end[1] - w.start[1]);
|
||||
let l = hypot2(dx, dy);
|
||||
if !(l > 1e-9) || !(w.thickness > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let (ux, uy) = (dx / l, dy / l);
|
||||
let (nx, ny) = (-uy, ux);
|
||||
let h = w.thickness / 2.0;
|
||||
let at = |p: [f64; 2], o: f64, cut: Option<[f64; 4]>| -> [f64; 2] {
|
||||
let q = [p[0] + nx * o, p[1] + ny * o];
|
||||
let Some([cx, cy, ex, ey]) = cut else { return q };
|
||||
let den = ux * ey - uy * ex;
|
||||
if den.abs() < 1e-12 {
|
||||
return q;
|
||||
}
|
||||
let t = ((cx - q[0]) * ey - (cy - q[1]) * ex) / den;
|
||||
if t.is_finite() && t.abs() < l {
|
||||
[q[0] + ux * t, q[1] + uy * t]
|
||||
} else {
|
||||
q
|
||||
}
|
||||
};
|
||||
Some([at(w.start, h, w.start_cut), at(w.end, h, w.end_cut), at(w.end, -h, w.end_cut), at(w.start, -h, w.start_cut)])
|
||||
}
|
||||
|
||||
/// Oberkante eines Wandkörpers an einem Grundriss-Punkt (ebene Oberkante unter einem Dach, [G2]).
|
||||
pub(crate) fn wall_top_at(w: &RWall, q: [f64; 2]) -> f64 {
|
||||
let zt = w.base_elevation + w.height;
|
||||
match w.top_plane {
|
||||
Some(c) => (c[0] + c[1] * (q[0] - w.start[0]) + c[2] * (q[1] - w.start[1])).clamp(w.base_elevation, zt),
|
||||
None => zt,
|
||||
}
|
||||
}
|
||||
|
||||
/// Wandkörper mit ebener Oberkante als geschlossenes Netz (Modell x, y, z), ohne Löcher.
|
||||
pub(crate) fn wall_piece_mesh(w: &RWall) -> Option<crate::solid_bool::Mesh> {
|
||||
let fp = wall_footprint(w)?;
|
||||
let zb = w.base_elevation;
|
||||
let m = crate::solid_bool::Mesh::prism_between(&fp, &|_, _| zb, &|x, y| wall_top_at(w, [x, y]));
|
||||
(!m.is_empty()).then_some(m)
|
||||
}
|
||||
|
||||
/// Volumen eines Wandkörpers ohne Löcher: Grundfläche × Höhe im Schwerpunkt (exakt bei ebener Oberkante).
|
||||
pub(crate) fn wall_piece_volume(w: &RWall) -> f64 {
|
||||
let Some(q) = wall_footprint(w) else { return 0.0 };
|
||||
let (mut a, mut cx, mut cy) = (0.0, 0.0, 0.0);
|
||||
for i in 0..4 {
|
||||
let (p0, p1) = (q[i], q[(i + 1) % 4]);
|
||||
let c = p0[0] * p1[1] - p1[0] * p0[1];
|
||||
a += c;
|
||||
cx += (p0[0] + p1[0]) * c;
|
||||
cy += (p0[1] + p1[1]) * c;
|
||||
}
|
||||
if a.abs() < 1e-15 {
|
||||
return 0.0;
|
||||
}
|
||||
(a / 2.0).abs() * (wall_top_at(w, [cx / (3.0 * a), cy / (3.0 * a)]) - w.base_elevation)
|
||||
}
|
||||
|
||||
// ── Öffnungs-Einbauteile (Glas, Rahmen, Sprossen, Bank, Kasten) ─────────────
|
||||
|
||||
/// Farbe je Bauteil-Klasse (Index = `Part` in `openings3d.rs`).
|
||||
@@ -1058,7 +1132,7 @@ fn rail_rgb() -> Rgb {
|
||||
hex_to_rgb("#74797f", SLAB_RGB)
|
||||
}
|
||||
|
||||
/// Flache Eingabe der Treppen für `stairs3d` (23 Zahlen je Treppe); `wanted` wählt vor.
|
||||
/// Flache Eingabe der Treppen für `stairs3d` (24 Zahlen je Treppe); `wanted` wählt vor.
|
||||
fn stair_input<'a>(p: &'a Project, wanted: impl Fn(&Stair, Option<&StairType>) -> bool) -> Option<(Vec<(usize, &'a Stair)>, Vec<f64>)> {
|
||||
let mut stairs: Vec<(usize, &Stair)> = Vec::new();
|
||||
let mut types: Vec<Option<&StairType>> = Vec::new();
|
||||
@@ -1093,6 +1167,7 @@ fn stair_input<'a>(p: &'a Project, wanted: impl Fn(&Stair, Option<&StairType>) -
|
||||
Some(StairTypeRailing::Beide) => 3.0,
|
||||
_ => 0.0,
|
||||
});
|
||||
buf.push(s.center_column.filter(|r| r.is_finite() && *r > 0.0).unwrap_or(0.0));
|
||||
}
|
||||
Some((stairs, buf))
|
||||
}
|
||||
@@ -1123,17 +1198,17 @@ fn meshes_of(meshes: Vec<crate::mesh3d::Mesh>, color: Rgb) -> Vec<RMesh> {
|
||||
meshes.into_iter().map(|m| RMesh { positions: m.positions, indices: m.indices, kind: "extrusion", color, vertex_colors: None, material_index: None }).collect()
|
||||
}
|
||||
|
||||
/// Glatte Ortbeton-Laufplatten gerader Treppen (`emitStairMeshes`).
|
||||
/// Glatte Ortbeton-Laufplatten gerader Treppen und Wendelfläche (Schraubenfläche) von Wendeltreppen (`emitStairMeshes`).
|
||||
pub fn emit_stair_meshes(p: &Project) -> Vec<RMesh> {
|
||||
match stair_input(p, |s, st| st.is_some_and(|t| t.structure == StairTypeStructure::Beton) && s.shape == StairShape::Straight) {
|
||||
match stair_input(p, |s, st| st.is_some_and(|t| t.structure == StairTypeStructure::Beton) && matches!(s.shape, StairShape::Straight | StairShape::Spiral)) {
|
||||
Some((_, buf)) => meshes_of(crate::stairs3d::slab_meshes(&buf), stair_rgb()),
|
||||
None => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Handlauf und Pfosten gerader Treppen (`emitStairRailings`).
|
||||
/// Handlauf und Pfosten gerader Treppen (`emitStairRailings`); bei Wendeltreppen als Schraubensweep.
|
||||
pub fn emit_stair_railings(p: &Project) -> Vec<RMesh> {
|
||||
match stair_input(p, |s, st| s.shape == StairShape::Straight && st.and_then(|t| t.railing).is_some_and(|r| r != StairTypeRailing::Keine)) {
|
||||
match stair_input(p, |s, st| matches!(s.shape, StairShape::Straight | StairShape::Spiral) && st.and_then(|t| t.railing).is_some_and(|r| r != StairTypeRailing::Keine)) {
|
||||
Some((_, buf)) => meshes_of(crate::stairs3d::railings(&buf), rail_rgb()),
|
||||
None => vec![],
|
||||
}
|
||||
@@ -1712,14 +1787,18 @@ pub fn emit_context_meshes(p: &Project) -> Vec<RMesh> {
|
||||
let mut out = Vec::new();
|
||||
for obj in p.context.as_deref().unwrap_or(&[]) {
|
||||
match obj {
|
||||
ContextObject::TerrainMesh(m) if m.positions.len() >= 9 && m.indices.len() >= 3 => out.push(RMesh {
|
||||
positions: m.positions.clone(),
|
||||
indices: indices_u32(&m.indices),
|
||||
kind: "terrain",
|
||||
color: TERRAIN_RGB,
|
||||
vertex_colors: m.vertex_colors.clone().filter(|v| !v.is_empty()),
|
||||
material_index: None,
|
||||
}),
|
||||
ContextObject::TerrainMesh(m) if m.positions.len() >= 9 && m.indices.len() >= 3 => {
|
||||
// [T6] Baugruben schneiden das Gelände; Höhen im Modellbezug (Luftbild-Farben nur ungeändert).
|
||||
let (pos, idx, changed) = crate::excavation::terrain_model_mesh(p, m);
|
||||
out.push(RMesh {
|
||||
positions: pos.into_owned(),
|
||||
indices: indices_u32(&idx),
|
||||
kind: "terrain",
|
||||
color: TERRAIN_RGB,
|
||||
vertex_colors: if changed { None } else { m.vertex_colors.clone().filter(|v| !v.is_empty()) },
|
||||
material_index: None,
|
||||
})
|
||||
}
|
||||
ContextObject::ImportedMesh(m) if m.positions.len() >= 9 && m.indices.len() >= 3 => out.push(RMesh {
|
||||
positions: m.positions.clone(),
|
||||
indices: indices_u32(&m.indices),
|
||||
@@ -1810,24 +1889,28 @@ fn for_each_drawing_chunk(p: &Project, with_color: bool, mut f: impl FnMut(&[f64
|
||||
buf.truncate(1);
|
||||
};
|
||||
for d in &p.drawings2d {
|
||||
let (kind, pts): (f64, Vec<Vec2>) = match &d.geom {
|
||||
Drawing2DGeom::Line { a, b } => (1.0, vec![*a, *b]),
|
||||
Drawing2DGeom::Rect { min, max } => (3.0, vec![*min, *max]),
|
||||
Drawing2DGeom::Polyline { pts, .. } => (2.0, pts.clone()),
|
||||
// Teile einer Zeichnung: (Art, Punkte); ein Achsraster mit `show3d` liefert je Achse eines.
|
||||
let parts: Vec<(f64, Vec<Vec2>)> = match &d.geom {
|
||||
Drawing2DGeom::Line { a, b } => vec![(1.0, vec![*a, *b])],
|
||||
Drawing2DGeom::Rect { min, max } => vec![(3.0, vec![*min, *max])],
|
||||
Drawing2DGeom::Polyline { pts, .. } => vec![(2.0, pts.clone())],
|
||||
Drawing2DGeom::Grid { show_3d: Some(true), .. } => crate::grid::Spec::of(&d.geom).map(|s| crate::grid::polylines_3d(&s)).unwrap_or_default().into_iter().map(|q| (2.0, q.into_iter().map(|(x, y)| Vec2 { x, y }).collect())).collect(),
|
||||
_ => continue,
|
||||
};
|
||||
let need = 7 + 2 * pts.len();
|
||||
if buf.len() + need > CHUNK_DOUBLES {
|
||||
flush(&mut buf, &mut ids, &mut f);
|
||||
}
|
||||
let closed = matches!(&d.geom, Drawing2DGeom::Polyline { closed: true, .. });
|
||||
let elev = *elevations.entry(d.level_id.as_str()).or_insert_with(|| p.floor(&d.level_id).map_or(0.0, |l| l.base_elevation.unwrap_or(0.0)) + DRAWING_LINE_ELEVATION_EPS);
|
||||
let rgb = if with_color { drawing_color(d, &by_category, &by_line_style) } else { [0.0; 3] };
|
||||
let closed = matches!(&d.geom, Drawing2DGeom::Polyline { closed: true, .. });
|
||||
buf.extend([kind, elev, rgb[0], rgb[1], rgb[2], if closed { 1.0 } else { 0.0 }, pts.len() as f64]);
|
||||
for q in &pts {
|
||||
buf.extend([q.x, q.y]);
|
||||
for (kind, pts) in parts {
|
||||
let need = 7 + 2 * pts.len();
|
||||
if buf.len() + need > CHUNK_DOUBLES {
|
||||
flush(&mut buf, &mut ids, &mut f);
|
||||
}
|
||||
buf.extend([kind, elev, rgb[0], rgb[1], rgb[2], if closed { 1.0 } else { 0.0 }, pts.len() as f64]);
|
||||
for q in &pts {
|
||||
buf.extend([q.x, q.y]);
|
||||
}
|
||||
ids.push(d);
|
||||
}
|
||||
ids.push(d);
|
||||
}
|
||||
flush(&mut buf, &mut ids, &mut f);
|
||||
}
|
||||
@@ -1982,10 +2065,14 @@ pub fn pick_geometry(p: &Project) -> Result<PickGeometry, String> {
|
||||
let mut context_meshes = Vec::new();
|
||||
for obj in p.context.as_deref().unwrap_or(&[]) {
|
||||
let (pos, idx, id) = match obj {
|
||||
ContextObject::TerrainMesh(m) => (&m.positions, &m.indices, &m.id),
|
||||
ContextObject::ImportedMesh(m) => (&m.positions, &m.indices, &m.id),
|
||||
ContextObject::TerrainMesh(m) => {
|
||||
let (pos, idx, _) = crate::excavation::terrain_model_mesh(p, m);
|
||||
(pos, idx, &m.id)
|
||||
}
|
||||
ContextObject::ImportedMesh(m) => (std::borrow::Cow::Borrowed(m.positions.as_slice()), std::borrow::Cow::Borrowed(m.indices.as_slice()), &m.id),
|
||||
_ => continue,
|
||||
};
|
||||
let (pos, idx) = (&*pos, &*idx);
|
||||
let vcount = pos.len() / 3;
|
||||
let at = |i: usize| -> V3 { [pos[i * 3], pos[i * 3 + 2], -pos[i * 3 + 1]] };
|
||||
let mut tris: Vec<Tri> = Vec::new();
|
||||
@@ -2015,6 +2102,25 @@ pub fn pick_geometry(p: &Project) -> Result<PickGeometry, String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// [112] Achsraster mit `show3d` erscheint als Boden-Spur (eine Strecke je Achse), ohne Flag nicht.
|
||||
#[test]
|
||||
fn achsraster_im_3d_nur_mit_flag() {
|
||||
let mk = |show: serde_json::Value| -> Project {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "layers": [], "openings": [], "walls": [],
|
||||
"drawingLevels": [{"id": "F", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3.0, "baseElevation": 1.0}],
|
||||
"drawings2d": [{"id": "G", "type": "drawing2d", "levelId": "F", "categoryCode": "20", "geom": {"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0,
|
||||
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 4}], "b": [{"label": "A", "pos": 0}], "show3d": show}}]
|
||||
}))
|
||||
.unwrap()
|
||||
};
|
||||
assert!(drawing_line_verts(&mk(serde_json::json!(false))).is_empty());
|
||||
let v = drawing_line_verts(&mk(serde_json::json!(true)));
|
||||
// 3 Achsen × 1 Segment × 2 Endpunkte × 6 Zahlen.
|
||||
assert_eq!(v.len(), 3 * 2 * 6);
|
||||
assert!((v[1] - 1.01).abs() < 1e-4, "Höhe = Geschoss-UK + 0.01: {}", v[1]);
|
||||
}
|
||||
|
||||
/// Walmdach 12×7 m: zwei Trapeze + zwei Walm-Dreiecke, First (3,3)-(8,3).
|
||||
fn walm_planes() -> Vec<Vec<V3>> {
|
||||
vec![
|
||||
|
||||
@@ -65,6 +65,7 @@ pub fn plan_context(c: &Ctx, out: &mut Vec<Primitive>) {
|
||||
ContextObject::ContourSet(s) => s.category_code.as_deref(),
|
||||
ContextObject::TerrainMesh(t) => t.category_code.as_deref(),
|
||||
ContextObject::Image(i) => i.category_code.as_deref(),
|
||||
ContextObject::Excavation(e) => e.category_code.as_deref(),
|
||||
};
|
||||
if code.is_some_and(|k| !c.shown(k)) {
|
||||
continue;
|
||||
@@ -99,12 +100,109 @@ pub fn plan_context(c: &Ctx, out: &mut Vec<Primitive>) {
|
||||
}
|
||||
out.push(pick_band(q, Some(&t.id), None));
|
||||
}
|
||||
terrain_contours(c, t, out);
|
||||
}
|
||||
ContextObject::Excavation(e) => excavation_lines(c, e, out),
|
||||
ContextObject::Image(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const TERRAIN_INK: &str = "#7a5b3a";
|
||||
const EXCAVATION_INK: &str = "#1f242c";
|
||||
|
||||
fn ink_line(a: Vec2, b: Vec2, w: f64, color: &str, dash: Option<Vec<f64>>) -> Primitive {
|
||||
Primitive::Line { a, b, cls: "context-line".into(), weight_mm: w, dash: dash.map(Some), zigzag: None, motif: None, color: Some(color.into()), drawing_id: None, opening_id: None, stair_id: None, greyed: None, opacity: None }
|
||||
}
|
||||
|
||||
/// [T6] Höhenlinien aus dem Gelände-Netz (samt Baugruben) in der Äquidistanz `contourInterval`; jede
|
||||
/// `contourIndexEvery`-te ist Zähllinie (dicker, mit Höhenangabe, lesbar gedreht).
|
||||
fn terrain_contours(c: &Ctx, t: &TerrainMesh, out: &mut Vec<Primitive>) {
|
||||
let Some(iv) = t.contour_interval.filter(|v| v.is_finite() && *v > 0.0) else { return };
|
||||
let every = t.contour_index_every.filter(|v| v.is_finite() && *v >= 1.0).map_or(5, |v| v.round() as i64);
|
||||
let st = crate::excavation::site_terrain(c.p, t);
|
||||
let text_h = 0.002 * c.a.scale.max(1.0);
|
||||
for l in crate::terrain::isolines(st.current(), iv, 0.0) {
|
||||
let k = (l.level / iv).round() as i64;
|
||||
let index = k.rem_euclid(every) == 0;
|
||||
let w = if index { 0.25 } else { 0.1 };
|
||||
let n = l.pts.len();
|
||||
let segs = if l.closed { n } else { n - 1 };
|
||||
for i in 0..segs {
|
||||
let (a, b) = (l.pts[i], l.pts[(i + 1) % n]);
|
||||
out.push(ink_line(v2(a[0], a[1]), v2(b[0], b[1]), w, TERRAIN_INK, None));
|
||||
}
|
||||
if !index {
|
||||
continue;
|
||||
}
|
||||
// Beschriftung in der Mitte der Linie (nur, wenn sie lang genug ist).
|
||||
let len: f64 = (0..segs).map(|i| (l.pts[(i + 1) % n][0] - l.pts[i][0]).hypot(l.pts[(i + 1) % n][1] - l.pts[i][1])).sum();
|
||||
if len < 12.0 * text_h {
|
||||
continue;
|
||||
}
|
||||
let mut acc = 0.0;
|
||||
for i in 0..segs {
|
||||
let (a, b) = (l.pts[i], l.pts[(i + 1) % n]);
|
||||
let d = (b[0] - a[0]).hypot(b[1] - a[1]);
|
||||
if acc + d >= len / 2.0 && d > 0.0 {
|
||||
let f = (len / 2.0 - acc) / d;
|
||||
let mut ang = (b[1] - a[1]).atan2(b[0] - a[0]);
|
||||
if ang > std::f64::consts::FRAC_PI_2 || ang <= -std::f64::consts::FRAC_PI_2 {
|
||||
ang += std::f64::consts::PI;
|
||||
}
|
||||
// Text mittig auf die Linie (Breite ≈ 0.6 · Höhe je Zeichen, Grundlinie ≈ −0.35 · Höhe).
|
||||
let text = crate::js_fmt::to_fixed(l.level, if iv.fract() == 0.0 { 0 } else { 1 });
|
||||
let half = 0.3 * text_h * text.chars().count() as f64;
|
||||
let (c, s) = (ang.cos(), ang.sin());
|
||||
let m = (a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f);
|
||||
out.push(Primitive::DrawingText {
|
||||
at: v2(m.0 - c * half + s * 0.35 * text_h, m.1 - s * half - c * 0.35 * text_h),
|
||||
text,
|
||||
height_m: text_h,
|
||||
angle: ang,
|
||||
color: TERRAIN_INK.into(),
|
||||
marks: None,
|
||||
wrap_width: None,
|
||||
doc: None,
|
||||
drawing_id: None,
|
||||
greyed: None,
|
||||
opacity: None,
|
||||
});
|
||||
break;
|
||||
}
|
||||
acc += d;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [68] Baugrube im Grundriss: Sohle (Böschungsfuss) und Böschungsoberkante, Böschungsschraffur.
|
||||
fn excavation_lines(c: &Ctx, e: &Excavation, out: &mut Vec<Primitive>) {
|
||||
let ring: Vec<Vec2> = e.outline.iter().copied().filter(|q| q.x.is_finite() && q.y.is_finite()).collect();
|
||||
if ring.len() < 3 {
|
||||
return;
|
||||
}
|
||||
for i in 0..ring.len() {
|
||||
out.push(ink_line(ring[i], ring[(i + 1) % ring.len()], 0.25, EXCAVATION_INK, None));
|
||||
}
|
||||
out.push(pick_band(ring.clone(), Some(&e.id), None));
|
||||
let spacing = (0.004 * c.a.scale.max(1.0)).max(0.2);
|
||||
for t in crate::excavation::terrains(c.p) {
|
||||
let st = crate::excavation::site_terrain(c.p, t);
|
||||
let Some((_, spec, daylight)) = st.items.iter().find(|(id, ..)| *id == e.id) else { continue };
|
||||
for l in daylight {
|
||||
for w in l.windows(2) {
|
||||
out.push(ink_line(v2(w[0][0], w[0][1]), v2(w[1][0], w[1][1]), 0.18, EXCAVATION_INK, None));
|
||||
}
|
||||
}
|
||||
if let Some(before) = crate::excavation::terrain_before(&st, &e.id) {
|
||||
for (a, b) in crate::excavation::slope_hatch(&before, spec, spacing) {
|
||||
out.push(ink_line(v2(a[0], a[1]), v2(b[0], b[1]), 0.1, EXCAVATION_INK, None));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// Kurz-Tag eines Schnitt-Labels: letztes Wort des Namens, sonst der ganze (getrimmte) Name.
|
||||
pub fn section_label_tag(name: &str) -> String {
|
||||
let t = js_trim(name);
|
||||
@@ -185,6 +283,36 @@ pub fn plan_section_lines(c: &Ctx, out: &mut Vec<Primitive>) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// [T6]/[68] Höhenlinien (Zähllinien dicker + beschriftet) und Baugrube (Sohle, Oberkante, Schraffur).
|
||||
#[test]
|
||||
fn hoehenlinien_und_baugrube() {
|
||||
// Ebene schräg: z = x/10 über 0..40 m → Linien bei x = 10, 20, 30 (Äquidistanz 1), Zähllinie bei 0/5 m.
|
||||
let t = TerrainMesh {
|
||||
id: "t".into(),
|
||||
positions: vec![0.0, 0.0, 0.0, 60.0, 0.0, 6.0, 60.0, 40.0, 6.0, 0.0, 40.0, 0.0],
|
||||
indices: vec![0.0, 1.0, 2.0, 0.0, 2.0, 3.0],
|
||||
category_code: Some("02".into()),
|
||||
contour_interval: Some(1.0),
|
||||
..Default::default()
|
||||
};
|
||||
let pit = Excavation {
|
||||
id: "bg".into(),
|
||||
outline: vec![v2(20.0, 15.0), v2(30.0, 15.0), v2(30.0, 25.0), v2(20.0, 25.0)],
|
||||
bottom: 1.0,
|
||||
..Default::default()
|
||||
};
|
||||
let p = Project { context: Some(vec![ContextObject::TerrainMesh(t), ContextObject::Excavation(pit)]), ..Default::default() };
|
||||
let a = super::super::domains::PlanArgs::parse(1.0, r#"{"show": ["02"], "scale": 100}"#).unwrap();
|
||||
let mut out = Vec::new();
|
||||
plan_context(&Ctx::new(&p, &a), &mut out);
|
||||
let w = |m: f64| out.iter().filter(|q| matches!(q, Primitive::Line { weight_mm, color: Some(c), .. } if *weight_mm == m && c == TERRAIN_INK)).count();
|
||||
assert!(w(0.1) > 4 && w(0.25) > 0, "{} {}", w(0.1), w(0.25));
|
||||
let labels: Vec<&str> = out.iter().filter_map(|q| if let Primitive::DrawingText { text, .. } = q { Some(text.as_str()) } else { None }).collect();
|
||||
assert!(labels.contains(&"5"), "{labels:?}");
|
||||
let ex = out.iter().filter(|q| matches!(q, Primitive::Line { color: Some(c), .. } if c == EXCAVATION_INK)).count();
|
||||
assert!(ex > 20, "{ex}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn label_tag_wie_ts() {
|
||||
assert_eq!(section_label_tag("Schnitt A"), "A");
|
||||
|
||||
@@ -54,6 +54,9 @@ pub fn symbol_factor(p: &Project, level: &str) -> f64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Rand um die Achsen im Ausmass, damit die Blasen ins Bild passen (Meter).
|
||||
const GRID_BUBBLE_MARGIN_M: f64 = 1.0;
|
||||
|
||||
// Massstabsbalken, Papier-mm.
|
||||
const SCALEBAR_HEIGHT_MM: f64 = 1.5;
|
||||
const SCALEBAR_TICK_MM: f64 = 1.0;
|
||||
@@ -211,6 +214,7 @@ pub fn shape_name(g: &Drawing2DGeom) -> &'static str {
|
||||
Drawing2DGeom::Detailref { .. } => "detailref",
|
||||
Drawing2DGeom::Scalebar { .. } => "scalebar",
|
||||
Drawing2DGeom::Pointmarker { .. } => "pointmarker",
|
||||
Drawing2DGeom::Grid { .. } => "grid",
|
||||
Drawing2DGeom::Text { .. } => "text",
|
||||
Drawing2DGeom::Block { .. } => "block",
|
||||
Drawing2DGeom::Image { .. } => "image",
|
||||
@@ -738,9 +742,22 @@ fn emit_inner(c: &Ctx, d: &Drawing2D, attrs: Attrs, geom: &Drawing2DGeom, greyed
|
||||
em.seg(q[q.len() - 1], q[0]);
|
||||
}
|
||||
}
|
||||
Drawing2DGeom::Dimension { pts, offset, gap_mm, overshoot_mm, tick_len_mm, text_height_mm, line_weight_mm, ext_weight_mm, tick_weight_mm, text_offsets_mm, refs } => {
|
||||
Drawing2DGeom::Dimension { pts, offset, gap_mm, overshoot_mm, tick_len_mm, text_height_mm, line_weight_mm, ext_weight_mm, tick_weight_mm, text_offsets_mm, refs, kind } => {
|
||||
let mm = |x: f64| mm_to_model(x, scale);
|
||||
for i in 0..pts.len().saturating_sub(1) {
|
||||
if let Some(k) = kind {
|
||||
let st = DimStyle {
|
||||
gap: mm(gap_mm.unwrap_or(DIM_GAP_MM)),
|
||||
overshoot: mm(overshoot_mm.unwrap_or(DIM_OVERSHOOT_MM)),
|
||||
tick_len: mm(tick_len_mm.unwrap_or(DIM_TICK_LEN_MM)),
|
||||
text_height: mm(text_height_mm.unwrap_or(DIM_TEXT_HEIGHT_MM)),
|
||||
line_weight: line_weight_mm.unwrap_or(em.weight),
|
||||
ext_weight: ext_weight_mm.unwrap_or(em.weight),
|
||||
tick_weight: tick_weight_mm.unwrap_or(em.weight * 2.0),
|
||||
text_offset: (0.0, 0.0),
|
||||
};
|
||||
dimension_round(&mut em, pts, *offset, *k, &st);
|
||||
}
|
||||
for i in 0..(if kind.is_some() { 0 } else { pts.len().saturating_sub(1) }) {
|
||||
let st = DimStyle {
|
||||
gap: mm(gap_mm.unwrap_or(DIM_GAP_MM)),
|
||||
overshoot: mm(overshoot_mm.unwrap_or(DIM_OVERSHOOT_MM)),
|
||||
@@ -817,6 +834,11 @@ fn emit_inner(c: &Ctx, d: &Drawing2D, attrs: Attrs, geom: &Drawing2DGeom, greyed
|
||||
em.seg(v(at.x - cross, at.y), v(at.x + cross, at.y));
|
||||
em.seg(v(at.x, at.y - cross), v(at.x, at.y + cross));
|
||||
}
|
||||
Drawing2DGeom::Grid { bubble_mm, .. } => {
|
||||
if let Some(spec) = crate::grid::Spec::of(geom) {
|
||||
emit_grid(&mut em, &spec, crate::grid::bubble_diameter(*bubble_mm, scale), scale);
|
||||
}
|
||||
}
|
||||
Drawing2DGeom::Text { at, text: s, height, angle, width, marks, doc, leader_target, leader_bend_points, path_pts } => {
|
||||
let color = marks.as_ref().and_then(|m| m.color.clone()).unwrap_or_else(|| em.color.to_string());
|
||||
if let Some(path) = path_pts.as_ref().filter(|q| q.len() >= 2) {
|
||||
@@ -941,6 +963,110 @@ fn dimension_segment(em: &mut Em, a: Vec2, b: Vec2, offset: f64, st: &DimStyle)
|
||||
em.sink.push(p, 0);
|
||||
}
|
||||
|
||||
/// Achsraster ([112]): Achsen strichpunktiert, an den Enden Blasen mit der Beschriftung.
|
||||
fn emit_grid(em: &mut Em, spec: &crate::grid::Spec, diameter: f64, scale: f64) {
|
||||
use crate::grid::Shape;
|
||||
let mm = |x: f64| mm_to_model(x, scale);
|
||||
let dash = [mm(12.0), mm(2.5), mm(1.5), mm(2.5)];
|
||||
let dash_ref = em.sink.fresh_ref();
|
||||
let w = jsnum::min(em.weight, XLINE_WEIGHT_MM.max(0.18));
|
||||
let r = diameter / 2.0;
|
||||
let text_h = diameter * 0.5;
|
||||
for ax in spec.axes() {
|
||||
match ax.shape {
|
||||
Shape::Line { a, b } => em.line(v(a.0, a.1), v(b.0, b.1), w, Some(&dash), dash_ref),
|
||||
Shape::Arc { c, r: rad, a0, a1 } => {
|
||||
let dash_v = Some(dash.to_vec());
|
||||
if a1 - a0 >= std::f64::consts::TAU - 1e-9 {
|
||||
em.sink.push(
|
||||
Primitive::DrawingCircle { center: v(c.0, c.1), r: rad, fill: "none".into(), stroke: em.color.into(), weight_mm: w, dash: Some(dash_v), drawing_id: Some(em.id.into()), greyed: Some(em.greyed), opacity: None },
|
||||
dash_ref,
|
||||
);
|
||||
} else {
|
||||
em.sink.push(
|
||||
Primitive::DrawingArc { center: v(c.0, c.1), r: rad, a0, a1, stroke: em.color.into(), weight_mm: w, dash: Some(dash_v), drawing_id: Some(em.id.into()), greyed: Some(em.greyed), opacity: None },
|
||||
dash_ref,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (end, dir) in ax.bubbles.iter().flatten() {
|
||||
let c = v(end.0 + dir.0 * r, end.1 + dir.1 * r);
|
||||
em.circle(c, r, "none", Some(None));
|
||||
let n = ax.label.chars().count() as f64;
|
||||
em.text(v(c.x - text_h * 0.3 * n, c.y - text_h * 0.35), ax.label.clone(), text_h);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Radius-, Durchmesser- und Bogenlängen-Mass ([38]): `pts` = Mittelpunkt, Punkt auf dem Kreis
|
||||
/// (bzw. Bogenanfang, Bogenende); Mass auf dem Rand mit Massstrichen und Masszahl.
|
||||
fn dimension_round(em: &mut Em, pts: &[Vec2], offset: f64, kind: DimKind, st: &DimStyle) {
|
||||
let (Some(&c), Some(&p)) = (pts.first(), pts.get(1)) else { return };
|
||||
let r = hypot2(p.x - c.x, p.y - c.y);
|
||||
if !(r > 1e-6) {
|
||||
return;
|
||||
}
|
||||
let (ux, uy) = ((p.x - c.x) / r, (p.y - c.y) / r);
|
||||
let tick = |em: &mut Em, q: Vec2, tx: f64, ty: f64| {
|
||||
let (nx, ny) = (-ty, tx);
|
||||
let (dx, dy) = ((tx + nx) / std::f64::consts::SQRT_2, (ty + ny) / std::f64::consts::SQRT_2);
|
||||
let h = st.tick_len / 2.0;
|
||||
em.line(v(q.x - dx * h, q.y - dy * h), v(q.x + dx * h, q.y + dy * h), st.tick_weight, None, 0);
|
||||
};
|
||||
let label = |em: &mut Em, at: Vec2, ang: f64, s: String| {
|
||||
let mut a = ang;
|
||||
if jsnum::cos(a) < 0.0 {
|
||||
a += std::f64::consts::PI;
|
||||
}
|
||||
let up = v(-jsnum::sin(a), jsnum::cos(a));
|
||||
let q = v(at.x + up.x * st.text_height * 0.6, at.y + up.y * st.text_height * 0.6);
|
||||
let pr = text(q, s, st.text_height, a, em.color, em.greyed, Some(em.id));
|
||||
em.sink.push(pr, 0);
|
||||
};
|
||||
let (dash, dref) = (em.dash.clone(), em.dash_ref);
|
||||
let dash = dash.as_deref();
|
||||
match kind {
|
||||
DimKind::Radius => {
|
||||
em.line(c, p, st.line_weight, dash, dref);
|
||||
tick(em, p, ux, uy);
|
||||
tick(em, c, ux, uy);
|
||||
let mid = v((c.x + p.x) / 2.0, (c.y + p.y) / 2.0);
|
||||
label(em, mid, jsnum::atan2(uy, ux), format!("R {}", to_fixed(r, 2)));
|
||||
}
|
||||
DimKind::Diameter => {
|
||||
let q = v(c.x - ux * r, c.y - uy * r);
|
||||
em.line(q, p, st.line_weight, dash, dref);
|
||||
tick(em, p, ux, uy);
|
||||
tick(em, q, ux, uy);
|
||||
label(em, c, jsnum::atan2(uy, ux), format!("\u{d8} {}", to_fixed(2.0 * r, 2)));
|
||||
}
|
||||
DimKind::Arc => {
|
||||
let Some(&p1) = pts.get(2) else { return };
|
||||
let a0 = jsnum::atan2(p.y - c.y, p.x - c.x);
|
||||
let a1 = jsnum::atan2(p1.y - c.y, p1.x - c.x);
|
||||
let sweep = (a1 - a0).rem_euclid(std::f64::consts::TAU);
|
||||
let rr = r + offset;
|
||||
if !(rr > 1e-6) || !(sweep > 1e-9) {
|
||||
return;
|
||||
}
|
||||
let sign = if offset >= 0.0 { 1.0 } else { -1.0 };
|
||||
for (a, pt) in [(a0, p), (a1, p1)] {
|
||||
let (cx, cy) = (jsnum::cos(a), jsnum::sin(a));
|
||||
em.line(v(pt.x + cx * st.gap * sign, pt.y + cy * st.gap * sign), v(c.x + cx * (rr + st.overshoot * sign), c.y + cy * (rr + st.overshoot * sign)), st.ext_weight, dash, dref);
|
||||
tick(em, v(c.x + cx * rr, c.y + cy * rr), -cy, cx);
|
||||
}
|
||||
em.sink.push(
|
||||
Primitive::DrawingArc { center: c, r: rr, a0, a1: a0 + sweep, stroke: em.color.into(), weight_mm: st.line_weight, dash: Some(dash.map(|x| x.to_vec())), drawing_id: Some(em.id.into()), greyed: Some(em.greyed), opacity: None },
|
||||
if dash.is_some() { dref } else { 0 },
|
||||
);
|
||||
let am = a0 + sweep / 2.0;
|
||||
let at = v(c.x + jsnum::cos(am) * rr, c.y + jsnum::sin(am) * rr);
|
||||
label(em, at, am + std::f64::consts::FRAC_PI_2, format!("L {}", to_fixed(r * sweep, 2)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Dreht die Umlauf-Orientierung um (Spiegelung)? Flächenvorzeichen eines Test-Dreiecks.
|
||||
fn reverses_orientation(f: &dyn Fn(Vec2) -> Vec2) -> bool {
|
||||
let (p0, p1, p2) = (f(v(0.0, 0.0)), f(v(1.0, 0.0)), f(v(0.0, 1.0)));
|
||||
@@ -986,6 +1112,19 @@ pub fn mv_geom(g: &Drawing2DGeom, f: &dyn Fn(Vec2) -> Vec2) -> Drawing2DGeom {
|
||||
G::Detailref { at, label, sheet_layout_id, sheet_label } => G::Detailref { at: f(*at), label: label.clone(), sheet_layout_id: sheet_layout_id.clone(), sheet_label: sheet_label.clone() },
|
||||
G::Scalebar { at, segment_length, segments } => G::Scalebar { at: f(*at), segment_length: *segment_length, segments: *segments },
|
||||
G::Pointmarker { at } => G::Pointmarker { at: f(*at) },
|
||||
G::Grid { origin, angle, radial, a, b, extend, bubbles, bubble_mm, levels, show_3d } => {
|
||||
let o = f(*origin);
|
||||
let ex = f(v(origin.x + angle.cos(), origin.y + angle.sin()));
|
||||
let flip = reverses_orientation(f);
|
||||
let neg = |l: &Vec<GridAxis>| l.iter().map(|x| GridAxis { label: x.label.clone(), pos: -x.pos }).collect::<Vec<_>>();
|
||||
let ang = (ex.y - o.y).atan2(ex.x - o.x);
|
||||
let (a2, b2) = match (flip, radial == &Some(true)) {
|
||||
(false, _) => (a.clone(), b.clone()),
|
||||
(true, false) => (a.clone(), neg(b)),
|
||||
(true, true) => (neg(a), b.clone()),
|
||||
};
|
||||
G::Grid { origin: o, angle: ang, radial: *radial, a: a2, b: b2, extend: *extend, bubbles: *bubbles, bubble_mm: *bubble_mm, levels: levels.clone(), show_3d: *show_3d }
|
||||
}
|
||||
G::Text { at, text, height, angle, width, marks, doc, leader_target, leader_bend_points, path_pts } => G::Text {
|
||||
at: f(*at),
|
||||
text: text.clone(),
|
||||
@@ -1024,6 +1163,15 @@ pub fn scale_geom(g: &Drawing2DGeom, f: &dyn Fn(Vec2) -> Vec2, k: f64) -> Drawin
|
||||
*ry *= k;
|
||||
}
|
||||
G::Dimension { offset, .. } => *offset *= k,
|
||||
G::Grid { a, b, extend, radial, .. } => {
|
||||
if *radial != Some(true) {
|
||||
a.iter_mut().for_each(|x| x.pos *= k);
|
||||
}
|
||||
b.iter_mut().for_each(|x| x.pos *= k);
|
||||
if let Some(e) = extend {
|
||||
*e *= k;
|
||||
}
|
||||
}
|
||||
G::Text { height, width, .. } => {
|
||||
*height *= k;
|
||||
if let Some(w) = width {
|
||||
@@ -1097,6 +1245,25 @@ fn acc_bounds(g: &Drawing2DGeom, b: &mut Bounds) {
|
||||
}
|
||||
}
|
||||
G::Kote { at, .. } | G::Detailref { at, .. } | G::Pointmarker { at } | G::Text { at, .. } => acc(at),
|
||||
G::Grid { .. } => {
|
||||
if let Some(spec) = crate::grid::Spec::of(g) {
|
||||
for ax in spec.axes() {
|
||||
match ax.shape {
|
||||
// Rand für die Blasen an den Enden (Durchmesser bis ≈ 1 m bei 1:100).
|
||||
crate::grid::Shape::Line { a, b: e } => {
|
||||
acc(&v(a.0 - GRID_BUBBLE_MARGIN_M, a.1 - GRID_BUBBLE_MARGIN_M));
|
||||
acc(&v(e.0 + GRID_BUBBLE_MARGIN_M, e.1 + GRID_BUBBLE_MARGIN_M));
|
||||
acc(&v(a.0 + GRID_BUBBLE_MARGIN_M, a.1 + GRID_BUBBLE_MARGIN_M));
|
||||
acc(&v(e.0 - GRID_BUBBLE_MARGIN_M, e.1 - GRID_BUBBLE_MARGIN_M));
|
||||
}
|
||||
crate::grid::Shape::Arc { c, r, .. } => {
|
||||
acc(&v(c.0 - r - GRID_BUBBLE_MARGIN_M, c.1 - r - GRID_BUBBLE_MARGIN_M));
|
||||
acc(&v(c.0 + r + GRID_BUBBLE_MARGIN_M, c.1 + r + GRID_BUBBLE_MARGIN_M));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
G::Scalebar { at, segment_length, segments } => {
|
||||
acc(at);
|
||||
acc(&v(at.x + segment_length * segments, at.y));
|
||||
@@ -1107,7 +1274,7 @@ fn acc_bounds(g: &Drawing2DGeom, b: &mut Bounds) {
|
||||
|
||||
/// Liegt die Zeichnung auf dem Geschoss (und ist sie im Druck nicht ausgenommen, `noPrint`)?
|
||||
fn on_floor(c: &Ctx, d: &Drawing2D) -> bool {
|
||||
d.level_id == c.a.floor && !(c.a.for_print && d.no_print == Some(true))
|
||||
crate::grid::visible_on(d, &c.a.floor) && !(c.a.for_print && d.no_print == Some(true))
|
||||
}
|
||||
|
||||
/// Domäne „2D-Zeichnungen" von `planDomains`: alle gezeichneten Zeichnungen des Geschosses in
|
||||
@@ -1475,6 +1642,69 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// [112] Achsraster: strichpunktierte Achsen, Blasen (Kreis + Beschriftung) an beiden Enden,
|
||||
/// Ringe als Bögen, Blasengrösse folgt dem Massstab; auf anderen Geschossen sichtbar (`levels` leer).
|
||||
#[test]
|
||||
fn achsraster_achsen_und_blasen() {
|
||||
let p = project(serde_json::json!({}));
|
||||
let grid = |radial: bool| {
|
||||
drawing(serde_json::json!({"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0, "radial": radial,
|
||||
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": if radial { 90.0 } else { 5.0 }}], "b": [{"label": "A", "pos": 0}, {"label": "B", "pos": 4}], "extend": 1}))
|
||||
};
|
||||
let prims = render(&p, grid(false), 100.0);
|
||||
let lines = prims.iter().filter(|q| matches!(q, Primitive::Line { dash: Some(Some(_)), .. })).count();
|
||||
let circles: Vec<f64> = prims.iter().filter_map(|q| if let Primitive::DrawingCircle { r, .. } = q { Some(*r) } else { None }).collect();
|
||||
let texts: Vec<String> = prims.iter().filter_map(|q| if let Primitive::DrawingText { text, .. } = q { Some(text.clone()) } else { None }).collect();
|
||||
assert_eq!(lines, 4);
|
||||
assert_eq!(circles.len(), 8);
|
||||
// 8 mm Durchmesser bei 1:100 = 0.8 m → Radius 0.4.
|
||||
assert!(circles.iter().all(|r| (r - 0.4).abs() < 1e-9), "{circles:?}");
|
||||
assert_eq!(texts.len(), 8);
|
||||
assert!(["1", "2", "A", "B"].iter().all(|t| texts.iter().any(|x| x == t)));
|
||||
// Halber Massstab → halbe Blase.
|
||||
let half: Vec<f64> = render(&p, grid(false), 50.0).iter().filter_map(|q| if let Primitive::DrawingCircle { r, .. } = q { Some(*r) } else { None }).collect();
|
||||
assert!((half[0] - 0.2).abs() < 1e-9);
|
||||
// Radial: 2 Strahlen (Linien) und 2 Ringe (Bögen, Ring A mit Radius 0 entfällt als Vollkreis-Punkt).
|
||||
let prims = render(&p, grid(true), 100.0);
|
||||
assert_eq!(prims.iter().filter(|q| matches!(q, Primitive::Line { .. })).count(), 2);
|
||||
assert!(prims.iter().any(|q| matches!(q, Primitive::DrawingArc { r, .. } if (*r - 4.0).abs() < 1e-9)));
|
||||
}
|
||||
|
||||
/// [112] Raster erscheint in jedem Geschoss, bei `levels` nur in den genannten.
|
||||
#[test]
|
||||
fn achsraster_je_geschoss() {
|
||||
let g = |levels: Option<Vec<&str>>| {
|
||||
let mut d: Drawing2D = serde_json::from_value(drawing(serde_json::json!({"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0, "a": [], "b": []}))).unwrap();
|
||||
if let Drawing2DGeom::Grid { levels: l, .. } = &mut d.geom {
|
||||
*l = levels.map(|v| v.into_iter().map(String::from).collect());
|
||||
}
|
||||
d
|
||||
};
|
||||
let p = project(serde_json::json!({}));
|
||||
let a = args(100.0);
|
||||
let c = Ctx::new(&p, &a);
|
||||
let mut d = g(None);
|
||||
d.level_id = "og".into();
|
||||
assert!(on_floor(&c, &d), "ohne levels: in allen Geschossen (Plan zeigt eg)");
|
||||
assert!(!on_floor(&c, &g(Some(vec!["og"]))));
|
||||
assert!(on_floor(&c, &g(Some(vec!["og", "eg"]))));
|
||||
}
|
||||
|
||||
/// [38] Radius-, Durchmesser- und Bogenlängen-Mass: Linien, Masszahl mit R / Ø / L.
|
||||
#[test]
|
||||
fn rund_bemassung_zeichnet_zahl() {
|
||||
let p = project(serde_json::json!({}));
|
||||
let dim = |kind: &str, pts: serde_json::Value| drawing(serde_json::json!({"shape": "dimension", "pts": pts, "offset": 0.5, "kind": kind}));
|
||||
let texts = |prims: &[Primitive]| -> Vec<String> { prims.iter().filter_map(|q| if let Primitive::DrawingText { text, .. } = q { Some(text.clone()) } else { None }).collect() };
|
||||
let r = render(&p, dim("radius", serde_json::json!([{"x": 0, "y": 0}, {"x": 3, "y": 0}])), 100.0);
|
||||
assert_eq!(texts(&r), ["R 3.00"]);
|
||||
let r = render(&p, dim("diameter", serde_json::json!([{"x": 0, "y": 0}, {"x": 3, "y": 0}])), 100.0);
|
||||
assert_eq!(texts(&r), ["\u{d8} 6.00"]);
|
||||
let r = render(&p, dim("arc", serde_json::json!([{"x": 0, "y": 0}, {"x": 2, "y": 0}, {"x": 0, "y": 2}])), 100.0);
|
||||
assert_eq!(texts(&r), ["L 3.14"]);
|
||||
assert!(r.iter().any(|q| matches!(q, Primitive::DrawingArc { r, .. } if (*r - 2.5).abs() < 1e-9)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rechteck_flaeche_und_vier_linien_in_ebenenfarbe() {
|
||||
let p = project(serde_json::json!({}));
|
||||
|
||||
@@ -77,6 +77,229 @@ struct Face {
|
||||
normal: [f64; 3],
|
||||
}
|
||||
|
||||
/// Stirnflächen der Dachscheibe an den freien Rändern der Dachflächen (Traufe, Ortgang): je Rand ein
|
||||
/// Viereck von der Oberkante senkrecht zur Fläche um die Dicke nach innen (wie die 3D-Schichten).
|
||||
fn fascia_quads(planes: &[Vec<[f64; 3]>], total: f64) -> Vec<[[f64; 3]; 4]> {
|
||||
let mut out = Vec::new();
|
||||
if !(total > 1e-6) {
|
||||
return out;
|
||||
}
|
||||
let same = |a: [f64; 3], b: [f64; 3]| (a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6 && (a[2] - b[2]).abs() < 1e-6;
|
||||
for (i, pl) in planes.iter().enumerate() {
|
||||
if pl.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let n = model3d::plane_normal_up(pl);
|
||||
if !(n[2] > 1e-3) {
|
||||
continue;
|
||||
}
|
||||
for k in 0..pl.len() {
|
||||
let (a, b) = (pl[k], pl[(k + 1) % pl.len()]);
|
||||
let shared = planes.iter().enumerate().any(|(j, o)| j != i && (0..o.len()).any(|m| { let (c, d) = (o[m], o[(m + 1) % o.len()]); (same(a, c) && same(b, d)) || (same(a, d) && same(b, c)) }));
|
||||
if shared || same(a, b) {
|
||||
continue;
|
||||
}
|
||||
let off = |q: [f64; 3]| [q[0] - n[0] * total, q[1] - n[1] * total, q[2] - n[2] * total];
|
||||
out.push([a, b, off(b), off(a)]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Dach-Scheiben für die Verdeckung der Wände darunter ([G2]): je Dachfläche Ober- und Unterkante,
|
||||
/// dazu die Stirnflächen der Ränder.
|
||||
struct RoofSheet {
|
||||
top: Vec<crate::wall_bands::RoofFacet>,
|
||||
under: Vec<crate::wall_bands::RoofFacet>,
|
||||
fascia: Vec<[[f64; 3]; 4]>,
|
||||
bounds: [f64; 4],
|
||||
}
|
||||
|
||||
/// Kreuzt die waagrechte Strecke `a → b` (Grundriss) auf Höhe `z` eine Stirnfläche (im Innern)?
|
||||
fn crosses_fascia(q: &[[f64; 3]; 4], a: (f64, f64), b: (f64, f64), z: f64) -> bool {
|
||||
let e1 = [q[1][0] - q[0][0], q[1][1] - q[0][1], q[1][2] - q[0][2]];
|
||||
let e2 = [q[3][0] - q[0][0], q[3][1] - q[0][1], q[3][2] - q[0][2]];
|
||||
let m = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]];
|
||||
let side = |x: f64, y: f64| m[0] * (x - q[0][0]) + m[1] * (y - q[0][1]) + m[2] * (z - q[0][2]);
|
||||
let (s0, s1) = (side(a.0, a.1), side(b.0, b.1));
|
||||
if !(s0 * s1 < 0.0) {
|
||||
return false;
|
||||
}
|
||||
let t = s0 / (s0 - s1);
|
||||
let x = [a.0 + (b.0 - a.0) * t - q[0][0], a.1 + (b.1 - a.1) * t - q[0][1], z - q[0][2]];
|
||||
let dot = |u: [f64; 3], v: [f64; 3]| u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
|
||||
let (l1, l2) = (dot(e1, e1), dot(e2, e2));
|
||||
if !(l1 > 1e-12 && l2 > 1e-12) {
|
||||
return false;
|
||||
}
|
||||
let (al, be) = (dot(x, e1) / l1, dot(x, e2) / l2);
|
||||
(0.0..=1.0).contains(&al) && be > 1e-6 && be < 1.0 - 1e-6
|
||||
}
|
||||
|
||||
impl RoofSheet {
|
||||
/// Oberkante minus `z` über dem Grundriss-Punkt (`None`: kein Dach), nur wo die Unterkante echt unter
|
||||
/// `z` liegt oder die Oberkante darunter (Strahl über dem Dach).
|
||||
fn above(&self, x: f64, y: f64, z: f64) -> Option<f64> {
|
||||
let b = self.bounds;
|
||||
if x < b[0] || x > b[2] || y < b[1] || y > b[3] {
|
||||
return None;
|
||||
}
|
||||
self.top.iter().zip(&self.under).filter(|(t, _)| t.contains(x, y)).map(|(t, u)| if u.z(x, y) < z - 1e-4 { t.z(x, y) - z } else { -1.0 }).reduce(f64::max)
|
||||
}
|
||||
}
|
||||
|
||||
/// Wandflächen unter Dächern ([G2]) gegen die Dachscheiben vor ihnen: Ecken, deren Sichtstrahl (zum
|
||||
/// Betrachter) durch ein Dach läuft, sind verdeckt. Ganz verdeckte Flächen entfallen (Oberseiten,
|
||||
/// Laibungen und Stirnen innen unter dem Dach); bei senkrechten Kanten wird die Fläche auf die Höhe
|
||||
/// gekappt, ab der das Dach sie verdeckt (Traufe vor der Wand). Ersetzt keine HLR ([G4]).
|
||||
fn cull_under_roofs(p: &Project, frame: &[f64; 9], walls: &[RWall], faces: &mut Vec<Face>) {
|
||||
let affected: std::collections::HashSet<&str> = walls.iter().filter(|w| w.top_plane.is_some() || w.joint != [false; 2]).map(|w| w.wall_id.as_str()).collect();
|
||||
if affected.is_empty() {
|
||||
return;
|
||||
}
|
||||
let sheets: Vec<RoofSheet> = p
|
||||
.roofs
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let g = crate::roof::roof_geometry(&r.params(), p.roof_base_elevation(r));
|
||||
let total: f64 = p.roof_layers(r).iter().map(|l| l.thickness.max(0.0)).sum();
|
||||
let top = crate::wall_bands::plane_facets(&g.planes, 0.0);
|
||||
let under = crate::wall_bands::plane_facets(&g.planes, total);
|
||||
let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
|
||||
for q in g.planes.iter().flatten() {
|
||||
b = [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[0]), b[3].max(q[1])];
|
||||
}
|
||||
// Stirnflächen, die in einem anderen Dach stecken (Kehlen verschnittener Dächer), verdecken nicht.
|
||||
let others: Vec<Vec<[f64; 3]>> = p
|
||||
.roofs
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.filter(|o| o.id != r.id && o.floor_id == r.floor_id)
|
||||
.flat_map(|o| crate::roof::roof_geometry(&o.params(), p.roof_base_elevation(o)).planes)
|
||||
.collect();
|
||||
let fascia = fascia_quads(&g.planes, total)
|
||||
.into_iter()
|
||||
.filter(|q| !others.iter().any(|o| crate::dormer::point_in_xy((q[0][0] + q[1][0]) / 2.0, (q[0][1] + q[1][1]) / 2.0, o)))
|
||||
.collect();
|
||||
RoofSheet { top, under, fascia, bounds: b }
|
||||
})
|
||||
.filter(|s| s.top.len() == s.under.len() && !s.top.is_empty())
|
||||
.collect();
|
||||
if sheets.is_empty() {
|
||||
return;
|
||||
}
|
||||
let (o, n, u) = ([frame[0], frame[2]], [frame[3], frame[5]], [frame[6], frame[8]]);
|
||||
let reach = sheets.iter().map(|s| (s.bounds[2] - s.bounds[0]).max(s.bounds[3] - s.bounds[1])).fold(0.0, f64::max) + 1.0;
|
||||
// Gaubenstirnen und -wangen als senkrechte Verdecker (lokal u, v; z von der Hauptdach-Unterkante bis
|
||||
// zum Gaubendach).
|
||||
let dormers: Vec<crate::dormer::DormerGeom> = p
|
||||
.roofs
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.flat_map(|r| r.dormers.as_deref().unwrap_or(&[]).iter().filter_map(move |d| crate::dormer::geometry(p, r, d)))
|
||||
.collect();
|
||||
let dormer_hit = |a: (f64, f64), b: (f64, f64), z: f64| -> bool {
|
||||
dormers.iter().any(|g| {
|
||||
let (la, lb) = (g.frame.local(a.0, a.1), g.frame.local(b.0, b.1));
|
||||
let hw = g.width / 2.0;
|
||||
let z_ok = |u: f64, v: f64| z >= g.frame.main_top(v) - g.main_thickness * 2.0 && z <= g.under(u, v) + g.roof_vertical();
|
||||
// Stirn (v = 0) oder Wange (|u| = hw) gekreuzt.
|
||||
let front = (la[1] > 0.0) != (lb[1] > 0.0) && la[0].abs() <= hw && z_ok(la[0], 0.0);
|
||||
let cheek = (la[0].abs() < hw) != (lb[0].abs() < hw) && la[1] >= 0.0 && la[1] <= g.hole_v(la[0]) && z_ok(la[0].clamp(-hw, hw), la[1]);
|
||||
front || cheek
|
||||
})
|
||||
};
|
||||
// Verdeckt: der Strahl zum Betrachter (−n im Grundriss) kreuzt die Dachoberfläche von unten nach
|
||||
// oben gesehen (erst darunter, näher zum Betrachter darüber) oder eine Gaubenwand.
|
||||
let hidden = |x: f64, y: f64, z: f64| -> bool {
|
||||
let steps = ((reach / 0.04).ceil() as usize).min(5000);
|
||||
let mut under = false;
|
||||
let mut prev = (x, y);
|
||||
let at = |t: f64| sheets.iter().filter_map(|s| s.above(x - n[0] * t, y - n[1] * t, z)).reduce(f64::max);
|
||||
for i in 1..=steps {
|
||||
let t = i as f64 * 0.04;
|
||||
let q = (x - n[0] * t, y - n[1] * t);
|
||||
if dormer_hit(prev, q, z) || sheets.iter().any(|s| s.fascia.iter().any(|f| crosses_fascia(f, prev, q, z))) {
|
||||
return true;
|
||||
}
|
||||
prev = q;
|
||||
match at(t) {
|
||||
Some(d) if d >= 0.0 => under = true,
|
||||
Some(_) if under => return true,
|
||||
None if under => {
|
||||
// Aus der Scheibe heraus (Traufkante): Oberkante genau an der Kante unter z?
|
||||
let (mut lo, mut hi) = (t - 0.04, t);
|
||||
for _ in 0..30 {
|
||||
let m = (lo + hi) / 2.0;
|
||||
if at(m).is_some() {
|
||||
lo = m;
|
||||
} else {
|
||||
hi = m;
|
||||
}
|
||||
}
|
||||
if at(lo).is_some_and(|d| d < -1e-6) {
|
||||
return true;
|
||||
}
|
||||
under = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
false
|
||||
};
|
||||
faces.retain_mut(|f| {
|
||||
if f.role != Role::Wall || !affected.contains(f.id.as_str()) || f.pts.len() < 3 {
|
||||
return true;
|
||||
}
|
||||
// Tiefe je Ecke aus der Flächenebene (Normale in Welt x, Höhe, Grundriss-y).
|
||||
let k = f.normal[0] * n[0] + f.normal[2] * n[1];
|
||||
if k.abs() < 1e-9 {
|
||||
return true;
|
||||
}
|
||||
let m = f.pts.len() as f64;
|
||||
let (cu, cv) = (f.pts.iter().map(|q| q[0]).sum::<f64>() / m, f.pts.iter().map(|q| q[1]).sum::<f64>() / m);
|
||||
let nu = f.normal[0] * u[0] + f.normal[2] * u[1];
|
||||
let world = |q: Pt| -> (f64, f64, f64) {
|
||||
let d = f.depth + (nu * (cu - q[0]) + f.normal[1] * (cv - q[1])) / k;
|
||||
(o[0] + u[0] * q[0] + n[0] * d, o[1] + u[1] * q[0] + n[1] * d, q[1])
|
||||
};
|
||||
let hid: Vec<bool> = f.pts.iter().map(|&q| {
|
||||
let (x, y, z) = world(q);
|
||||
hidden(x, y, z - 1e-6)
|
||||
}).collect();
|
||||
if hid.iter().all(|h| *h) {
|
||||
return false;
|
||||
}
|
||||
if !hid.iter().any(|h| *h) {
|
||||
return true;
|
||||
}
|
||||
// Verdeckte Ecke mit sichtbarer Ecke senkrecht darunter: auf die Verdeckungsgrenze senken.
|
||||
let pts = f.pts.clone();
|
||||
for i in 0..pts.len() {
|
||||
if !hid[i] {
|
||||
continue;
|
||||
}
|
||||
let Some(j) = (0..pts.len()).find(|&j| !hid[j] && (pts[j][0] - pts[i][0]).abs() < 1e-6 && pts[j][1] < pts[i][1]) else { continue };
|
||||
let (x, y, _) = world(pts[i]);
|
||||
let (mut lo, mut hi) = (pts[j][1], pts[i][1]);
|
||||
for _ in 0..40 {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if hidden(x, y, mid) {
|
||||
hi = mid;
|
||||
} else {
|
||||
lo = mid;
|
||||
}
|
||||
}
|
||||
f.pts[i][1] = lo;
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// `elevationFrame` flach: `[P, N, U]`.
|
||||
fn frame_of(plane: &super::section::Plane) -> [f64; 9] {
|
||||
let [nx, ny, nz] = plane.normal;
|
||||
@@ -101,13 +324,21 @@ struct RoofIn {
|
||||
fn project_faces(frame: &[f64; 9], walls: &[RWall], slabs: &[RSlab], roofs: &[RoofIn]) -> Vec<Face> {
|
||||
let mut w = vec![walls.len() as f64];
|
||||
// Mit Schnittlinien (Bogen-Teilkörper, [T2]): die Ecken liegen auf der Gehrung statt rechtwinklig.
|
||||
let cut = walls.iter().any(|x| x.start_cut.is_some() || x.end_cut.is_some() || x.joint != [false; 2]);
|
||||
let planes = walls.iter().any(|x| x.top_plane.is_some());
|
||||
let cut = planes || walls.iter().any(|x| x.start_cut.is_some() || x.end_cut.is_some() || x.joint != [false; 2]);
|
||||
for x in walls {
|
||||
w.extend([x.start[0], x.start[1], x.end[0], x.end[1], x.thickness, x.height, x.base_elevation]);
|
||||
if cut {
|
||||
w.extend(corner_shifts(x));
|
||||
w.extend([if x.joint[0] { 1.0 } else { 0.0 }, if x.joint[1] { 1.0 } else { 0.0 }]);
|
||||
}
|
||||
// Ebene Oberkante unter einem Dach ([G2]).
|
||||
if planes {
|
||||
match x.top_plane {
|
||||
Some(c) => w.extend([1.0, c[0], c[1], c[2]]),
|
||||
None => w.extend([0.0; 4]),
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut sl = vec![slabs.len() as f64];
|
||||
for x in slabs {
|
||||
@@ -173,7 +404,10 @@ pub(crate) fn corner_shifts(x: &RWall) -> [f64; 4] {
|
||||
}
|
||||
|
||||
/// `collectRoofFaces`.
|
||||
fn collect_roof_faces(p: &Project, frame: &[f64; 9]) -> Result<Vec<Face>, String> {
|
||||
fn collect_roof_faces(p: &Project, frame: &[f64; 9], walls: &[RWall]) -> Result<Vec<Face>, String> {
|
||||
// Giebeldreiecke nur ohne Wand darunter ([G2]): sonst zeigt die Ansicht die Giebelwand selbst.
|
||||
let reached: std::collections::HashSet<&str> = walls.iter().filter(|w| w.top_plane.is_some()).map(|w| w.wall_id.as_str()).collect();
|
||||
let floors: std::collections::HashSet<&str> = p.walls.iter().filter(|w| reached.contains(w.id.as_str())).map(|w| w.floor_id.as_str()).collect();
|
||||
let mut roofs = Vec::new();
|
||||
for (ri, roof) in p.roofs.as_deref().unwrap_or(&[]).iter().enumerate() {
|
||||
let g = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof));
|
||||
@@ -207,7 +441,29 @@ fn collect_roof_faces(p: &Project, frame: &[f64; 9]) -> Result<Vec<Face>, String
|
||||
.collect()
|
||||
};
|
||||
// Wie die übrigen Dächer: Oberfläche der Eindeckung (Dach + Gaubendächer), dazu die Gaubenwände.
|
||||
roofs.push(RoofIn { id: roof.id.clone(), fill, planes: crate::roof_assembly::planar_faces(&solids.top, &front(&solids.top)), gables: g.gables.clone() });
|
||||
// Wände reichen ans Dach ([G2]): Stirnflächen der Ränder, die nicht in einem anderen Dach stecken.
|
||||
let gables = if floors.contains(roof.floor_id.as_str()) {
|
||||
let total: f64 = p.roof_layers(roof).iter().map(|l| l.thickness.max(0.0)).sum();
|
||||
let others: Vec<Vec<[f64; 3]>> = p
|
||||
.roofs
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.filter(|o| o.id != roof.id && o.floor_id == roof.floor_id)
|
||||
.flat_map(|o| crate::roof::roof_geometry(&o.params(), p.roof_base_elevation(o)).planes)
|
||||
.collect();
|
||||
fascia_quads(&g.planes, total)
|
||||
.into_iter()
|
||||
.filter(|q| {
|
||||
let (mx, my) = ((q[0][0] + q[1][0]) / 2.0, (q[0][1] + q[1][1]) / 2.0);
|
||||
!others.iter().any(|o| crate::dormer::point_in_xy(mx, my, o))
|
||||
})
|
||||
.map(|q| q.to_vec())
|
||||
.collect()
|
||||
} else {
|
||||
g.gables.clone()
|
||||
};
|
||||
roofs.push(RoofIn { id: roof.id.clone(), fill, planes: crate::roof_assembly::planar_faces(&solids.top, &front(&solids.top)), gables });
|
||||
let wall_comp = solids.parts.iter().find(|pt| pt.role == crate::roof_assembly::Role::DormerWall && pt.layer == 0).and_then(|pt| p.component(&pt.component_id));
|
||||
let wf = wall_comp.map_or([0.85, 0.83, 0.8], |c| hex_to_rgb(&c.color, [0.85, 0.83, 0.8]));
|
||||
let wall_faces = crate::roof_assembly::planar_faces(&solids.walls, &front(&solids.walls));
|
||||
@@ -216,7 +472,14 @@ fn collect_roof_faces(p: &Project, frame: &[f64; 9]) -> Result<Vec<Face>, String
|
||||
}
|
||||
continue;
|
||||
}
|
||||
roofs.push(RoofIn { id: roof.id.clone(), fill, planes: g.planes.clone(), gables: g.gables.clone() });
|
||||
// Wände reichen ans Dach: statt der Giebeldreiecke die Stirnflächen der Dachscheibe (Traufe, Ortgang).
|
||||
let gables = if floors.contains(roof.floor_id.as_str()) {
|
||||
let total: f64 = p.roof_layers(roof).iter().map(|l| l.thickness.max(0.0)).sum();
|
||||
fascia_quads(&g.planes, total).into_iter().map(|q| q.to_vec()).collect()
|
||||
} else {
|
||||
g.gables.clone()
|
||||
};
|
||||
roofs.push(RoofIn { id: roof.id.clone(), fill, planes: g.planes.clone(), gables });
|
||||
}
|
||||
Ok(project_faces(frame, &[], &[], &roofs))
|
||||
}
|
||||
@@ -261,6 +524,10 @@ fn extend_wall_corners(p: &Project, rwalls: &mut [RWall], u: (f64, f64)) {
|
||||
if let Some(&i) = pieces.iter().find(|&&i| close(rwalls[i].start, w.start)) {
|
||||
let s = rwalls[i].start;
|
||||
rwalls[i].start = [s[0] - ux * e_start, s[1] - uz * e_start];
|
||||
// Ebene Oberkante bezieht sich auf den Anfang ([G2]).
|
||||
if let Some(c) = rwalls[i].top_plane.as_mut() {
|
||||
c[0] -= (c[1] * ux + c[2] * uz) * e_start;
|
||||
}
|
||||
}
|
||||
}
|
||||
if e_end > EPS {
|
||||
@@ -666,6 +933,78 @@ fn elevation_edges(p: &Project, faces: &[Face], openings: &[ProjOpening], frame:
|
||||
crate::hlr::hidden_lines(&hf, &opts).into_iter().map(|s| EdgeSeg { a: s.a, b: s.b, hidden: s.hidden }).collect()
|
||||
}
|
||||
|
||||
/// [T6] Obere Hüllkurve des Geländes (samt Baugruben) in der Ansicht: Dreiecke mit Tiefe in [0, `depth_max`]
|
||||
/// und u im Bereich `range`, abgetastet in ≤ 800 Spalten.
|
||||
fn terrain_silhouette(p: &Project, t: &TerrainMesh, frame: &[f64; 9], range: (f64, f64), depth_max: f64) -> Vec<Vec<[f64; 2]>> {
|
||||
let (fp, fnrm, fu) = ([frame[0], frame[1], frame[2]], [frame[3], frame[4], frame[5]], [frame[6], frame[7], frame[8]]);
|
||||
let (pos, idx, _) = crate::excavation::terrain_model_mesh(p, t);
|
||||
let proj = |i: usize| -> (f64, f64, f64) {
|
||||
let q = [pos[3 * i], pos[3 * i + 1], pos[3 * i + 2]];
|
||||
let w = [q[0] - fp[0], q[2] - fp[1], q[1] - fp[2]];
|
||||
(w[0] * fu[0] + w[1] * fu[1] + w[2] * fu[2], q[2], w[0] * fnrm[0] + w[1] * fnrm[1] + w[2] * fnrm[2])
|
||||
};
|
||||
let (u0, u1) = range;
|
||||
if !(u1 > u0) {
|
||||
return Vec::new();
|
||||
}
|
||||
let n = 800usize;
|
||||
let du = (u1 - u0) / n as f64;
|
||||
let mut env = vec![f64::NEG_INFINITY; n + 1];
|
||||
let nv = pos.len() / 3;
|
||||
for tr in idx.chunks_exact(3) {
|
||||
if !tr.iter().all(|v| *v >= 0.0 && (*v as usize) < nv) {
|
||||
continue;
|
||||
}
|
||||
let q = [proj(tr[0] as usize), proj(tr[1] as usize), proj(tr[2] as usize)];
|
||||
if q.iter().all(|v| v.2 < 0.0) || q.iter().all(|v| v.2 > depth_max) {
|
||||
continue;
|
||||
}
|
||||
let lo = q.iter().map(|v| v.0).fold(f64::INFINITY, f64::min).max(u0);
|
||||
let hi = q.iter().map(|v| v.0).fold(f64::NEG_INFINITY, f64::max).min(u1);
|
||||
if !(hi >= lo) {
|
||||
continue;
|
||||
}
|
||||
let (k0, k1) = (((lo - u0) / du).ceil() as usize, (((hi - u0) / du).floor() as usize).min(n));
|
||||
for (k, e) in env.iter_mut().enumerate().take(k1 + 1).skip(k0) {
|
||||
let u = u0 + k as f64 * du;
|
||||
for i in 0..3 {
|
||||
let (a, b) = (q[i], q[(i + 1) % 3]);
|
||||
if (a.0 - u) * (b.0 - u) <= 0.0 && a.0 != b.0 {
|
||||
let z = a.1 + (b.1 - a.1) * (u - a.0) / (b.0 - a.0);
|
||||
*e = e.max(z);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out: Vec<Vec<[f64; 2]>> = Vec::new();
|
||||
let mut cur: Vec<[f64; 2]> = Vec::new();
|
||||
for (k, z) in env.iter().enumerate() {
|
||||
if z.is_finite() {
|
||||
cur.push([u0 + k as f64 * du, *z]);
|
||||
} else if cur.len() > 1 {
|
||||
out.push(std::mem::take(&mut cur));
|
||||
} else {
|
||||
cur.clear();
|
||||
}
|
||||
}
|
||||
if cur.len() > 1 {
|
||||
out.push(cur);
|
||||
}
|
||||
// Kollineare Zwischenpunkte weglassen (Raster), Form bleibt.
|
||||
for l in &mut out {
|
||||
let mut s: Vec<[f64; 2]> = vec![l[0]];
|
||||
for i in 1..l.len() - 1 {
|
||||
let (a, b, c) = (s[s.len() - 1], l[i], l[i + 1]);
|
||||
if ((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])).abs() > 1e-9 {
|
||||
s.push(b);
|
||||
}
|
||||
}
|
||||
s.push(l[l.len() - 1]);
|
||||
*l = s;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `generateElevationPlan`: Primitive und Ausmass; `None` ohne Ansichtslinie.
|
||||
pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono: bool, vis: &Visibility, scale: f64) -> Result<Option<(Vec<Primitive>, [f64; 4])>, String> {
|
||||
let Some(plane) = level.plane() else { return Ok(None) };
|
||||
@@ -675,7 +1014,8 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono:
|
||||
slabs.extend(model3d::emit_stairs(p, false));
|
||||
extend_wall_corners(p, &mut walls, (frame[6], frame[8]));
|
||||
let mut faces = project_faces(&frame, &walls, &slabs, &[]);
|
||||
faces.extend(collect_roof_faces(p, &frame)?);
|
||||
cull_under_roofs(p, &frame, &walls, &mut faces);
|
||||
faces.extend(collect_roof_faces(p, &frame, &walls)?);
|
||||
|
||||
// Kategorie einer Fläche (erstes Element mit der id, wie `find`).
|
||||
let mut wall_cat: HashMap<&str, &str> = HashMap::new();
|
||||
@@ -752,7 +1092,7 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono:
|
||||
// die Haarfugen zwischen ihnen.
|
||||
let fill = fill_for(f.fill);
|
||||
let seam = is_roof && assembled.contains(f.id.as_str());
|
||||
let mut prim = if seam { polygon(pts, &fill, &fill, 0.05, no_hatch()) } else { polygon(pts, &fill, "none", 0.0, no_hatch()) };
|
||||
let mut prim = if seam { polygon(pts, &fill, &fill, 0.15, no_hatch()) } else { polygon(pts, &fill, "none", 0.0, no_hatch()) };
|
||||
if let Primitive::Polygon { greyed: g, wall_id, ceiling_id, roof_id, .. } = &mut prim {
|
||||
*g = Some(greyed(f));
|
||||
if !f.id.is_empty() {
|
||||
@@ -942,7 +1282,33 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono:
|
||||
prims.push(outline_line(e.a, e.b));
|
||||
}
|
||||
}
|
||||
if acc.min_x.is_finite() && acc.min_y.is_finite() {
|
||||
// [T6] Gelände-Silhouette (gestaltetes Terrain) zwischen Ansichtsebene und vorderster Gebäudefläche; was
|
||||
// darunter liegt, verdeckt das Gelände (Papierfläche über dem Gebäude).
|
||||
let depth_max = faces.iter().map(|f| f.depth_min).fold(f64::INFINITY, f64::min) + 0.3;
|
||||
let mut has_terrain = false;
|
||||
if acc.min_x.is_finite() && depth_max.is_finite() && !crate::excavation::terrains(p).is_empty() {
|
||||
let terrain_shown = |c: Option<&str>| c.is_none_or(|c| !vis.has_vis || !vis.has_display || (vis.visible(c) && vis.render(c)));
|
||||
for t in crate::excavation::terrains(p) {
|
||||
if !terrain_shown(t.category_code.as_deref()) {
|
||||
continue;
|
||||
}
|
||||
for l in terrain_silhouette(p, t, &frame, (acc.min_x - 6.0, acc.max_x + 6.0), depth_max) {
|
||||
has_terrain = true;
|
||||
let low = l.iter().map(|q| q[1]).fold(acc.min_y, f64::min) - 1.0;
|
||||
let mut ring: Vec<Vec2> = l.iter().map(|q| v2(q[0], q[1])).collect();
|
||||
ring.push(v2(l[l.len() - 1][0], low));
|
||||
ring.push(v2(l[0][0], low));
|
||||
prims.push(polygon(ring, "#ffffff", "none", 0.0, no_hatch()));
|
||||
for w in l.windows(2) {
|
||||
acc.add(w[0][0], w[0][1]);
|
||||
acc.add(w[1][0], w[1][1]);
|
||||
prims.push(line(v2(w[0][0], w[0][1]), v2(w[1][0], w[1][1]), "elevation-terrain", GROUND_MM, GROUND_INK));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Mit Gelände ersetzt die Silhouette die Grundlinie ([T6]).
|
||||
if acc.min_x.is_finite() && acc.min_y.is_finite() && !has_terrain {
|
||||
prims.push(line(v2(acc.min_x, acc.min_y), v2(acc.max_x, acc.min_y), "elevation-ground", GROUND_MM, GROUND_INK));
|
||||
}
|
||||
Ok(Some((prims, acc.bounds())))
|
||||
@@ -1107,7 +1473,12 @@ pub fn elevation_plan_buf(p: &Project, args: &[f64], text: &str) -> Result<Vec<u
|
||||
let mut w = crate::plan_buf::Writer::new(true);
|
||||
if let Some((prims, bounds)) = elevation_primitives(p, &level, shadows, mono, &vis, scale)? {
|
||||
w.group(&prims);
|
||||
w.bounds = Some(bounds);
|
||||
// Achsraster ([112]): Achsen quer zur Blickebene.
|
||||
let grid = super::grid_view::grid_prims(p, &level, bounds, scale);
|
||||
if !grid.is_empty() {
|
||||
w.group(&grid);
|
||||
}
|
||||
w.bounds = Some(super::grid_view::union_bounds(bounds, &grid));
|
||||
}
|
||||
Ok(w.finish())
|
||||
}
|
||||
@@ -1177,6 +1548,55 @@ mod tests {
|
||||
serde_json::to_string(&prims).unwrap()
|
||||
}
|
||||
|
||||
/// [G2] Wände unter dem Dach: in der Traufansicht verdeckt das Dach Giebel- und Innenwände (keine
|
||||
/// Wandfläche über der Traufkante), in der Giebelansicht steht die Giebelwand bis unter das Dach.
|
||||
#[test]
|
||||
fn waende_unter_dem_dach_in_der_ansicht() {
|
||||
let p: Project = serde_json::from_value(serde_json::json!({
|
||||
"id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "layers": [], "drawings2d": [], "openings": [],
|
||||
"drawingLevels": [
|
||||
{"id": "F", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3.0, "baseElevation": 0},
|
||||
{"id": "s", "name": "S", "kind": "elevation", "visible": true, "locked": false, "linePoints": [{"x": -2, "y": -3}, {"x": 12, "y": -3}], "directionSign": 1},
|
||||
{"id": "w", "name": "W", "kind": "elevation", "visible": true, "locked": false, "linePoints": [{"x": -3, "y": 10}, {"x": -3, "y": -2}], "directionSign": 1}
|
||||
],
|
||||
"walls": [
|
||||
{"id": "WS", "type": "wall", "floorId": "F", "categoryCode": "20", "start": {"x": 0, "y": 0}, "end": {"x": 10, "y": 0}, "height": 3.5},
|
||||
{"id": "WW", "type": "wall", "floorId": "F", "categoryCode": "20", "start": {"x": 0, "y": 8}, "end": {"x": 0, "y": 0}, "height": 9.0},
|
||||
{"id": "WI", "type": "wall", "floorId": "F", "categoryCode": "20", "start": {"x": 5, "y": 0}, "end": {"x": 5, "y": 8}, "height": 9.0}
|
||||
],
|
||||
"roofs": [{"id": "R", "type": "roof", "floorId": "F", "categoryCode": "35",
|
||||
"outline": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 8}, {"x": 0, "y": 8}],
|
||||
"shape": "sattel", "pitchDeg": 45, "overhang": 0.5, "overhangGable": 0.3, "ridgeAxis": "x", "thickness": 0.3}]
|
||||
}))
|
||||
.unwrap();
|
||||
let view = |id: &str| {
|
||||
let l = p.drawing_levels.iter().find(|l| l.id == id).unwrap();
|
||||
let level = LevelSpec::from_json(&serde_json::to_value(l).unwrap());
|
||||
elevation_primitives(&p, &level, false, false, &Visibility::default(), 100.0).unwrap().unwrap().0
|
||||
};
|
||||
let wall_top = |prims: &[Primitive], id: &str| -> f64 {
|
||||
prims
|
||||
.iter()
|
||||
.filter_map(|q| match q {
|
||||
Primitive::Polygon { pts, wall_id: Some(w), .. } if w == id => Some(pts.iter().map(|v| v.y).fold(f64::NEG_INFINITY, f64::max)),
|
||||
_ => None,
|
||||
})
|
||||
.fold(f64::NEG_INFINITY, f64::max)
|
||||
};
|
||||
// Traufe: Oberkante der Dachfläche an der Vorderkante (tiefster Punkt der Dachflächen).
|
||||
let r = &p.roofs.as_ref().unwrap()[0];
|
||||
let eave = crate::roof::roof_geometry(&r.params(), p.roof_base_elevation(r)).planes.iter().flatten().map(|q| q[2]).fold(f64::INFINITY, f64::min);
|
||||
let s = view("s");
|
||||
// Sichtbar bis unter die Traufstirn (Dicke 0.3 senkrecht zur 45°-Fläche: 0.3·cos 45° tiefer).
|
||||
let fascia = eave - 0.3 * 0.5f64.sqrt();
|
||||
assert!(wall_top(&s, "WW") <= fascia + 1e-3 && wall_top(&s, "WI") <= fascia + 1e-3, "{} {} {fascia}", wall_top(&s, "WW"), wall_top(&s, "WI"));
|
||||
assert!((wall_top(&s, "WS") - fascia).abs() < 1e-3, "Traufwand bis zur Traufstirn sichtbar: {}", wall_top(&s, "WS"));
|
||||
// Giebel: First-Unterkante = Traufkante 3.0 + 4.5 (bei 45°) − 0.3·√2.
|
||||
let w = view("w");
|
||||
let ridge_under = 7.5 - 0.3 * 2f64.sqrt();
|
||||
assert!((wall_top(&w, "WW") - ridge_under).abs() < 1e-6, "{}", wall_top(&w, "WW"));
|
||||
}
|
||||
|
||||
/// [T2] Bogenwand in der Ansicht: keine Facetten-Fugen der Sehnen-Teilkörper, Umriss bleibt.
|
||||
#[test]
|
||||
fn bogenwand_ohne_facettenfugen() {
|
||||
@@ -1241,7 +1661,14 @@ mod tests {
|
||||
assert!(o1.len() == 2 && o1.iter().all(|n| *n >= 40), "Rahmen + Glas als Ellipse: {o1:?}");
|
||||
assert_eq!(polys("DF"), vec![4, 4], "Dachfenster: Rahmen + Glas");
|
||||
let first_df = prims.iter().position(|pr| matches!(pr, Primitive::Polygon { opening_id: Some(o), .. } if o == "DF")).unwrap();
|
||||
let last_roof = prims.iter().rposition(|pr| matches!(pr, Primitive::Polygon { roof_id: Some(_), .. })).unwrap();
|
||||
// Dachflächen, die das Dachfenster überdecken (die Traufstirn [G2] liegt davor, berührt es nicht).
|
||||
let bb = |pts: &[Vec2]| pts.iter().fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |b, q| [b[0].min(q.x), b[1].min(q.y), b[2].max(q.x), b[3].max(q.y)]);
|
||||
let Primitive::Polygon { pts: df_pts, .. } = &prims[first_df] else { unreachable!() };
|
||||
let d = bb(df_pts);
|
||||
let last_roof = prims
|
||||
.iter()
|
||||
.rposition(|pr| matches!(pr, Primitive::Polygon { roof_id: Some(_), pts, .. } if { let r = bb(pts); r[0] < d[2] && r[2] > d[0] && r[1] < d[3] && r[3] > d[1] }))
|
||||
.unwrap();
|
||||
assert!(first_df > last_roof, "Dachfenster vor der Dachfläche gezeichnet");
|
||||
}
|
||||
|
||||
|
||||
@@ -436,6 +436,11 @@ pub fn extra_bounds(p: &Project, extra: &[(Primitive, u32)]) -> Bounds {
|
||||
}
|
||||
ContextObject::ImportedMesh(m) => mesh_bounds(&m.positions, &mut b),
|
||||
ContextObject::TerrainMesh(m) => mesh_bounds(&m.positions, &mut b),
|
||||
ContextObject::Excavation(e) => {
|
||||
for q in &e.outline {
|
||||
b.acc(q.x, q.y);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
b
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
//! Achsraster in Schnitt und Ansicht ([112]): Rasterachsen quer zur Blickebene als senkrechte
|
||||
//! strichpunktierte Linien (x = Lage entlang der Schnittlinie, y = Höhe) mit Blase und Beschriftung
|
||||
//! oben (bzw. unten bei „nur Anfang"). Hängt als eigene Gruppe hinter dem Schnitt/der Ansicht.
|
||||
|
||||
use super::prim::Primitive;
|
||||
use super::section::{LevelSpec, Plane};
|
||||
use crate::grid::{bubble_diameter, section_axes, Spec};
|
||||
use crate::model::{Drawing2DGeom, GridBubbles, Project, Vec2};
|
||||
|
||||
const INK: &str = "#5a5f66";
|
||||
const AXIS_MM: f64 = 0.18;
|
||||
/// Überstand der Achse über die Gebäudehöhe und unter die Bodenlinie (Meter).
|
||||
const OVER_TOP: f64 = 0.8;
|
||||
const OVER_BOTTOM: f64 = 0.3;
|
||||
|
||||
fn v2(x: f64, y: f64) -> Vec2 {
|
||||
Vec2 { x, y }
|
||||
}
|
||||
|
||||
/// Achslinien und Blasen für eine Ebene; `bounds` = Ausmass des Schnitts/der Ansicht (x0, y0, x1, y1),
|
||||
/// `scale` = Massstabsnenner. Leer ohne Raster oder ohne Ebene.
|
||||
pub fn grid_prims(p: &Project, level: &LevelSpec, bounds: [f64; 4], scale: f64) -> Vec<Primitive> {
|
||||
let Some(plane) = level.plane() else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for d in &p.drawings2d {
|
||||
let Drawing2DGeom::Grid { bubble_mm, bubbles, .. } = &d.geom else { continue };
|
||||
let Some(spec) = Spec::of(&d.geom) else { continue };
|
||||
out.extend(one(&spec, &plane, level, bounds, scale, bubble_diameter(*bubble_mm, scale), bubbles.unwrap_or(GridBubbles::Both)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Ausmass der Achsen (für die Bounds des Aufrufers).
|
||||
pub fn extent(prims: &[Primitive]) -> Option<[f64; 4]> {
|
||||
let mut b: Option<[f64; 4]> = None;
|
||||
let mut acc = |x: f64, y: f64| {
|
||||
let r = b.get_or_insert([x, y, x, y]);
|
||||
r[0] = r[0].min(x);
|
||||
r[1] = r[1].min(y);
|
||||
r[2] = r[2].max(x);
|
||||
r[3] = r[3].max(y);
|
||||
};
|
||||
for q in prims {
|
||||
match q {
|
||||
Primitive::Line { a, b, .. } => {
|
||||
acc(a.x, a.y);
|
||||
acc(b.x, b.y);
|
||||
}
|
||||
Primitive::DrawingCircle { center, r, .. } => {
|
||||
acc(center.x - r, center.y - r);
|
||||
acc(center.x + r, center.y + r);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Vereinigt das Ausmass `bounds` mit dem der Achsen.
|
||||
pub fn union_bounds(bounds: [f64; 4], grid: &[Primitive]) -> [f64; 4] {
|
||||
extent(grid).map_or(bounds, |g| [bounds[0].min(g[0]), bounds[1].min(g[1]), bounds[2].max(g[2]), bounds[3].max(g[3])])
|
||||
}
|
||||
|
||||
fn one(spec: &Spec, plane: &Plane, level: &LevelSpec, bounds: [f64; 4], scale: f64, diameter: f64, bubbles: GridBubbles) -> Vec<Primitive> {
|
||||
let (bx, by) = plane.base();
|
||||
let (ux, uy) = plane.u_model();
|
||||
let l = ux.hypot(uy);
|
||||
if !(l > 1e-12) || !bounds.iter().all(|x| x.is_finite()) {
|
||||
return Vec::new();
|
||||
}
|
||||
let u = (ux / l, uy / l);
|
||||
// Länge der Schnittlinie in u: die Achsen ausserhalb dieser Spanne gehören nicht zum Bild.
|
||||
let [p0, p1] = level.line.unwrap_or([v2(bx, by), v2(bx, by)]);
|
||||
let e = (p1.x - p0.x) * u.0 + (p1.y - p0.y) * u.1;
|
||||
let (lo, hi) = (e.min(0.0), e.max(0.0));
|
||||
let mm = |x: f64| x * scale / 1000.0;
|
||||
let dash = vec![mm(12.0), mm(2.5), mm(1.5), mm(2.5)];
|
||||
let (y0, y1) = (bounds[1] - OVER_BOTTOM, bounds[3] + OVER_TOP);
|
||||
let (r, text_h) = (diameter / 2.0, diameter * 0.5);
|
||||
let mut out = Vec::new();
|
||||
for (label, x) in section_axes(spec, (bx, by), u, level.kind == "elevation") {
|
||||
if x < lo - 1e-9 || x > hi + 1e-9 {
|
||||
continue;
|
||||
}
|
||||
out.push(Primitive::Line {
|
||||
a: v2(x, y0),
|
||||
b: v2(x, y1),
|
||||
cls: "draw2d".into(),
|
||||
weight_mm: AXIS_MM,
|
||||
dash: Some(Some(dash.clone())),
|
||||
zigzag: None,
|
||||
motif: None,
|
||||
color: Some(INK.into()),
|
||||
drawing_id: None,
|
||||
opening_id: None,
|
||||
stair_id: None,
|
||||
greyed: None,
|
||||
opacity: None,
|
||||
});
|
||||
let (y, dir) = if bubbles == GridBubbles::Start { (y0, -1.0) } else { (y1, 1.0) };
|
||||
let c = v2(x, y + dir * r);
|
||||
out.push(Primitive::DrawingCircle { center: c, r, fill: "none".into(), stroke: INK.into(), weight_mm: 0.25, dash: None, drawing_id: None, greyed: None, opacity: None });
|
||||
let n = label.chars().count() as f64;
|
||||
out.push(Primitive::DrawingText {
|
||||
at: v2(c.x - text_h * 0.3 * n, c.y - text_h * 0.35),
|
||||
text: label.clone(),
|
||||
height_m: text_h,
|
||||
angle: 0.0,
|
||||
color: INK.into(),
|
||||
marks: None,
|
||||
wrap_width: None,
|
||||
doc: None,
|
||||
drawing_id: None,
|
||||
greyed: None,
|
||||
opacity: None,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn project(grid: serde_json::Value) -> Project {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "layers": [], "openings": [], "walls": [],
|
||||
"drawingLevels": [{"id": "F", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3.0, "baseElevation": 0}],
|
||||
"drawings2d": [{"id": "G", "type": "drawing2d", "levelId": "F", "categoryCode": "20", "geom": grid}]
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn texts(prims: &[Primitive]) -> Vec<String> {
|
||||
prims.iter().filter_map(|q| if let Primitive::DrawingText { text, .. } = q { Some(text.clone()) } else { None }).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn senkrechte_achsen_mit_blase() {
|
||||
let p = project(serde_json::json!({"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0,
|
||||
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 4}], "b": [{"label": "A", "pos": 0}, {"label": "B", "pos": 6}]}));
|
||||
// Schnitt entlang +x bei y = 3 von x = -1 bis 8: schneidet die Achsen 1 und 2 (u = 1 und 5).
|
||||
let level = LevelSpec { kind: "section".into(), line: Some([v2(-1.0, 3.0), v2(8.0, 3.0)]), ..Default::default() };
|
||||
let prims = grid_prims(&p, &level, [0.0, 0.0, 9.0, 6.0], 100.0);
|
||||
let lines: Vec<(f64, f64, f64)> = prims.iter().filter_map(|q| if let Primitive::Line { a, b, .. } = q { Some((a.x, a.y, b.y)) } else { None }).collect();
|
||||
assert_eq!(lines.len(), 2, "{prims:?}");
|
||||
assert!((lines[0].0 - 1.0).abs() < 1e-9 && (lines[1].0 - 5.0).abs() < 1e-9);
|
||||
assert!(lines[0].1 < 0.0 && lines[0].2 > 6.0);
|
||||
assert_eq!(texts(&prims), ["1", "2"]);
|
||||
// Schnitt längs der Achsen 1/2: nur die waagrechten Achsen A, B queren.
|
||||
let level = LevelSpec { kind: "section".into(), line: Some([v2(2.0, -1.0), v2(2.0, 9.0)]), ..Default::default() };
|
||||
let prims = grid_prims(&p, &level, [0.0, 0.0, 9.0, 6.0], 100.0);
|
||||
assert_eq!(texts(&prims), ["A", "B"]);
|
||||
assert!(union_bounds([0.0, 0.0, 9.0, 6.0], &prims)[3] > 6.0);
|
||||
// Ansicht von Süden (y = -3): Achsen 1, 2 stehen senkrecht zur Ebene und erscheinen an ihrer Lage.
|
||||
let level = LevelSpec { kind: "elevation".into(), line: Some([v2(-1.0, -3.0), v2(8.0, -3.0)]), ..Default::default() };
|
||||
assert_eq!(texts(&grid_prims(&p, &level, [0.0, 0.0, 9.0, 6.0], 100.0)), ["1", "2"]);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ pub mod context;
|
||||
pub mod drawings;
|
||||
pub mod section;
|
||||
pub mod elevation;
|
||||
pub mod grid_view;
|
||||
pub mod cache;
|
||||
pub mod extras;
|
||||
pub mod underlay;
|
||||
|
||||
@@ -25,6 +25,9 @@ const SECTION_VISIBLE_MM: f64 = 0.18;
|
||||
const SECTION_GROUND_MM: f64 = 0.5;
|
||||
const SECTION_HIDDEN_MM: f64 = 0.13;
|
||||
const SECTION_HIDDEN_DASH: [f64; 2] = [0.12, 0.08];
|
||||
/// [T6] gewachsenes Terrain im Schnitt: gestrichelt, dünner als das gestaltete.
|
||||
const SECTION_NATURAL_MM: f64 = 0.25;
|
||||
const SECTION_NATURAL_DASH: [f64; 2] = [0.4, 0.2];
|
||||
/// Achswinkel geschnittener Wände/Decken für wandrelative Muster (s. `toSection.ts`).
|
||||
const SECTION_WALL_AXIS_ANGLE_DEG: f64 = 90.0;
|
||||
/// Decken liegen: wandbezogene Muster laufen waagrecht entlang der Schicht ([109]; vorher 90° wie Wände,
|
||||
@@ -187,6 +190,8 @@ pub struct Edge {
|
||||
pub struct Profile {
|
||||
pub category: Option<String>,
|
||||
pub pts: Vec<[f64; 2]>,
|
||||
/// [T6] gewachsenes Terrain (gestrichelt), nur wenn Baugruben das Gelände ändern.
|
||||
pub natural: bool,
|
||||
}
|
||||
|
||||
/// Ergebnis eines Schnitts (`SectionOutput`).
|
||||
@@ -196,6 +201,8 @@ pub struct Output {
|
||||
pub visible: Vec<Edge>,
|
||||
pub hidden: Vec<Edge>,
|
||||
pub profiles: Vec<Profile>,
|
||||
/// [T6] Erdreich unter dem gestalteten Terrain (Band, ohne Gebäude-Inneres), mit Schraffur.
|
||||
pub earth: Vec<(Vec<[f64; 2]>, HatchRender)>,
|
||||
}
|
||||
|
||||
/// Ein truck-Körper (aus TS, asynchron gebaut): Index in `extrudedSolids` + Netz.
|
||||
@@ -321,6 +328,7 @@ fn wall_input(w: &RWall) -> render3d::WallInput {
|
||||
height: json_f32(w.height),
|
||||
base_elevation: json_f32(w.base_elevation),
|
||||
top_drop: w.top_drop.map_or([0.0, 0.0], f32s2),
|
||||
top_plane: w.top_plane.map(f32s3),
|
||||
color: f32s3(w.color),
|
||||
openings: Vec::new(),
|
||||
layers: Some(Vec::new()),
|
||||
@@ -1448,14 +1456,85 @@ fn append_terrain_profiles(out: &mut Output, p: &Project, base: (f64, f64), u: (
|
||||
if t.positions.len() < 9 {
|
||||
continue;
|
||||
}
|
||||
let (_, lines) = cut_mesh(&t.positions, &t.indices, base, u);
|
||||
for line in lines {
|
||||
let parts = match range {
|
||||
Some((lo, hi)) => clip_line_to_u(&line, lo - TERRAIN_MARGIN, hi + TERRAIN_MARGIN),
|
||||
None => vec![line],
|
||||
};
|
||||
for pts in parts {
|
||||
out.profiles.push(Profile { category: t.category_code.clone(), pts });
|
||||
// [T6] Gelände samt Baugruben, Höhen im Modellbezug; das gewachsene Terrain gestrichelt dazu.
|
||||
let st = crate::excavation::site_terrain(p, t);
|
||||
let mut meshes = vec![(st.current().to_flat(-st.datum), false)];
|
||||
if st.modified.is_some() {
|
||||
meshes.push((st.orig.to_flat(-st.datum), true));
|
||||
}
|
||||
for ((pos, idx), natural) in meshes {
|
||||
let (_, lines) = cut_mesh(&pos, &idx, base, u);
|
||||
for line in lines {
|
||||
let parts = match range {
|
||||
Some((lo, hi)) => clip_line_to_u(&line, lo - TERRAIN_MARGIN, hi + TERRAIN_MARGIN),
|
||||
None => vec![line],
|
||||
};
|
||||
for pts in parts {
|
||||
out.profiles.push(Profile { category: t.category_code.clone(), pts, natural });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
append_earth(out, p, base, u);
|
||||
}
|
||||
|
||||
/// Tiefe des Erdreich-Bands unter der Geländelinie (m).
|
||||
const EARTH_BAND: f64 = 1.5;
|
||||
|
||||
/// [T6]/[109] Erdreich: Band unter dem gestalteten Terrain mit SIA-Erdreich-Schraffur, ohne das
|
||||
/// Gebäude-Innere (Grundfläche im Schnitt, von der tiefsten Schnittfläche aufwärts); die geschnittenen
|
||||
/// Bauteile selbst liegen ohnehin darüber.
|
||||
fn append_earth(out: &mut Output, p: &Project, base: (f64, f64), u: (f64, f64)) {
|
||||
let mut band: Vec<crate::flat::Polygon> = Vec::new();
|
||||
for pr in out.profiles.iter().filter(|pr| !pr.natural && pr.pts.len() >= 2) {
|
||||
let mut ring = pr.pts.clone();
|
||||
ring.extend(pr.pts.iter().rev().map(|q| [q[0], q[1] - EARTH_BAND]));
|
||||
band.push(vec![ring]);
|
||||
}
|
||||
if band.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut band = crate::polygon_bool::union(&band);
|
||||
// Gebäude-Inneres: Abschnitte der Schnittlinie in der Grundfläche.
|
||||
let mut holes: Vec<crate::flat::Polygon> = Vec::new();
|
||||
for poly in crate::site_rules::building_footprint(p) {
|
||||
let mut ts: Vec<f64> = Vec::new();
|
||||
for ring in &poly {
|
||||
let n = ring.len();
|
||||
for i in 0..n {
|
||||
let (a, b) = (ring[i], ring[(i + 1) % n]);
|
||||
// Schnitt der Geraden base + s·u mit der Kante a–b.
|
||||
let (ex, ey) = (b.x - a.x, b.y - a.y);
|
||||
let den = u.0 * ey - u.1 * ex;
|
||||
if den.abs() < 1e-12 {
|
||||
continue;
|
||||
}
|
||||
let (wx, wy) = (a.x - base.0, a.y - base.1);
|
||||
let s_ = (wx * ey - wy * ex) / den;
|
||||
let t_ = (wx * u.1 - wy * u.0) / den;
|
||||
if (0.0..1.0).contains(&t_) {
|
||||
ts.push(s_);
|
||||
}
|
||||
}
|
||||
}
|
||||
ts.sort_by(|a, b| a.total_cmp(b));
|
||||
for w in ts.chunks_exact(2) {
|
||||
let (u0, u1) = (w[0], w[1]);
|
||||
let low = out.cuts.iter().flat_map(|c| c.pts.iter()).filter(|q| q[0] >= u0 - 1e-6 && q[0] <= u1 + 1e-6).map(|q| q[1]).fold(f64::INFINITY, f64::min);
|
||||
if low.is_finite() {
|
||||
holes.push(vec![vec![[u0, low], [u1, low], [u1, 1e4], [u0, 1e4]]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !holes.is_empty() {
|
||||
band = crate::polygon_bool::difference(&band, &holes);
|
||||
}
|
||||
let hatch = super::style::resolve_hatch(p, "std-h-erdreich", None, None, None)
|
||||
.unwrap_or(HatchRender { pattern: HatchPattern::Earth, scale: 1.0, angle: 45.0, color: HATCH_INK.into(), line_weight: 0.1, ..no_hatch_base() });
|
||||
for poly in band {
|
||||
if let Some(outer) = poly.into_iter().next() {
|
||||
if outer.len() >= 3 {
|
||||
out.earth.push((outer, hatch.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1735,7 +1814,7 @@ pub fn compute_section(p: &Project, level: &LevelSpec, bodies: &[BodyMesh]) -> R
|
||||
// Projektion hinter der Ebene exakt ([G4]); die Schnittflächen verdecken, was hinter ihnen liegt.
|
||||
let (mut visible, hidden) = projection_edges(p, &plane, &walls_r, &wi, &slabs_r, bodies, &cuts, level.hidden_lines);
|
||||
shaped_projection(&mut visible, p, &walls_r, &plane);
|
||||
let mut out = Output { cuts, visible, hidden, profiles: Vec::new() };
|
||||
let mut out = Output { cuts, visible, hidden, profiles: Vec::new(), earth: Vec::new() };
|
||||
append_terrain_profiles(&mut out, p, base, u);
|
||||
if let Some(d) = level.depth {
|
||||
filter_by_depth(&mut out, p, &plane, d, &walls, &slabs, &slabs_r);
|
||||
@@ -1818,6 +1897,14 @@ pub fn section_primitives(out: &Output, mono: bool, hidden_lines: bool, vis: &Vi
|
||||
let mut prims = Vec::new();
|
||||
let mut acc = Acc::new();
|
||||
let shown = |code: &str| vis.visible(code) && vis.render(code);
|
||||
// [T6] Erdreich zuerst (unter allem), ohne Umriss; Kategorie wie das Gelände.
|
||||
let terrain_shown = out.profiles.iter().all(|pr| pr.category.as_deref().is_none_or(shown));
|
||||
if terrain_shown {
|
||||
for (ring, hatch) in &out.earth {
|
||||
let hatch = if mono { HatchRender { color: SECTION_INK.into(), ..hatch.clone() } } else { hatch.clone() };
|
||||
prims.push(polygon(ring.iter().map(|q| v2(q[0], q[1])).collect(), "none", "none", 0.0, hatch));
|
||||
}
|
||||
}
|
||||
for cp in &out.cuts {
|
||||
if cp.pts.len() < 3 {
|
||||
continue;
|
||||
@@ -1867,7 +1954,13 @@ pub fn section_primitives(out: &Output, mono: bool, hidden_lines: bool, vis: &Vi
|
||||
for w in pr.pts.windows(2) {
|
||||
acc.add(w[0][0], w[0][1]);
|
||||
acc.add(w[1][0], w[1][1]);
|
||||
prims.push(line(v2(w[0][0], w[0][1]), v2(w[1][0], w[1][1]), "section-terrain", SECTION_GROUND_MM, SECTION_INK));
|
||||
let mut l = line(v2(w[0][0], w[0][1]), v2(w[1][0], w[1][1]), "section-terrain", if pr.natural { SECTION_NATURAL_MM } else { SECTION_GROUND_MM }, SECTION_INK);
|
||||
if pr.natural {
|
||||
if let Primitive::Line { dash, .. } = &mut l {
|
||||
*dash = Some(Some(SECTION_NATURAL_DASH.to_vec()));
|
||||
}
|
||||
}
|
||||
prims.push(l);
|
||||
}
|
||||
}
|
||||
if hidden_lines {
|
||||
@@ -1886,7 +1979,8 @@ pub fn section_primitives(out: &Output, mono: bool, hidden_lines: bool, vis: &Vi
|
||||
acc.add(e.b[0], e.b[1]);
|
||||
prims.push(line(v2(e.a[0], e.a[1]), v2(e.b[0], e.b[1]), "section-visible", SECTION_VISIBLE_MM, SECTION_VISIBLE_INK));
|
||||
}
|
||||
if acc.min_x.is_finite() && acc.max_x > acc.min_x {
|
||||
// Mit Gelände ersetzt die Geländelinie die Grundlinie ([T6]).
|
||||
if acc.min_x.is_finite() && acc.max_x > acc.min_x && !(terrain_shown && !out.profiles.is_empty()) {
|
||||
prims.push(line(v2(acc.min_x, acc.min_y), v2(acc.max_x, acc.min_y), "section-ground", SECTION_GROUND_MM, SECTION_INK));
|
||||
}
|
||||
(prims, acc.bounds())
|
||||
@@ -2382,7 +2476,12 @@ pub fn section_plan_buf(p: &Project, args: &[f64], text: &str) -> Result<Vec<u8>
|
||||
w.group(&prims);
|
||||
let ops = if openings { section_opening_primitives(p, &level, &vis)? } else { Vec::new() };
|
||||
w.group(&ops);
|
||||
w.bounds = Some(bounds);
|
||||
// Achsraster ([112]): Achsen quer zur Schnittebene.
|
||||
let grid = super::grid_view::grid_prims(p, &level, bounds, v.get("scale").and_then(|s| s.as_f64()).filter(|s| *s > 0.0).unwrap_or(100.0));
|
||||
if !grid.is_empty() {
|
||||
w.group(&grid);
|
||||
}
|
||||
w.bounds = Some(super::grid_view::union_bounds(bounds, &grid));
|
||||
Ok(w.finish())
|
||||
}
|
||||
|
||||
@@ -2608,6 +2707,43 @@ mod tests {
|
||||
assert!(serde_json::to_string(&prims).unwrap().contains("section-hidden"));
|
||||
}
|
||||
|
||||
/// [T6]/[68] Gelände mit Baugrube: gestaltetes + gewachsenes Terrain, Erdreich ohne Gebäude-Inneres;
|
||||
/// Fassaden-Geländehöhen fürs Baurecht.
|
||||
#[test]
|
||||
fn gelaende_mit_baugrube_im_schnitt() {
|
||||
let mut p = sample();
|
||||
let flat = TerrainMesh {
|
||||
id: "t".into(),
|
||||
positions: vec![-50.0, -50.0, 0.0, 50.0, -50.0, 0.0, 50.0, 50.0, 0.0, -50.0, 50.0, 0.0],
|
||||
indices: vec![0.0, 1.0, 2.0, 0.0, 2.0, 3.0],
|
||||
category_code: Some("02".into()),
|
||||
..Default::default()
|
||||
};
|
||||
let pit = Excavation {
|
||||
id: "bg".into(),
|
||||
outline: vec![Vec2 { x: -1.0, y: -1.0 }, Vec2 { x: 6.0, y: -1.0 }, Vec2 { x: 6.0, y: 5.0 }, Vec2 { x: -1.0, y: 5.0 }],
|
||||
bottom: -2.0,
|
||||
..Default::default()
|
||||
};
|
||||
p.context = Some(vec![ContextObject::TerrainMesh(flat), ContextObject::Excavation(pit)]);
|
||||
let out = compute_section(&p, &level(&p, "schnitt-a"), &[]).unwrap().unwrap();
|
||||
assert!(out.profiles.iter().any(|pr| pr.natural) && out.profiles.iter().any(|pr| !pr.natural));
|
||||
let designed_min = out.profiles.iter().filter(|pr| !pr.natural).flat_map(|pr| pr.pts.iter().map(|q| q[1])).fold(f64::INFINITY, f64::min);
|
||||
assert!((designed_min + 2.0).abs() < 1e-6, "{designed_min}");
|
||||
assert!(!out.earth.is_empty());
|
||||
let (prims, _) = section_primitives(&out, false, false, &Visibility::default());
|
||||
assert!(prims.iter().any(|q| matches!(q, Primitive::Polygon { hatch, .. } if hatch.pattern == HatchPattern::Earth)));
|
||||
assert!(prims.iter().any(|q| matches!(q, Primitive::Line { cls, dash: Some(Some(_)), .. } if cls == "section-terrain")));
|
||||
let (ep, _) = super::super::elevation::elevation_primitives(&p, &level(&p, "ansicht-sued"), false, false, &Visibility::default(), 100.0).unwrap().unwrap();
|
||||
let sil: Vec<f64> = ep.iter().filter_map(|q| if let Primitive::Line { cls, a, b, .. } = q { (cls == "elevation-terrain").then_some(a.y.min(b.y)) } else { None }).collect();
|
||||
// Die Ansichtslinie (y = −2) liegt in der Böschung: die Silhouette taucht vor dem Gebäude ein, nie unter die Sohle.
|
||||
assert!(!sil.is_empty() && sil.iter().all(|z| *z <= 1e-6 && *z >= -2.0 - 1e-6) && sil.iter().any(|z| *z < -0.5), "{sil:?}");
|
||||
assert!(ep.iter().any(|q| matches!(q, Primitive::Polygon { fill, .. } if fill == "#ffffff")));
|
||||
assert!(!ep.iter().any(|q| matches!(q, Primitive::Line { cls, .. } if cls == "elevation-ground")));
|
||||
let f = crate::site_rules::facade_terrain(&p);
|
||||
assert!(!f.is_empty() && f.iter().all(|q| q.natural == Some(0.0) && q.designed.is_some_and(|z| (z + 2.0).abs() < 1e-6)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn beschnittene_baender_behalten_ihre_ebene() {
|
||||
// Von der Dominanz beschnittene Wand-/Deckenstücke tragen ihre Kategorie weiter: Ebene aus → weg.
|
||||
@@ -3032,3 +3168,84 @@ mod abzug_faelle {
|
||||
assert_eq!(out[0].nse.as_ref().map(|n| n.len()), Some(2), "Schlüsselloch-Stege ungestrichen");
|
||||
}
|
||||
}
|
||||
|
||||
/// [G2] Wand an Dach: Schnitt und 3D-Körper der Wände unter einem Satteldach.
|
||||
#[cfg(test)]
|
||||
mod wand_an_dach {
|
||||
use super::*;
|
||||
|
||||
fn haus() -> Project {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "layers": [], "drawings2d": [],
|
||||
"drawingLevels": [
|
||||
{"id": "F", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3.0, "baseElevation": 0},
|
||||
{"id": "q", "name": "Q", "kind": "section", "visible": true, "locked": false, "linePoints": [{"x": 2, "y": -2}, {"x": 2, "y": 10}], "directionSign": 1},
|
||||
{"id": "l", "name": "L", "kind": "section", "visible": true, "locked": false, "linePoints": [{"x": -2, "y": 4}, {"x": 12, "y": 4}], "directionSign": 1}
|
||||
],
|
||||
"walls": [
|
||||
{"id": "WS", "type": "wall", "floorId": "F", "categoryCode": "20", "start": {"x": 0, "y": 0}, "end": {"x": 10, "y": 0}, "height": 3.5},
|
||||
{"id": "WW", "type": "wall", "floorId": "F", "categoryCode": "20", "start": {"x": 0, "y": 8}, "end": {"x": 0, "y": 0}, "height": 9.0},
|
||||
{"id": "WB", "type": "wall", "floorId": "F", "categoryCode": "20", "start": {"x": 6, "y": 1}, "end": {"x": 6, "y": 7}, "height": 9.0, "bulge": 0.4}
|
||||
],
|
||||
"openings": [{"id": "F1", "type": "opening", "hostWallId": "WW", "categoryCode": "21", "kind": "window", "position": 3.5, "width": 1.0, "height": 1.2, "sillHeight": 3.6}],
|
||||
"roofs": [{"id": "R", "type": "roof", "floorId": "F", "categoryCode": "35",
|
||||
"outline": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 8}, {"x": 0, "y": 8}],
|
||||
"shape": "sattel", "pitchDeg": 45, "overhang": 0.5, "ridgeAxis": "x", "thickness": 0.3}]
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Dach-Unterkante (Traufkante 3.0 bei y = −0.5, 45°, Dicke 0.3 senkrecht).
|
||||
fn under(y: f64) -> f64 {
|
||||
3.0 + (4.5 - (y - 4.0).abs()) - 0.3 * 2f64.sqrt()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schnitt_endet_an_der_dachunterkante() {
|
||||
let p = haus();
|
||||
for id in ["q", "l"] {
|
||||
let l = p.drawing_levels.iter().find(|l| l.id == id).unwrap();
|
||||
let level = LevelSpec::from_json(&serde_json::to_value(l).unwrap());
|
||||
let out = compute_section(&p, &level, &[]).unwrap().unwrap();
|
||||
let walls: Vec<&Cut> = out.cuts.iter().filter(|c| c.kind == Kind::Wall).collect();
|
||||
assert!(!walls.is_empty());
|
||||
let top = walls.iter().flat_map(|c| c.pts.iter().map(|q| q[1])).fold(f64::NEG_INFINITY, f64::max);
|
||||
// Nie über der First-Unterkante.
|
||||
assert!(top <= under(4.0) + 1e-4, "{id}: {top}");
|
||||
}
|
||||
// Querschnitt quer zum First: Traufwand mit schräger Krone.
|
||||
let l = p.drawing_levels.iter().find(|l| l.id == "q").unwrap();
|
||||
let out = compute_section(&p, &LevelSpec::from_json(&serde_json::to_value(l).unwrap()), &[]).unwrap().unwrap();
|
||||
let sloped = out.cuts.iter().filter(|c| c.kind == Kind::Wall).any(|c| {
|
||||
let ys: Vec<f64> = c.pts.iter().map(|q| q[1]).filter(|v| *v > 2.0).collect();
|
||||
ys.len() >= 2 && (ys.iter().copied().fold(f64::NEG_INFINITY, f64::max) - ys.iter().copied().fold(f64::INFINITY, f64::min)) > 0.1
|
||||
});
|
||||
assert!(sloped, "Traufwand im Querschnitt mit schräger Krone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn koerper_dicht_und_volumen_exakt() {
|
||||
let p = haus();
|
||||
let walls = model3d::emit_walls(&p, true).unwrap();
|
||||
let ww: Vec<&RWall> = walls.iter().filter(|w| w.wall_id == "WW").collect();
|
||||
let mut vol = 0.0;
|
||||
for w in walls.iter().filter(|w| w.top_plane.is_some()) {
|
||||
let m = model3d::wall_piece_mesh(w).unwrap();
|
||||
assert!(m.is_closed(), "{w:?}");
|
||||
assert!((m.volume().abs() - model3d::wall_piece_volume(w)).abs() < 1e-9);
|
||||
}
|
||||
for w in &ww {
|
||||
assert!(w.holes.as_ref().is_none_or(|h| h.is_empty()), "Fenster unter dem Dach als Teilkörper: {w:?}");
|
||||
vol += model3d::wall_piece_volume(w);
|
||||
}
|
||||
// Giebelwand: Fünfeck unter der Unterkante × Dicke, minus Fenster.
|
||||
let t = p.wall_thickness(&p.walls[1], 0.2);
|
||||
let area = |y0: f64, y1: f64| (y1 - y0) * (under(y0) + under(y1)) / 2.0;
|
||||
let expect = t * (area(0.0, 4.0) + area(4.0, 8.0) - 1.2);
|
||||
// Gehrungen an den Ecken ändern das Volumen nur an den Enden.
|
||||
assert!((vol - expect).abs() < t * t * 7.0, "{vol} vs {expect}");
|
||||
// Bogenwand ([T2]): Sehnen-Teilwände ebenfalls unter dem Dach.
|
||||
let wb: Vec<&RWall> = walls.iter().filter(|w| w.wall_id == "WB").collect();
|
||||
assert!(wb.len() > 4 && wb.iter().all(|w| w.base_elevation + w.height <= under(4.0) + 1e-6), "{}", wb.len());
|
||||
}
|
||||
}
|
||||
@@ -1231,7 +1231,8 @@ fn emit_entries(cx: &mut Ctx, main: &mut Buf, entries: &[Entry], layer_by_code:
|
||||
let mut block_by_id: HashMap<&str, &Drawing2D> = HashMap::new();
|
||||
for d in &project.drawings2d {
|
||||
match d.geom {
|
||||
Drawing2DGeom::Dimension { .. } => {
|
||||
// Radius-/Durchmesser-/Bogenmass (`kind`) geht als Linien, Bögen und Text hinaus.
|
||||
Drawing2DGeom::Dimension { kind: None, .. } => {
|
||||
dim_by_id.insert(d.id.as_str(), d);
|
||||
}
|
||||
Drawing2DGeom::Block { .. } => {
|
||||
|
||||
@@ -476,8 +476,22 @@ fn wall_faces(f: &Frame, w: &[f64], src: usize, out: &mut Vec<Projected>) {
|
||||
let ht = w[4] / 2.0;
|
||||
let zb = w[6];
|
||||
let zt = w[6] + w[5];
|
||||
// Ebene Oberkante unter einem Dach ([G2]): Deckel-Ecken auf der Ebene.
|
||||
let plane = (w.len() >= 17 && w[13] == 1.0).then(|| [w[14], w[15], w[16]]);
|
||||
let corner = |s_along: f64, t_off: f64, y: f64| -> V3 {
|
||||
[sx + a_hat[0] * s_along + n_hat[0] * t_off, y, sz + a_hat[2] * s_along + n_hat[2] * t_off]
|
||||
let (x, z) = (sx + a_hat[0] * s_along + n_hat[0] * t_off, sz + a_hat[2] * s_along + n_hat[2] * t_off);
|
||||
let y = match plane {
|
||||
Some(c) if y == zt => (c[0] + c[1] * (x - sx) + c[2] * (z - sz)).clamp(zb, zt),
|
||||
_ => y,
|
||||
};
|
||||
[x, y, z]
|
||||
};
|
||||
let top_n: V3 = match plane {
|
||||
Some(c) => {
|
||||
let l = (c[1] * c[1] + 1.0 + c[2] * c[2]).sqrt();
|
||||
[-c[1] / l, 1.0 / l, -c[2] / l]
|
||||
}
|
||||
None => [0.0, 1.0, 0.0],
|
||||
};
|
||||
// Schnitt-Verschiebungen der vier Ecken längs der Achse ([T2]: Gehrung der Bogen-Teilkörper):
|
||||
// Anfang +n, Anfang −n, Ende +n, Ende −n; ohne Angabe 0 (rechtwinklig wie bisher).
|
||||
@@ -506,7 +520,7 @@ fn wall_faces(f: &Frame, w: &[f64], src: usize, out: &mut Vec<Projected>) {
|
||||
(neg(n_hat), [corner(s_m, -ht, zb), corner(s_m, -ht, zt), corner(e_m, -ht, zt), corner(e_m, -ht, zb)]),
|
||||
(start_n, [corner(s_m, -ht, zb), corner(s_p, ht, zb), corner(s_p, ht, zt), corner(s_m, -ht, zt)]),
|
||||
(end_n, [corner(e_m, -ht, zb), corner(e_m, -ht, zt), corner(e_p, ht, zt), corner(e_p, ht, zb)]),
|
||||
([0.0, 1.0, 0.0], [corner(s_m, -ht, zt), corner(s_p, ht, zt), corner(e_p, ht, zt), corner(e_m, -ht, zt)]),
|
||||
(top_n, [corner(s_m, -ht, zt), corner(s_p, ht, zt), corner(e_p, ht, zt), corner(e_m, -ht, zt)]),
|
||||
([0.0, -1.0, 0.0], [corner(s_m, -ht, zb), corner(e_m, -ht, zb), corner(e_p, ht, zb), corner(s_p, ht, zb)]),
|
||||
];
|
||||
for (i, (normal, poly)) in faces.into_iter().enumerate() {
|
||||
@@ -648,6 +662,9 @@ pub(crate) fn faces_full(frame: &[f64], walls: &[f64], slabs: &[f64], roofs: &[f
|
||||
7
|
||||
} else if walls.len() == 1 + 13 * nw {
|
||||
13
|
||||
} else if walls.len() == 1 + 17 * nw {
|
||||
// + ebene Oberkante ([G2]): Kennung (1 = vorhanden), z am Anfang, dz/dx, dz/dy.
|
||||
17
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
|
||||
@@ -23,6 +23,7 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
|
||||
json(&room_program::layout(p, &opt))
|
||||
}
|
||||
("siteCheck", _) => json(&site_rules::check_project(p)),
|
||||
("excavationQuantities", _) => json(&crate::excavation::quantities(p)),
|
||||
("buildingFootprint", _) => json(&site_rules::building_footprint(p)),
|
||||
("modelTop", _) => json(&site_rules::model_top(p)),
|
||||
("shadows", 2) => json(&site_rules::area_out(&sun::shadow_polygons_project(p, sun::SunPosition { azimuth: args[0], elevation: args[1] }))),
|
||||
|
||||
@@ -826,7 +826,7 @@ mod tests {
|
||||
#[test]
|
||||
fn planar_faces_keep_area() {
|
||||
let mut r = sattel("R", [[0.0, 0.0], [10.0, 8.0]], "x");
|
||||
r["dormers"] = serde_json::json!([{"id": "D", "kind": "sattel", "position": {"x": 4.0, "y": 1.2}, "width": 2.4, "frontHeight": 1.3}]);
|
||||
r["dormers"] = serde_json::json!([{"id": "D", "kind": "sattel", "position": {"x": 4.0, "y": 1.2}, "width": 2.4, "frontHeight": 1.0}]);
|
||||
let p = base_project(serde_json::json!([r]));
|
||||
let s = roof_solids(&p, 0).unwrap();
|
||||
let all: Vec<usize> = (0..s.skin.indices.len() / 3).collect();
|
||||
@@ -844,7 +844,8 @@ mod tests {
|
||||
let faces = planar_faces(&s.skin, &all);
|
||||
let face_area: f64 = faces.iter().map(|f| area3(f)).sum();
|
||||
assert!((tri_area - face_area).abs() < 1e-6 * tri_area, "{tri_area} vs {face_area}");
|
||||
assert!(faces.len() * 2 < all.len(), "zusammengefasst: {} Flächen aus {} Dreiecken", faces.len(), all.len());
|
||||
// Gaubendach endet am First ([G5]): ein paar Dreiecke mehr im Hauptdach-Querschnitt.
|
||||
assert!(faces.len() * 3 < all.len() * 2, "zusammengefasst: {} Flächen aus {} Dreiecken", faces.len(), all.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -488,6 +488,8 @@ fn wall_selection(root: &Map<String, Value>, w: &Value) -> Result<J, String> {
|
||||
.raw("referenceOffset", w, "referenceOffset")
|
||||
.v("layerBoundaries", J::arr(boundaries))
|
||||
.v("sliceTermination", nn(field(w, "sliceTermination")).cloned().unwrap_or_else(|| "both".into()))
|
||||
// An Dach anschliessen ([G2]): fehlt = automatisch.
|
||||
.v("roofAttach", Value::String(match field(w, "roofAttach").and_then(|v| v.as_bool()) { Some(true) => "on", Some(false) => "off", None => "auto" }.into()))
|
||||
.raw("wallTypeId", w, "wallTypeId")
|
||||
.n("thickness", thickness)
|
||||
.v("singleLayer", Value::Bool(layers.len() <= 1))
|
||||
@@ -912,6 +914,7 @@ fn stair_selection(root: &Map<String, Value>, s: &Value) -> Result<J, String> {
|
||||
.v("up", Value::Bool(field(s, "up") != Some(&Value::Bool(false))))
|
||||
.raw("arrowStyle", s, "arrowStyle")
|
||||
.raw("referenz", s, "referenz")
|
||||
.raw("centerColumn", s, "centerColumn")
|
||||
.raw("typeId", s, "typeId")
|
||||
.raw("floorId", s, "floorId")
|
||||
.o("floorName", floor_name(floor, field(s, "floorId")))
|
||||
@@ -1133,6 +1136,16 @@ pub fn geom_bbox(g: &Value) -> [f64; 4] {
|
||||
}
|
||||
}
|
||||
Some("kote" | "text" | "block" | "detailref" | "pointmarker") => pts.push(p("at")),
|
||||
Some("grid") => {
|
||||
if let Some(spec) = serde_json::from_value::<crate::model::Drawing2DGeom>(g.clone()).ok().as_ref().and_then(crate::grid::Spec::of) {
|
||||
for ax in spec.axes() {
|
||||
match ax.shape {
|
||||
crate::grid::Shape::Line { a, b } => pts.extend([a, b]),
|
||||
crate::grid::Shape::Arc { c, r, .. } => pts.extend([(c.0 - r, c.1 - r), (c.0 + r, c.1 + r)]),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("scalebar") => {
|
||||
let at = p("at");
|
||||
pts.extend([at, (at.0 + num_of(field(g, "segmentLength")) * num_of(field(g, "segments")), at.1)]);
|
||||
|
||||
@@ -86,6 +86,15 @@ const ELEMENTS: &[Col] = &[
|
||||
c("ext", "openings.col.ext", 1.4, false, false),
|
||||
];
|
||||
|
||||
const EARTHWORKS: &[Col] = &[
|
||||
c("name", "sheetTable.col.name", 2.4, false, true),
|
||||
c("bottom", "sheetTable.col.bottom", 1.3, true, true),
|
||||
c("area", "sheetTable.col.area", 1.3, true, true),
|
||||
c("cut", "sheetTable.col.cut", 1.4, true, true),
|
||||
c("fill", "sheetTable.col.fill", 1.4, true, true),
|
||||
c("backfill", "sheetTable.col.backfill", 1.6, true, true),
|
||||
];
|
||||
|
||||
/// Schlüssel der Werttexte (Art, aussen/innen, Aufschlag …).
|
||||
pub const VALUE_KEYS: &[&str] = &[
|
||||
"sheetTable.v.window",
|
||||
@@ -111,6 +120,7 @@ pub fn catalog(source: LayoutTableSource) -> &'static [Col] {
|
||||
LayoutTableSource::Areas => AREAS,
|
||||
LayoutTableSource::Rooms => ROOMS,
|
||||
LayoutTableSource::Elements => ELEMENTS,
|
||||
LayoutTableSource::Earthworks => EARTHWORKS,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,7 +128,7 @@ pub fn catalog(source: LayoutTableSource) -> &'static [Col] {
|
||||
pub fn catalog_json() -> Value {
|
||||
let one = |s: &[Col]| s.iter().map(|k| json!({"id": k.id, "key": k.key, "numeric": k.numeric, "default": k.default})).collect::<Vec<_>>();
|
||||
json!({
|
||||
"sources": {"openings": one(OPENINGS), "areas": one(AREAS), "rooms": one(ROOMS), "elements": one(ELEMENTS)},
|
||||
"sources": {"openings": one(OPENINGS), "areas": one(AREAS), "rooms": one(ROOMS), "elements": one(ELEMENTS), "earthworks": one(EARTHWORKS)},
|
||||
"valueKeys": VALUE_KEYS,
|
||||
})
|
||||
}
|
||||
@@ -250,9 +260,22 @@ fn data_of(p: &Project, t: &LayoutTable, lb: &Labels) -> Data {
|
||||
LayoutTableSource::Areas => areas_data(p, lb),
|
||||
LayoutTableSource::Rooms => rooms_data(p),
|
||||
LayoutTableSource::Elements => elements_data(p, lb),
|
||||
LayoutTableSource::Earthworks => earthworks_data(p, lb),
|
||||
}
|
||||
}
|
||||
|
||||
/// [68] Erdarbeiten je Baugrube (m³ gegen das gewachsene Terrain) mit Summenzeile.
|
||||
fn earthworks_data(p: &Project, lb: &Labels) -> Data {
|
||||
let q = crate::excavation::quantities(p);
|
||||
let mut rows: Vec<Vec<Cell>> = q.iter().map(|e| vec![txt(e.name.clone()), num(e.bottom, 2), num(e.bottom_area, 1), num(e.cut, 1), num(e.fill, 1), num(e.backfill, 1)]).collect();
|
||||
let total_last = q.len() > 1;
|
||||
if total_last {
|
||||
let s = |f: fn(&crate::excavation::ExQty) -> f64| q.iter().map(f).sum::<f64>();
|
||||
rows.push(vec![txt(lb.get("sheetTable.v.total")), num(f64::NAN, 2), num(s(|e| e.bottom_area), 1), num(s(|e| e.cut), 1), num(s(|e| e.fill), 1), num(s(|e| e.backfill), 1)]);
|
||||
}
|
||||
Data { rows, total_last }
|
||||
}
|
||||
|
||||
/// Gewählte Spalten als Indizes in den Katalog (unbekannte Kennungen fallen weg; leer ⇒ Standard).
|
||||
fn column_indices(t: &LayoutTable) -> Vec<usize> {
|
||||
let cat = catalog(t.source);
|
||||
|
||||
@@ -340,6 +340,43 @@ pub struct SiteCheckOut {
|
||||
pub violation_area: f64,
|
||||
pub max_top: Option<f64>,
|
||||
pub height_exceeded: bool,
|
||||
/// [T6] Geländehöhen an der Fassade (Grundfläche, Ecken + alle ≤ 2 m), Modellbezug; leer ohne Gelände.
|
||||
pub facade_terrain: Vec<FacadePoint>,
|
||||
/// Tiefster Punkt des gewachsenen Terrains an der Fassade (massgebendes Terrain, vereinfacht).
|
||||
pub terrain_min: Option<f64>,
|
||||
/// Gesamthöhe über dem massgebenden Terrain (`maxTop − terrainMin`); ohne Gelände `None` (dann gilt ±0.00).
|
||||
pub height_above_terrain: Option<f64>,
|
||||
}
|
||||
|
||||
/// Fassadenpunkt mit gewachsenem und gestaltetem Terrain (Modellbezug; `None` ausserhalb des Geländes).
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct FacadePoint {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub natural: Option<f64>,
|
||||
pub designed: Option<f64>,
|
||||
}
|
||||
|
||||
/// Geländehöhen an der Fassade: Ecken der Aussenringe der Grundfläche und Zwischenpunkte (≤ 2 m).
|
||||
pub fn facade_terrain(p: &Project) -> Vec<FacadePoint> {
|
||||
if crate::excavation::terrains(p).is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for poly in building_footprint(p) {
|
||||
let Some(ring) = poly.first() else { continue };
|
||||
let n = ring.len();
|
||||
for i in 0..n {
|
||||
let (a, b) = (ring[i], ring[(i + 1) % n]);
|
||||
let k = (hypot2(b.x - a.x, b.y - a.y) / 2.0).ceil().max(1.0) as usize;
|
||||
for j in 0..k {
|
||||
let f = j as f64 / k as f64;
|
||||
let (x, y) = (a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f);
|
||||
out.push(FacadePoint { x, y, natural: crate::excavation::terrain_z(p, x, y, false), designed: crate::excavation::terrain_z(p, x, y, true) });
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Prüft das Modell gegen `siteRules`; `None` ohne (gültiges) Baurecht.
|
||||
@@ -351,7 +388,12 @@ pub fn check_project(p: &Project) -> Option<SiteCheckOut> {
|
||||
setbacks: (0..r.parcel.len()).map(|i| r.setbacks.as_ref().and_then(|s| s.get(i)).copied().unwrap_or(r.default_setback)).collect(),
|
||||
lines: r.building_lines.as_deref().unwrap_or(&[]).iter().map(|l| BuildingLine { a: [l.a.x, l.a.y], b: [l.b.x, l.b.y] }).collect(),
|
||||
};
|
||||
let c = check_site_rules(&rules, &footprint_parts(p), r.max_height.unwrap_or(f64::NAN), max_top.unwrap_or(f64::NAN))?;
|
||||
let facade = facade_terrain(p);
|
||||
let terrain_min = facade.iter().filter_map(|f| f.natural).reduce(f64::min);
|
||||
let height_above_terrain = max_top.zip(terrain_min).map(|(t, g)| t - g);
|
||||
// Mit Gelände zählt die Höhe über dem massgebenden Terrain, sonst über ±0.00.
|
||||
let top_for_check = height_above_terrain.or(max_top);
|
||||
let c = check_site_rules(&rules, &footprint_parts(p), r.max_height.unwrap_or(f64::NAN), top_for_check.unwrap_or(f64::NAN))?;
|
||||
Some(SiteCheckOut {
|
||||
parcel_area: c.parcel_area,
|
||||
allowed: area_out(&c.allowed),
|
||||
@@ -360,5 +402,8 @@ pub fn check_project(p: &Project) -> Option<SiteCheckOut> {
|
||||
violation_area: c.violation_area,
|
||||
max_top,
|
||||
height_exceeded: c.height_exceeded,
|
||||
facade_terrain: facade,
|
||||
terrain_min,
|
||||
height_above_terrain,
|
||||
})
|
||||
}
|
||||
@@ -265,18 +265,31 @@ pub fn collect_drawings(p: &Project, level: &str, codes: &HashSet<String>) -> Sn
|
||||
let mut segs: Vec<Seg> = Vec::new();
|
||||
let mut circles = Vec::new();
|
||||
let mut ellipses = Vec::new();
|
||||
let mut anchors = Vec::new();
|
||||
for d in &p.drawings2d {
|
||||
if d.level_id != level || !codes.contains(&d.category_code) {
|
||||
if !crate::grid::visible_on(d, level) || !codes.contains(&d.category_code) {
|
||||
continue;
|
||||
}
|
||||
match &d.geom {
|
||||
// Achsraster ([112]): Achsen als Strecken/Bögen, Achsschnittpunkte als Endpunkte.
|
||||
g @ Drawing2DGeom::Grid { .. } => {
|
||||
if let Some(spec) = crate::grid::Spec::of(g) {
|
||||
for ax in spec.axes() {
|
||||
match ax.shape {
|
||||
crate::grid::Shape::Line { a, b } => segs.push([a.0, a.1, b.0, b.1]),
|
||||
crate::grid::Shape::Arc { c, r, a0, a1 } => circles.push(Circle { cx: c.0, cy: c.1, r, arc: (a1 - a0 < std::f64::consts::TAU - 1e-9).then_some((a0, a1)) }),
|
||||
}
|
||||
}
|
||||
anchors.extend(spec.crossings());
|
||||
}
|
||||
}
|
||||
Drawing2DGeom::Circle { center, r } => circles.push(Circle { cx: center.x, cy: center.y, r: *r, arc: None }),
|
||||
Drawing2DGeom::Arc { center, r, a0, a1 } => circles.push(Circle { cx: center.x, cy: center.y, r: *r, arc: Some((*a0, *a1)) }),
|
||||
Drawing2DGeom::Ellipse { center, .. } => ellipses.push((center.x, center.y)),
|
||||
g => drawing_segs(g, &mut segs),
|
||||
}
|
||||
}
|
||||
SnapPart { segs: SnapSet::new(segs), circles, anchors: Vec::new(), ellipses }
|
||||
SnapPart { segs: SnapSet::new(segs), circles, anchors, ellipses }
|
||||
}
|
||||
|
||||
/// Die Kandidaten eines Geschosses: Modell, Zeichnungen, Nahmodus.
|
||||
@@ -656,6 +669,29 @@ mod tests {
|
||||
assert!(o.dwell.is_none() && o.a.is_none() && o.b.is_none());
|
||||
}
|
||||
|
||||
/// [112] Achsraster: Achsen als Strecken, Ringe als Kreise, Achsschnittpunkte als Endpunkte; in allen Geschossen.
|
||||
#[test]
|
||||
fn achsraster_fang() {
|
||||
let mut v = base();
|
||||
v["drawings2d"] = json!([{"id": "G", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "grid", "origin": {"x": 1, "y": 2}, "angle": 0,
|
||||
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 4}], "b": [{"label": "A", "pos": 0}, {"label": "B", "pos": 3}], "extend": 1}}]);
|
||||
let p: Project = serde_json::from_value(v).unwrap();
|
||||
let codes: HashSet<String> = ["20".to_string()].into_iter().collect();
|
||||
for level in ["eg", "og"] {
|
||||
let part = collect_drawings(&p, level, &codes);
|
||||
assert_eq!(part.anchors.len(), 4, "{level}");
|
||||
assert!(part.anchors.contains(&(5.0, 5.0)));
|
||||
}
|
||||
let mut v = base();
|
||||
v["drawings2d"] = json!([{"id": "G", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0, "radial": true,
|
||||
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 90}], "b": [{"label": "A", "pos": 3}], "extend": 1}}]);
|
||||
let p: Project = serde_json::from_value(v).unwrap();
|
||||
let part = collect_drawings(&p, "eg", &codes);
|
||||
assert_eq!(part.circles.len(), 1);
|
||||
assert_eq!(part.circles[0].r, 3.0);
|
||||
assert_eq!(part.anchors.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gleiche_nummer_solange_nichts_relevantes_aendert_teile_einzeln_neu() {
|
||||
let mut v = base();
|
||||
|
||||
+266
-10
@@ -3,9 +3,10 @@
|
||||
//! (`railings`). Die Treppengeometrie selbst kommt aus `kernel2d` (`stair_geometry`); TS sammelt aus
|
||||
//! dem `Project` nur Parameter, Höhen und Tragart und färbt die Ergebnisse ein.
|
||||
//!
|
||||
//! Eingabe (je Treppe 23 Zahlen, davor die Anzahl): die 16 Treppen-Parameter (s. [`crate::stair`]),
|
||||
//! Eingabe (je Treppe 24 Zahlen, davor die Anzahl): die 16 Treppen-Parameter (s. [`crate::stair`]),
|
||||
//! `zUnten, zOben, tragart (0 massiv, 1 beton, 2 offen: Wange/aufgesattelt/Spindel),
|
||||
//! trittdicke, nase, geschlosseneSetzstufen (0/1), gelaender (0 keine, 1 links, 2 rechts, 3 beide)`.
|
||||
//! trittdicke, nase, geschlosseneSetzstufen (0/1), gelaender (0 keine, 1 links, 2 rechts, 3 beide),
|
||||
//! saeulenRadius (0 keine; nur Wendel)`.
|
||||
//!
|
||||
//! Ausgabe Slabs: `[n, (treppe, monolith 0/1, zUnten, zOben, nPkt, x, y …)…]`; Ausgabe Meshes
|
||||
//! (Laufplatte, Geländer): `[n, (treppe, nPos, nIdx, positionen…, indizes…)…]`. `treppe` ist der
|
||||
@@ -41,12 +42,16 @@ struct StairIn {
|
||||
nosing: f64,
|
||||
closed_risers: bool,
|
||||
railing: u8,
|
||||
column_radius: f64,
|
||||
}
|
||||
|
||||
impl StairIn {
|
||||
fn straight(&self) -> bool {
|
||||
self.params.shape == "straight"
|
||||
}
|
||||
fn spiral(&self) -> bool {
|
||||
self.params.shape == "spiral"
|
||||
}
|
||||
}
|
||||
|
||||
fn decode(buf: &[f64]) -> Option<Vec<Option<StairIn>>> {
|
||||
@@ -58,8 +63,8 @@ fn decode(buf: &[f64]) -> Option<Vec<Option<StairIn>>> {
|
||||
for v in p.iter_mut() {
|
||||
*v = r.num()?;
|
||||
}
|
||||
let (z_bottom, z_top, structure, tread_thickness, nosing, closed, railing) =
|
||||
(r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?);
|
||||
let (z_bottom, z_top, structure, tread_thickness, nosing, closed, railing, column) =
|
||||
(r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?);
|
||||
// Eine unbrauchbare Treppe fällt einzeln weg (Index bleibt erhalten).
|
||||
let valid = [z_bottom, z_top, tread_thickness, nosing].iter().all(|v| v.is_finite());
|
||||
out.push(match (valid, decode_params(&p)) {
|
||||
@@ -72,6 +77,7 @@ fn decode(buf: &[f64]) -> Option<Vec<Option<StairIn>>> {
|
||||
nosing,
|
||||
closed_risers: closed != 0.0,
|
||||
railing: railing.clamp(0.0, 3.0) as u8,
|
||||
column_radius: if column.is_finite() && column > 0.0 { column.min(5.0) } else { 0.0 },
|
||||
}),
|
||||
_ => None,
|
||||
});
|
||||
@@ -237,7 +243,21 @@ fn slabs_of(s: &StairIn, idx: usize, for_section: bool, out: &mut Vec<Slab>) {
|
||||
let Some((geo, total_rise)) = geometry_of(s) else { return };
|
||||
let z_bottom = s.z_bottom;
|
||||
let structure = s.structure;
|
||||
if structure == BETON && s.straight() && !for_section {
|
||||
let mut column: Option<Slab> = None;
|
||||
if s.spiral() && s.column_radius > 0.0 {
|
||||
if let Some(c) = &s.params.center {
|
||||
let pts = (0..COLUMN_SEGMENTS)
|
||||
.map(|k| {
|
||||
let a = std::f64::consts::TAU * k as f64 / COLUMN_SEGMENTS as f64;
|
||||
[c.x + s.column_radius * a.cos(), c.y + s.column_radius * a.sin()]
|
||||
})
|
||||
.collect();
|
||||
// Säule zuletzt einfügen: siehe unten; hier nur vormerken
|
||||
column = Some(Slab { src: idx, monolith: true, z_bottom, z_top: s.z_top, pts });
|
||||
}
|
||||
}
|
||||
if structure == BETON && (s.straight() || s.spiral()) && !for_section {
|
||||
out.extend(column);
|
||||
return;
|
||||
}
|
||||
let riser = geo.riser_height;
|
||||
@@ -317,9 +337,114 @@ fn slabs_of(s: &StairIn, idx: usize, for_section: bool, out: &mut Vec<Slab>) {
|
||||
});
|
||||
}
|
||||
}
|
||||
out.extend(column);
|
||||
}
|
||||
|
||||
/// Kreisbogenstücke je Tritt in Wendelfläche und Handlauf.
|
||||
const HELIX_SEGMENTS: usize = 6;
|
||||
/// Ecken der Mittelsäule (Vieleck).
|
||||
const COLUMN_SEGMENTS: usize = 24;
|
||||
|
||||
/// Wendel-Masse: Zentrum, Winkelbereich, Radien (wie `spiral_geometry` in `kernel2d`).
|
||||
struct Helix {
|
||||
center: P,
|
||||
a0: f64,
|
||||
sweep: f64,
|
||||
r_in: f64,
|
||||
r_out: f64,
|
||||
}
|
||||
|
||||
fn helix_of(s: &StairIn) -> Option<Helix> {
|
||||
let p = &s.params;
|
||||
let half_w = 0.05_f64.max(p.width / 2.0);
|
||||
let center = p.center.unwrap_or(p.start);
|
||||
let radius = (half_w + 0.1).max(p.radius.unwrap_or(p.width));
|
||||
let a0 = (p.start.y - center.y).atan2(p.start.x - center.x);
|
||||
let sweep = p.sweep.unwrap_or(270.0).to_radians();
|
||||
if !(sweep.abs() > 1e-6) {
|
||||
return None;
|
||||
}
|
||||
Some(Helix { center: [center.x, center.y], a0, sweep, r_in: (radius - half_w).max(0.02), r_out: radius + half_w })
|
||||
}
|
||||
|
||||
impl Helix {
|
||||
fn at(&self, r: f64, ang: f64) -> P {
|
||||
[self.center[0] + r * ang.cos(), self.center[1] + r * ang.sin()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Wendelfläche einer Ortbetontreppe: je Tritt ein geschlossener Block, dessen Untersicht eine echte
|
||||
/// Schraubenfläche ist (z linear im Winkel, radiale Erzeugende); Oberseite = ebener Tritt.
|
||||
fn spiral_mesh(s: &StairIn, idx: usize, out: &mut Vec<Mesh>) {
|
||||
let Some((geo, total_rise)) = geometry_of(s) else { return };
|
||||
let Some(h) = helix_of(s) else { return };
|
||||
let n = geo.treads.len();
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
let waist = concrete_waist(geo.riser_height);
|
||||
let z_bottom = s.z_bottom;
|
||||
let soffit = |frac: f64| z_bottom.max(z_bottom + frac * total_rise - waist);
|
||||
let d_a = h.sweep / n as f64;
|
||||
let mut positions: Vec<f64> = Vec::new();
|
||||
let mut indices: Vec<u32> = Vec::new();
|
||||
for (i, tr) in geo.treads.iter().enumerate() {
|
||||
let top = z_bottom + tr.top_rise;
|
||||
// Ringe entlang des Tritts: (innen unten, aussen unten, Winkel)
|
||||
let m = HELIX_SEGMENTS;
|
||||
let base = (positions.len() / 3) as u32;
|
||||
for j in 0..=m {
|
||||
let f = j as f64 / m as f64;
|
||||
let ang = h.a0 + (i as f64 + f) * d_a;
|
||||
let zb = soffit((i as f64 + f) / n as f64);
|
||||
for (r, z) in [(h.r_in, zb), (h.r_out, zb), (h.r_in, top), (h.r_out, top)] {
|
||||
let q = h.at(r, ang);
|
||||
positions.extend([q[0], q[1], z]);
|
||||
}
|
||||
}
|
||||
// Eckindizes je Ring j: 0 = innen unten, 1 = aussen unten, 2 = innen oben, 3 = aussen oben
|
||||
let v = |j: usize, k: u32| base + 4 * j as u32 + k;
|
||||
let mut quad = |a: u32, b: u32, c: u32, d: u32| indices.extend([a, b, c, a, c, d]);
|
||||
for j in 0..m {
|
||||
quad(v(j, 0), v(j, 1), v(j + 1, 1), v(j + 1, 0)); // Untersicht (Wendelfläche)
|
||||
quad(v(j, 2), v(j + 1, 2), v(j + 1, 3), v(j, 3)); // Trittfläche
|
||||
quad(v(j, 0), v(j + 1, 0), v(j + 1, 2), v(j, 2)); // innere Wange
|
||||
quad(v(j, 1), v(j, 3), v(j + 1, 3), v(j + 1, 1)); // äussere Wange
|
||||
}
|
||||
quad(v(0, 0), v(0, 2), v(0, 3), v(0, 1)); // Setzstufe (Anfang)
|
||||
quad(v(m, 0), v(m, 1), v(m, 3), v(m, 2)); // Ende
|
||||
}
|
||||
if indices.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Drehsinn legt die Orientierung fest: bei negativem Volumen alle Dreiecke wenden.
|
||||
let mut mesh = Mesh { src: idx, positions, indices };
|
||||
if signed_volume(&mesh) < 0.0 {
|
||||
for t in mesh.indices.chunks_mut(3) {
|
||||
t.swap(1, 2);
|
||||
}
|
||||
}
|
||||
out.push(mesh);
|
||||
}
|
||||
|
||||
fn signed_volume(m: &Mesh) -> f64 {
|
||||
let p = |i: u32| {
|
||||
let k = 3 * i as usize;
|
||||
[m.positions[k], m.positions[k + 1], m.positions[k + 2]]
|
||||
};
|
||||
m.indices
|
||||
.chunks(3)
|
||||
.map(|t| {
|
||||
let (a, b, c) = (p(t[0]), p(t[1]), p(t[2]));
|
||||
(a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn meshes_of(s: &StairIn, idx: usize, out: &mut Vec<Mesh>) {
|
||||
if s.structure == BETON && s.spiral() {
|
||||
return spiral_mesh(s, idx, out);
|
||||
}
|
||||
if s.structure != BETON || !s.straight() || s.params.run_length <= EPS {
|
||||
return;
|
||||
}
|
||||
@@ -414,8 +539,63 @@ fn strut_box(a: V3, b: V3, half: f64) -> Option<(Vec<f64>, Vec<u32>)> {
|
||||
Some((positions, indices))
|
||||
}
|
||||
|
||||
/// Handlauf einer Wendeltreppe als Schraubensweep (Quader-Stücke auf der Schraubenlinie) samt
|
||||
/// Pfosten auf den Trittmitten, in einem Netz je Treppe.
|
||||
fn spiral_railing(s: &StairIn, idx: usize, out: &mut Vec<Mesh>) {
|
||||
let Some((geo, total_rise)) = geometry_of(s) else { return };
|
||||
let Some(h) = helix_of(s) else { return };
|
||||
let n = geo.treads.len();
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
// Laufrichtung = Drehsinn: links der Laufrichtung liegt bei CCW der Innenrand.
|
||||
let ccw = h.sweep > 0.0;
|
||||
let sides: &[bool] = match s.railing {
|
||||
3 => &[true, false],
|
||||
1 => &[true],
|
||||
_ => &[false],
|
||||
};
|
||||
let half = RAIL_THICK / 2.0;
|
||||
let mut positions: Vec<f64> = Vec::new();
|
||||
let mut indices: Vec<u32> = Vec::new();
|
||||
let mut push = |m: Option<(Vec<f64>, Vec<u32>)>| {
|
||||
if let Some((p, i)) = m {
|
||||
let base = (positions.len() / 3) as u32;
|
||||
positions.extend(p);
|
||||
indices.extend(i.into_iter().map(|k| k + base));
|
||||
}
|
||||
};
|
||||
let rail_z = |frac: f64| s.z_bottom + frac * total_rise + RAIL_HEIGHT;
|
||||
for &left in sides {
|
||||
let r = if left == ccw { h.r_in } else { h.r_out };
|
||||
let total_seg = n * HELIX_SEGMENTS;
|
||||
let pt_at = |k: usize| {
|
||||
let f = k as f64 / total_seg as f64;
|
||||
let q = h.at(r, h.a0 + f * h.sweep);
|
||||
[q[0], q[1], rail_z(f)]
|
||||
};
|
||||
for k in 0..total_seg {
|
||||
push(strut_box(pt_at(k), pt_at(k + 1), half));
|
||||
}
|
||||
for (i, tr) in geo.treads.iter().enumerate() {
|
||||
let f = (i as f64 + 0.5) / n as f64;
|
||||
let q = h.at(r, h.a0 + f * h.sweep);
|
||||
push(strut_box([q[0], q[1], s.z_bottom + tr.top_rise], [q[0], q[1], rail_z(f)], half));
|
||||
}
|
||||
}
|
||||
if !indices.is_empty() {
|
||||
out.push(Mesh { src: idx, positions, indices });
|
||||
}
|
||||
}
|
||||
|
||||
fn railings_of(s: &StairIn, idx: usize, out: &mut Vec<Mesh>) {
|
||||
if !s.straight() || s.railing == 0 {
|
||||
if s.railing == 0 {
|
||||
return;
|
||||
}
|
||||
if s.spiral() {
|
||||
return spiral_railing(s, idx, out);
|
||||
}
|
||||
if !s.straight() {
|
||||
return;
|
||||
}
|
||||
let Some((geo, _)) = geometry_of(s) else { return };
|
||||
@@ -502,7 +682,7 @@ mod tests {
|
||||
vec![
|
||||
1.0, // eine Treppe
|
||||
0.0, 0.0, 0.0, 1.0, 0.0, 3.0, nan, nan, nan, nan, nan, nan, 1.0, 10.0, nan, 0.0, // Parameter
|
||||
0.0, 2.8, structure, 0.04, nosing, closed, railing,
|
||||
0.0, 2.8, structure, 0.04, nosing, closed, railing, 0.0,
|
||||
]
|
||||
}
|
||||
|
||||
@@ -573,7 +753,7 @@ mod tests {
|
||||
let nan = f64::NAN;
|
||||
let l = vec![
|
||||
1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 2.0, 1.5, 1.0, nan, nan, nan, nan, 1.0, 10.0, nan, 0.0, // L
|
||||
0.0, 2.8, 0.0, 0.04, 0.0, 0.0, 0.0,
|
||||
0.0, 2.8, 0.0, 0.04, 0.0, 0.0, 0.0, 0.0,
|
||||
];
|
||||
let s = slabs(&l, false);
|
||||
assert!(s.len() >= 10);
|
||||
@@ -581,9 +761,85 @@ mod tests {
|
||||
assert!((last.z_top - 1.4).abs() < 1e-9 && last.z_bottom == 0.0);
|
||||
let w = vec![
|
||||
1.0, 2.0, 1.0, 0.0, 1.0, 0.0, 1.0, nan, nan, 0.0, 0.0, 1.5, 270.0, 1.0, 12.0, nan, 0.0, // Wendel
|
||||
0.0, 2.8, 2.0, 0.04, 0.0, 0.0, 3.0,
|
||||
0.0, 2.8, 2.0, 0.04, 0.0, 0.0, 3.0, 0.0,
|
||||
];
|
||||
assert!(!slabs(&w, false).is_empty());
|
||||
assert!(railings(&w).is_empty()); // Geländer nur für gerade Läufe
|
||||
assert!(!railings(&w).is_empty()); // Wendelgeländer = Schraubensweep
|
||||
}
|
||||
|
||||
fn spiral(structure: f64, railing: f64, column: f64) -> Vec<f64> {
|
||||
let nan = f64::NAN;
|
||||
vec![
|
||||
1.0, 2.0, 1.0, 0.0, 1.0, 0.0, 1.0, nan, nan, 0.0, 0.0, 1.5, 270.0, 1.0, 12.0, nan, 0.0, // Wendel
|
||||
0.0, 2.8, structure, 0.04, 0.0, 0.0, railing, column,
|
||||
]
|
||||
}
|
||||
|
||||
/// Volumen eines geschlossenen Netzes (Divergenzsatz); positiv = Normalen nach aussen.
|
||||
fn volume(m: &Mesh) -> f64 {
|
||||
let p = |i: u32| [m.positions[3 * i as usize], m.positions[3 * i as usize + 1], m.positions[3 * i as usize + 2]];
|
||||
m.indices
|
||||
.chunks(3)
|
||||
.map(|t| {
|
||||
let (a, b, c) = (p(t[0]), p(t[1]), p(t[2]));
|
||||
(a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wendel_beton_hat_schraubenfläche() {
|
||||
let ms = slab_meshes(&spiral(1.0, 0.0, 0.0));
|
||||
assert_eq!(ms.len(), 1);
|
||||
let m = &ms[0];
|
||||
// Ringsektor 270° (r 1…2) = 7.07 m², mittlere Dicke ≈ Laufplatte + halbe Steigung
|
||||
let v = volume(m);
|
||||
assert!(v > 1.5 && v < 3.2, "Volumen {v}");
|
||||
// Untersicht folgt der Schraube: an jedem Punkt z_unten = z0 + Winkelanteil·Steighöhe − Dicke (oder 0)
|
||||
let a0 = 0.0_f64; // Start (1,0) um Zentrum (0,0)
|
||||
let waist = concrete_waist(2.8 / 12.0);
|
||||
let mut checked = 0;
|
||||
for c in m.positions.chunks(3) {
|
||||
let ang = c[1].atan2(c[0]).rem_euclid(std::f64::consts::TAU) - a0;
|
||||
let f = ang / (270.0_f64).to_radians();
|
||||
let on_helix = (0.0..=1.0).contains(&f) && (c[2] - (f * 2.8 - waist).max(0.0)).abs() < 1e-6;
|
||||
if on_helix {
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert!(checked > 12 * 2, "zu wenige Punkte auf der Wendelfläche: {checked}");
|
||||
// Im Grundriss/3D werden die Tritt-Prismen für Beton nicht doppelt gezeichnet, im Schnitt schon
|
||||
assert!(slabs(&spiral(1.0, 0.0, 0.0), false).is_empty());
|
||||
assert!(!slabs(&spiral(1.0, 0.0, 0.0), true).is_empty());
|
||||
// Drehsinn negativ: Netz bleibt geschlossen/nach aussen orientiert
|
||||
let mut cw = spiral(1.0, 0.0, 0.0);
|
||||
cw[12] = -270.0;
|
||||
assert!(volume(&slab_meshes(&cw)[0]) > 1.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wendel_handlauf_ist_schraubensweep() {
|
||||
let rs = railings(&spiral(1.0, 1.0, 0.0));
|
||||
assert!(!rs.is_empty());
|
||||
let zs: Vec<f64> = rs.iter().flat_map(|m| m.positions.chunks(3).map(|c| c[2])).collect();
|
||||
let (lo, hi) = (zs.iter().cloned().fold(f64::INFINITY, f64::min), zs.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
|
||||
assert!(lo < 0.95 && hi > 2.8 + 0.85, "{lo} {hi}");
|
||||
// Handlauf liegt auf einem Kreis (Innenkante r = 1.0 bei Linksgeländer, CCW) — alle Punkte r ≈ 1 ± Querschnitt
|
||||
let big = rs.iter().max_by_key(|m| m.indices.len()).unwrap();
|
||||
let r: Vec<f64> = big.positions.chunks(3).map(|c| c[0].hypot(c[1])).collect();
|
||||
assert!(r.iter().all(|r| (r - 1.0).abs() < 0.05), "Radius streut");
|
||||
assert!(big.positions.chunks(3).any(|c| c[2] > 2.0) && big.positions.chunks(3).any(|c| c[2] < 1.2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wendel_mittelsaeule_als_block() {
|
||||
let none = slabs(&spiral(0.0, 0.0, 0.0), false).len();
|
||||
let with = slabs(&spiral(0.0, 0.0, 0.12), false);
|
||||
assert_eq!(with.len(), none + 1);
|
||||
let col = with.last().unwrap();
|
||||
assert!(col.z_bottom == 0.0 && (col.z_top - 2.8).abs() < 1e-9 && col.pts.len() >= 12);
|
||||
assert!(col.pts.iter().all(|p| (p[0].hypot(p[1]) - 0.12).abs() < 1e-9));
|
||||
// auch bei Beton (Grundriss ohne Tritt-Prismen) und nur für Wendel
|
||||
assert_eq!(slabs(&spiral(1.0, 0.0, 0.12), false).len(), 1);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+609
-121
@@ -9,13 +9,13 @@
|
||||
//! als Löcher) und Schnitt-Eingabe (Pfeiler/Brüstung/Sturz-Segmente ohne Löcher).
|
||||
|
||||
use crate::joins::{js_hypot, reference_offset, Line, Reference, WallCuts};
|
||||
use crate::roof::roof_underside_at;
|
||||
use kernel2d::{add, dot, left_normal, line_intersect, point_in_outline, scale, sub, Vec2};
|
||||
|
||||
/// Toleranz der Wand-Ableitung (`EPS` in `toWalls3d/shared.ts`).
|
||||
pub const EPS: f64 = 1e-4;
|
||||
/// Schrittweite (Meter) der Dach-Unterkanten-Abtastung.
|
||||
const ROOF_CLIP_STEP: f64 = 0.15;
|
||||
/// Schrittweite (Meter) der Dach-Unterkanten-Abtastung (Wechsel der Dachfläche suchen; die Grenzen
|
||||
/// selbst sind exakt).
|
||||
const ROOF_SAMPLE: f64 = 0.05;
|
||||
|
||||
/// Ein Schicht-Band: Dicke und Verschneidungs-Rang (`None`: keine Decken-Subtraktion).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -65,13 +65,96 @@ pub struct CeilingIn {
|
||||
pub layers: Option<Vec<(f64, Option<f64>)>>,
|
||||
}
|
||||
|
||||
/// Ein Dach desselben Geschosses: Traufhöhe, Summe der Schichtdicken, Traufe-Umriss, Flächen.
|
||||
/// Ein Dach desselben Geschosses: Traufhöhe, Summe der Schichtdicken, Traufe-Umriss, Flächen und
|
||||
/// die Unterkanten-Facetten ([G2]), an denen Wände enden.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RoofIn {
|
||||
pub eaves_z: f64,
|
||||
pub total_thickness: f64,
|
||||
pub eaves: Vec<[f64; 2]>,
|
||||
pub planes: Vec<Vec<[f64; 3]>>,
|
||||
pub facets: Vec<RoofFacet>,
|
||||
}
|
||||
|
||||
impl RoofIn {
|
||||
/// Facetten aus den Dachflächen (Schichten senkrecht zur Fläche, Summe `total`).
|
||||
pub fn new(eaves_z: f64, total: f64, eaves: Vec<[f64; 2]>, planes: Vec<Vec<[f64; 3]>>) -> Self {
|
||||
let facets = plane_facets(&planes, total);
|
||||
RoofIn { eaves_z, total_thickness: total, eaves, planes, facets }
|
||||
}
|
||||
}
|
||||
|
||||
/// Ebene Unterkante eines Dachteils über dem Grundriss-Bereich `ring`: `z = c + gx·x + gy·y`. Wo sich
|
||||
/// Facetten überdecken (Kehlen verschnittener Dächer, Gaube über dem Hauptdach), gilt die obere Hülle.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RoofFacet {
|
||||
pub ring: Vec<[f64; 2]>,
|
||||
pub plane: [f64; 3],
|
||||
bounds: [f64; 4],
|
||||
}
|
||||
|
||||
impl RoofFacet {
|
||||
/// `None` bei weniger als drei Ecken oder nicht endlichen Werten.
|
||||
pub fn new(ring: Vec<[f64; 2]>, plane: [f64; 3]) -> Option<Self> {
|
||||
if ring.len() < 3 || !plane.iter().all(|v| v.is_finite()) || !ring.iter().all(|q| q[0].is_finite() && q[1].is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let b = outline_bounds(ring.iter().map(|q| (q[0], q[1])));
|
||||
Some(RoofFacet { ring, plane, bounds: [b.min_x, b.min_y, b.max_x, b.max_y] })
|
||||
}
|
||||
pub(crate) fn z(&self, x: f64, y: f64) -> f64 {
|
||||
self.plane[0] + self.plane[1] * x + self.plane[2] * y
|
||||
}
|
||||
pub(crate) fn contains(&self, x: f64, y: f64) -> bool {
|
||||
let b = self.bounds;
|
||||
if x < b[0] || x > b[2] || y < b[1] || y > b[3] {
|
||||
return false;
|
||||
}
|
||||
let mut inside = false;
|
||||
let n = self.ring.len();
|
||||
let mut j = n - 1;
|
||||
for i in 0..n {
|
||||
let (a, c) = (self.ring[i], self.ring[j]);
|
||||
if (a[1] > y) != (c[1] > y) && x < (c[0] - a[0]) * (y - a[1]) / (c[1] - a[1]) + a[0] {
|
||||
inside = !inside;
|
||||
}
|
||||
j = i;
|
||||
}
|
||||
inside
|
||||
}
|
||||
/// Höchster Wert über den Ecken.
|
||||
fn z_max(&self) -> f64 {
|
||||
self.ring.iter().map(|q| self.z(q[0], q[1])).fold(f64::NEG_INFINITY, f64::max)
|
||||
}
|
||||
}
|
||||
|
||||
/// Unterkanten-Facetten der Dachflächen: Oberfläche um `total` senkrecht zur Fläche gesenkt (wie die
|
||||
/// 3D-Schichten); senkrechte Flächen entfallen.
|
||||
pub fn plane_facets(planes: &[Vec<[f64; 3]>], total: f64) -> Vec<RoofFacet> {
|
||||
let t = if total.is_finite() { total.max(0.0) } else { 0.0 };
|
||||
let mut out = Vec::new();
|
||||
for pts in planes {
|
||||
if pts.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let (mut a, mut b, mut c) = (0.0, 0.0, 0.0);
|
||||
for i in 0..pts.len() {
|
||||
let (p, q) = (pts[i], pts[(i + 1) % pts.len()]);
|
||||
a += (p[1] - q[1]) * (p[2] + q[2]);
|
||||
b += (p[2] - q[2]) * (p[0] + q[0]);
|
||||
c += (p[0] - q[0]) * (p[1] + q[1]);
|
||||
}
|
||||
let len = (a * a + b * b + c * c).sqrt();
|
||||
if !(len > 1e-12) || c.abs() < 1e-6 * len {
|
||||
continue; // senkrecht oder entartet
|
||||
}
|
||||
let (gx, gy) = (-a / c, -b / c);
|
||||
let c0 = pts[0][2] - gx * pts[0][0] - gy * pts[0][1] - t * len / c.abs();
|
||||
if let Some(f) = RoofFacet::new(pts.iter().map(|q| [q[0], q[1]]).collect(), [c0, gx, gy]) {
|
||||
out.push(f);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Terminierung am Deckenanschluss (`Wall.sliceTermination`).
|
||||
@@ -102,6 +185,10 @@ pub struct WallIn {
|
||||
pub cuts: WallCuts,
|
||||
/// Schichteinzug ([106]); leer = alle Schichten bündig.
|
||||
pub reveals: Vec<RevealIn>,
|
||||
/// An Dach anschliessen ([G2], `Wall.roofAttach`): `None` = automatisch (Wand endet an der
|
||||
/// Dach-Unterkante, wo ihre Krone darüber liegt), `Some(true)` = zusätzlich bis unter das Dach
|
||||
/// verlängert, `Some(false)` = Dächer schneiden die Wand nicht.
|
||||
pub roof_attach: Option<bool>,
|
||||
}
|
||||
|
||||
/// Decken und Dächer eines Geschosses — einmal je Geschoss gelesen, für alle seine Wände; die
|
||||
@@ -125,7 +212,7 @@ impl FloorContext {
|
||||
roofs: roofs
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let b = outline_bounds(r.eaves.iter().map(|p| (p[0], p[1])));
|
||||
let b = outline_bounds(r.eaves.iter().map(|p| (p[0], p[1])).chain(r.facets.iter().flat_map(|f| f.ring.iter().map(|q| (q[0], q[1])))));
|
||||
(r, b)
|
||||
})
|
||||
.collect(),
|
||||
@@ -149,8 +236,15 @@ pub struct Piece {
|
||||
/// beginnt/endet dort, wo die Band-Mittellinie sie trifft. `None`: rechtwinklig.
|
||||
pub start_cut: Option<Line>,
|
||||
pub end_cut: Option<Line>,
|
||||
/// Eigene Dicke (Schichteinzug-Stück, [106]); `None` = Banddicke.
|
||||
/// Eigene Dicke (Schichteinzug-Stück, [106]; seitlich geteiltes Band unter einem Dach, [G2]);
|
||||
/// `None` = Banddicke.
|
||||
pub thickness: Option<f64>,
|
||||
/// Ebene Oberkante unter einer Dachfläche ([G2]): `z = c + gx·x + gy·y` (Welt); `None` = waagrecht
|
||||
/// auf `z_top`. `z_top` ist dann der höchste Eckwert, `top_drop` die Absenkung auf der Mittellinie.
|
||||
pub top_plane: Option<[f64; 3]>,
|
||||
/// Anfang/Ende liegt an einer inneren Stossfuge (Teilung an Dachkanten oder Öffnungen unter einem
|
||||
/// Dach): dort keine sichtbare Stirnfläche (Ansicht).
|
||||
pub joint: [bool; 2],
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -475,94 +569,337 @@ impl Emitter<'_> {
|
||||
start_cut: None,
|
||||
end_cut: None,
|
||||
thickness: None,
|
||||
top_plane: None,
|
||||
joint: [false; 2],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Oberkante des Bands unter den Dächern: Dach-Unterkante entlang der Achse abtasten, zu geraden
|
||||
/// Stücken (Toleranz 2 mm) zusammenfassen, Knicke exakt als Schnitt der Nachbargeraden; je Stück
|
||||
/// ein Körper mit schräger Oberkante. Ohne Dach darüber: ein Körper, unverändert.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn clip_to_roofs(w: &WallIn, ctx: &FloorContext, u: Vec2, n: Vec2, offset: f64, a: f64, bb: f64, zb: f64, zt: f64, emit: &mut dyn FnMut(f64, f64, f64, f64, f64)) {
|
||||
if zt - zb <= EPS || bb - a <= EPS {
|
||||
return;
|
||||
}
|
||||
let wb = wall_bounds(w, offset.abs() + 0.01);
|
||||
let roofs: Vec<&RoofIn> = ctx.roofs.iter().filter(|(r, rb)| r.eaves_z + 50.0 >= zb && bounds_overlap(wb, *rb)).map(|(r, _)| r).collect();
|
||||
if roofs.is_empty() {
|
||||
emit(a, bb, zb, zt, zt);
|
||||
return;
|
||||
}
|
||||
let span = bb - a;
|
||||
let count = 1usize.max((span / ROOF_CLIP_STEP).ceil() as usize);
|
||||
let top_at = |t: f64| {
|
||||
let tt = (bb - 1e-3).min((a + 1e-3).max(t));
|
||||
let p = add(add(w.start, scale(u, tt)), scale(n, offset));
|
||||
let mut clip = zt;
|
||||
for r in &roofs {
|
||||
if let Some(under) = roof_underside_at(&r.planes, r.total_thickness, p.x, p.y) {
|
||||
if under < clip {
|
||||
clip = under;
|
||||
// ── Wand an Dach ([G2]) ───────────────────────────────────────────────────────
|
||||
//
|
||||
// Die Oberkante eines Bands ist `clamp(U, zb, zt)` mit U = obere Hülle der Dach-Unterkanten-Facetten
|
||||
// über dem Punkt (stückweise eben). Das Band wird an den Grenzen der Bereiche geteilt — längs der
|
||||
// Achse mit der exakten Grenzlinie als Schnittlinie (First, Grat, Kehle, Höhenlinie U = zt bzw. zb),
|
||||
// quer über die Dicke (seitlich), wo eine Grenze längs durch das Band läuft (Traufwand, deren Krone die
|
||||
// Dachfläche schneidet). Jedes Stück bekommt eine ebene Oberkante: exakt je Schicht, an jeder Ecke.
|
||||
|
||||
/// Bereich der Oberkante an einem Punkt.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Fac {
|
||||
/// Kein Dach darüber: Wandkrone.
|
||||
Free,
|
||||
/// Unter dem Dach, Unterkante über der (verlängerten) Krone: waagrecht auf der Krone.
|
||||
Cap,
|
||||
/// Unterkante unter dem Fuss: kein Körper.
|
||||
Floor,
|
||||
/// Unterkante der Facette `k`.
|
||||
Roof(usize),
|
||||
}
|
||||
|
||||
struct Tops<'a> {
|
||||
facets: Vec<&'a RoofFacet>,
|
||||
zb: f64,
|
||||
zt_free: f64,
|
||||
zt_cap: f64,
|
||||
}
|
||||
|
||||
impl Tops<'_> {
|
||||
fn at(&self, p: Vec2) -> Fac {
|
||||
let mut best: Option<(f64, usize)> = None;
|
||||
for (k, f) in self.facets.iter().enumerate() {
|
||||
if f.contains(p.x, p.y) {
|
||||
let z = f.z(p.x, p.y);
|
||||
if best.is_none_or(|b| z > b.0) {
|
||||
best = Some((z, k));
|
||||
}
|
||||
}
|
||||
}
|
||||
zb.max(clip)
|
||||
};
|
||||
let mut ts = Vec::with_capacity(count + 1);
|
||||
let mut tops = Vec::with_capacity(count + 1);
|
||||
for i in 0..=count {
|
||||
ts.push(a + (span * i as f64) / count as f64);
|
||||
tops.push(top_at(ts[i]));
|
||||
}
|
||||
const TOL: f64 = 0.002;
|
||||
let mut runs: Vec<(usize, usize)> = Vec::new();
|
||||
let mut i0 = 0;
|
||||
while i0 < count {
|
||||
let mut i1 = i0 + 1;
|
||||
while i1 < count {
|
||||
let k = i1 + 1;
|
||||
let slope = (tops[k] - tops[i0]) / (ts[k] - ts[i0]);
|
||||
let ok = (i0 + 1..=k).all(|m| (tops[i0] + slope * (ts[m] - ts[i0]) - tops[m]).abs() <= TOL);
|
||||
if !ok {
|
||||
break;
|
||||
match best {
|
||||
None => Fac::Free,
|
||||
Some((z, _)) if z >= self.zt_cap - 1e-9 => {
|
||||
if self.zt_cap == self.zt_free {
|
||||
Fac::Free
|
||||
} else {
|
||||
Fac::Cap
|
||||
}
|
||||
}
|
||||
i1 = k;
|
||||
Some((z, _)) if z <= self.zb + 1e-9 => Fac::Floor,
|
||||
Some((_, k)) => Fac::Roof(k),
|
||||
}
|
||||
runs.push((i0, i1));
|
||||
i0 = i1;
|
||||
}
|
||||
let line = |r: (usize, usize)| {
|
||||
let m = (tops[r.1] - tops[r.0]) / (ts[r.1] - ts[r.0]);
|
||||
(m, tops[r.0] - m * ts[r.0])
|
||||
fn coef(&self, f: Fac) -> [f64; 3] {
|
||||
match f {
|
||||
Fac::Free => [self.zt_free, 0.0, 0.0],
|
||||
Fac::Cap => [self.zt_cap, 0.0, 0.0],
|
||||
Fac::Floor => [self.zb, 0.0, 0.0],
|
||||
Fac::Roof(k) => self.facets[k].plane,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ein Stück der Band-Oberkante: Achsmass `[a, b]` auf seiner Mittellinie (Versatz `off`, Dicke `th`),
|
||||
/// Schnittlinien, Höhe (`top` = höchster Eckwert) und Ebene.
|
||||
#[derive(Clone, Debug)]
|
||||
struct TopPiece {
|
||||
a: f64,
|
||||
b: f64,
|
||||
cut_a: Option<Line>,
|
||||
cut_b: Option<Line>,
|
||||
off: f64,
|
||||
th: f64,
|
||||
top: f64,
|
||||
plane: Option<[f64; 3]>,
|
||||
joint: [bool; 2],
|
||||
}
|
||||
|
||||
/// Dächer, die eine Wand im Höhenbereich `[zb, zt]` betreffen; `None` = keine (unverändert).
|
||||
fn roof_tops_ctx<'a>(w: &WallIn, ctx: &'a FloorContext, zb: f64, zt: f64) -> Option<Tops<'a>> {
|
||||
if w.roof_attach == Some(false) || ctx.roofs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let wb = wall_bounds(w, w.thickness_safe.max(0.0) + 0.01);
|
||||
let facets: Vec<&RoofFacet> = ctx
|
||||
.roofs
|
||||
.iter()
|
||||
.filter(|(r, rb)| r.eaves_z + 50.0 >= zb && bounds_overlap(wb, *rb))
|
||||
.flat_map(|(r, _)| r.facets.iter())
|
||||
.filter(|f| bounds_overlap(wb, Bounds { min_x: f.bounds[0], min_y: f.bounds[1], max_x: f.bounds[2], max_y: f.bounds[3] }))
|
||||
.collect();
|
||||
if facets.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Verlängern nur, wo der Höhenbereich bis zur Wandkrone reicht (nicht unter einer Decke).
|
||||
let zt_cap = if w.roof_attach == Some(true) && (zt - w.z_top).abs() < EPS { facets.iter().map(|f| f.z_max()).fold(zt, f64::max) } else { zt };
|
||||
Some(Tops { facets, zb, zt_free: zt, zt_cap })
|
||||
}
|
||||
|
||||
/// Ecken der Grundfläche eines Bandstücks (aussen +n, innen −n) an den Schnittlinien.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn strip_corners(w: &WallIn, u: Vec2, n: Vec2, off: f64, th: f64, a: f64, b: f64, cut_a: Option<Line>, cut_b: Option<Line>) -> [Vec2; 4] {
|
||||
let base = add(w.start, scale(n, off));
|
||||
let at = |s: f64, o: f64, cut: Option<Line>| {
|
||||
let q = add(add(base, scale(u, s)), scale(n, o));
|
||||
cut.and_then(|c| line_intersect(q, u, c.point, c.dir)).filter(|r| r.x.is_finite() && r.y.is_finite()).unwrap_or(q)
|
||||
};
|
||||
let mut cuts = vec![a];
|
||||
for r in 0..runs.len().saturating_sub(1) {
|
||||
let l1 = line(runs[r]);
|
||||
let l2 = line(runs[r + 1]);
|
||||
let lo = ts[runs[r].1 - 1];
|
||||
let hi = ts[count.min(runs[r].1 + 1)];
|
||||
let mut x = ts[runs[r].1];
|
||||
if (l1.0 - l2.0).abs() > 1e-9 {
|
||||
let cx = (l2.1 - l1.1) / (l1.0 - l2.0);
|
||||
if cx >= lo && cx <= hi {
|
||||
x = cx;
|
||||
}
|
||||
}
|
||||
cuts.push(x);
|
||||
let h = th / 2.0;
|
||||
[at(a, h, cut_a), at(b, h, cut_b), at(b, -h, cut_b), at(a, -h, cut_a)]
|
||||
}
|
||||
|
||||
/// Oberkante eines Bandstreifens `[a, b]` (Mittellinie `off`, Dicke `th`) unter den Dächern `t`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn strip_tops(w: &WallIn, t: &Tops, u: Vec2, n: Vec2, off: f64, th: f64, a: f64, b: f64, cut_a: Option<Line>, cut_b: Option<Line>, joint: [bool; 2], depth: u32, out: &mut Vec<TopPiece>) {
|
||||
if !(b - a > EPS) || !(th > 0.0) {
|
||||
return;
|
||||
}
|
||||
cuts.push(bb);
|
||||
for (k, &r) in runs.iter().enumerate() {
|
||||
let (sa, sb) = (cuts[k], cuts[k + 1]);
|
||||
if sb - sa <= EPS {
|
||||
let base = add(w.start, scale(n, off));
|
||||
let pt = |s: f64| add(base, scale(u, s));
|
||||
let steps = 8usize.max(((b - a) / ROOF_SAMPLE).ceil() as usize).min(20_000);
|
||||
let ts: Vec<f64> = (0..=steps).map(|i| if i == steps { b } else { a + (b - a) * i as f64 / steps as f64 }).collect();
|
||||
let inner = |s: f64| s.clamp(a + 1e-6, b - 1e-6);
|
||||
let fac: Vec<Fac> = ts.iter().map(|&s| t.at(pt(inner(s)))).collect();
|
||||
// Läufe gleicher Bereiche und die Grenzen dazwischen (Achsmass, Schnittlinie).
|
||||
let mut runs: Vec<(Fac, f64, Option<Line>)> = vec![(fac[0], a, cut_a)];
|
||||
for i in 1..=steps {
|
||||
let last = runs.last().map_or(fac[0], |r| r.0);
|
||||
if fac[i] == last {
|
||||
continue;
|
||||
}
|
||||
let value_at = |x: f64| {
|
||||
let l = line(r);
|
||||
zt.min(zb.max(l.0 * x + l.1))
|
||||
let (fa, fb) = (fac[i - 1], fac[i]);
|
||||
// Wechselstelle auf der Mittellinie (Bisektion), dann die exakte Grenzlinie beider Ebenen.
|
||||
let (mut lo, mut hi) = (ts[i - 1], ts[i]);
|
||||
for _ in 0..50 {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if t.at(pt(inner(mid))) == fa {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
let sm = (lo + hi) / 2.0;
|
||||
let p = pt(sm);
|
||||
let (ca, cb) = (t.coef(fa), t.coef(fb));
|
||||
let d = [ca[0] - cb[0], ca[1] - cb[1], ca[2] - cb[2]];
|
||||
let g = js_hypot(d[1], d[2]);
|
||||
let mut line = None;
|
||||
if g > 1e-9 {
|
||||
let dist = (d[0] + d[1] * p.x + d[2] * p.y) / g;
|
||||
let dir = Vec2::new(-d[2] / g, d[1] / g);
|
||||
// Nur, wenn die Grenze wirklich hier liegt (sonst Sprung, z. B. Traufe) und quer genug steht.
|
||||
if dist.abs() < 0.02 && (dir.x * u.y - dir.y * u.x).abs() > 0.17 {
|
||||
line = Some(Line { point: Vec2::new(p.x - d[1] / g * dist, p.y - d[2] / g * dist), dir });
|
||||
}
|
||||
}
|
||||
let prev = runs.last().map_or(a, |r| r.1);
|
||||
let s_cut = line.and_then(|l| band_cut_distance(w, u, n, off, &l)).filter(|x| x.is_finite()).unwrap_or(sm).clamp(prev, b);
|
||||
runs.push((fb, s_cut, line));
|
||||
}
|
||||
let k_last = runs.len() - 1;
|
||||
for k in 0..runs.len() {
|
||||
let (f, s0, c0) = runs[k];
|
||||
let (s1, c1) = if k < k_last { (runs[k + 1].1, runs[k + 1].2) } else { (b, cut_b) };
|
||||
if !(s1 - s0 > EPS) {
|
||||
continue;
|
||||
}
|
||||
let jt = [if k == 0 { joint[0] } else { true }, if k == k_last { joint[1] } else { true }];
|
||||
// Seitlich: läuft eine Grenze längs durchs Band (Kanten sehen einen anderen Bereich)?
|
||||
if depth < 3 && th > 0.004 {
|
||||
let mut other = None;
|
||||
'edges: for side in [1.0, -1.0] {
|
||||
let eo = side * (th / 2.0 - 1e-4);
|
||||
let e_lo = c0.and_then(|l| band_cut_distance(w, u, n, off + eo, &l)).unwrap_or(s0);
|
||||
let e_hi = c1.and_then(|l| band_cut_distance(w, u, n, off + eo, &l)).unwrap_or(s1);
|
||||
if !(e_hi - e_lo > 4.0 * EPS) {
|
||||
continue;
|
||||
}
|
||||
let m = 4usize.max(((e_hi - e_lo) / ROOF_SAMPLE).ceil() as usize).min(20_000);
|
||||
for j in 0..m {
|
||||
let s = e_lo + (e_hi - e_lo) * (j as f64 + 0.5) / m as f64;
|
||||
let fe = t.at(add(pt(s), scale(n, eo)));
|
||||
if fe != f {
|
||||
other = Some(fe);
|
||||
break 'edges;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(fo) = other {
|
||||
let (ca, cb) = (t.coef(f), t.coef(fo));
|
||||
let d = [ca[0] - cb[0], ca[1] - cb[1], ca[2] - cb[2]];
|
||||
let mid = pt((s0 + s1) / 2.0);
|
||||
let den = d[1] * n.x + d[2] * n.y;
|
||||
if den.abs() > 1e-9 {
|
||||
let o = -(d[0] + d[1] * mid.x + d[2] * mid.y) / den;
|
||||
if o.abs() < th / 2.0 - 1e-3 {
|
||||
for (lo_o, hi_o) in [(-th / 2.0, o), (o, th / 2.0)] {
|
||||
let c = off + (lo_o + hi_o) / 2.0;
|
||||
let sa = c0.and_then(|l| band_cut_distance(w, u, n, c, &l)).unwrap_or(s0);
|
||||
let sb = c1.and_then(|l| band_cut_distance(w, u, n, c, &l)).unwrap_or(s1);
|
||||
strip_tops(w, t, u, n, c, hi_o - lo_o, sa, sb, c0, c1, jt, depth + 1, out);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let (plane, top) = match f {
|
||||
Fac::Floor => continue,
|
||||
Fac::Free => (None, t.zt_free),
|
||||
Fac::Cap => (None, t.zt_cap),
|
||||
Fac::Roof(_) => {
|
||||
let c = t.coef(f);
|
||||
let zmax = strip_corners(w, u, n, off, th, s0, s1, c0, c1).iter().map(|q| c[0] + c[1] * q.x + c[2] * q.y).fold(f64::NEG_INFINITY, f64::max);
|
||||
(Some(c), zmax.min(t.zt_cap).max(t.zb))
|
||||
}
|
||||
};
|
||||
let (z0, z1) = (value_at(sa), value_at(sb));
|
||||
if z0.max(z1) - zb > EPS {
|
||||
emit(sa, sb, zb, z0, z1);
|
||||
out.push(TopPiece { a: s0, b: s1, cut_a: c0, cut_b: c1, off, th, top, plane, joint: jt });
|
||||
}
|
||||
}
|
||||
|
||||
/// Oberkante eines Bandstücks unter den Dächern; `None`, wenn kein Dach die Wand betrifft (dann
|
||||
/// unverändert ein Körper auf der Krone).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn roof_tops(w: &WallIn, ctx: &FloorContext, u: Vec2, n: Vec2, off: f64, th: f64, a: f64, b: f64, cut_a: Option<Line>, cut_b: Option<Line>, zb: f64, zt: f64) -> Option<Vec<TopPiece>> {
|
||||
if zt - zb <= EPS || b - a <= EPS {
|
||||
return None;
|
||||
}
|
||||
let t = roof_tops_ctx(w, ctx, zb, zt)?;
|
||||
let mut out = Vec::new();
|
||||
strip_tops(w, &t, u, n, off, th, a, b, cut_a, cut_b, [false; 2], 0, &mut out);
|
||||
// Nichts geteilt, nichts geneigt: wie ohne Dach.
|
||||
if out.len() == 1 && out[0].plane.is_none() && out[0].top == zt && out[0].th == th && out[0].a == a && out[0].b == b {
|
||||
return None;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Löcher eines Bandkörpers ab `a` (Achsmass) im Höhenbereich `[zb, zt]`, mit Schichteinzug.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn band_holes(w: &WallIn, li: usize, cutouts: &[OpeningIn], innermost: bool, recess: f64, a: f64, zb: f64, zt: f64) -> Vec<[f64; 4]> {
|
||||
let reveals = &w.reveals;
|
||||
cutouts
|
||||
.iter()
|
||||
.filter(|h| h.z_top > zb + EPS && h.z_bottom < zt - EPS)
|
||||
.map(|h| {
|
||||
if let Some(s) = reveals.iter().find(|r| r.of(h)).and_then(|r| r.shifts.get(li)) {
|
||||
[h.from - a - s[0], h.to - a + s[1], h.z_bottom - s[3], h.z_top + s[2]]
|
||||
} else if innermost && h.recess_inner_layer {
|
||||
[h.from - a - recess, h.to - a + recess, h.z_bottom - recess, h.z_top + recess]
|
||||
} else {
|
||||
[h.from - a, h.to - a, h.z_bottom, h.z_top]
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Ein Körper aus einem Oberkanten-Stück: Achsmass `[x0, x1]` relativ zu `tp.a`, Höhe `[zb, top]`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn push_top_piece(em: &mut Emitter, li: usize, band_th: f64, tp: &TopPiece, x0: f64, x1: f64, zb: f64, top: f64, plane: Option<[f64; 3]>, holes: Vec<[f64; 4]>) {
|
||||
let len = tp.b - tp.a;
|
||||
let first = x0 <= EPS;
|
||||
let last = x1 >= len - EPS;
|
||||
let before = em.out.len();
|
||||
em.push(li, tp.a + x0, tp.a + x1, zb, top, tp.off, holes, [0.0, 0.0]);
|
||||
let Some(pc) = em.out.get_mut(before) else { return };
|
||||
pc.start_cut = if first { tp.cut_a } else { None };
|
||||
pc.end_cut = if last { tp.cut_b } else { None };
|
||||
pc.joint = [if first { tp.joint[0] } else { true }, if last { tp.joint[1] } else { true }];
|
||||
if (tp.th - band_th).abs() > 1e-12 {
|
||||
pc.thickness = Some(tp.th);
|
||||
}
|
||||
if let Some(c) = plane {
|
||||
pc.top_plane = Some(c);
|
||||
let at = |q: Vec2| c[0] + c[1] * q.x + c[2] * q.y;
|
||||
let d = [top - at(pc.start), top - at(pc.end)];
|
||||
pc.top_drop = (d[0] > EPS || d[1] > EPS).then_some(d);
|
||||
}
|
||||
}
|
||||
|
||||
/// Körper eines Oberkanten-Stücks; unter einer Dachfläche ohne Löcher (Pfeiler, Brüstung, Sturz je mit
|
||||
/// eigener ebener Oberkante statt Treppung).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn emit_top_piece(em: &mut Emitter, li: usize, band_th: f64, tp: &TopPiece, u: Vec2, n: Vec2, zb: f64, cutouts: &[OpeningIn], innermost: bool, recess: f64) {
|
||||
let w = em.w;
|
||||
let holes = if w.layered { band_holes(w, li, cutouts, innermost, recess, tp.a, zb, tp.top) } else { Vec::new() };
|
||||
let len = tp.b - tp.a;
|
||||
let Some(c) = tp.plane else {
|
||||
push_top_piece(em, li, band_th, tp, 0.0, len, zb, tp.top, None, holes);
|
||||
return;
|
||||
};
|
||||
if holes.is_empty() {
|
||||
push_top_piece(em, li, band_th, tp, 0.0, len, zb, tp.top, Some(c), holes);
|
||||
return;
|
||||
}
|
||||
let mut xs = vec![0.0, len];
|
||||
for h in &holes {
|
||||
for x in [h[0], h[1]] {
|
||||
if x > EPS && x < len - EPS {
|
||||
xs.push(x);
|
||||
}
|
||||
}
|
||||
}
|
||||
xs.sort_by(|p, q| p.total_cmp(q));
|
||||
xs.dedup_by(|p, q| (*p - *q).abs() <= EPS);
|
||||
for i in 0..xs.len() - 1 {
|
||||
let (x0, x1) = (xs[i], xs[i + 1]);
|
||||
if x1 - x0 <= EPS {
|
||||
continue;
|
||||
}
|
||||
let mid = (x0 + x1) / 2.0;
|
||||
let mut zs: Vec<[f64; 2]> = holes.iter().filter(|h| h[0] <= mid && h[1] >= mid).map(|h| [h[2], h[3]]).collect();
|
||||
zs.sort_by(|p, q| p[0].total_cmp(&q[0]));
|
||||
let mut cur = zb;
|
||||
for [h0, h1] in zs {
|
||||
if h0 > cur + EPS {
|
||||
push_top_piece(em, li, band_th, tp, x0, x1, cur, h0, None, Vec::new());
|
||||
}
|
||||
cur = cur.max(h1);
|
||||
}
|
||||
let ca = if x0 <= EPS { tp.cut_a } else { None };
|
||||
let cb = if x1 >= len - EPS { tp.cut_b } else { None };
|
||||
let zc: Vec<f64> = strip_corners(w, u, n, tp.off, tp.th, tp.a + x0, tp.a + x1, ca, cb).iter().map(|q| c[0] + c[1] * q.x + c[2] * q.y).collect();
|
||||
let (zmin, zmax) = (zc.iter().copied().fold(f64::INFINITY, f64::min), zc.iter().copied().fold(f64::NEG_INFINITY, f64::max));
|
||||
// Sturz/Pfeiler bis unter die Dachfläche (Fenster, das ins Dach ragt: der Rest entfällt).
|
||||
if zmin > cur + EPS {
|
||||
push_top_piece(em, li, band_th, tp, x0, x1, cur, zmax.min(tp.top), Some(c), Vec::new());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -599,9 +936,20 @@ pub fn wall_bands(w: &WallIn, ctx: &FloorContext) -> Vec<Piece> {
|
||||
|
||||
if !w.layered {
|
||||
// Schnitt-Pfad: Pfeiler/Brüstung/Sturz, je Segment alle Bänder.
|
||||
// Unter Dächern ([G2]) je Segment die exakte Oberkante.
|
||||
let u = Vec2::new((w.end.x - w.start.x) / axis_len, (w.end.y - w.start.y) / axis_len);
|
||||
let n = left_normal(u);
|
||||
let seg = |em: &mut Emitter, from: f64, to: f64, zb: f64, zt: f64| {
|
||||
for (i, &off) in offsets.iter().enumerate() {
|
||||
em.push(i, from, to, zb, zt, off, vec![], [0.0, 0.0]);
|
||||
let th = w.bands[i].thickness;
|
||||
match roof_tops(w, ctx, u, n, off, th, from, to, None, None, zb, zt) {
|
||||
None => em.push(i, from, to, zb, zt, off, vec![], [0.0, 0.0]),
|
||||
Some(tops) => {
|
||||
for tp in &tops {
|
||||
emit_top_piece(em, i, th, tp, u, n, zb, &[], false, 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if cutouts.is_empty() {
|
||||
@@ -696,8 +1044,14 @@ pub fn wall_bands(w: &WallIn, ctx: &FloorContext) -> Vec<Piece> {
|
||||
let recess = b.thickness;
|
||||
for ([a, bb], cut_a, cut_b) in axis_pieces {
|
||||
let n0 = em.out.len();
|
||||
let mut emit_piece = |a: f64, bb: f64, zb: f64, zt_start: f64, zt_end: f64| {
|
||||
emit_band_piece(&mut em, li, off, &cutouts, innermost, recess, a, bb, zb, zt_start, zt_end);
|
||||
let th = b.thickness;
|
||||
let mut emit_piece = |a: f64, bb: f64, ca: Option<Line>, cb: Option<Line>, zb: f64, zt: f64| match roof_tops(w, ctx, u, n, off, th, a, bb, ca, cb, zb, zt) {
|
||||
None => emit_band_piece(&mut em, li, off, &cutouts, innermost, recess, a, bb, zb, zt),
|
||||
Some(tops) => {
|
||||
for tp in &tops {
|
||||
emit_top_piece(&mut em, li, th, tp, u, n, zb, &cutouts, innermost, recess);
|
||||
}
|
||||
}
|
||||
};
|
||||
let local: Vec<[f64; 4]> = band_z_cuts
|
||||
.iter()
|
||||
@@ -705,7 +1059,7 @@ pub fn wall_bands(w: &WallIn, ctx: &FloorContext) -> Vec<Piece> {
|
||||
.filter(|c| c[1] > c[0] + EPS)
|
||||
.collect();
|
||||
if local.is_empty() {
|
||||
clip_to_roofs(w, ctx, u, n, off, a, bb, z_bottom, z_top, &mut emit_piece);
|
||||
emit_piece(a, bb, cut_a, cut_b, z_bottom, z_top);
|
||||
set_piece_cuts(&mut em.out[n0..], w, u, a, bb, cut_a, cut_b);
|
||||
continue;
|
||||
}
|
||||
@@ -724,7 +1078,7 @@ pub fn wall_bands(w: &WallIn, ctx: &FloorContext) -> Vec<Piece> {
|
||||
let mid = (xa + xb) / 2.0;
|
||||
let z_cutters: Vec<[f64; 2]> = local.iter().filter(|c| c[0] <= mid && c[1] >= mid).map(|c| [c[2], c[3]]).collect();
|
||||
for [zb, zt] in terminate_or_subtract(z_bottom, z_top, &z_cutters, w.termination) {
|
||||
clip_to_roofs(w, ctx, u, n, off, xa, xb, zb, zt, &mut emit_piece);
|
||||
emit_piece(xa, xb, if xa == a { cut_a } else { None }, if xb == bb { cut_b } else { None }, zb, zt);
|
||||
}
|
||||
}
|
||||
set_piece_cuts(&mut em.out[n0..], w, u, a, bb, cut_a, cut_b);
|
||||
@@ -781,35 +1135,11 @@ fn reveal_pieces(em: &mut Emitter, offsets: &[f64]) {
|
||||
/// Ein Körper eines Bands im layered-Pfad: Öffnungs-Löcher auf den Körper-Start umrechnen (an der
|
||||
/// innersten Schicht mit Laibungs-Rücksprung geweitet); schräge Oberkante mit Löchern geht in
|
||||
/// render3d nicht → gestuft annähern.
|
||||
/// Körper eines Bandstücks ohne Dach darüber (waagrechte Krone, Öffnungen als Löcher).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn emit_band_piece(em: &mut Emitter, li: usize, off: f64, cutouts: &[OpeningIn], innermost: bool, recess: f64, a: f64, bb: f64, zb: f64, zt_start: f64, zt_end: f64) {
|
||||
let zt = zt_start.max(zt_end);
|
||||
let reveals = &em.w.reveals;
|
||||
let holes: Vec<[f64; 4]> = cutouts
|
||||
.iter()
|
||||
.filter(|h| h.z_top > zb + EPS && h.z_bottom < zt - EPS)
|
||||
.map(|h| {
|
||||
if let Some(s) = reveals.iter().find(|r| r.of(h)).and_then(|r| r.shifts.get(li)) {
|
||||
// [106]: Schicht springt je Seite zurück.
|
||||
[h.from - a - s[0], h.to - a + s[1], h.z_bottom - s[3], h.z_top + s[2]]
|
||||
} else if innermost && h.recess_inner_layer {
|
||||
[h.from - a - recess, h.to - a + recess, h.z_bottom - recess, h.z_top + recess]
|
||||
} else {
|
||||
[h.from - a, h.to - a, h.z_bottom, h.z_top]
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if !holes.is_empty() && (zt_start - zt_end).abs() > EPS {
|
||||
let k = 1usize.max(((bb - a) / ROOF_CLIP_STEP).ceil() as usize);
|
||||
for i in 0..k {
|
||||
let sa = a + ((bb - a) * i as f64) / k as f64;
|
||||
let sb = a + ((bb - a) * (i + 1) as f64) / k as f64;
|
||||
let zm = zt_start + ((zt_end - zt_start) * (i as f64 + 0.5)) / k as f64;
|
||||
emit_band_piece(em, li, off, cutouts, innermost, recess, sa, sb, zb, zm, zm);
|
||||
}
|
||||
return;
|
||||
}
|
||||
em.push(li, a, bb, zb, zt, off, holes, [zt - zt_start, zt - zt_end]);
|
||||
fn emit_band_piece(em: &mut Emitter, li: usize, off: f64, cutouts: &[OpeningIn], innermost: bool, recess: f64, a: f64, bb: f64, zb: f64, zt: f64) {
|
||||
let holes = band_holes(em.w, li, cutouts, innermost, recess, a, zb, zt);
|
||||
em.push(li, a, bb, zb, zt, off, holes, [0.0, 0.0]);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -832,6 +1162,7 @@ mod tests {
|
||||
openings: vec![],
|
||||
cuts: WallCuts::default(),
|
||||
reveals: vec![],
|
||||
roof_attach: None,
|
||||
}
|
||||
}
|
||||
fn band(t: f64, p: f64) -> BandIn {
|
||||
@@ -844,9 +1175,6 @@ mod tests {
|
||||
wall_bands(w, &FloorContext::default())
|
||||
}
|
||||
/// Achsen-Länge eines Körpers.
|
||||
fn plen(p: &Piece) -> f64 {
|
||||
js_hypot(p.end.x - p.start.x, p.end.y - p.start.y)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schichten_gestapelt_und_referenzversetzt() {
|
||||
@@ -1093,7 +1421,7 @@ mod tests {
|
||||
w.z_top = 5.0;
|
||||
// Ebene z = 2 + 0.5·x über [−1, 5]².
|
||||
let plane = vec![[-1.0, -1.0, 1.5], [5.0, -1.0, 4.5], [5.0, 5.0, 4.5], [-1.0, 5.0, 1.5]];
|
||||
let roof = RoofIn { eaves_z: 1.5, total_thickness: 0.0, eaves: plane.iter().map(|p| [p[0], p[1]]).collect(), planes: vec![plane] };
|
||||
let roof = RoofIn::new(1.5, 0.0, plane.iter().map(|p| [p[0], p[1]]).collect(), vec![plane]);
|
||||
let ctx = FloorContext::new(vec![], vec![roof]);
|
||||
let p = wall_bands(&w, &ctx);
|
||||
assert_eq!(p.len(), 1, "{p:?}");
|
||||
@@ -1101,12 +1429,172 @@ mod tests {
|
||||
// Abtastung 1 mm innerhalb der Enden (wie TS) → Toleranz 1e-3.
|
||||
let near = |a: f64, b: f64| (a - b).abs() < 1e-3;
|
||||
assert!(near(p[0].z_top, 4.0) && near(d[0], 2.0) && d[1] == 0.0, "{p:?}");
|
||||
// Mit Öffnung: gestuft, ohne top_drop.
|
||||
// Mit Öffnung ([G2]): Pfeiler und Sturz mit schräger Oberkante statt Treppung.
|
||||
w.openings.push(OpeningIn { from: 1.0, to: 2.0, z_bottom: 0.0, z_top: 2.0, recess_inner_layer: false });
|
||||
let p = wall_bands(&w, &ctx);
|
||||
assert!(p.len() > 10 && p.iter().all(|q| q.top_drop.is_none()));
|
||||
let total: f64 = p.iter().map(plen).sum();
|
||||
assert!(close(total, 4.0));
|
||||
assert!(p.len() == 3 && p.iter().all(|q| q.holes.is_empty() && q.top_plane.is_some()), "{p:?}");
|
||||
let vol: f64 = p.iter().map(|q| volume(&w, q)).sum();
|
||||
assert!((vol - 2.0).abs() < 1e-9, "{vol}");
|
||||
}
|
||||
|
||||
// ── [G2] Wand an Dach: exakte Oberkante je Schicht ──────────────────────────
|
||||
|
||||
/// Satteldach über [-1, 9] × [-1, 7], First bei y = 3 (längs x), Traufe z = 3, Neigung 45°.
|
||||
fn gable(total: f64) -> RoofIn {
|
||||
let s = vec![[-1.0, -1.0, 3.0], [9.0, -1.0, 3.0], [9.0, 3.0, 7.0], [-1.0, 3.0, 7.0]];
|
||||
let n = vec![[-1.0, 3.0, 7.0], [9.0, 3.0, 7.0], [9.0, 7.0, 3.0], [-1.0, 7.0, 3.0]];
|
||||
RoofIn::new(3.0, total, vec![[-1.0, -1.0], [9.0, -1.0], [9.0, 7.0], [-1.0, 7.0]], vec![s, n])
|
||||
}
|
||||
|
||||
/// Unterkante des Satteldachs (Dicke `t` senkrecht zur Fläche, 45° ⇒ lotrecht t·√2).
|
||||
fn gable_under(t: f64, y: f64) -> f64 {
|
||||
7.0 - (y - 3.0).abs() - t * 2f64.sqrt()
|
||||
}
|
||||
|
||||
/// Ecken einer Band-Grundfläche (mit Schnittlinien, Eigendicke).
|
||||
fn corners(w: &WallIn, p: &Piece) -> [Vec2; 4] {
|
||||
let u = sub(w.end, w.start);
|
||||
let u = scale(u, 1.0 / js_hypot(u.x, u.y));
|
||||
let n = left_normal(u);
|
||||
let h = p.thickness.unwrap_or(w.bands[p.band].thickness) / 2.0;
|
||||
let clip = |base: Vec2, c: Option<Line>| c.and_then(|c| line_intersect(base, u, c.point, c.dir)).unwrap_or(base);
|
||||
[clip(add(p.start, scale(n, h)), p.start_cut), clip(add(p.end, scale(n, h)), p.end_cut), clip(add(p.end, scale(n, -h)), p.end_cut), clip(add(p.start, scale(n, -h)), p.start_cut)]
|
||||
}
|
||||
|
||||
fn top_at(p: &Piece, q: Vec2) -> f64 {
|
||||
p.top_plane.map_or(p.z_top, |c| c[0] + c[1] * q.x + c[2] * q.y)
|
||||
}
|
||||
|
||||
/// Volumen eines Körpers: Grundfläche × Höhe im Schwerpunkt (exakt bei ebener Oberkante), ohne Löcher.
|
||||
fn volume(w: &WallIn, p: &Piece) -> f64 {
|
||||
let q = corners(w, p);
|
||||
let mut a = 0.0;
|
||||
let (mut cx, mut cy) = (0.0, 0.0);
|
||||
for i in 0..4 {
|
||||
let (p0, p1) = (q[i], q[(i + 1) % 4]);
|
||||
let c = p0.x * p1.y - p1.x * p0.y;
|
||||
a += c;
|
||||
cx += (p0.x + p1.x) * c;
|
||||
cy += (p0.y + p1.y) * c;
|
||||
}
|
||||
if a.abs() < 1e-15 {
|
||||
return 0.0;
|
||||
}
|
||||
let c = Vec2::new(cx / (3.0 * a), cy / (3.0 * a));
|
||||
let holes: f64 = p.holes.iter().map(|h| (h[1] - h[0]) * (h[3] - h[2])).sum::<f64>() * p.thickness.unwrap_or(w.bands[p.band].thickness);
|
||||
(a / 2.0).abs() * (top_at(p, c) - p.z_bottom) - holes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn giebelwand_folgt_beiden_dachflaechen_je_schicht() {
|
||||
// Giebelwand quer zum First (x = 0, y 0 → 6), zwei Schichten, Oberkante weit über dem Dach.
|
||||
let mut w = base((0.0, 0.0), (0.0, 6.0), vec![band(0.1, 10.0), band(0.2, 50.0)]);
|
||||
w.z_top = 9.0;
|
||||
let ctx = FloorContext::new(vec![], vec![gable(0.2)]);
|
||||
let p = wall_bands(&w, &ctx);
|
||||
// Je Schicht zwei Körper (links/rechts vom First), beide mit ebener Oberkante.
|
||||
assert_eq!(p.len(), 4, "{p:?}");
|
||||
for q in &p {
|
||||
assert!(q.top_plane.is_some() && q.holes.is_empty(), "{q:?}");
|
||||
for c in corners(&w, q) {
|
||||
assert!((top_at(q, c) - gable_under(0.2, c.y)).abs() < 1e-9, "Ecke {c:?} {q:?}");
|
||||
}
|
||||
}
|
||||
// Volumen = Fläche unter der Unterkante × Dicke (Fünfeck), exakt.
|
||||
let vol: f64 = p.iter().map(|q| volume(&w, q)).sum();
|
||||
let h0 = gable_under(0.2, 0.0);
|
||||
let h1 = gable_under(0.2, 3.0);
|
||||
let expect = 0.3 * (6.0 * h0 + 3.0 * (h1 - h0));
|
||||
assert!((vol - expect).abs() < 1e-9, "{vol} vs {expect}");
|
||||
// Innere Stossfuge am First: keine sichtbare Stirn.
|
||||
assert!(p.iter().filter(|q| q.joint[0] || q.joint[1]).count() == 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traufwand_schraeg_ueber_die_dicke_und_seitlich_geteilt() {
|
||||
// Traufwand längs x bei y = 0.5 (Dicke 0.3: y 0.35 … 0.65), Dach steigt quer zur Wand.
|
||||
let mut w = base((0.0, 0.5), (8.0, 0.5), vec![band(0.3, 50.0)]);
|
||||
w.z_top = 9.0;
|
||||
let ctx = FloorContext::new(vec![], vec![gable(0.0)]);
|
||||
let p = wall_bands(&w, &ctx);
|
||||
assert_eq!(p.len(), 1, "{p:?}");
|
||||
let c = p[0].top_plane.unwrap();
|
||||
assert!(c[1].abs() < 1e-12 && (c[2] - 1.0).abs() < 1e-12, "Oberkante steigt mit y: {c:?}");
|
||||
for k in corners(&w, &p[0]) {
|
||||
assert!((top_at(&p[0], k) - gable_under(0.0, k.y)).abs() < 1e-9);
|
||||
}
|
||||
// Wandkrone 4.5 schneidet die Unterkante in der Dicke (y = 0.5): zwei Streifen nebeneinander.
|
||||
w.z_top = 4.5;
|
||||
let p = wall_bands(&w, &ctx);
|
||||
assert_eq!(p.len(), 2, "{p:?}");
|
||||
let vol: f64 = p.iter().map(|q| volume(&w, q)).sum();
|
||||
// Aussen (y 0.35 … 0.5) schräg 4.35 … 4.5, innen flach 4.5.
|
||||
let expect = 8.0 * (0.15 * (4.35 + 4.5) / 2.0 + 0.15 * 4.5);
|
||||
assert!((vol - expect).abs() < 1e-9, "{vol} vs {expect}");
|
||||
assert!(p.iter().all(|q| q.thickness.is_some_and(|t| (t - 0.15).abs() < 1e-9)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wand_mit_fenster_unter_dachschraege_ohne_treppung() {
|
||||
let mut w = base((0.0, 0.0), (0.0, 6.0), vec![band(0.2, 50.0)]);
|
||||
w.z_top = 9.0;
|
||||
w.openings.push(OpeningIn { from: 1.0, to: 2.0, z_bottom: 1.0, z_top: 2.5, recess_inner_layer: false });
|
||||
let ctx = FloorContext::new(vec![], vec![gable(0.0)]);
|
||||
let p = wall_bands(&w, &ctx);
|
||||
// Pfeiler, Brüstung, Sturz, Pfeiler bis zum First, Pfeiler danach: keine Treppen, keine Löcher.
|
||||
assert!(p.len() <= 6 && p.iter().all(|q| q.holes.is_empty()), "{p:?}");
|
||||
let vol: f64 = p.iter().map(|q| volume(&w, q)).sum();
|
||||
let gross = 0.2 * (6.0 * 4.0 + 3.0 * 3.0);
|
||||
assert!((vol - (gross - 0.2 * 1.5)).abs() < 1e-9, "{vol}");
|
||||
for q in &p {
|
||||
for c in corners(&w, q) {
|
||||
assert!(top_at(q, c) <= gable_under(0.0, c.y) + 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_dach_anschliessen_verlaengert_oder_ignoriert() {
|
||||
// Wandkrone 2.5 unter der Traufe: automatisch unverändert.
|
||||
let mut w = base((0.0, 0.0), (0.0, 6.0), vec![band(0.2, 50.0)]);
|
||||
w.z_top = 2.5;
|
||||
let ctx = FloorContext::new(vec![], vec![gable(0.0)]);
|
||||
let p = wall_bands(&w, &ctx);
|
||||
assert!(p.len() == 1 && p[0].top_plane.is_none() && close(p[0].z_top, 2.5));
|
||||
// An Dach anschliessen: bis unter die Dachfläche verlängert.
|
||||
w.roof_attach = Some(true);
|
||||
let p = wall_bands(&w, &ctx);
|
||||
let vol: f64 = p.iter().map(|q| volume(&w, q)).sum();
|
||||
assert!((vol - 0.2 * (6.0 * 4.0 + 9.0)).abs() < 1e-9, "{vol} {p:?}");
|
||||
// Nie: Wand bleibt durchgehend, auch wenn sie über das Dach ragt.
|
||||
w.roof_attach = Some(false);
|
||||
w.z_top = 9.0;
|
||||
let p = wall_bands(&w, &ctx);
|
||||
assert!(p.len() == 1 && close(p[0].z_top, 9.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kehle_zweier_daecher_nimmt_die_obere_huelle() {
|
||||
// Zwei Pultdächer überdecken sich: Unterkante = obere Hülle (Maximum) der beiden.
|
||||
let a = RoofIn::new(0.0, 0.0, vec![], vec![vec![[0.0, -1.0, 2.0], [6.0, -1.0, 5.0], [6.0, 1.0, 5.0], [0.0, 1.0, 2.0]]]);
|
||||
let b = RoofIn::new(0.0, 0.0, vec![], vec![vec![[0.0, -1.0, 5.0], [6.0, -1.0, 2.0], [6.0, 1.0, 2.0], [0.0, 1.0, 5.0]]]);
|
||||
let mut w = base((0.0, 0.0), (6.0, 0.0), vec![band(0.2, 50.0)]);
|
||||
w.z_top = 9.0;
|
||||
let p = wall_bands(&w, &FloorContext::new(vec![], vec![a, b]));
|
||||
assert_eq!(p.len(), 2, "{p:?}");
|
||||
let vol: f64 = p.iter().map(|q| volume(&w, q)).sum();
|
||||
assert!((vol - 0.2 * 25.5).abs() < 1e-9, "{vol}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schnitt_pfad_schneidet_ebenfalls_am_dach() {
|
||||
let mut w = base((0.0, 0.0), (0.0, 6.0), vec![band(0.3, 50.0)]);
|
||||
w.z_top = 9.0;
|
||||
w.layered = false;
|
||||
w.openings.push(OpeningIn { from: 1.0, to: 2.0, z_bottom: 1.0, z_top: 2.5, recess_inner_layer: false });
|
||||
let p = wall_bands(&w, &FloorContext::new(vec![], vec![gable(0.0)]));
|
||||
let vol: f64 = p.iter().map(|q| volume(&w, q)).sum();
|
||||
assert!((vol - 0.3 * (6.0 * 4.0 + 9.0 - 1.5)).abs() < 1e-9, "{vol}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1122,7 +1610,7 @@ mod tests {
|
||||
w.bands.push(band(0.0, 1.0));
|
||||
let ctx = FloorContext::new(
|
||||
vec![CeilingIn { z_bottom: 0.5, z_top: 0.5, outline: vec![Vec2::new(0.0, 0.0); 3], layers: Some(vec![]) }],
|
||||
vec![RoofIn { eaves_z: 0.0, total_thickness: 0.0, eaves: vec![], planes: vec![vec![]] }],
|
||||
vec![RoofIn::new(0.0, 0.0, vec![], vec![vec![]]), RoofIn::new(0.0, f64::NAN, vec![], vec![vec![[0.0, 0.0, f64::NAN], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], vec![[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 2.0]]])],
|
||||
);
|
||||
let _ = wall_bands(&w, &ctx);
|
||||
|
||||
|
||||
@@ -70,3 +70,16 @@ pub fn terrain_from_contours_json(contours_json: &str, id: &str) -> String {
|
||||
let c: Value = serde_json::from_str(contours_json).unwrap_or(Value::Null);
|
||||
crate::cmd_solid::terrain_from_contours(c.as_array().map(Vec::as_slice).unwrap_or(&[]), id).to_string()
|
||||
}
|
||||
|
||||
/// Wie [`terrain_from_contours_json`] mit Optionen ([T6]): `smooth` Glättungsstufen (0–4), `max_edge` grösste
|
||||
/// Kante in m (≤ 0 automatisch), `breaklines` ≠ 0 erzwingt die Konturen als Bruchkanten.
|
||||
#[wasm_bindgen]
|
||||
pub fn terrain_from_contours_opts_json(contours_json: &str, id: &str, smooth: f64, max_edge: f64, breaklines: f64) -> String {
|
||||
let c: Value = serde_json::from_str(contours_json).unwrap_or(Value::Null);
|
||||
let o = crate::terrain::TerrainOpts {
|
||||
smooth: if smooth.is_finite() { smooth.clamp(0.0, 4.0) as u32 } else { 2 },
|
||||
max_edge: if max_edge.is_finite() { max_edge } else { 0.0 },
|
||||
breaklines: breaklines != 0.0,
|
||||
};
|
||||
crate::cmd_solid::terrain_from_contours_with(c.as_array().map(Vec::as_slice).unwrap_or(&[]), id, o).to_string()
|
||||
}
|
||||
@@ -20,6 +20,7 @@ fn l_wall_scene() -> (Vec<WallInput>, Vec<SlabInput>) {
|
||||
// Bruestung 0.8 m, Fensterhoehe 1.0 m (Sturz ab Y-Hoehe 1.8).
|
||||
WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [0.0, 0.0],
|
||||
end: [0.0, 3.0],
|
||||
thickness: 0.2,
|
||||
@@ -42,6 +43,7 @@ fn l_wall_scene() -> (Vec<WallInput>, Vec<SlabInput>) {
|
||||
},
|
||||
WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [0.0, 3.0],
|
||||
end: [3.0, 3.0],
|
||||
thickness: 0.2,
|
||||
@@ -64,6 +66,7 @@ fn l_wall_scene() -> (Vec<WallInput>, Vec<SlabInput>) {
|
||||
// 0.8..1.8), verdeckt darueber/darunter.
|
||||
WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [1.5, 1.2],
|
||||
end: [1.5, 1.8],
|
||||
thickness: 0.2,
|
||||
|
||||
@@ -73,6 +73,7 @@ mod tests {
|
||||
fn wall_x(len: f32, thickness: f32, height: f32) -> WallInput {
|
||||
WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [0.0, 0.0],
|
||||
end: [len, 0.0],
|
||||
thickness,
|
||||
@@ -219,6 +220,7 @@ mod tests {
|
||||
fn wall_x_hatched(len: f32, thickness: f32, height: f32) -> WallInput {
|
||||
WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
hatch: Some(Hatch { pattern: 3, angle: 45.0, scale: 1.0, line_weight: 0.13, top_angle: None }),
|
||||
..wall_x(len, thickness, height)
|
||||
}
|
||||
@@ -277,6 +279,7 @@ mod tests {
|
||||
let a = wall_x_hatched(3.0, 0.2, 2.5); // (0,0) frei .. (3,0) verbunden
|
||||
let b = WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [3.0, 0.0],
|
||||
end: [3.0, 4.0],
|
||||
..wall_x_hatched(4.0, 0.2, 2.5) // (3,0) verbunden .. (3,4) frei
|
||||
@@ -305,6 +308,7 @@ mod tests {
|
||||
wall_x(3.0, 0.2, 2.5),
|
||||
WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [3.0, 0.0],
|
||||
end: [3.0, 4.0],
|
||||
thickness: 0.2,
|
||||
@@ -390,6 +394,7 @@ mod tests {
|
||||
// Auch nicht-achsparallele Waende extrudieren korrekt (nur andere Ecken).
|
||||
let w = WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [0.0, 0.0],
|
||||
end: [2.0, 2.0],
|
||||
thickness: 0.3,
|
||||
@@ -418,6 +423,7 @@ mod tests {
|
||||
// Start == Ende -> keine Richtung -> uebersprungen (kein Absturz).
|
||||
let w = WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [1.0, 1.0],
|
||||
end: [1.0, 1.0],
|
||||
thickness: 0.2,
|
||||
@@ -638,6 +644,7 @@ mod tests {
|
||||
// weder darueber hinaus (Ueberstand) noch darunter (Spalt).
|
||||
let a = WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [0.0, 0.0],
|
||||
end: [3.0, 0.0],
|
||||
thickness: 0.4,
|
||||
@@ -655,6 +662,7 @@ mod tests {
|
||||
};
|
||||
let b = WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [0.0, 0.0],
|
||||
end: [0.0, 3.0],
|
||||
thickness: 0.4,
|
||||
@@ -721,6 +729,7 @@ mod tests {
|
||||
// rechtwinklig. Regressions-Absicherung: keine Panik, stabile Zaehlung.
|
||||
let mk = |s: [f32; 2], e: [f32; 2]| WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: s,
|
||||
end: e,
|
||||
thickness: 0.2,
|
||||
@@ -756,6 +765,7 @@ mod tests {
|
||||
// Geschoss weiterhin auf der 45-Grad-Linie relativ zu SEINER Basis).
|
||||
let mk = |s: [f32; 2], e: [f32; 2], base: f32| WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: s,
|
||||
end: e,
|
||||
thickness: 0.4,
|
||||
@@ -851,6 +861,7 @@ mod tests {
|
||||
};
|
||||
let a = WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [0.0, 0.0],
|
||||
end: [3.0, 0.0],
|
||||
thickness: 0.3,
|
||||
|
||||
@@ -159,8 +159,9 @@ fn extrude_wall_with_miters(mesh: &mut Mesh, wall: &WallInput, miters: WallMiter
|
||||
);
|
||||
} else {
|
||||
let drop = if segments.len() == 1 { wall.top_drop } else { [0.0, 0.0] };
|
||||
let plane = if segments.len() == 1 { wall.top_plane } else { None };
|
||||
extrude_layer_segment(
|
||||
mesh, wall, n, length, a0, a1, y0, y1, drop, off_a, off_b, start_cut, end_cut,
|
||||
mesh, wall, n, length, a0, a1, y0, y1, drop, plane, off_a, off_b, start_cut, end_cut,
|
||||
layer.color,
|
||||
);
|
||||
}
|
||||
@@ -240,6 +241,7 @@ fn extrude_layer_segment(
|
||||
y0: f32,
|
||||
y1: f32,
|
||||
top_drop: [f32; 2],
|
||||
top_plane: Option<[f32; 3]>,
|
||||
off_a: f32,
|
||||
off_b: f32,
|
||||
start_cut: Option<MiterLine>,
|
||||
@@ -285,14 +287,21 @@ fn extrude_layer_segment(
|
||||
top_drop[0] + (top_drop[1] - top_drop[0]) * t
|
||||
};
|
||||
let (ya, yb) = (y1 - drop_at(a0), y1 - drop_at(a1));
|
||||
let t0 = w(g0, ya);
|
||||
let t1 = w(g1, yb);
|
||||
let t2 = w(g2, yb);
|
||||
let t3 = w(g3, ya);
|
||||
// Ebene Oberkante ([G2]): jede Ecke auf der Dach-Unterkante (auch quer über die Dicke).
|
||||
let top_y = |g: Point2, fallback: f32| -> f32 {
|
||||
match top_plane {
|
||||
Some(p) => p[0] + p[1] * (g[0] - wall.start[0]) + p[2] * (g[1] - wall.start[1]),
|
||||
None => fallback,
|
||||
}
|
||||
};
|
||||
let t0 = w(g0, top_y(g0, ya));
|
||||
let t1 = w(g1, top_y(g1, yb));
|
||||
let t2 = w(g2, top_y(g2, yb));
|
||||
let t3 = w(g3, top_y(g3, ya));
|
||||
|
||||
// Sechs Seiten als Quads (Ecken CCW von aussen gesehen -> Normale zeigt raus).
|
||||
// Deckel oben (+Y): t0,t1,t2,t3 von oben CCW.
|
||||
let top_normal = if ya == yb { [0.0, 1.0, 0.0] } else { quad_normal(t0, t1, t3) };
|
||||
let top_normal = if ya == yb && top_plane.is_none() { [0.0, 1.0, 0.0] } else { quad_normal(t0, t1, t3) };
|
||||
push_quad(mesh, t0, t1, t2, t3, top_normal, color);
|
||||
// Boden unten (-Y): b0,b3,b2,b1 (von unten gesehen CCW).
|
||||
push_quad(mesh, b0, b3, b2, b1, [0.0, -1.0, 0.0], color);
|
||||
@@ -1021,6 +1030,9 @@ pub fn build_free_wall_end_caps(walls: &[WallInput]) -> Vec<f32> {
|
||||
let dz = wall.end[1] - wall.start[1];
|
||||
let len2 = (dx * dx + dz * dz).max(1e-12);
|
||||
let y_at = |p: Point2| -> f32 {
|
||||
if let Some(q) = wall.top_plane {
|
||||
return q[0] + q[1] * (p[0] - wall.start[0]) + q[2] * (p[1] - wall.start[1]);
|
||||
}
|
||||
let t = (((p[0] - wall.start[0]) * dx + (p[1] - wall.start[1]) * dz) / len2).clamp(0.0, 1.0);
|
||||
y_top - (wall.top_drop[0] + (wall.top_drop[1] - wall.top_drop[0]) * t)
|
||||
};
|
||||
|
||||
@@ -342,6 +342,19 @@ struct Prism {
|
||||
cut: Option<CutBandMeta>,
|
||||
/// Monolith-Gruppe (siehe `SlabInput::monolith`); Waende: immer `None`.
|
||||
monolith: Option<String>,
|
||||
/// Ebene Oberkante unter einer Dachfläche ([G2], `WallInput::top_plane`): Ursprung (Grundriss)
|
||||
/// und `[z, dz/dx, dz/dy]`; `z1` ist dann der höchste Eckwert.
|
||||
top: Option<(Point2, [f32; 3])>,
|
||||
}
|
||||
|
||||
impl Prism {
|
||||
/// Oberkante an einem Grundriss-Punkt.
|
||||
fn top_at(&self, p: Point2) -> f32 {
|
||||
match self.top {
|
||||
Some((o, c)) => (c[0] + c[1] * (p[0] - o[0]) + c[2] * (p[1] - o[1])).clamp(self.z0, self.z1),
|
||||
None => self.z1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wandachse + Oeffnungen, wie sie fuer die Oeffnungs-Zuordnung bei Cut-
|
||||
@@ -433,6 +446,7 @@ fn wall_prism(index: usize, wall: &WallInput) -> Option<Prism> {
|
||||
}),
|
||||
cut: wall.cut.clone(),
|
||||
monolith: None,
|
||||
top: wall.top_plane.map(|c| (wall.start, c)),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -457,6 +471,7 @@ fn slab_prism(index: usize, slab: &SlabInput) -> Option<Prism> {
|
||||
wall_axis: None,
|
||||
cut: slab.cut.clone(),
|
||||
monolith: slab.monolith.clone(),
|
||||
top: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -884,7 +899,7 @@ fn prism_wireframe_edges(prism: &Prism) -> Vec<([f32; 3], [f32; 3], HeightBias)>
|
||||
for i in 0..n {
|
||||
edges.push((
|
||||
to_world(prism.footprint[i], prism.z0),
|
||||
to_world(prism.footprint[i], prism.z1),
|
||||
to_world(prism.footprint[i], prism.top_at(prism.footprint[i])),
|
||||
HeightBias::Vertical,
|
||||
));
|
||||
}
|
||||
@@ -892,7 +907,9 @@ fn prism_wireframe_edges(prism: &Prism) -> Vec<([f32; 3], [f32; 3], HeightBias)>
|
||||
let a = prism.footprint[i];
|
||||
let b = prism.footprint[(i + 1) % n];
|
||||
edges.push((to_world(a, prism.z0), to_world(b, prism.z0), HeightBias::BottomCap));
|
||||
edges.push((to_world(a, prism.z1), to_world(b, prism.z1), HeightBias::TopCap));
|
||||
// Schräge Deckelkante ([G2]): Höhe variiert, geschlossene Randbehandlung.
|
||||
let bias = if prism.top.is_some() { HeightBias::Vertical } else { HeightBias::TopCap };
|
||||
edges.push((to_world(a, prism.top_at(a)), to_world(b, prism.top_at(b)), bias));
|
||||
}
|
||||
edges
|
||||
}
|
||||
@@ -1201,6 +1218,16 @@ fn cut_polygons_and_prisms(
|
||||
for (u0, u1) in footprint_u_intervals(plane, &prism.cut_footprint) {
|
||||
let (lo, hi) = (u0.min(u1), u0.max(u1));
|
||||
for (rlo, rhi, rz0, rz1) in wall_cut_rectangles(plane, prism, lo, hi) {
|
||||
// Ebene Oberkante ([G2]): Deckelkante längs der Schnittlinie schräg.
|
||||
let (za, zb) = if prism.top.is_some() && rz1 >= prism.z1 {
|
||||
let at = |u: f32| {
|
||||
let (p0, ua) = (plane.plan_point(), plane.plan_u_axis());
|
||||
prism.top_at([p0[0] + u * ua[0], p0[1] + u * ua[1]])
|
||||
};
|
||||
(at(rlo), at(rhi))
|
||||
} else {
|
||||
(rz1, rz1)
|
||||
};
|
||||
cut_polygons.push(CutPolygon {
|
||||
component: ComponentRef {
|
||||
kind: prism.kind,
|
||||
@@ -1208,7 +1235,7 @@ fn cut_polygons_and_prisms(
|
||||
},
|
||||
color: prism.color,
|
||||
hatch: prism.hatch,
|
||||
pts: vec![[rlo, rz0], [rhi, rz0], [rhi, rz1], [rlo, rz1]],
|
||||
pts: vec![[rlo, rz0], [rhi, rz0], [rhi, zb], [rlo, za]],
|
||||
cut: prism.cut.clone(),
|
||||
});
|
||||
}
|
||||
@@ -1246,6 +1273,7 @@ mod tests {
|
||||
let walls = vec![
|
||||
WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [0.0, 0.0],
|
||||
end: [0.0, 3.0],
|
||||
thickness: 0.2,
|
||||
@@ -1263,6 +1291,7 @@ mod tests {
|
||||
},
|
||||
WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [0.0, 3.0],
|
||||
end: [3.0, 3.0],
|
||||
thickness: 0.2,
|
||||
@@ -1341,6 +1370,7 @@ mod tests {
|
||||
fn wand_vor_der_ebene_verdeckt_nichts_dahinter() {
|
||||
let mk = |start: [f32; 2], end: [f32; 2]| WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start,
|
||||
end,
|
||||
thickness: 0.2,
|
||||
@@ -1562,6 +1592,7 @@ mod tests {
|
||||
fn wall_with_window() -> WallInput {
|
||||
WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [0.0, 0.0],
|
||||
end: [4.0, 0.0],
|
||||
thickness: 0.2,
|
||||
@@ -1584,6 +1615,25 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ebene_oberkante_schraeg_im_schnitt_und_in_der_projektion() {
|
||||
// Traufwand längs x (y −0.1 … 0.1), Oberkante steigt quer zur Wand: z = 2.5 + 1·y.
|
||||
let mut w = wall_with_window();
|
||||
w.openings.clear();
|
||||
w.height = 2.6;
|
||||
w.top_plane = Some([2.5, 0.0, 1.0]);
|
||||
// Schnitt quer zur Wand (Ebene x = 2, Blick +x): u längs −y.
|
||||
let out = cut_section(&SectionPlane::looking_plus_x(2.0), &[w.clone()], &[], &[]);
|
||||
let c = &out.cut_polygons[0];
|
||||
let tops: Vec<f32> = c.pts.iter().map(|p| p[1]).filter(|v| *v > 1.0).collect();
|
||||
assert_eq!(tops.len(), 2);
|
||||
assert!((tops[0] - tops[1]).abs() > 0.19 && tops.iter().all(|v| (*v - 2.5).abs() <= 0.1 + 1e-5), "{:?}", c.pts);
|
||||
// Mesh: jede Deckel-Ecke auf der Ebene.
|
||||
let m = crate::mesh::build_walls_mesh(&[w]);
|
||||
let ys: Vec<f32> = m.verts.chunks(9).filter(|p| p[1] > 1.0).map(|p| p[1] - (2.5 + p[2])).collect();
|
||||
assert!(!ys.is_empty() && ys.iter().all(|d| d.abs() < 1e-5), "{ys:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schnitt_durch_fenster_liefert_bruestung_und_sturz() {
|
||||
// Schnittebene bei Grundriss-X = 2.0: liegt MITTEN im Fenster (1.5..2.5).
|
||||
@@ -1659,6 +1709,7 @@ mod tests {
|
||||
let w0 = wall_with_window();
|
||||
let w1 = WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [2.0, 1.0],
|
||||
end: [4.0, 1.0],
|
||||
thickness: 0.2,
|
||||
@@ -1780,6 +1831,7 @@ mod tests {
|
||||
fn cut_section_mit_wand_und_dach_liefert_beide_cut_polygone() {
|
||||
let wall = WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [2.0, -1.0],
|
||||
end: [2.0, 1.0],
|
||||
thickness: 0.3,
|
||||
|
||||
@@ -340,6 +340,7 @@ mod tests {
|
||||
fn hatch_muster_id_landet_in_den_cap_vertices() {
|
||||
let wall = WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [0.0, 0.0],
|
||||
end: [3.0, 0.0],
|
||||
thickness: 0.3,
|
||||
@@ -389,6 +390,7 @@ mod tests {
|
||||
fn generator_muster_kommt_als_ribbons() {
|
||||
let mk = |pattern: u32| WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [0.0, 0.0],
|
||||
end: [3.0, 0.0],
|
||||
thickness: 0.3,
|
||||
@@ -426,6 +428,7 @@ mod tests {
|
||||
fn ohne_hatch_fallback_auf_diagonale() {
|
||||
let wall = WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [0.0, 0.0],
|
||||
end: [3.0, 0.0],
|
||||
thickness: 0.3,
|
||||
@@ -462,6 +465,7 @@ mod tests {
|
||||
// Wand entlang +X bei x in [0,3], Dicke 0.4, volle Hoehe [0,2.5]; Prio 50.
|
||||
let wall = WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [0.0, 0.0],
|
||||
end: [3.0, 0.0],
|
||||
thickness: 0.4,
|
||||
@@ -539,6 +543,7 @@ mod tests {
|
||||
// volle Hoehe [0,2.5]; Prio 50, Muster 2 (diagonal).
|
||||
let wall = WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [0.0, 0.0],
|
||||
end: [3.0, 0.0],
|
||||
thickness: 0.4,
|
||||
@@ -624,6 +629,7 @@ mod tests {
|
||||
let color = [0.2, 0.4, 0.9];
|
||||
let wall = WallInput {
|
||||
top_drop: [0.0, 0.0],
|
||||
top_plane: None,
|
||||
start: [0.0, 0.0],
|
||||
end: [3.0, 0.0],
|
||||
thickness: 0.4,
|
||||
|
||||
@@ -136,6 +136,10 @@ pub struct WallInput {
|
||||
/// gestuft. Nur für Wände ohne `openings`/`holes` wirksam; `[0,0]` (Default) = flach.
|
||||
#[serde(default, rename = "topDrop")]
|
||||
pub top_drop: [f32; 2],
|
||||
/// Ebene Oberkante unter einer Dachfläche ([G2]): `[z an start, dz/dx, dz/dy]` (Grundriss-Meter).
|
||||
/// Übersteuert `top_drop`; jede Ecke liegt exakt auf der Ebene (auch quer über die Dicke).
|
||||
#[serde(default, rename = "topPlane", skip_serializing_if = "Option::is_none")]
|
||||
pub top_plane: Option<[f32; 3]>,
|
||||
/// Albedo-Farbe der Wand (RGB 0..1). Default helles Grau wie die three.js-Sicht.
|
||||
/// Nur wirksam, wenn `layers` fehlt/leer ist (Vollkoerper-Fallback).
|
||||
#[serde(default = "default_wall_color")]
|
||||
|
||||
@@ -1127,6 +1127,32 @@ mod dbg_step {
|
||||
assert!((vol(&mir) - 6.0).abs() < 1e-6, "mir {}", vol(&mir));
|
||||
}
|
||||
|
||||
/// [T7] Rotationskörper um eine waagrechte Planachse (Befehl `revolve`, `cmd_solid.rs`): Zylinder r=1, l=2
|
||||
/// auf dem Boden; Halbdrehung = halbes Volumen; STEP-Export klappt.
|
||||
#[test]
|
||||
fn revolve_um_waagrechte_achse_steht_auf_dem_boden() {
|
||||
let spec = |angle: f64| SolidSpec::Transform {
|
||||
m: [-1.0, 0.0, 0.0, 3.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0],
|
||||
solid: Box::new(SolidSpec::Revolve { profile: vec![0.0, 0.0, 0.0, 2.0, 1.0, 2.0, 1.0, 0.0], cx: 0.0, cy: 0.0, angle_deg: angle }),
|
||||
};
|
||||
let vol_zmin = |sp: &SolidSpec| {
|
||||
let m = solid_mesh_core(sp, 0.005).unwrap();
|
||||
let p: Vec<[f64; 3]> = m.positions.chunks(3).map(|c| [c[0] as f64, c[1] as f64, c[2] as f64]).collect();
|
||||
let v: f64 = m.indices.chunks(3).map(|t| {
|
||||
let (a, b, c) = (p[t[0] as usize], p[t[1] as usize], p[t[2] as usize]);
|
||||
(a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0
|
||||
}).sum();
|
||||
(v, p.iter().map(|q| q[2]).fold(f64::INFINITY, f64::min), p.iter().map(|q| q[2]).fold(f64::NEG_INFINITY, f64::max))
|
||||
};
|
||||
let (v, z0, z1) = vol_zmin(&spec(360.0));
|
||||
assert!((v - 2.0 * std::f64::consts::PI).abs() < 0.02, "Volumen {v}");
|
||||
assert!(z0.abs() < 1e-3 && (z1 - 2.0).abs() < 1e-3, "z {z0}..{z1}");
|
||||
let (vh, h0, _) = vol_zmin(&spec(180.0));
|
||||
assert!((vh - std::f64::consts::PI).abs() < 0.02, "halb {vh}");
|
||||
assert!(h0 > 0.99, "Halbdrehung steigt nach oben: {h0}");
|
||||
assert!(export_step_core(&[spec(360.0)], &StepHeader::default()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bool_result_step_dump() {
|
||||
let dir = std::env::var("STEP_DUMP_DIR").unwrap_or_default();
|
||||
|
||||
+6
-18
@@ -66,7 +66,7 @@ import { IfcImportDialog, type IfcImportMode } from "./ui/IfcImportDialog";
|
||||
import { MeshImportHost } from "./ui/MeshImportDialog";
|
||||
import { openMeshFileDialog, requestMeshImport, splitMeshFiles } from "./state/meshImportStore";
|
||||
import { formatMeshReport, isMeshFile } from "./io/meshImport";
|
||||
import { clashMarkerOps, runClashCheck } from "./analysis/clash";
|
||||
import { runClashAndStore } from "./panels/clashSession";
|
||||
import { checkForUpdate } from "./update/checkForUpdate";
|
||||
import type { PlanViewHandle } from "./views/plan/PlanView";
|
||||
import type { DisplayResolver } from "./viewport/Viewport3D";
|
||||
@@ -292,6 +292,7 @@ const TOOL_COMMAND: Partial<Record<ToolId, string>> = {
|
||||
scalebar: "scalebar",
|
||||
revcloud: "revcloud",
|
||||
pointmarker: "pointmarker",
|
||||
grid: "grid",
|
||||
wipeout: "wipeout",
|
||||
text: "text",
|
||||
leader: "leader",
|
||||
@@ -1650,6 +1651,7 @@ export default function App() {
|
||||
removeContextObject,
|
||||
removeContextObjects,
|
||||
generateTerrain,
|
||||
patchContextObject,
|
||||
moveGripOf,
|
||||
moveElementByOf,
|
||||
moveEdgeOf,
|
||||
@@ -2375,23 +2377,8 @@ export default function App() {
|
||||
onImportPointCloud: () => openPointCloudFileDialog(),
|
||||
onImportMesh: () => openMeshFileDialog(),
|
||||
onClashCheck: () => {
|
||||
const p0 = project;
|
||||
runClashCheck(p0)
|
||||
.then((clashes) => {
|
||||
applyChange((p) => clashMarkerOps(p, clashes, activeCategoryCode));
|
||||
// window.alert ist im Tauri-WKWebView wirkungslos → Toast.
|
||||
notify(
|
||||
clashes.length === 0
|
||||
? t("clash.none")
|
||||
: `${t("clash.found")}: ${clashes.length} — ` +
|
||||
clashes
|
||||
.slice(0, 5)
|
||||
.map((c, k) => `K${k + 1} ${c.a.kind}↔${c.b.kind}${c.volume !== null ? ` ${c.volume.toFixed(3)} m³` : ""}`)
|
||||
.join(", "),
|
||||
clashes.length === 0 ? "info" : "warning",
|
||||
);
|
||||
})
|
||||
.catch((err) => notify(`${t("clash.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error"));
|
||||
setLayout((l) => revealPanel(l, "clash"));
|
||||
void runClashAndStore();
|
||||
},
|
||||
onKennzahlen: () => {
|
||||
const k = computeKennzahlen(project);
|
||||
@@ -3261,6 +3248,7 @@ export default function App() {
|
||||
removeContextObject,
|
||||
removeContextObjects,
|
||||
generateTerrain,
|
||||
patchContextObject,
|
||||
commitTransformOn,
|
||||
setElementColor,
|
||||
setElementWeight,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { candidatePairs, clashItems, clashMarkerOps, CLASH_MARKER_PREFIX } from "./clash";
|
||||
import { candidatePairs, clashHighlightLines, clashItems, clashMarkerOps, clashSelection, CLASH_MARKER_PREFIX } from "./clash";
|
||||
import { applyOps } from "../core/ops";
|
||||
import type { Project } from "../model/types";
|
||||
import type { Clash } from "./clash";
|
||||
@@ -22,11 +22,28 @@ describe("Kollisionspruefung", () => {
|
||||
expect(items.some((i) => i.kind === "wall")).toBe(true);
|
||||
});
|
||||
it("Marker ersetzen alte Marker", () => {
|
||||
const clash = { a: it0("a", "solid"), b: it0("b", "wall"), volume: 0.12, center: [1, 2, 0.5] as [number, number, number] };
|
||||
const clash = { a: it0("a", "solid"), b: it0("b", "wall"), volume: 0.12, center: [1, 2, 0.5] as [number, number, number], min: [0.5, 1.5, 0] as [number, number, number], max: [1.5, 2.5, 1] as [number, number, number] };
|
||||
const p1 = applyClashMarkers(sampleProject, [clash, clash], "A");
|
||||
const n1 = p1.drawings2d.filter((d) => d.id.startsWith(CLASH_MARKER_PREFIX)).length;
|
||||
expect(n1).toBe(4);
|
||||
const p2 = applyClashMarkers(p1, [clash], "A");
|
||||
expect(p2.drawings2d.filter((d) => d.id.startsWith(CLASH_MARKER_PREFIX)).length).toBe(2);
|
||||
});
|
||||
it("3D-Hervorhebung: 12 Kanten je Kollision als Linienpaare im Viewport-Raum (y/z getauscht)", () => {
|
||||
const clash = { a: it0("a", "solid"), b: it0("b", "wall"), volume: 0.12, center: [1, 2, 0.5] as [number, number, number], min: [0.5, 1.5, 0] as [number, number, number], max: [1.5, 2.5, 1] as [number, number, number] };
|
||||
const lines = clashHighlightLines([clash], [1, 0, 0]);
|
||||
expect(lines.length).toBe(12 * 2 * 6);
|
||||
// erster Eckpunkt: Modell (min.x, min.y, min.z) → world (x, Höhe, y), Farbe rot
|
||||
const verts = [];
|
||||
for (let k = 0; k < lines.length; k += 6) verts.push([...lines.slice(k, k + 6)]);
|
||||
expect(verts.every((v) => v[3] === 1 && v[4] === 0 && v[5] === 0)).toBe(true);
|
||||
expect(verts.every((v) => v[0] >= 0.5 && v[0] <= 1.5 && v[1] >= 0 && v[1] <= 1 && v[2] >= 1.5 && v[2] <= 2.5)).toBe(true);
|
||||
expect(clashHighlightLines([], [1, 0, 0]).length).toBe(0);
|
||||
});
|
||||
it("Auswahl eines Paars je Bauteilart", () => {
|
||||
const clash = { a: it0("s1", "solid"), b: it0("w1", "wall"), volume: null, center: [0, 0, 0] as [number, number, number], min: [0, 0, 0] as [number, number, number], max: [1, 1, 1] as [number, number, number] };
|
||||
expect(clashSelection(clash)).toEqual({ wallIds: ["w1"], ceilingIds: [], extrudedSolidIds: ["s1"], contextObjectIds: [] });
|
||||
const m = { ...clash, a: it0("m1", "mesh"), b: it0("c1", "slab") };
|
||||
expect(clashSelection(m)).toEqual({ wallIds: [], ceilingIds: ["c1"], extrudedSolidIds: [], contextObjectIds: ["m1"] });
|
||||
});
|
||||
});
|
||||
+53
-5
@@ -30,8 +30,11 @@ export interface Clash {
|
||||
b: ClashItem;
|
||||
/** Durchdringungsvolumen (m³), `null` wenn nicht berechenbar. */
|
||||
volume: number | null;
|
||||
/** Mittelpunkt der Durchdringungslinien (Welt-Meter). */
|
||||
/** Mittelpunkt der Durchdringungslinien (Modell-Meter, z = Höhe). */
|
||||
center: [number, number, number];
|
||||
/** Hüllquader der Durchdringungslinien (Modell-Meter) — für Hervorhebung und Zoom. */
|
||||
min: [number, number, number];
|
||||
max: [number, number, number];
|
||||
}
|
||||
|
||||
/** Prefix der Marker-Ids (ein neuer Lauf ersetzt die alten Marker). */
|
||||
@@ -127,13 +130,17 @@ export async function runClashCheck(
|
||||
if (!r.colliding || r.lines.length === 0) continue;
|
||||
if (r.overlapVolume !== null && r.overlapVolume < MIN_VOLUME) continue;
|
||||
const c: [number, number, number] = [0, 0, 0];
|
||||
const min: [number, number, number] = [Infinity, Infinity, Infinity];
|
||||
const max: [number, number, number] = [-Infinity, -Infinity, -Infinity];
|
||||
for (const l of r.lines) {
|
||||
c[0] += (l[0] + l[3]) / 2;
|
||||
c[1] += (l[1] + l[4]) / 2;
|
||||
c[2] += (l[2] + l[5]) / 2;
|
||||
for (let k = 0; k < 3; k++) {
|
||||
c[k] += (l[k] + l[k + 3]) / 2;
|
||||
min[k] = Math.min(min[k], l[k], l[k + 3]);
|
||||
max[k] = Math.max(max[k], l[k], l[k + 3]);
|
||||
}
|
||||
}
|
||||
const n = r.lines.length;
|
||||
const clash: Clash = { a: items[i], b: items[j], volume: r.overlapVolume, center: [c[0] / n, c[1] / n, c[2] / n] };
|
||||
const clash: Clash = { a: items[i], b: items[j], volume: r.overlapVolume, center: [c[0] / n, c[1] / n, c[2] / n], min, max };
|
||||
// Mehrere Wandschichten derselben Wand → eine Kollision (grösstes Volumen).
|
||||
const key = [items[i].id, items[j].id].sort().join("|");
|
||||
const prev = found.get(key);
|
||||
@@ -175,3 +182,44 @@ export function clashMarkerOps(project: Project, clashes: Clash[], categoryCode:
|
||||
...addItems("drawings2d", markers),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Rote Hüllquader der Kollisionen als Linienliste für den 3D-Viewport (`set_highlight_lines`):
|
||||
* `[x, y, z, r, g, b]` je Vertex, 2 Vertices je Kante, 12 Kanten je Kollision. Modell (x, y, Höhe)
|
||||
* → Viewport-Welt (x, Höhe, y). Mindestkantenlänge 0.1 m, damit hauchdünne Durchdringungen sichtbar bleiben.
|
||||
*/
|
||||
export function clashHighlightLines(clashes: Clash[], rgb: readonly [number, number, number]): Float32Array {
|
||||
const out = new Float32Array(clashes.length * 12 * 2 * 6);
|
||||
let o = 0;
|
||||
const vert = (p: readonly number[]) => {
|
||||
out[o++] = p[0];
|
||||
out[o++] = p[2];
|
||||
out[o++] = p[1];
|
||||
out[o++] = rgb[0];
|
||||
out[o++] = rgb[1];
|
||||
out[o++] = rgb[2];
|
||||
};
|
||||
for (const c of clashes) {
|
||||
const lo = [0, 1, 2].map((k) => Math.min(c.min[k], c.center[k] - 0.05));
|
||||
const hi = [0, 1, 2].map((k) => Math.max(c.max[k], c.center[k] + 0.05));
|
||||
const corner = (i: number) => [i & 1 ? hi[0] : lo[0], i & 2 ? hi[1] : lo[1], i & 4 ? hi[2] : lo[2]];
|
||||
for (let i = 0; i < 8; i++) {
|
||||
for (const bit of [1, 2, 4]) {
|
||||
if (i & bit) continue;
|
||||
vert(corner(i));
|
||||
vert(corner(i | bit));
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Bauteile einer Kollision je Auswahlkanal (Wand, Decke, Körper, Import). */
|
||||
export function clashSelection(c: Clash): { wallIds: string[]; ceilingIds: string[]; extrudedSolidIds: string[]; contextObjectIds: string[] } {
|
||||
const sel = { wallIds: [] as string[], ceilingIds: [] as string[], extrudedSolidIds: [] as string[], contextObjectIds: [] as string[] };
|
||||
for (const it of [c.a, c.b]) {
|
||||
const list = it.kind === "wall" ? sel.wallIds : it.kind === "slab" ? sel.ceilingIds : it.kind === "solid" ? sel.extrudedSolidIds : sel.contextObjectIds;
|
||||
if (!list.includes(it.id)) list.push(it.id);
|
||||
}
|
||||
return sel;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Project } from "../model/types";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { excavationQuantities } from "./excavation";
|
||||
import { generateTerrainFromContours } from "../model/terrain";
|
||||
|
||||
/** Flaches Gelände 100 × 100 m auf ±0 und eine Baugrube 10 × 10 m, 3 m tief, 45°. */
|
||||
function project(): Project {
|
||||
return {
|
||||
...sampleProject,
|
||||
walls: [],
|
||||
context: [
|
||||
{
|
||||
id: "t",
|
||||
type: "terrainMesh",
|
||||
name: "Gelände",
|
||||
positions: [-50, -50, 0, 50, -50, 0, 50, 50, 0, -50, 50, 0],
|
||||
indices: [0, 1, 2, 0, 2, 3],
|
||||
},
|
||||
{
|
||||
id: "bg",
|
||||
type: "excavation",
|
||||
name: "Baugrube",
|
||||
outline: [
|
||||
{ x: -5, y: -5 },
|
||||
{ x: 5, y: -5 },
|
||||
{ x: 5, y: 5 },
|
||||
{ x: -5, y: 5 },
|
||||
],
|
||||
bottom: -3,
|
||||
slope: 45,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("[68] Baugrube", () => {
|
||||
it("Abtrag wie analytisch (Kegelecken)", () => {
|
||||
const [q] = excavationQuantities(project());
|
||||
const exact = 300 + (40 * 9) / 2 + (Math.PI * 27) / 3;
|
||||
expect(q.id).toBe("bg");
|
||||
expect(Math.abs(q.cut - exact) / exact).toBeLessThan(0.01);
|
||||
expect(q.fill).toBeCloseTo(0, 6);
|
||||
expect(q.bottomArea).toBeCloseTo(100, 6);
|
||||
});
|
||||
|
||||
it("ohne Baugrube leer", () => {
|
||||
expect(excavationQuantities({ ...sampleProject, context: [] })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("[T6] Gelände aus Höhenlinien", () => {
|
||||
it("glättet ohne Überschwingen und setzt die Äquidistanz", () => {
|
||||
const ring = (r: number) =>
|
||||
Array.from({ length: 32 }, (_, i) => ({ x: r * Math.cos((i / 32) * 2 * Math.PI), y: r * Math.sin((i / 32) * 2 * Math.PI) }));
|
||||
const contours = [0, 1, 2, 3].map((k) => ({ z: k, pts: ring(40 - 10 * k), closed: true }));
|
||||
const raw = generateTerrainFromContours(contours, { smooth: 0 });
|
||||
const smooth = generateTerrainFromContours(contours);
|
||||
expect(smooth.contourInterval).toBe(1);
|
||||
expect(smooth.indices.length).toBeGreaterThan(raw.indices.length);
|
||||
const zs = smooth.positions.filter((_, i) => i % 3 === 2);
|
||||
expect(Math.min(...zs)).toBeGreaterThanOrEqual(-1e-9);
|
||||
expect(Math.max(...zs)).toBeLessThan(3.5);
|
||||
expect(Math.max(...zs)).toBeGreaterThan(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
// Erdarbeiten ([68]): Mengen der Baugruben aus dem Rust-Kern (`src-tauri/core/src/excavation.rs`).
|
||||
// Abtrag/Auftrag je Baugrube gegen das gewachsene Terrain (Integral über ein feines Raster der exakten
|
||||
// Böschungsfunktion), Hinterfüllung = Abtrag ausserhalb der Gebäude-Grundfläche.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { documentFor } from "../core/document";
|
||||
|
||||
export interface ExcavationQuantity {
|
||||
id: string;
|
||||
name: string;
|
||||
/** Sohle (m, Modell ±0.00). */
|
||||
bottom: number;
|
||||
/** Sohlenfläche (m²). */
|
||||
bottomArea: number;
|
||||
/** Abtrag (m³). */
|
||||
cut: number;
|
||||
/** Auftrag/Schüttung (m³). */
|
||||
fill: number;
|
||||
/** Hinterfüllung (m³). */
|
||||
backfill: number;
|
||||
}
|
||||
|
||||
export function excavationQuantities(project: Project): ExcavationQuantity[] {
|
||||
if (!(project.context ?? []).some((o) => o.type === "excavation")) return [];
|
||||
return documentFor(project).query<ExcavationQuantity[]>("excavationQuantities");
|
||||
}
|
||||
@@ -57,6 +57,12 @@ export interface SiteCheck {
|
||||
violationArea: number;
|
||||
maxTop: number | null;
|
||||
heightExceeded: boolean;
|
||||
/** [T6] Geländehöhen an der Fassade (gewachsen/gestaltet, Modellbezug); leer ohne Gelände. */
|
||||
facadeTerrain: { x: number; y: number; natural: number | null; designed: number | null }[];
|
||||
/** Tiefstes gewachsenes Terrain an der Fassade (massgebendes Terrain, vereinfacht). */
|
||||
terrainMin: number | null;
|
||||
/** Gesamthöhe über dem massgebenden Terrain; mit Gelände prüft die Höhe dagegen statt gegen ±0.00. */
|
||||
heightAboveTerrain: number | null;
|
||||
}
|
||||
|
||||
/** Prüft das Modell gegen `project.siteRules`; `null` ohne (gültiges) Baurecht. Rechnung im Rust-Kern (`site_rules.rs`). */
|
||||
|
||||
@@ -13,34 +13,43 @@
|
||||
<polygon points="5.8275,7.08564 6.1725,7.08564 6.1725,4.48564 5.8275,4.48564" fill="#ffffff" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="1.1725,7.08564 1.1725,4.48564 0.8275,4.48564 0.8275,7.08564" fill="#ffffff" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="3.325,7.08564 3.475,7.08564 3.475,4.48564 3.325,4.48564" fill="#8c5544" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="1,4.48564 6,4.48564 6,2.05885 1,2.05885" fill="#ffffff" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="5.8275,4.48564 6.1725,4.48564 6.1725,1.88564 5.8275,1.88564" fill="#ffffff" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="1.1725,4.48564 1.1725,1.88564 0.8275,1.88564 0.8275,4.48564" fill="#ffffff" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<line x1="6.1725" y1="4.48564" x2="6.1725" y2="2.05885" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="0.8275" y1="4.48564" x2="0.8275" y2="2.05885" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<polygon points="6,2.05885 6,2.28564 1,2.28564 1,2.05885" fill="#8f959e" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="5.8275,1.88564 6.1725,1.88564 6.1725,2.28564 5.8275,2.28564" fill="#8f959e" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="0.8275,1.88564 1.1725,1.88564 1.1725,2.28564 1,2.28564 0.8275,2.11314" fill="#8f959e" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="1,2.05885 6,2.05885 6,2.45885 1,2.45885" fill="#8f959e" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="5.8275,2.05885 6.1725,2.05885 6.1725,2.45885 5.8275,2.45885" fill="#8f959e" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="0.8275,2.05885 1.1725,2.05885 1.1725,2.45885 1,2.45885 0.8275,2.28635" fill="#8f959e" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="0.8275,7.08564 1.8,7.08564 1.8,4.48564 0.8275,4.48564" fill="#ffffff" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="1.8,4.98564 2.7,4.98564 2.7,4.48564 1.8,4.48564" fill="#ffffff" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="2.7,7.08564 4,7.08564 4,4.48564 2.7,4.48564" fill="#ffffff" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="4,7.08564 5,7.08564 5,6.18564 4,6.18564" fill="#ffffff" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="4,4.98564 5,4.98564 5,4.48564 4,4.48564" fill="#ffffff" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="5,7.08564 6.1725,7.08564 6.1725,4.48564 5,4.48564" fill="#ffffff" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="0.8275,4.48564 6.1725,4.48564 6.1725,1.88564 0.8275,1.88564" fill="#ffffff" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="1,4.48564 6,4.48564 6,2.05885 1,2.05885" fill="#ffffff" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<line x1="0.8275" y1="7.08564" x2="1.8" y2="7.08564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="2.7" y1="7.08564" x2="4" y2="7.08564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="4" y1="7.08564" x2="5" y2="7.08564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="5" y1="7.08564" x2="6.1725" y2="7.08564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="0.8275" y1="4.48564" x2="1" y2="4.48564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="6" y1="4.48564" x2="6.1725" y2="4.48564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="1.8" y1="4.98564" x2="2.7" y2="4.98564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="4" y1="4.98564" x2="5" y2="4.98564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="4" y1="6.18564" x2="5" y2="6.18564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="0.8275" y1="1.88564" x2="6.1725" y2="1.88564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="1.8" y1="7.08564" x2="1.8" y2="4.98564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="0.8275" y1="7.08564" x2="0.8275" y2="4.48564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="0.8275" y1="4.48564" x2="0.8275" y2="1.88564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="2.7" y1="7.08564" x2="2.7" y2="4.98564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="4" y1="6.18564" x2="4" y2="4.98564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="5" y1="6.18564" x2="5" y2="4.98564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="6.1725" y1="7.08564" x2="6.1725" y2="4.48564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="6.1725" y1="4.48564" x2="6.1725" y2="1.88564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<polygon points="0.8275,1.88564 6.1725,1.88564 6.1725,2.11314 0.8275,2.11314 0.8275,2.11314" fill="#8f959e" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<line x1="6" y1="4.48564" x2="6" y2="2.05885" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="1" y1="4.48564" x2="1" y2="2.05885" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<polygon points="6,2.05885 6,2.11314 1,2.11314 1,2.05885" fill="#8f959e" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="1,2.05885 6,2.05885 6,2.28635 1,2.28635" fill="#8f959e" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<polygon points="1.8,7.08564 2.7,7.08564 2.7,4.98564 1.8,4.98564" fill="#d9d9d4" stroke="#2b3039" stroke-width="0.018" stroke-linejoin="round"/>
|
||||
<polygon points="1.836,7.08564 2.664,7.08564 2.664,5.04864 1.836,5.04864" fill="#ede6d9" stroke="#2b3039" stroke-width="0.013" stroke-linejoin="round"/>
|
||||
<polygon points="1.8,5.06564 2.7,5.06564 2.7,4.98564 1.8,4.98564" fill="#a7adb5" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
@@ -56,9 +65,14 @@
|
||||
<line x1="4.88" y1="5.10564" x2="4.12" y2="5.58564" stroke="#7d858f" stroke-width="0.01" stroke-dasharray="0.22 0.18"/>
|
||||
<line x1="4.12" y1="6.06564" x2="4.5" y2="5.10564" stroke="#7d858f" stroke-width="0.01" stroke-dasharray="0.22 0.18"/>
|
||||
<line x1="4.88" y1="6.06564" x2="4.5" y2="5.10564" stroke="#7d858f" stroke-width="0.01" stroke-dasharray="0.22 0.18"/>
|
||||
<polygon points="0.6,1.88564 6.4,1.88564 6.4,2.05885 0.6,2.05885" fill="#b8735c" stroke="none" stroke-width="0" stroke-linejoin="round"/>
|
||||
<line x1="0.6" y1="1.88564" x2="6.4" y2="1.88564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="6.4" y1="1.88564" x2="6.4" y2="0.5" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="6.4" y1="0.5" x2="0.6" y2="0.5" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="0.6" y1="0.5" x2="0.6" y2="1.88564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="0.6" y1="1.88564" x2="6.4" y2="1.88564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="6.4" y1="1.88564" x2="6.4" y2="2.05885" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="6.4" y1="2.05885" x2="0.6" y2="2.05885" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="0.6" y1="2.05885" x2="0.6" y2="1.88564" stroke="#2b3039" stroke-width="0.013"/>
|
||||
<line x1="0.6" y1="7.08564" x2="6.4" y2="7.08564" stroke="#1f242c" stroke-width="0.05"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 7.4 KiB After Width: | Height: | Size: 8.9 KiB |
+5
-2
@@ -84,6 +84,7 @@ import {
|
||||
addProgramSheet,
|
||||
defaultSheetLabels,
|
||||
checkSiteRules,
|
||||
excavationQuantities,
|
||||
exportStl,
|
||||
exportGlb,
|
||||
exportGltf,
|
||||
@@ -602,7 +603,7 @@ async function execute(project: Project, file: string, command: string, rest: st
|
||||
const o = await computeSection(project, lvl);
|
||||
if (!o) fail("keine gültige Schnittlinie");
|
||||
// Wie die App: verdeckte Kanten nach der Ebene, geschnittene Fenster/Türen.
|
||||
plan = generateSectionPlan(o, false, { visibleCodes: allCodes, hiddenLines: lvl.hiddenLines, openings: true });
|
||||
plan = generateSectionPlan(o, false, { visibleCodes: allCodes, hiddenLines: lvl.hiddenLines, openings: true, scaleDenominator: scale });
|
||||
} else {
|
||||
plan = generateElevationPlan(project, lvl, { scaleDenominator: scale });
|
||||
if (!plan) fail("keine gültige Ansichtslinie");
|
||||
@@ -683,7 +684,9 @@ async function execute(project: Project, file: string, command: string, rest: st
|
||||
const k = computeKennzahlen(project);
|
||||
const prog = checkRoomProgram(project);
|
||||
const baurecht = checkSiteRules(project);
|
||||
out(args, JSON.stringify({ kennzahlen: k, raumprogramm: prog, baurecht }, null, 2), `${project.name || "projekt"}-kennzahlen.json`);
|
||||
// [68] Erdarbeiten je Baugrube (Abtrag/Auftrag/Hinterfüllung, m³).
|
||||
const erdarbeiten = excavationQuantities(project);
|
||||
out(args, JSON.stringify({ kennzahlen: k, raumprogramm: prog, baurecht, erdarbeiten }, null, 2), `${project.name || "projekt"}-kennzahlen.json`);
|
||||
return 0;
|
||||
}
|
||||
case "raumprogramm": {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// Radius-, Durchmesser- und Bogenlängen-Bemassung ([38]): Klick auf den Rand eines Kreises, Bogens oder
|
||||
// einer Bogenwand (Fläche oder Achse). Der Kern (`cmd_draw.rs`, `dim_assoc::round_dimension`) findet den
|
||||
// Kreis, setzt Mittelpunkt und Randpunkte und hängt sie daran (Bezug `center`/`rim`): Verschieben oder
|
||||
// Vergrössern des Kreises, Strecken der Bogenwand führt das Mass nach. Radius und Durchmesser: ein Klick;
|
||||
// Bogenlänge: Anfang, Ende (gegen den Uhrzeigersinn), dann Lage der Masslinie.
|
||||
|
||||
import type { Command, CommandContext, CommandResult, CommandState, ToolDraft, Vec2 } from "../types";
|
||||
import { createMutation, createPreview, xy } from "../createCore";
|
||||
|
||||
export type RoundKind = "radius" | "diameter" | "arc";
|
||||
|
||||
interface RoundState extends CommandState {
|
||||
phase: "first" | "second" | "offset";
|
||||
pts: Vec2[];
|
||||
}
|
||||
|
||||
const fresh = (): RoundState => ({ phase: "first", lastPoint: null, pts: [] });
|
||||
const idle = (): [CommandState, CommandResult] => [fresh(), { draft: null, done: true }];
|
||||
|
||||
/** Fangtoleranz auf dem Rand (Modell-Meter). */
|
||||
const TOL = 0.2;
|
||||
|
||||
function draft(ctx: CommandContext, kind: RoundKind, pts: Vec2[], cursor: Vec2 | null): ToolDraft | null {
|
||||
const all = cursor ? [...pts, cursor] : pts;
|
||||
if (all.length === 0) return null;
|
||||
const pv = createPreview(ctx, { cmd: "dimround", kind, tol: TOL }, all);
|
||||
return { preview: pv.shapes, vertices: pts };
|
||||
}
|
||||
|
||||
function make(kind: RoundKind, name: string): Command {
|
||||
const keyOf = (s: RoundState) => (s.phase === "first" ? `cmd.${name}.first` : s.phase === "second" ? `cmd.${name}.second` : `cmd.${name}.offset`);
|
||||
return {
|
||||
name,
|
||||
labelKey: `cmd.${name}.label` as never,
|
||||
prompt: (s) => keyOf(s as RoundState) as never,
|
||||
accepts: () => ["point"],
|
||||
options: () => [],
|
||||
init: fresh,
|
||||
|
||||
onInput: (state, input, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as RoundState;
|
||||
if (input.kind !== "point") return [s, { draft: null }];
|
||||
const pts = [...s.pts, input.point];
|
||||
if (kind !== "arc" || s.phase === "offset") {
|
||||
const commit = createMutation(ctx, { cmd: "dimround", kind, tol: TOL, pts: pts.slice(0, kind === "arc" ? 2 : 1).map(xy), side: kind === "arc" ? xy(input.point) : null });
|
||||
return [fresh(), { draft: null, done: true, commit }];
|
||||
}
|
||||
const ns: RoundState = { phase: pts.length >= 2 ? "offset" : "second", pts, lastPoint: input.point };
|
||||
return [ns, { draft: draft(ctx, kind, pts, null) }];
|
||||
},
|
||||
|
||||
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => [state, { draft: draft(ctx, kind, (state as RoundState).pts, point) }],
|
||||
onConfirm: () => idle(),
|
||||
onCancel: () => idle(),
|
||||
};
|
||||
}
|
||||
|
||||
export const radiusDimCommand = make("radius", "dimradius");
|
||||
export const diameterDimCommand = make("diameter", "dimdiameter");
|
||||
export const arcDimCommand = make("arc", "dimarc");
|
||||
@@ -0,0 +1,109 @@
|
||||
// Baugrube ([68]) — Umriss der Sohle per Klicks; der Kern (`cmd_solid.rs`) legt ein Kontext-Objekt
|
||||
// `excavation` an (Sohle = Geschoss-Unterkante − 0.30 m, Böschung 45°), das jedes Gelände-Netz unter dem
|
||||
// Umriss schneidet. Sohle, Böschung und Bermen danach im Panel „Gelände & Kontext".
|
||||
//
|
||||
// Schritte:
|
||||
// 1) „Erster Punkt der Baugrubensohle:" → Punkt
|
||||
// 2) „Nächster Punkt …" → Punkt … Schliessen per Klick auf den Startpunkt, Option „Schliessen" oder
|
||||
// Enter (≥ 3 Punkte; bei genau 2 Punkten: Rechteck aus den Ecken).
|
||||
|
||||
import type { Command, CommandContext, CommandResult, CommandState, CmdOption, DraftShape, ToolDraft, Vec2 } from "../types";
|
||||
import { createMutation } from "../createCore";
|
||||
|
||||
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);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit (Kern, `cmd_solid.rs`): Baugrube aus dem Umriss (≥ 3 Punkte wie gezeichnet, 2 Punkte als Rechteck);
|
||||
* entartet → nichts.
|
||||
*/
|
||||
const excavationOps = (points: Vec2[], ctx: CommandContext) => createMutation(ctx, { cmd: "excavation", pts: points });
|
||||
|
||||
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: excavationOps(points, ctx) },
|
||||
];
|
||||
|
||||
export const excavationCommand: Command = {
|
||||
name: "excavation",
|
||||
labelKey: "cmd.excavation.label",
|
||||
floorOnly: true,
|
||||
prompt: (s) => ((s as HoleState).phase === "next" ? "cmd.excavation.next" : "cmd.excavation.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 den Umriss.
|
||||
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(),
|
||||
};
|
||||
@@ -32,25 +32,25 @@ let lastTaper = 0;
|
||||
// ── Profil (Kern, `cmd_create.rs`): geschlossene polyline/rect/circle → Punktliste ─
|
||||
|
||||
/** Profil eines extrudierbaren 2D-Elements (Kreis: 48-Eck + Mittelpunkt/Radius). */
|
||||
interface Profile {
|
||||
export interface Profile {
|
||||
pts: Vec2[];
|
||||
circle?: { center: Vec2; r: number };
|
||||
}
|
||||
|
||||
type ProfileHit = { id: string } & Profile;
|
||||
export type ProfileHit = { id: string } & Profile;
|
||||
|
||||
function profileQuery(project: Project, req: { q: string } & Record<string, unknown>): ProfileHit | null {
|
||||
return createQuery<{ hit: (ProfileHit & { circle: Profile["circle"] | null }) | null }>(project, req).hit ?? null;
|
||||
}
|
||||
|
||||
/** Genau EIN geeignetes Profil vorgewählt (sonst null). */
|
||||
function singleSelectedProfile(project: Project, sel: CommandSelection): ProfileHit | null {
|
||||
export function singleSelectedProfile(project: Project, sel: CommandSelection): ProfileHit | null {
|
||||
if (!sel.drawingId || sel.wallIds.length > 0) return null;
|
||||
return profileQuery(project, { q: "profile", id: sel.drawingId });
|
||||
}
|
||||
|
||||
/** Nächstes Profil der Ebene am Klickpunkt (Kanten-Abstand < 0.25 m). */
|
||||
const pickProfileAt = (project: Project, levelId: string, pt: Vec2): ProfileHit | null =>
|
||||
export const pickProfileAt = (project: Project, levelId: string, pt: Vec2): ProfileHit | null =>
|
||||
profileQuery(project, { q: "pickProfile", level: levelId, pt: xy(pt) });
|
||||
|
||||
/** Commit (Kern): Quelle entfernen, Körper (Punkte + Höhe + Verjüngung) anlegen. */
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* `gridCommand` ([112]) und die Rundmass-Befehle ([38]): Eingabe → Zeichnung im Kern. Die Nachführung der
|
||||
* Bezüge im Store prüft `src/state/gridAssoc.test.ts`.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { gridCommand } from "./grid";
|
||||
import { arcDimCommand, diameterDimCommand, radiusDimCommand } from "./dimround";
|
||||
import type { CommandContext, Project } from "../types";
|
||||
import type { Drawing2D } from "../../model/types";
|
||||
|
||||
function project(extra: Drawing2D[] = []): 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: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }],
|
||||
walls: [],
|
||||
openings: [],
|
||||
ceilings: [],
|
||||
stairs: [],
|
||||
rooms: [],
|
||||
drawings2d: extra,
|
||||
context: [],
|
||||
};
|
||||
}
|
||||
|
||||
function ctxOf(p: Project): CommandContext {
|
||||
return { project: p, level: p.drawingLevels[0], defaultCategoryCode: "20", activeLineStyleId: "solid", activeWallTypeId: "aw", lastPoint: null, selection: { wallIds: [], drawingId: null } };
|
||||
}
|
||||
|
||||
describe("gridCommand", () => {
|
||||
it("Ursprung + Feldweiten → Achsraster mit Beschriftung 1, 2, 3 / A, B", () => {
|
||||
const p = project();
|
||||
const ctx = ctxOf(p);
|
||||
let [s] = gridCommand.onInput(gridCommand.init(), { kind: "point", point: { x: 2, y: 1 } }, ctx);
|
||||
[s] = gridCommand.onInput(s, { kind: "text", text: "6 4.5 3x5" }, ctx);
|
||||
const [, r] = gridCommand.onInput(s, { kind: "text", text: "5 5" }, ctx);
|
||||
expect(r.done).toBe(true);
|
||||
const g = r.commit!(p).drawings2d[0].geom;
|
||||
expect(g.shape).toBe("grid");
|
||||
if (g.shape !== "grid") return;
|
||||
expect(g.origin).toEqual({ x: 2, y: 1 });
|
||||
expect(g.a.map((x) => [x.label, x.pos])).toEqual([["1", 0], ["2", 6], ["3", 10.5], ["4", 15.5], ["5", 20.5], ["6", 25.5]]);
|
||||
expect(g.b.map((x) => [x.label, x.pos])).toEqual([["A", 0], ["B", 5], ["C", 10]]);
|
||||
});
|
||||
|
||||
it("radial: Option umschalten, Strahlen und Ringe; Enter übernimmt die Vorgaben", () => {
|
||||
const p = project();
|
||||
const ctx = ctxOf(p);
|
||||
let [s] = gridCommand.onInput(gridCommand.init(), { kind: "option", id: "radial" }, ctx);
|
||||
[s] = gridCommand.onInput(s, { kind: "point", point: { x: 0, y: 0 } }, ctx);
|
||||
[s] = gridCommand.onInput(s, { kind: "text", text: "2x45" }, ctx);
|
||||
const [, r] = gridCommand.onInput(s, { kind: "text", text: "3 3" }, ctx);
|
||||
const g = r.commit!(p).drawings2d[0].geom;
|
||||
expect(g.shape === "grid" && g.radial).toBe(true);
|
||||
if (g.shape === "grid") {
|
||||
expect(g.a.map((x) => x.pos)).toEqual([0, 45, 90]);
|
||||
expect(g.b.map((x) => x.pos)).toEqual([3, 6]);
|
||||
}
|
||||
// Vorgaben (Enter, Enter) im rechtwinkligen Raster: 6 6 6 / 6 6.
|
||||
let [t] = gridCommand.onInput(gridCommand.init(), { kind: "point", point: { x: 0, y: 0 } }, ctx);
|
||||
[t] = gridCommand.onConfirm(t, ctx);
|
||||
const [, e] = gridCommand.onConfirm(t, ctx);
|
||||
const d = e.commit!(p).drawings2d[0].geom;
|
||||
expect(d.shape === "grid" && [d.a.length, d.b.length]).toEqual([4, 3]);
|
||||
});
|
||||
|
||||
it("unlesbare Feldweiten legen nichts an; Vorschau am Cursor liefert Achsen", () => {
|
||||
const p = project();
|
||||
const ctx = ctxOf(p);
|
||||
let [s] = gridCommand.onInput(gridCommand.init(), { kind: "point", point: { x: 0, y: 0 } }, ctx);
|
||||
[s] = gridCommand.onInput(s, { kind: "text", text: "abc" }, ctx);
|
||||
const [, r] = gridCommand.onInput(s, { kind: "text", text: "5" }, ctx);
|
||||
expect(r.commit!(p).drawings2d.length).toBe(0);
|
||||
const [, mv] = gridCommand.onMove(gridCommand.init(), { x: 1, y: 1 }, null, ctx);
|
||||
expect(mv.draft?.preview.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Rundmass-Befehle", () => {
|
||||
const circle = { id: "K", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "circle", center: { x: 5, y: 5 }, r: 2 } } as Drawing2D;
|
||||
|
||||
it("Radius/Durchmesser: ein Klick auf den Rand → Mass mit Bezug", () => {
|
||||
for (const [cmd, kind] of [[radiusDimCommand, "radius"], [diameterDimCommand, "diameter"]] as const) {
|
||||
const p = project([circle]);
|
||||
const [, r] = cmd.onInput(cmd.init(), { kind: "point", point: { x: 7, y: 5.02 } }, ctxOf(p));
|
||||
const g = r.commit!(p).drawings2d[1].geom;
|
||||
expect(g.shape === "dimension" && g.kind).toBe(kind);
|
||||
expect(g.shape === "dimension" && g.refs?.map((x) => x?.feature)).toEqual(["center", "rim"]);
|
||||
}
|
||||
});
|
||||
|
||||
it("Bogenlänge: Anfang, Ende, Lage → drei Punkte; Klick ins Leere legt nichts an", () => {
|
||||
const p = project([circle]);
|
||||
const ctx = ctxOf(p);
|
||||
let [s] = arcDimCommand.onInput(arcDimCommand.init(), { kind: "point", point: { x: 7, y: 5 } }, ctx);
|
||||
[s] = arcDimCommand.onInput(s, { kind: "point", point: { x: 5, y: 7 } }, ctx);
|
||||
const [, r] = arcDimCommand.onInput(s, { kind: "point", point: { x: 5, y: 8 } }, ctx);
|
||||
const dim = r.commit!(p).drawings2d[1];
|
||||
expect(dim.geom.shape === "dimension" && dim.geom.pts.length).toBe(3);
|
||||
expect(dim.geom.shape === "dimension" && dim.geom.offset).toBeCloseTo(1, 6);
|
||||
const [, none] = radiusDimCommand.onInput(radiusDimCommand.init(), { kind: "point", point: { x: 50, y: 50 } }, ctx);
|
||||
expect(none.commit!(p).drawings2d.length).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
// Achsraster ([112]): Ursprung klicken, dann die Feldweiten als Text (`6 4.5 3x5`: Zahlen, `N x W` =
|
||||
// N Felder zu W). Rechtwinklig: erst die Richtung 1, 2, 3 …, dann A, B, C …; radial: Strahlwinkel in
|
||||
// Grad und Ringabstände. Das Raster ist eine 2D-Zeichnung (Kern, `grid.rs`): Achsen mit Blasen in
|
||||
// allen Plänen, Schnitten und Ansichten, Fang auf Achsen und Schnittpunkte, Griffe je Achse.
|
||||
|
||||
import type { Command, CommandContext, CommandResult, CommandState, CmdOption, ToolDraft, Vec2 } from "../types";
|
||||
import { createMutation, createPreview, xy } from "../createCore";
|
||||
|
||||
type Phase = "origin" | "xs" | "ys";
|
||||
|
||||
interface GridState extends CommandState {
|
||||
phase: Phase;
|
||||
origin: Vec2 | null;
|
||||
radial: boolean;
|
||||
xs: string;
|
||||
ys: string;
|
||||
}
|
||||
|
||||
const DEFAULTS = {
|
||||
ortho: { xs: "6 6 6", ys: "6 6" },
|
||||
radial: { xs: "4x45", ys: "3 3 3" },
|
||||
};
|
||||
|
||||
const RADIAL: CmdOption = { id: "radial", labelKey: "cmd.grid.radial" };
|
||||
|
||||
const start = (radial = false): GridState => ({
|
||||
phase: "origin",
|
||||
lastPoint: null,
|
||||
origin: null,
|
||||
radial,
|
||||
xs: radial ? DEFAULTS.radial.xs : DEFAULTS.ortho.xs,
|
||||
ys: radial ? DEFAULTS.radial.ys : DEFAULTS.ortho.ys,
|
||||
});
|
||||
|
||||
const idle = (): [CommandState, CommandResult] => [start(), { draft: null, done: true }];
|
||||
|
||||
/** Vorschau (Kern): die Achsen des Rasters am Cursor. */
|
||||
function draft(ctx: CommandContext, s: GridState, at: Vec2): ToolDraft {
|
||||
const pv = createPreview(ctx, { cmd: "grid", xs: s.xs, ys: s.ys, radial: s.radial, angle: 0 }, [at]);
|
||||
return { preview: pv.shapes, vertices: [at] };
|
||||
}
|
||||
|
||||
const commit = (ctx: CommandContext, s: GridState, ys: string) =>
|
||||
createMutation(ctx, { cmd: "grid", at: xy(s.origin as Vec2), xs: s.xs, ys, radial: s.radial, angle: 0 });
|
||||
|
||||
export const gridCommand: Command = {
|
||||
name: "grid",
|
||||
labelKey: "cmd.grid.label",
|
||||
prompt: (state) => {
|
||||
const s = state as GridState;
|
||||
if (s.phase === "origin") return "cmd.grid.origin";
|
||||
if (s.phase === "xs") return s.radial ? "cmd.grid.xsRadial" : "cmd.grid.xs";
|
||||
return s.radial ? "cmd.grid.ysRadial" : "cmd.grid.ys";
|
||||
},
|
||||
accepts: (state) => ((state as GridState).phase === "origin" ? ["point", "option"] : ["text"]),
|
||||
options: (state): CmdOption[] => ((state as GridState).phase === "origin" ? [{ ...RADIAL, value: (state as GridState).radial ? "ja" : "nein" }] : []),
|
||||
floorOnly: false,
|
||||
init: () => start(),
|
||||
|
||||
onInput: (state, input, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as GridState;
|
||||
if (s.phase === "origin") {
|
||||
if (input.kind === "option" && input.id === "radial") return [start(!s.radial), { draft: null }];
|
||||
if (input.kind !== "point") return [s, { draft: null }];
|
||||
const ns: GridState = { ...s, phase: "xs", origin: input.point, lastPoint: input.point };
|
||||
return [ns, { draft: draft(ctx, ns, input.point) }];
|
||||
}
|
||||
if (input.kind !== "text") return [s, { draft: null }];
|
||||
const text = input.text.trim();
|
||||
if (s.phase === "xs") {
|
||||
const ns: GridState = { ...s, phase: "ys", xs: text === "" ? s.xs : text };
|
||||
return [ns, { draft: s.origin ? draft(ctx, ns, s.origin) : null }];
|
||||
}
|
||||
const ys = text === "" && !s.radial ? s.ys : text;
|
||||
return [start(), { draft: null, done: true, commit: commit(ctx, s, ys) }];
|
||||
},
|
||||
|
||||
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as GridState;
|
||||
if (s.phase !== "origin") return [s, { draft: s.origin ? draft(ctx, s, s.origin) : null }];
|
||||
return [s, { draft: draft(ctx, s, point) }];
|
||||
},
|
||||
|
||||
// Enter: Vorgabe-Feldweiten übernehmen.
|
||||
onConfirm: (state, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as GridState;
|
||||
if (s.phase === "origin") return idle();
|
||||
if (s.phase === "xs") {
|
||||
const ns: GridState = { ...s, phase: "ys" };
|
||||
return [ns, { draft: s.origin ? draft(ctx, ns, s.origin) : null }];
|
||||
}
|
||||
return [start(), { draft: null, done: true, commit: commit(ctx, s, s.ys) }];
|
||||
},
|
||||
onCancel: () => idle(),
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
// Loft ([T7]): ≥ 2 geschlossene Plan-Profile nacheinander anklicken (erstes = unten), Enter, dann die
|
||||
// Gesamthöhe. Die Profile werden gleichmässig über die Höhe verteilt (Kern `cmd_solid.rs`: gleiche
|
||||
// Punktzahl durch Kantenteilung, Drehsinn angeglichen) und zu einem truck-`loft`-B-Rep-Körper
|
||||
// (`ExtrudedSolid.brep`) verbunden; die Quellprofile entfallen wie beim Extrudieren.
|
||||
|
||||
import type { Command, CommandContext, CommandResult, CommandState, Vec2 } from "../types";
|
||||
import { createMutation } from "../createCore";
|
||||
import { pickProfileAt, type ProfileHit } from "./extrude";
|
||||
|
||||
let lastHeight = 3;
|
||||
|
||||
interface LoftState extends CommandState {
|
||||
phase: "pick" | "height" | "done";
|
||||
picks: ProfileHit[];
|
||||
}
|
||||
|
||||
const draft = (s: LoftState, cursor: Vec2 | null): CommandResult["draft"] => ({
|
||||
preview: s.picks.map((p) => ({ kind: "poly" as const, pts: p.pts, closed: true })),
|
||||
vertices: [],
|
||||
hud: cursor ? { at: cursor, text: s.phase === "height" ? `${lastHeight.toFixed(2)} m` : `${s.picks.length}` } : undefined,
|
||||
});
|
||||
|
||||
const finished = (): LoftState => ({ phase: "done", picks: [], lastPoint: null });
|
||||
const done = (): [CommandState, CommandResult] => [finished(), { draft: null, done: true }];
|
||||
|
||||
function commit(s: LoftState, height: number, ctx: CommandContext): [CommandState, CommandResult] {
|
||||
lastHeight = height;
|
||||
return [
|
||||
finished(),
|
||||
{ draft: null, done: true, commit: createMutation(ctx, { cmd: "loft", sources: s.picks.map((p) => p.id), height }) },
|
||||
];
|
||||
}
|
||||
|
||||
export const loftCommand: Command = {
|
||||
name: "loft",
|
||||
labelKey: "cmd.loft.label",
|
||||
prompt: (st) => ((st as LoftState).phase === "height" ? "cmd.loft.height" : (st as LoftState).picks.length < 2 ? "cmd.loft.pick" : "cmd.loft.pickMore"),
|
||||
accepts: (st) => ((st as LoftState).phase === "height" ? ["number"] : ["point"]),
|
||||
options: () => [],
|
||||
floorOnly: true,
|
||||
|
||||
init: (): LoftState => ({ phase: "pick", picks: [], lastPoint: null }),
|
||||
|
||||
onInput: (state, input, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as LoftState;
|
||||
if (s.phase === "done") return done();
|
||||
if (s.phase === "pick") {
|
||||
if (input.kind !== "point") return [s, { draft: draft(s, null) }];
|
||||
const hit = pickProfileAt(ctx.project, ctx.level.id, input.point);
|
||||
if (!hit || s.picks.some((p) => p.id === hit.id)) return [s, { draft: draft(s, null) }];
|
||||
const ns: LoftState = { ...s, picks: [...s.picks, hit] };
|
||||
return [ns, { draft: draft(ns, input.point) }];
|
||||
}
|
||||
if (input.kind !== "number" || !(input.value > 0)) return [s, { draft: draft(s, null) }];
|
||||
return commit(s, input.value, ctx);
|
||||
},
|
||||
|
||||
onMove: (state, point): [CommandState, CommandResult] => [state, { draft: draft(state as LoftState, point) }],
|
||||
|
||||
// Enter: mit ≥ 2 Profilen zur Höhe; bei der Höhe die zuletzt benutzte übernehmen.
|
||||
onConfirm: (state, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as LoftState;
|
||||
if (s.phase === "pick") {
|
||||
if (s.picks.length < 2) return [s, { draft: draft(s, null) }];
|
||||
const ns: LoftState = { ...s, phase: "height" };
|
||||
return [ns, { draft: draft(ns, null) }];
|
||||
}
|
||||
return s.phase === "height" ? commit(s, lastHeight, ctx) : done();
|
||||
},
|
||||
onCancel: () => done(),
|
||||
};
|
||||
@@ -0,0 +1,98 @@
|
||||
// Rotationskörper ([T7]): geschlossenes Plan-Profil + Drehachse (2 Punkte im Plan) + Winkel → truck-
|
||||
// `revolve` als B-Rep-Körper (`ExtrudedSolid.brep`, Kern `cmd_solid.rs`). Das Profil muss ganz auf einer
|
||||
// Seite der Achse liegen; die Achse liegt waagrecht auf Höhe des grössten Profilabstands, ein voller
|
||||
// Körper steht also auf der Geschoss-UK. Die Quelle (Profil) wird ersetzt wie beim Extrudieren.
|
||||
//
|
||||
// Schritte: Profil wählen (oder vorselektiert) → Achse Anfang → Achse Ende → Winkel (Zahl oder Enter = zuletzt, 360).
|
||||
|
||||
import type { Command, CommandContext, CommandResult, CommandState, Vec2 } from "../types";
|
||||
import { createMutation } from "../createCore";
|
||||
import { pickProfileAt, singleSelectedProfile, type Profile } from "./extrude";
|
||||
|
||||
let lastAngle = 360;
|
||||
|
||||
interface RevState extends CommandState {
|
||||
phase: "pick" | "axisA" | "axisB" | "angle" | "done";
|
||||
profile: Profile | null;
|
||||
sourceId: string | null;
|
||||
a: Vec2 | null;
|
||||
b: Vec2 | null;
|
||||
cursor: Vec2 | null;
|
||||
}
|
||||
|
||||
const draft = (s: RevState, cursor: Vec2 | null): CommandResult["draft"] => {
|
||||
const preview: NonNullable<CommandResult["draft"]>["preview"] = [];
|
||||
if (s.profile) preview.push({ kind: "poly", pts: s.profile.pts, closed: true });
|
||||
const end = s.b ?? cursor;
|
||||
if (s.a && end) preview.push({ kind: "line", a: s.a, b: end });
|
||||
return { preview, vertices: s.a ? [s.a] : [], hud: cursor && s.phase === "angle" ? { at: cursor, text: `${lastAngle}°` } : undefined };
|
||||
};
|
||||
|
||||
const finished = (): RevState => ({ phase: "done", profile: null, sourceId: null, a: null, b: null, cursor: null, lastPoint: null });
|
||||
|
||||
const done = (): [CommandState, CommandResult] => [finished(), { draft: null, done: true }];
|
||||
|
||||
function commit(s: RevState, angle: number, ctx: CommandContext): [CommandState, CommandResult] {
|
||||
lastAngle = angle;
|
||||
return [
|
||||
finished(),
|
||||
{ draft: null, done: true, commit: createMutation(ctx, { cmd: "revolve", source: s.sourceId, a: s.a, b: s.b, angle }) },
|
||||
];
|
||||
}
|
||||
|
||||
export const revolveCommand: Command = {
|
||||
name: "revolve",
|
||||
labelKey: "cmd.revolve.label",
|
||||
prompt: (st) => {
|
||||
const p = (st as RevState).phase;
|
||||
return p === "axisA" ? "cmd.revolve.axisA" : p === "axisB" ? "cmd.revolve.axisB" : p === "angle" ? "cmd.revolve.angle" : "cmd.revolve.pick";
|
||||
},
|
||||
accepts: (st) => ((st as RevState).phase === "angle" ? ["number"] : ["point"]),
|
||||
options: () => [],
|
||||
floorOnly: true,
|
||||
|
||||
init: (): RevState => ({ phase: "pick", profile: null, sourceId: null, a: null, b: null, cursor: null, lastPoint: null }),
|
||||
|
||||
onInput: (state, input, ctx): [CommandState, CommandResult] => {
|
||||
let s = state as RevState;
|
||||
if (s.phase === "done") return done();
|
||||
if (s.phase === "pick") {
|
||||
if (input.kind !== "point") return [s, { draft: null }];
|
||||
// Vorselektiertes Profil: der erste Punkt ist gleich der Achsenanfang.
|
||||
const pre = singleSelectedProfile(ctx.project, ctx.selection);
|
||||
if (pre) {
|
||||
s = { ...s, phase: "axisA", profile: pre, sourceId: pre.id };
|
||||
} else {
|
||||
const hit = pickProfileAt(ctx.project, ctx.level.id, input.point);
|
||||
if (!hit) return [s, { draft: null }];
|
||||
const ns: RevState = { ...s, phase: "axisA", profile: hit, sourceId: hit.id };
|
||||
return [ns, { draft: draft(ns, null) }];
|
||||
}
|
||||
}
|
||||
if (s.phase === "axisA") {
|
||||
if (input.kind !== "point") return [s, { draft: draft(s, s.cursor) }];
|
||||
const ns: RevState = { ...s, phase: "axisB", a: input.point, lastPoint: input.point };
|
||||
return [ns, { draft: draft(ns, input.point) }];
|
||||
}
|
||||
if (s.phase === "axisB") {
|
||||
if (input.kind !== "point" || !s.a || Math.hypot(input.point.x - s.a.x, input.point.y - s.a.y) < 1e-6) return [s, { draft: draft(s, s.cursor) }];
|
||||
const ns: RevState = { ...s, phase: "angle", b: input.point, lastPoint: input.point };
|
||||
return [ns, { draft: draft(ns, input.point) }];
|
||||
}
|
||||
// angle
|
||||
if (input.kind !== "number" || !(input.value > 0)) return [s, { draft: draft(s, s.cursor) }];
|
||||
return commit(s, Math.min(360, input.value), ctx);
|
||||
},
|
||||
|
||||
onMove: (state, point): [CommandState, CommandResult] => {
|
||||
const s = { ...(state as RevState), cursor: point };
|
||||
return [s, { draft: draft(s, point) }];
|
||||
},
|
||||
|
||||
// Enter beim Winkel: zuletzt benutzten Winkel übernehmen.
|
||||
onConfirm: (state, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as RevState;
|
||||
return s.phase === "angle" ? commit(s, lastAngle, ctx) : done();
|
||||
},
|
||||
onCancel: () => done(),
|
||||
};
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* [T7] `revolveCommand` (Profil + Achse + Winkel) und `loftCommand` (≥ 2 Profile + Höhe): beide legen
|
||||
* einen B-Rep-Körper (`ExtrudedSolid.brep`) an und entfernen die Quellprofile.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { revolveCommand } from "./revolve";
|
||||
import { loftCommand } from "./loft";
|
||||
import type { CommandContext, CmdInput, Project } from "../types";
|
||||
|
||||
const rect = (id: string, x: number, y: number, w: number, h: number) => ({
|
||||
id,
|
||||
type: "drawing2d" as const,
|
||||
levelId: "eg",
|
||||
categoryCode: "20",
|
||||
geom: { shape: "rect" as const, min: { x, y }, max: { x: x + w, y: y + h } },
|
||||
});
|
||||
|
||||
function project(): 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: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }],
|
||||
walls: [],
|
||||
openings: [],
|
||||
ceilings: [],
|
||||
stairs: [],
|
||||
rooms: [],
|
||||
drawings2d: [rect("A", 0, 1, 2, 1), rect("B", 10, 0, 1, 1)],
|
||||
extrudedSolids: [],
|
||||
context: [],
|
||||
} as unknown as Project;
|
||||
}
|
||||
|
||||
function makeCtx(p: Project, drawingId: string | null = null): CommandContext {
|
||||
return {
|
||||
project: p,
|
||||
level: p.drawingLevels[0],
|
||||
defaultCategoryCode: "20",
|
||||
activeLineStyleId: "solid",
|
||||
activeWallTypeId: "aw",
|
||||
lastPoint: null,
|
||||
selection: { wallIds: [], drawingId },
|
||||
} as CommandContext;
|
||||
}
|
||||
|
||||
/** Spielt Eingaben ab; liefert das Projekt nach dem Commit (oder null). */
|
||||
function run(cmd: typeof revolveCommand, p: Project, inputs: Array<CmdInput | "confirm">, selected: string | null = null) {
|
||||
const ctx = makeCtx(p, selected);
|
||||
let state = cmd.init();
|
||||
let commit: ((p: Project) => Project) | undefined;
|
||||
for (const i of inputs) {
|
||||
const [ns, res] = i === "confirm" ? cmd.onConfirm(state, ctx) : cmd.onInput(state, i, ctx);
|
||||
state = ns;
|
||||
if (res.commit) commit = res.commit as typeof commit;
|
||||
}
|
||||
return commit ? commit(p) : null;
|
||||
}
|
||||
|
||||
const pt = (x: number, y: number): CmdInput => ({ kind: "point", point: { x, y } });
|
||||
|
||||
describe("revolveCommand", () => {
|
||||
it("Profil wählen, Achse (2 Punkte), Winkel → Rotationskörper, Quelle entfernt", () => {
|
||||
const next = run(revolveCommand, project(), [pt(1, 1), pt(-1, 0), pt(5, 0), { kind: "number", value: 180 }])!;
|
||||
expect(next.drawings2d.map((d) => d.id)).toEqual(["B"]);
|
||||
const s = next.extrudedSolids![0];
|
||||
expect(s.brep!.spec).toMatchObject({ kind: "transform", solid: { kind: "revolve", angleDeg: 180 } });
|
||||
expect(s.height).toBeCloseTo(4, 9); // Profil 1 … 2 m neben der Achse y=0 → r_max = 2
|
||||
});
|
||||
|
||||
it("Enter beim Winkel übernimmt den zuletzt benutzten; vorgewähltes Profil überspringt die Wahl", () => {
|
||||
run(revolveCommand, project(), [pt(1, 1), pt(-1, 0), pt(5, 0), { kind: "number", value: 90 }]);
|
||||
const next = run(revolveCommand, project(), [pt(-1, 0), pt(5, 0), "confirm"], "A")!;
|
||||
expect(next.extrudedSolids![0].brep!.spec).toMatchObject({ solid: { angleDeg: 90 } });
|
||||
});
|
||||
|
||||
it("Profil, das die Achse überquert, ergibt keinen Körper", () => {
|
||||
const next = run(revolveCommand, project(), [pt(1, 1), pt(-1, 1.5), pt(5, 1.5), "confirm"]);
|
||||
expect(next?.extrudedSolids ?? []).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("loftCommand", () => {
|
||||
it("zwei Profile wählen, Enter, Höhe → Loft-Körper, Quellen entfernt", () => {
|
||||
const next = run(loftCommand, project(), [pt(1, 1), pt(10.5, 0), "confirm", { kind: "number", value: 3 }])!;
|
||||
expect(next.drawings2d).toHaveLength(0);
|
||||
const s = next.extrudedSolids![0];
|
||||
expect(s.height).toBe(3);
|
||||
expect(s.brep!.spec).toMatchObject({ kind: "loft" });
|
||||
expect((s.brep!.spec as { sections: unknown[] }).sections).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("mit nur einem Profil bleibt Enter wirkungslos", () => {
|
||||
const next = run(loftCommand, project(), [pt(1, 1), "confirm", { kind: "number", value: 3 }]);
|
||||
expect(next?.extrudedSolids ?? []).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -47,12 +47,16 @@ import { scaleCommand } from "./cmds/scale";
|
||||
import { explodeCommand } from "./cmds/explode";
|
||||
import { dimdetachCommand } from "./cmds/dimdetach";
|
||||
import { autodimCommand } from "./cmds/autodim";
|
||||
import { gridCommand } from "./cmds/grid";
|
||||
import { arcDimCommand, diameterDimCommand, radiusDimCommand } from "./cmds/dimround";
|
||||
import { alignCommand } from "./cmds/align";
|
||||
import { joinCommand } from "./cmds/join";
|
||||
import { copyCommand } from "./cmds/copy";
|
||||
import { arrayCommand } from "./cmds/array";
|
||||
import { offsetCommand } from "./cmds/offset";
|
||||
import { extrudeCommand } from "./cmds/extrude";
|
||||
import { revolveCommand } from "./cmds/revolve";
|
||||
import { loftCommand } from "./cmds/loft";
|
||||
import { trimCommand } from "./cmds/trim";
|
||||
import { breakCommand } from "./cmds/break";
|
||||
import { extendCommand } from "./cmds/extend";
|
||||
@@ -61,6 +65,7 @@ import { chamferCommand } from "./cmds/chamfer";
|
||||
import { multilineCommand } from "./cmds/multiline";
|
||||
import { importCommand } from "./cmds/import";
|
||||
import { terrainCommand } from "./cmds/terrain";
|
||||
import { excavationCommand } from "./cmds/excavation";
|
||||
import { measureCommand } from "./cmds/measure";
|
||||
import { sectionLineCommand, viewLineCommand } from "./cmds/sectionline";
|
||||
import { georefCommand } from "./cmds/georef";
|
||||
@@ -114,12 +119,18 @@ export const COMMANDS: Record<string, Command> = {
|
||||
explode: explodeCommand,
|
||||
dimdetach: dimdetachCommand,
|
||||
autodim: autodimCommand,
|
||||
grid: gridCommand,
|
||||
dimradius: radiusDimCommand,
|
||||
dimdiameter: diameterDimCommand,
|
||||
dimarc: arcDimCommand,
|
||||
align: alignCommand,
|
||||
join: joinCommand,
|
||||
copy: copyCommand,
|
||||
array: arrayCommand,
|
||||
offset: offsetCommand,
|
||||
extrude: extrudeCommand,
|
||||
revolve: revolveCommand,
|
||||
loft: loftCommand,
|
||||
trim: trimCommand,
|
||||
break: breakCommand,
|
||||
extend: extendCommand,
|
||||
@@ -128,6 +139,7 @@ export const COMMANDS: Record<string, Command> = {
|
||||
multiline: multilineCommand,
|
||||
import: importCommand,
|
||||
terrain: terrainCommand,
|
||||
excavation: excavationCommand,
|
||||
measure: measureCommand,
|
||||
sectionline: sectionLineCommand,
|
||||
viewline: viewLineCommand,
|
||||
@@ -234,6 +246,15 @@ export const ALIASES: Record<string, string> = {
|
||||
bml: "dimdetach",
|
||||
bemassungloesen: "dimdetach",
|
||||
ab: "autodim",
|
||||
axes: "grid",
|
||||
achsraster: "grid",
|
||||
achsen: "grid",
|
||||
rad: "dimradius",
|
||||
radiusmass: "dimradius",
|
||||
dm: "dimdiameter",
|
||||
durchmessermass: "dimdiameter",
|
||||
bogenl: "dimarc",
|
||||
bogenlaenge: "dimarc",
|
||||
aussenbemassung: "autodim",
|
||||
al: "align",
|
||||
ausrichten: "align",
|
||||
@@ -244,6 +265,9 @@ export const ALIASES: Record<string, string> = {
|
||||
feld: "array",
|
||||
o: "offset",
|
||||
ex: "extrude",
|
||||
rev: "revolve",
|
||||
rotation: "revolve",
|
||||
lf: "loft",
|
||||
tr: "trim",
|
||||
br: "break",
|
||||
unterbrechen: "break",
|
||||
@@ -258,6 +282,8 @@ export const ALIASES: Record<string, string> = {
|
||||
parallel: "multiline",
|
||||
imp: "import",
|
||||
ter: "terrain",
|
||||
baugrube: "excavation",
|
||||
aushub: "excavation",
|
||||
schnittlinie: "sectionline",
|
||||
ansichtslinie: "viewline",
|
||||
bezugspunkt: "georef",
|
||||
|
||||
@@ -68,6 +68,7 @@ export type QueryName =
|
||||
| "programLayout"
|
||||
| "ivhb"
|
||||
| "siteCheck"
|
||||
| "excavationQuantities"
|
||||
| "buildingFootprint"
|
||||
| "modelTop"
|
||||
| "shadows"
|
||||
|
||||
@@ -44,6 +44,7 @@ export type { AreaReport, AreaReportOptions } from "../export/areaReport";
|
||||
export { sunPosition, shadowPolygons, shadowOfPrism, projectLatLon } from "../analysis/sun";
|
||||
export type { SunPosition } from "../analysis/sun";
|
||||
export { checkSiteRules, allowedArea, multiPolygonArea, buildingFootprint, modelTop } from "../analysis/siteRules";
|
||||
export { excavationQuantities, type ExcavationQuantity } from "../analysis/excavation";
|
||||
export type { SiteCheck } from "../analysis/siteRules";
|
||||
export { sampleProject } from "../model/sampleProject";
|
||||
export { parseDxf } from "../io/dxfParser";
|
||||
|
||||
@@ -53,12 +53,12 @@ describe("Tabellen auf dem Blatt ([111])", () => {
|
||||
expect(b.prims.filter((x) => x.k === "text" && x.s === tableLabels(p)["openings.col.mark"]).length).toBe(1);
|
||||
});
|
||||
|
||||
it("alle vier Quellen liefern Primitive; Katalog nennt die Spalten", () => {
|
||||
it("alle Quellen liefern Primitive; Katalog nennt die Spalten", () => {
|
||||
const cat = tableCatalog(sampleProject);
|
||||
expect(Object.keys(cat.sources).sort()).toEqual(["areas", "elements", "openings", "rooms"]);
|
||||
const p = withTables((["openings", "areas", "rooms", "elements"] as const).map((source) => table({ id: source, source })));
|
||||
expect(Object.keys(cat.sources).sort()).toEqual(["areas", "earthworks", "elements", "openings", "rooms"]);
|
||||
const p = withTables((["openings", "areas", "rooms", "elements", "earthworks"] as const).map((source) => table({ id: source, source })));
|
||||
const out = sheetTables(p, "L1");
|
||||
expect(out.map((o) => o.id)).toEqual(["openings", "areas", "rooms", "elements"]);
|
||||
expect(out.map((o) => o.id)).toEqual(["openings", "areas", "rooms", "elements", "earthworks"]);
|
||||
for (const o of out) expect(o.prims.some((x) => x.k === "text")).toBe(true);
|
||||
});
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ interface Catalog {
|
||||
valueKeys: string[];
|
||||
}
|
||||
|
||||
export const TABLE_SOURCES: readonly LayoutTableSource[] = ["openings", "areas", "rooms", "elements"];
|
||||
export const TABLE_SOURCES: readonly LayoutTableSource[] = ["openings", "areas", "rooms", "elements", "earthworks"];
|
||||
|
||||
export function tableSourceLabel(s: LayoutTableSource): string {
|
||||
return t(`sheetTable.source.${s}`);
|
||||
|
||||
@@ -208,6 +208,8 @@ export const de = {
|
||||
"tool.revcloud.hint": "Revisionswolke: Punkte wie Polylinie klicken, Enter beendet offen, Klick nahe Start oder \"Schliessen\" schliesst",
|
||||
"tool.pointmarker": "Punktmarker",
|
||||
"tool.pointmarker.hint": "Punktmarker: Punkt setzen — Kreuz-in-Kreis-Symbol markiert einen Referenzpunkt",
|
||||
"tool.grid": "Achsraster",
|
||||
"tool.grid.hint": "Achsraster: Ursprung setzen, dann Feldweiten eingeben — Achsen mit Blasen in allen Plänen, Schnitten und Ansichten",
|
||||
"tool.wipeout": "Maskenregion",
|
||||
"tool.wipeout.hint": "Maskenregion: Punkte wie Polylinie klicken, Klick nahe Start oder Enter (ab 3 Punkten) schliesst und deckt darunterliegende Zeichnung ab",
|
||||
"tool.text": "Text",
|
||||
@@ -384,6 +386,17 @@ export const de = {
|
||||
"attr.ends.tick": "Schrägstrich",
|
||||
"attr.ends.square": "Quadrat",
|
||||
"attr.dim.section": "Bemassung",
|
||||
"attr.grid.section": "Achsraster",
|
||||
"attr.grid.bubbles": "Achsblasen",
|
||||
"attr.grid.bubbles.both": "Beide Enden",
|
||||
"attr.grid.bubbles.start": "Nur Anfang",
|
||||
"attr.grid.bubbles.end": "Nur Ende",
|
||||
"attr.grid.extend": "Überstand (m)",
|
||||
"attr.grid.bubbleMm": "Blase Ø (mm)",
|
||||
"attr.grid.levels": "Sichtbar in",
|
||||
"attr.grid.show3d": "Im 3D-Modell zeigen",
|
||||
"attr.grid.levels.all": "Allen Geschossen",
|
||||
"attr.grid.levels.here": "Nur diesem Geschoss",
|
||||
"attr.dim.gap": "Abstand Hilfslinie (mm)",
|
||||
"attr.dim.overshoot": "Überstand (mm)",
|
||||
"attr.dim.tick": "Massstrich-Länge (mm)",
|
||||
@@ -525,6 +538,11 @@ export const de = {
|
||||
"objinfo.wall.refLine.right": "Innen (rechts)",
|
||||
"objinfo.wall.refLine.joint": "Fuge",
|
||||
"objinfo.wall.sliceTermination": "An Decke enden",
|
||||
"objinfo.wall.roofAttach": "An Dach anschliessen",
|
||||
"objinfo.wall.roofAttach.auto": "Automatisch",
|
||||
"objinfo.wall.roofAttach.on": "Ja, bis unters Dach",
|
||||
"objinfo.wall.roofAttach.off": "Nein",
|
||||
"objinfo.wall.roofAttach.tip": "Automatisch: Die Wand endet je Schicht an der Dach-Unterkante, wo ihre Krone darüber liegt. Ja: zusätzlich bis unter das Dach verlängert. Nein: Dächer schneiden die Wand nicht.",
|
||||
"objinfo.wall.sliceTermination.both": "Aus",
|
||||
"objinfo.wall.sliceTermination.below": "Unten",
|
||||
"objinfo.wall.sliceTermination.above": "Oben",
|
||||
@@ -797,6 +815,7 @@ export const de = {
|
||||
"objinfo.stair.shape.L": "L-Treppe",
|
||||
"objinfo.stair.shape.spiral": "Wendel",
|
||||
"objinfo.stair.width": "Laufbreite",
|
||||
"objinfo.stair.column": "Mittelsäule (Radius)",
|
||||
"objinfo.stair.steps": "Stufenanzahl",
|
||||
"objinfo.stair.rise": "Steighöhe (gesamt)",
|
||||
"objinfo.stair.riser": "Steigungshöhe",
|
||||
@@ -1615,6 +1634,9 @@ export const de = {
|
||||
"cmd.ceilingOpening.start": "Erste Ecke der Aussparung (in einer Decke):",
|
||||
"cmd.ceilingOpening.corner": "Gegenecke:",
|
||||
"cmd.roofHole.label": "Dachhof",
|
||||
"cmd.excavation.label": "Baugrube",
|
||||
"cmd.excavation.start": "Erster Punkt der Baugrubensohle:",
|
||||
"cmd.excavation.next": "Nächster Punkt (Enter bei 2 Punkten = Rechteck, ab 3 Punkten Polygon):",
|
||||
"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",
|
||||
@@ -1758,6 +1780,23 @@ export const de = {
|
||||
"cmd.revcloud.arcSize": "Beulengrösse",
|
||||
"cmd.pointmarker.label": "Punktmarker",
|
||||
"cmd.pointmarker.point": "Punkt:",
|
||||
"cmd.grid.label": "Achsraster",
|
||||
"cmd.grid.origin": "Ursprung des Achsrasters ( Radial ):",
|
||||
"cmd.grid.radial": "Radial",
|
||||
"cmd.grid.xs": "Feldweiten Achsen 1, 2, 3 … (z. B. 6 4.5 3x5, Enter = 6 6 6):",
|
||||
"cmd.grid.ys": "Feldweiten Achsen A, B, C … (z. B. 5 5, Enter = 6 6):",
|
||||
"cmd.grid.xsRadial": "Strahlwinkel in Grad (z. B. 8x45, Enter = 4x45):",
|
||||
"cmd.grid.ysRadial": "Ringabstände ab der Mitte (z. B. 3 3 4):",
|
||||
"cmd.dimradius.label": "Radiusmass",
|
||||
"cmd.dimradius.first": "Kreis, Bogen oder Bogenwand anklicken:",
|
||||
"cmd.dimdiameter.label": "Durchmessermass",
|
||||
"cmd.dimdiameter.first": "Kreis, Bogen oder Bogenwand anklicken:",
|
||||
"cmd.dimarc.label": "Bogenlänge",
|
||||
"cmd.dimarc.first": "Bogenanfang auf Kreis, Bogen oder Bogenwand:",
|
||||
"cmd.dimarc.second": "Bogenende:",
|
||||
"cmd.dimarc.offset": "Lage der Masslinie:",
|
||||
"history.cmd.grid": "Achsraster",
|
||||
"history.cmd.dimround": "Radius-/Bogenmass",
|
||||
"cmd.wipeout.label": "Maskenregion",
|
||||
"cmd.wipeout.start": "Startpunkt:",
|
||||
"cmd.wipeout.next": "Nächster Punkt:",
|
||||
@@ -1838,6 +1877,17 @@ export const de = {
|
||||
"cmd.offset.label": "Versatz",
|
||||
"cmd.offset.pick": "Kurve wählen:",
|
||||
"cmd.offset.side": "Seite oder Distanz:",
|
||||
"cmd.revolve.label": "Rotationskörper",
|
||||
"cmd.revolve.pick": "Geschlossenes Profil wählen:",
|
||||
"cmd.revolve.axisA": "Drehachse: Anfangspunkt:",
|
||||
"cmd.revolve.axisB": "Drehachse: Endpunkt:",
|
||||
"cmd.revolve.angle": "Drehwinkel (°, Enter = zuletzt):",
|
||||
"cmd.loft.label": "Loft",
|
||||
"cmd.loft.pick": "Profile der Reihe nach wählen (unten zuerst):",
|
||||
"cmd.loft.pickMore": "Weiteres Profil wählen oder Enter:",
|
||||
"cmd.loft.height": "Gesamthöhe:",
|
||||
"history.cmd.revolve": "Rotationskörper",
|
||||
"history.cmd.loft": "Loft",
|
||||
"cmd.extrude.label": "Extrudieren",
|
||||
"cmd.extrude.pick": "Geschlossenes Profil wählen:",
|
||||
"cmd.extrude.height": "Höhe:",
|
||||
@@ -1968,6 +2018,20 @@ export const de = {
|
||||
"site.type.mesh": "Mesh",
|
||||
"site.type.contours": "Konturen",
|
||||
"site.type.terrain": "Gelände",
|
||||
"site.type.excavation": "Baugrube",
|
||||
"site.smooth": "Glätten",
|
||||
"site.smooth.hint": "Höhenlinien als Bruchkanten, flache Dreiecke behoben, Fläche ohne Überschwingen geglättet",
|
||||
"site.excavation.draw": "Baugrube zeichnen",
|
||||
"site.excavation.hint": "Umriss der Sohle zeichnen; Böschungen schneiden das Gelände",
|
||||
"site.contourInterval": "Äquidistanz [m]",
|
||||
"site.contourIndexEvery": "Zähllinie jede",
|
||||
"site.excavation.bottom": "Sohle [m]",
|
||||
"site.excavation.slope": "Böschung [°]",
|
||||
"site.excavation.fillSlope": "Schüttung [°]",
|
||||
"site.excavation.bermWidth": "Berme [m]",
|
||||
"site.excavation.bermHeight": "Berme alle [m]",
|
||||
"site.excavation.qty": "Abtrag {cut} m³ · Auftrag {fill} m³ · Hinterfüllung {backfill} m³",
|
||||
"site.excavation.noTerrain": "Kein Gelände unter der Baugrube",
|
||||
"site.type.image": "Luftbild",
|
||||
"site.group.image": "Luftbild",
|
||||
"site.dwgHint": "DWG? Zuerst mit dem gratis ODA File Converter in DXF umwandeln.",
|
||||
@@ -2238,6 +2302,7 @@ export const de = {
|
||||
"mesh.import.upUncertain": "Achse unsicher, angenommen: {axis} oben (im Import-Dialog wählbar)",
|
||||
"mesh.import.dropped": "{n} ungültige oder entartete Flächen verworfen",
|
||||
"mesh.import.truncated": "abgebrochen: zu viele Dreiecke",
|
||||
"mesh.import.repaired": "repariert: {welded} Ecken verschweisst, {tris} entartete Dreiecke entfernt, {holes} Löcher geschlossen",
|
||||
"mesh.import.noFaces": "Die PLY-Datei enthält keine Flächen (Punktwolke): sie wird als Punktwolke geöffnet.",
|
||||
"mesh.import.missingExternal": "Zusätzliche Dateien fehlen: {list}. Wählen Sie sie zusammen mit dem Modell aus (oder ziehen Sie alle Dateien gemeinsam ins Fenster).",
|
||||
"mesh.importDialog.files": "Begleitdateien: {list}",
|
||||
@@ -2412,6 +2477,7 @@ export const de = {
|
||||
"siteRules.inside": "Gebäude innerhalb der zulässigen Fläche",
|
||||
"siteRules.heightOk": "Höhe {top} m ≤ {max} m",
|
||||
"siteRules.heightOver": "Höhe {top} m über {max} m",
|
||||
"siteRules.terrainAtFacade": "Massgebendes Terrain an der Fassade: {z} m (Höhe darüber gemessen)",
|
||||
"siteRules.defaultSetback": "Grenzabstand",
|
||||
"siteRules.maxHeight": "Gesamthöhe max.",
|
||||
"siteRules.edges": "Grenzabstand je Kante ({n})",
|
||||
@@ -2421,6 +2487,15 @@ export const de = {
|
||||
"siteRules.addLine.hint": "Eine Linie wählen; das Gebäude bleibt auf der Seite der Parzelle.",
|
||||
"siteRules.clearLines": "Alle Baulinien entfernen",
|
||||
"clash.none": "Keine Kollisionen gefunden.",
|
||||
"clash.run": "Prüfung starten",
|
||||
"clash.running": "Prüfung läuft …",
|
||||
"clash.clear": "Leeren",
|
||||
"clash.empty": "Keine Treffer. Die Prüfung vergleicht freie Körper und Importe mit Wänden, Decken und anderen Körpern.",
|
||||
"clash.kind.wall": "Wand",
|
||||
"clash.kind.slab": "Decke",
|
||||
"clash.kind.solid": "Körper",
|
||||
"clash.kind.mesh": "Import",
|
||||
"nav.clash": "Kollisionen",
|
||||
"clash.found": "Kollisionen gefunden",
|
||||
"clash.failed": "Kollisionsprüfung fehlgeschlagen",
|
||||
"about.title": "Über dossier",
|
||||
@@ -2744,6 +2819,7 @@ export const de = {
|
||||
"sheetTable.source.areas": "Flächentabelle (SIA 416)",
|
||||
"sheetTable.source.rooms": "Raumprogramm Soll/Ist",
|
||||
"sheetTable.source.elements": "Bauteile mit U-Wert",
|
||||
"sheetTable.source.earthworks": "Erdarbeiten (Baugruben)",
|
||||
"sheetTable.filter": "Zeigen",
|
||||
"sheetTable.filter.all": "Fenster und Türen",
|
||||
"sheetTable.filter.window": "Nur Fenster",
|
||||
@@ -2791,6 +2867,11 @@ export const de = {
|
||||
"sheetTable.col.diffPct": "Diff. [%]",
|
||||
"sheetTable.col.buildup": "Aufbau",
|
||||
"sheetTable.col.area": "Fläche [m²]",
|
||||
"sheetTable.col.name": "Bezeichnung",
|
||||
"sheetTable.col.bottom": "Sohle [m]",
|
||||
"sheetTable.col.cut": "Abtrag [m³]",
|
||||
"sheetTable.col.fill": "Auftrag [m³]",
|
||||
"sheetTable.col.backfill": "Hinterfüllung [m³]",
|
||||
"sheetTable.col.thickness": "Dicke [cm]",
|
||||
"sheetTable.v.window": "Fenster",
|
||||
"sheetTable.v.door": "Tür",
|
||||
@@ -2976,6 +3057,7 @@ export const de = {
|
||||
"history.cmd.revcloud": "Revisionswolke",
|
||||
"history.cmd.roof": "Dach zeichnen",
|
||||
"history.cmd.roofHole": "Dachöffnung",
|
||||
"history.cmd.excavation": "Baugrube",
|
||||
"history.cmd.room": "Raum zeichnen",
|
||||
"history.cmd.roomInside": "Raum aus Umriss",
|
||||
"history.cmd.scalebar": "Massstabsbalken",
|
||||
|
||||
@@ -206,6 +206,8 @@ export const en: Record<TranslationKey, string> = {
|
||||
"tool.revcloud.hint": "Revision cloud: click points like a polyline, Enter finishes open, clicking near start or \"Close\" closes it",
|
||||
"tool.pointmarker": "Point marker",
|
||||
"tool.pointmarker.hint": "Point marker: set a point — a cross-in-circle symbol marks a reference point",
|
||||
"tool.grid": "Structural grid",
|
||||
"tool.grid.hint": "Structural grid: set the origin, then enter bay widths — axes with bubbles in all plans, sections and elevations",
|
||||
"tool.wipeout": "Mask region",
|
||||
"tool.wipeout.hint": "Mask region: click points like a polyline, clicking near start or Enter (3+ points) closes and covers the drawing underneath",
|
||||
"tool.text": "Text",
|
||||
@@ -382,6 +384,17 @@ export const en: Record<TranslationKey, string> = {
|
||||
"attr.ends.tick": "Tick",
|
||||
"attr.ends.square": "Square",
|
||||
"attr.dim.section": "Dimension",
|
||||
"attr.grid.section": "Structural grid",
|
||||
"attr.grid.bubbles": "Axis bubbles",
|
||||
"attr.grid.bubbles.both": "Both ends",
|
||||
"attr.grid.bubbles.start": "Start only",
|
||||
"attr.grid.bubbles.end": "End only",
|
||||
"attr.grid.extend": "Extension (m)",
|
||||
"attr.grid.bubbleMm": "Bubble Ø (mm)",
|
||||
"attr.grid.levels": "Visible on",
|
||||
"attr.grid.show3d": "Show in 3D model",
|
||||
"attr.grid.levels.all": "All levels",
|
||||
"attr.grid.levels.here": "This level only",
|
||||
"attr.dim.gap": "Extension gap (mm)",
|
||||
"attr.dim.overshoot": "Overshoot (mm)",
|
||||
"attr.dim.tick": "Tick length (mm)",
|
||||
@@ -523,6 +536,11 @@ export const en: Record<TranslationKey, string> = {
|
||||
"objinfo.wall.refLine.right": "Interior (right)",
|
||||
"objinfo.wall.refLine.joint": "Joint",
|
||||
"objinfo.wall.sliceTermination": "End at ceiling",
|
||||
"objinfo.wall.roofAttach": "Attach to roof",
|
||||
"objinfo.wall.roofAttach.auto": "Automatic",
|
||||
"objinfo.wall.roofAttach.on": "Yes, up to the roof",
|
||||
"objinfo.wall.roofAttach.off": "No",
|
||||
"objinfo.wall.roofAttach.tip": "Automatic: each wall layer ends at the roof underside where its top lies above it. Yes: also extended up to the roof. No: roofs do not cut the wall.",
|
||||
"objinfo.wall.sliceTermination.both": "Off",
|
||||
"objinfo.wall.sliceTermination.below": "Below",
|
||||
"objinfo.wall.sliceTermination.above": "Above",
|
||||
@@ -794,6 +812,7 @@ export const en: Record<TranslationKey, string> = {
|
||||
"objinfo.stair.shape.L": "L-shaped",
|
||||
"objinfo.stair.shape.spiral": "Spiral",
|
||||
"objinfo.stair.width": "Run width",
|
||||
"objinfo.stair.column": "Centre column (radius)",
|
||||
"objinfo.stair.steps": "Step count",
|
||||
"objinfo.stair.rise": "Total rise",
|
||||
"objinfo.stair.riser": "Riser height",
|
||||
@@ -1604,6 +1623,9 @@ export const en: Record<TranslationKey, string> = {
|
||||
"cmd.ceilingOpening.start": "First corner of the opening (inside a slab):",
|
||||
"cmd.ceilingOpening.corner": "Opposite corner:",
|
||||
"cmd.roofHole.label": "Roof court",
|
||||
"cmd.excavation.label": "Excavation",
|
||||
"cmd.excavation.start": "First point of the excavation bottom:",
|
||||
"cmd.excavation.next": "Next point (Enter with 2 points = rectangle, 3 or more = polygon):",
|
||||
"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",
|
||||
@@ -1747,6 +1769,23 @@ export const en: Record<TranslationKey, string> = {
|
||||
"cmd.revcloud.arcSize": "Arc size",
|
||||
"cmd.pointmarker.label": "Point marker",
|
||||
"cmd.pointmarker.point": "Point:",
|
||||
"cmd.grid.label": "Structural grid",
|
||||
"cmd.grid.origin": "Grid origin ( Radial ):",
|
||||
"cmd.grid.radial": "Radial",
|
||||
"cmd.grid.xs": "Bay widths for axes 1, 2, 3 … (e.g. 6 4.5 3x5, Enter = 6 6 6):",
|
||||
"cmd.grid.ys": "Bay widths for axes A, B, C … (e.g. 5 5, Enter = 6 6):",
|
||||
"cmd.grid.xsRadial": "Ray angles in degrees (e.g. 8x45, Enter = 4x45):",
|
||||
"cmd.grid.ysRadial": "Ring spacings from the centre (e.g. 3 3 4):",
|
||||
"cmd.dimradius.label": "Radius dimension",
|
||||
"cmd.dimradius.first": "Pick a circle, arc or arc wall:",
|
||||
"cmd.dimdiameter.label": "Diameter dimension",
|
||||
"cmd.dimdiameter.first": "Pick a circle, arc or arc wall:",
|
||||
"cmd.dimarc.label": "Arc length",
|
||||
"cmd.dimarc.first": "Arc start on a circle, arc or arc wall:",
|
||||
"cmd.dimarc.second": "Arc end:",
|
||||
"cmd.dimarc.offset": "Position of the dimension line:",
|
||||
"history.cmd.grid": "Structural grid",
|
||||
"history.cmd.dimround": "Radius/arc dimension",
|
||||
"cmd.wipeout.label": "Mask region",
|
||||
"cmd.wipeout.start": "Start point:",
|
||||
"cmd.wipeout.next": "Next point:",
|
||||
@@ -1826,6 +1865,17 @@ export const en: Record<TranslationKey, string> = {
|
||||
"cmd.offset.label": "Offset",
|
||||
"cmd.offset.pick": "Select curve:",
|
||||
"cmd.offset.side": "Side or distance:",
|
||||
"cmd.revolve.label": "Revolve",
|
||||
"cmd.revolve.pick": "Select closed profile:",
|
||||
"cmd.revolve.axisA": "Revolve axis: start point:",
|
||||
"cmd.revolve.axisB": "Revolve axis: end point:",
|
||||
"cmd.revolve.angle": "Revolve angle (°, Enter = last):",
|
||||
"cmd.loft.label": "Loft",
|
||||
"cmd.loft.pick": "Select profiles in order (bottom first):",
|
||||
"cmd.loft.pickMore": "Select another profile or Enter:",
|
||||
"cmd.loft.height": "Total height:",
|
||||
"history.cmd.revolve": "Revolve",
|
||||
"history.cmd.loft": "Loft",
|
||||
"cmd.extrude.label": "Extrude",
|
||||
"cmd.extrude.pick": "Select closed profile:",
|
||||
"cmd.extrude.height": "Height:",
|
||||
@@ -1956,6 +2006,20 @@ export const en: Record<TranslationKey, string> = {
|
||||
"site.type.mesh": "Mesh",
|
||||
"site.type.contours": "Contours",
|
||||
"site.type.terrain": "Terrain",
|
||||
"site.type.excavation": "Excavation",
|
||||
"site.smooth": "Smooth",
|
||||
"site.smooth.hint": "Contours as breaklines, flat triangles fixed, surface smoothed without overshoot",
|
||||
"site.excavation.draw": "Draw excavation",
|
||||
"site.excavation.hint": "Draw the outline of the pit bottom; slopes cut the terrain",
|
||||
"site.contourInterval": "Contour interval [m]",
|
||||
"site.contourIndexEvery": "Index contour every",
|
||||
"site.excavation.bottom": "Bottom [m]",
|
||||
"site.excavation.slope": "Slope [°]",
|
||||
"site.excavation.fillSlope": "Fill slope [°]",
|
||||
"site.excavation.bermWidth": "Berm [m]",
|
||||
"site.excavation.bermHeight": "Berm every [m]",
|
||||
"site.excavation.qty": "Cut {cut} m³ · Fill {fill} m³ · Backfill {backfill} m³",
|
||||
"site.excavation.noTerrain": "No terrain below the excavation",
|
||||
"site.type.image": "Aerial",
|
||||
"site.group.image": "Aerial imagery",
|
||||
"site.dwgHint": "DWG? Convert it to DXF first with the free ODA File Converter.",
|
||||
@@ -2188,6 +2252,7 @@ export const en: Record<TranslationKey, string> = {
|
||||
"mesh.import.upUncertain": "Axis uncertain, assumed: {axis} up (selectable in the import dialog)",
|
||||
"mesh.import.dropped": "{n} invalid or degenerate faces dropped",
|
||||
"mesh.import.truncated": "aborted: too many triangles",
|
||||
"mesh.import.repaired": "repaired: {welded} vertices welded, {tris} degenerate triangles removed, {holes} holes closed",
|
||||
"mesh.import.noFaces": "The PLY file has no faces (point cloud): opening it as a point cloud.",
|
||||
"mesh.import.missingExternal": "Additional files are missing: {list}. Select them together with the model (or drop all files into the window together).",
|
||||
"mesh.importDialog.files": "Companion files: {list}",
|
||||
@@ -2362,6 +2427,7 @@ export const en: Record<TranslationKey, string> = {
|
||||
"siteRules.inside": "Building inside the buildable area",
|
||||
"siteRules.heightOk": "Height {top} m ≤ {max} m",
|
||||
"siteRules.heightOver": "Height {top} m exceeds {max} m",
|
||||
"siteRules.terrainAtFacade": "Reference terrain at the façade: {z} m (height measured from it)",
|
||||
"siteRules.defaultSetback": "Boundary distance",
|
||||
"siteRules.maxHeight": "Max. total height",
|
||||
"siteRules.edges": "Distance per edge ({n})",
|
||||
@@ -2370,6 +2436,15 @@ export const en: Record<TranslationKey, string> = {
|
||||
"siteRules.addLine": "Building line from selection",
|
||||
"siteRules.addLine.hint": "Select a line; the building stays on the parcel side.",
|
||||
"siteRules.clearLines": "Remove all building lines",
|
||||
"clash.run": "Run check",
|
||||
"clash.running": "Checking …",
|
||||
"clash.clear": "Clear",
|
||||
"clash.empty": "No results. The check compares free solids and imports with walls, slabs and other solids.",
|
||||
"clash.kind.wall": "Wall",
|
||||
"clash.kind.slab": "Slab",
|
||||
"clash.kind.solid": "Solid",
|
||||
"clash.kind.mesh": "Import",
|
||||
"nav.clash": "Clashes",
|
||||
"clash.none": "No clashes found.",
|
||||
"clash.found": "Clashes found",
|
||||
"clash.failed": "Clash detection failed",
|
||||
@@ -2731,6 +2806,7 @@ export const en: Record<TranslationKey, string> = {
|
||||
"sheetTable.source.areas": "Area table (SIA 416)",
|
||||
"sheetTable.source.rooms": "Room program target/actual",
|
||||
"sheetTable.source.elements": "Elements with U-value",
|
||||
"sheetTable.source.earthworks": "Earthworks (excavations)",
|
||||
"sheetTable.filter": "Show",
|
||||
"sheetTable.filter.all": "Windows and doors",
|
||||
"sheetTable.filter.window": "Windows only",
|
||||
@@ -2778,6 +2854,11 @@ export const en: Record<TranslationKey, string> = {
|
||||
"sheetTable.col.diffPct": "Diff. [%]",
|
||||
"sheetTable.col.buildup": "Build-up",
|
||||
"sheetTable.col.area": "Area [m²]",
|
||||
"sheetTable.col.name": "Name",
|
||||
"sheetTable.col.bottom": "Bottom [m]",
|
||||
"sheetTable.col.cut": "Cut [m³]",
|
||||
"sheetTable.col.fill": "Fill [m³]",
|
||||
"sheetTable.col.backfill": "Backfill [m³]",
|
||||
"sheetTable.col.thickness": "Thickness [cm]",
|
||||
"sheetTable.v.window": "Window",
|
||||
"sheetTable.v.door": "Door",
|
||||
@@ -2962,6 +3043,7 @@ export const en: Record<TranslationKey, string> = {
|
||||
"history.cmd.revcloud": "Revision cloud",
|
||||
"history.cmd.roof": "Draw roof",
|
||||
"history.cmd.roofHole": "Roof opening",
|
||||
"history.cmd.excavation": "Excavation",
|
||||
"history.cmd.room": "Draw room",
|
||||
"history.cmd.roomInside": "Room from outline",
|
||||
"history.cmd.scalebar": "Scale bar",
|
||||
|
||||
@@ -192,6 +192,13 @@ describe("Mesh-Import: Abbildung auf Kontext-Meshes", () => {
|
||||
expect(text).toContain("mesh.import.done");
|
||||
expect(text).toContain("mesh.import.up");
|
||||
});
|
||||
|
||||
it("Bericht nennt die Reparatur ([T5]) nur, wenn etwas repariert wurde", () => {
|
||||
const base = { format: "stl" as const, up: "z" as const, upAuto: false, upCertain: true, unitScale: 1, triangles: 12, degenerate: 0, badFaces: 0, truncated: false, warnings: [] as string[], objects: 1 };
|
||||
const tr = (k: string, v?: Record<string, string | number>) => `${k}${v ? JSON.stringify(v) : ""}`;
|
||||
expect(formatMeshReport({ ...base, repaired: { welded: 0, degenerate: 0, holes: 0 } }, tr)).not.toContain("repaired");
|
||||
expect(formatMeshReport({ ...base, repaired: { welded: 28, degenerate: 1, holes: 2 } }, tr)).toContain('mesh.import.repaired{"welded":28,"tris":1,"holes":2}');
|
||||
});
|
||||
});
|
||||
|
||||
describe("Mesh-Import: Fehler", () => {
|
||||
|
||||
@@ -64,6 +64,8 @@ export interface MeshImportReport {
|
||||
truncated: boolean;
|
||||
warnings: string[];
|
||||
objects: number;
|
||||
/** Reparatur beim Import ([T5]): zusammengelegte Ecken, entfernte entartete Dreiecke, geschlossene Löcher. */
|
||||
repaired?: { welded: number; degenerate: number; holes: number };
|
||||
}
|
||||
|
||||
/** Rohergebnis aus Rust: Zahlenpuffer + Zeichenketten. */
|
||||
@@ -198,7 +200,7 @@ export async function readMesh(bytes: Uint8Array, name: string, opts?: MeshReadO
|
||||
export function formatMeshReport(
|
||||
r: MeshImportReport,
|
||||
tr: (
|
||||
key: "mesh.import.done" | "mesh.import.up" | "mesh.import.upUncertain" | "mesh.import.dropped" | "mesh.import.truncated",
|
||||
key: "mesh.import.done" | "mesh.import.up" | "mesh.import.upUncertain" | "mesh.import.dropped" | "mesh.import.truncated" | "mesh.import.repaired",
|
||||
vars?: Record<string, string | number>,
|
||||
) => string,
|
||||
): string {
|
||||
@@ -206,6 +208,8 @@ export function formatMeshReport(
|
||||
if (r.upAuto) parts.push(tr(r.upCertain ? "mesh.import.up" : "mesh.import.upUncertain", { axis: r.up.toUpperCase() }));
|
||||
const dropped = r.degenerate + r.badFaces;
|
||||
if (dropped) parts.push(tr("mesh.import.dropped", { n: dropped }));
|
||||
const fixed = r.repaired ? r.repaired.degenerate + r.repaired.holes : 0;
|
||||
if (r.repaired && (r.repaired.welded || fixed)) parts.push(tr("mesh.import.repaired", { welded: r.repaired.welded, tris: r.repaired.degenerate, holes: r.repaired.holes }));
|
||||
if (r.truncated) parts.push(tr("mesh.import.truncated"));
|
||||
return parts.join(" · ");
|
||||
}
|
||||
+25
-6
@@ -19,14 +19,32 @@ let terrainSeq = 0;
|
||||
export const TERRAIN_LAYER = "Terrain";
|
||||
|
||||
/**
|
||||
* Erzeugt ein TIN aus Konturen (Rust-Kern, `cmd_solid.rs::terrain_from_contours`): alle endlichen
|
||||
* Stützpunkte der Konturen als Vertices (Z = Kontur-Höhe, nicht endlich → 0), 2D-Delaunay über die
|
||||
* (x, y)-Projektion (`delaunay.rs`), Dreiecke mit (nahezu) null Fläche verworfen. Offene und
|
||||
* geschlossene Konturen gleich; unter 3 Punkten ein leeres Mesh.
|
||||
* Erzeugt ein Gelände aus Konturen (Rust-Kern, `terrain.rs`): Konturen verdichtet und als Bruchkanten
|
||||
* erzwungen (constrained Delaunay), flache Dreiecke behoben, adaptiv geglättet ohne Überschwingen.
|
||||
* `contourInterval` = kleinster Höhenabstand der Konturen (Höhenlinien im Grundriss). Unter 3 Punkten
|
||||
* ein leeres Mesh.
|
||||
*/
|
||||
export function generateTerrainFromContours(contours: Contour[]): TerrainMesh {
|
||||
export function generateTerrainFromContours(contours: Contour[], opts: TerrainOptions = {}): TerrainMesh {
|
||||
const id = `terrain-${Date.now()}-${terrainSeq++}`;
|
||||
return JSON.parse(core().terrain_from_contours_json(toMarkedJson(contours), id)) as TerrainMesh;
|
||||
const json = core().terrain_from_contours_opts_json(
|
||||
toMarkedJson(contours),
|
||||
id,
|
||||
opts.smooth ?? 2,
|
||||
opts.maxEdge ?? 0,
|
||||
opts.breaklines === false ? 0 : 1,
|
||||
);
|
||||
return JSON.parse(json) as TerrainMesh;
|
||||
}
|
||||
|
||||
/**
|
||||
* [T6] Optionen der Gelände-Erzeugung (`terrain.rs`): `smooth` = Glättungsstufen 0–4 (0 = reines TIN mit
|
||||
* Bruchkanten, Standard 2), `maxEdge` = Verdichtung/grösste Kante in m (0 = automatisch), `breaklines` =
|
||||
* Höhenlinien als Bruchkanten erzwingen (Standard ja).
|
||||
*/
|
||||
export interface TerrainOptions {
|
||||
smooth?: number;
|
||||
maxEdge?: number;
|
||||
breaklines?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -91,5 +109,6 @@ export function terrainMeshFromGrid(grid: TerrainGrid): TerrainMesh {
|
||||
categoryCode: TERRAIN_CATEGORY.code,
|
||||
positions,
|
||||
indices,
|
||||
contourInterval: 1,
|
||||
};
|
||||
}
|
||||
@@ -453,7 +453,7 @@ export type ContextImage = {
|
||||
};
|
||||
|
||||
/** Kontext-Objekt (Tag `type`). */
|
||||
export type ContextObject = ImportedMesh | ContourSet | TerrainMesh | ContextImage;
|
||||
export type ContextObject = ImportedMesh | ContourSet | TerrainMesh | ContextImage | Excavation;
|
||||
|
||||
/**
|
||||
* Eine einzelne Kontur (Höhenlinie / Polylinie) auf konstanter Höhe `z`. `pts`
|
||||
@@ -521,7 +521,16 @@ export type CustomPalette = {
|
||||
export type DetailLevel = "grob" | "mittel" | "fein";
|
||||
|
||||
/** Merkmal, an dem ein Bemassungspunkt hängt ([38], `dim_assoc.rs`). */
|
||||
export type DimFeature = "wall" | "opening" | "vertex" | "edge" | "center" | "intersection";
|
||||
export type DimFeature =
|
||||
| "wall"
|
||||
| "opening"
|
||||
| "vertex"
|
||||
| "edge"
|
||||
| "center"
|
||||
| "intersection"
|
||||
| "axis"
|
||||
| "axiscross"
|
||||
| "rim";
|
||||
|
||||
/** Bezug eines Bemassungspunkts auf ein Element ([38]). */
|
||||
export type DimRef = {
|
||||
@@ -887,6 +896,11 @@ export type Drawing2DGeom =
|
||||
* wenn ein Bezug ungültig wird. Fehlt das Feld, ist die Bemassung frei wie bisher.
|
||||
*/
|
||||
refs?: Array<DimRef | null>;
|
||||
/**
|
||||
* Art der Bemassung (fehlt = linear): Radius/Durchmesser (`pts` = Mittelpunkt, Punkt auf dem
|
||||
* Kreis) und Bogenlänge (`pts` = Mittelpunkt, Bogenanfang, Bogenende).
|
||||
*/
|
||||
kind?: "radius" | "diameter" | "arc";
|
||||
}
|
||||
| {
|
||||
shape: "kote";
|
||||
@@ -921,6 +935,24 @@ export type Drawing2DGeom =
|
||||
segments: number;
|
||||
}
|
||||
| { shape: "pointmarker"; at: Vec2 }
|
||||
| {
|
||||
shape: "grid";
|
||||
origin: Vec2;
|
||||
angle: number;
|
||||
radial?: boolean;
|
||||
a: Array<GridAxis>;
|
||||
b: Array<GridAxis>;
|
||||
/** Überstand der Achsen über die äusserste Querachse (Meter, Standard 1.5). */
|
||||
extend?: number;
|
||||
/** Enden mit Achsblase (Standard Anfang und Ende). */
|
||||
bubbles?: "start" | "end" | "both";
|
||||
/** Blasen-Durchmesser in Papier-mm (Standard 8). */
|
||||
bubbleMm?: number;
|
||||
/** Geschosse, in denen das Raster gezeigt wird; fehlt oder leer = in allen. */
|
||||
levels?: Array<string>;
|
||||
/** Im 3D-Modell als dünne Linien zeigen. */
|
||||
show3d?: boolean;
|
||||
}
|
||||
| {
|
||||
shape: "text";
|
||||
at: Vec2;
|
||||
@@ -1117,6 +1149,28 @@ export type DrawingLevelKind = "floor" | "section" | "elevation" | "drawing";
|
||||
*/
|
||||
export type EndMark = "none" | "arrow" | "arrowOpen" | "dot" | "tick" | "square";
|
||||
|
||||
/**
|
||||
* [68] Baugrube / Geländebearbeitung: Sohle als Umriss auf der Höhe `bottom` (m, Modell ±0.00).
|
||||
* Ausserhalb steigt die Böschung mit `slope` (Grad, Default 45; je Kante `edgeSlopes`, 0 = Default)
|
||||
* bis zum Gelände (Abtrag); liegt das Gelände tiefer, fällt eine Schüttung mit `fillSlope` (Default
|
||||
* 33.7 ≈ 2:3) bis zum Gelände (Auftrag). Bermen: alle `bermHeight` m Höhe eine waagrechte Berme der
|
||||
* Breite `bermWidth`. Schneidet jedes Gelände-Netz, das den Umriss enthält.
|
||||
*/
|
||||
export type Excavation = {
|
||||
type: "excavation";
|
||||
id: string;
|
||||
name: string;
|
||||
layer?: string;
|
||||
categoryCode?: string;
|
||||
outline: Array<Vec2>;
|
||||
bottom: number;
|
||||
slope?: number;
|
||||
fillSlope?: number;
|
||||
edgeSlopes?: Array<number>;
|
||||
bermWidth?: number;
|
||||
bermHeight?: number;
|
||||
};
|
||||
|
||||
/** Ein extrudierter Körper: geschlossenes Profil (Modell-Meter) + Höhe. */
|
||||
export type ExtrudedSolid = {
|
||||
id: string;
|
||||
@@ -1218,6 +1272,9 @@ export type FrameDetail = {
|
||||
rebates?: OpeningSides;
|
||||
};
|
||||
|
||||
/** Eine Achse des Achsrasters: Beschriftung und Lage (Abstand bzw. Winkel/Radius, s. `Grid`). */
|
||||
export type GridAxis = { label: string; pos: number };
|
||||
|
||||
/**
|
||||
* Raster-Regel: generiert Wände entlang gleichmäßiger X-/Y-Achsen.
|
||||
* Typischer Anwendungsfall: Tragwerks-Achsraster (z. B. 3 m Abstand).
|
||||
@@ -1627,7 +1684,7 @@ export type LayoutTable = {
|
||||
};
|
||||
|
||||
/** Quelle einer Blatt-Tabelle ([111]). */
|
||||
export type LayoutTableSource = "openings" | "areas" | "rooms" | "elements";
|
||||
export type LayoutTableSource = "openings" | "areas" | "rooms" | "elements" | "earthworks";
|
||||
|
||||
/**
|
||||
* Einfache Textfelder des Titelblocks (Master). Alle optional — leere Felder
|
||||
@@ -2852,6 +2909,11 @@ export type Stair = {
|
||||
* Dreieck als SIA-Vollpfeil). Fehlt sie, gilt "line".
|
||||
*/
|
||||
arrowStyle?: "line" | "filled";
|
||||
/**
|
||||
* Nur Wendel: Radius (Meter) der Mittelsäule (Spindel) im Zentrum. Fehlt er oder ist er
|
||||
* ≤ 0, gibt es keine Säule.
|
||||
*/
|
||||
centerColumn?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -2945,6 +3007,13 @@ export type TerrainMesh = {
|
||||
* statt mit der Grundfarbe. Fehlt es, bleibt das Gelände einfarbig.
|
||||
*/
|
||||
vertexColors?: Array<number>;
|
||||
/**
|
||||
* [T6] Äquidistanz der Höhenlinien im Grundriss in m (aus dem Netz neu erzeugt, inkl. Baugruben).
|
||||
* Fehlt der Wert oder ist er ≤ 0, zeigt der Grundriss nur den Rahmen.
|
||||
*/
|
||||
contourInterval?: number;
|
||||
/** [T6] Jede n-te Höhenlinie ist Zähllinie (dicker, beschriftet). Default 5. */
|
||||
contourIndexEvery?: number;
|
||||
};
|
||||
|
||||
/** Ein zusammenhängender Textabschnitt mit einheitlicher Formatierung. */
|
||||
@@ -3236,6 +3305,12 @@ export type Wall = {
|
||||
* Additiv; Alt-Projekte laden unverändert (Default = "both").
|
||||
*/
|
||||
sliceTermination?: SliceTermination;
|
||||
/**
|
||||
* An Dach anschliessen ([G2]): `undefined` = automatisch (die Wand endet an der Dach-Unterkante,
|
||||
* wo ihre Krone darüber liegt — je Schicht, Giebel/Traufe/Grat/Kehle/Gaube), `true` = zusätzlich bis
|
||||
* unter das Dach verlängert, `false` = Dächer schneiden die Wand nicht.
|
||||
*/
|
||||
roofAttach?: boolean;
|
||||
/**
|
||||
* Ansichtsschraffur ([100]): Drehung (Grad) des Oberflächenmusters dieses Elements gegenüber der
|
||||
* Ausrichtung am Element (Default 0).
|
||||
|
||||
@@ -501,6 +501,45 @@ export function AttributesPanel() {
|
||||
(Modellmass, s. `model/dimension.ts`); leer/0 fällt auf den
|
||||
Standard zurück. Die Masszahl selbst wird direkt im Plan am
|
||||
eigenen Griff verschoben (rastet nahe der Standardlage ein). */}
|
||||
{drawing?.geom.shape === "grid" && (() => {
|
||||
const geom = drawing.geom as Extract<typeof drawing.geom, { shape: "grid" }>;
|
||||
const here = geom.levels?.includes(drawing.levelId) && geom.levels.length === 1;
|
||||
return (
|
||||
<>
|
||||
<div className="attr-section-label">{t("attr.grid.section")}</div>
|
||||
<span className="attr-key">{t("attr.grid.bubbles")}</span>
|
||||
<span className="attr-val">
|
||||
<select value={geom.bubbles ?? "both"} onChange={(e) => host.onSetGridProps(drawing.id, { bubbles: e.target.value as "start" | "end" | "both" })}>
|
||||
<option value="both">{t("attr.grid.bubbles.both")}</option>
|
||||
<option value="start">{t("attr.grid.bubbles.start")}</option>
|
||||
<option value="end">{t("attr.grid.bubbles.end")}</option>
|
||||
</select>
|
||||
</span>
|
||||
<span className="attr-key">{t("attr.grid.extend")}</span>
|
||||
<span className="attr-val">
|
||||
<input className="attr-num" style={{ width: 72 }} type="number" step={0.1} min={0} value={geom.extend ?? 1.5}
|
||||
onChange={(e) => { const v = Number(e.target.value); if (Number.isFinite(v) && v >= 0) host.onSetGridProps(drawing.id, { extend: v }); }} />
|
||||
</span>
|
||||
<span className="attr-key">{t("attr.grid.bubbleMm")}</span>
|
||||
<span className="attr-val">
|
||||
<input className="attr-num" style={{ width: 72 }} type="number" step={0.5} min={2} value={geom.bubbleMm ?? 8}
|
||||
onChange={(e) => { const v = Number(e.target.value); if (Number.isFinite(v) && v >= 2) host.onSetGridProps(drawing.id, { bubbleMm: v }); }} />
|
||||
</span>
|
||||
<span className="attr-key">{t("attr.grid.show3d")}</span>
|
||||
<span className="attr-val">
|
||||
<input type="checkbox" checked={geom.show3d === true} onChange={(e) => host.onSetGridProps(drawing.id, { show3d: e.target.checked })} />
|
||||
</span>
|
||||
<span className="attr-key">{t("attr.grid.levels")}</span>
|
||||
<span className="attr-val">
|
||||
<select value={here ? "here" : "all"} onChange={(e) => host.onSetGridProps(drawing.id, { levels: e.target.value === "here" ? [drawing.levelId] : undefined })}>
|
||||
<option value="all">{t("attr.grid.levels.all")}</option>
|
||||
<option value="here">{t("attr.grid.levels.here")}</option>
|
||||
</select>
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
|
||||
{drawing?.geom.shape === "dimension" && (
|
||||
<>
|
||||
<div className="attr-section-label">{t("attr.dim.section")}</div>
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
// Kollisionen ([T8]): Liste der Treffer der letzten Prüfung. Klick wählt beide beteiligten Bauteile
|
||||
// (Auswahl-Umriss im 3D) und fährt die 3D-Kamera auf die Durchdringung; im 3D sind alle Treffer als
|
||||
// rote Hüllquader markiert (`clashHighlightLines`, `views/viewportContent.tsx`).
|
||||
|
||||
import { t } from "../i18n";
|
||||
import { getState } from "../state/appStore";
|
||||
import { clashSelection, type Clash } from "../analysis/clash";
|
||||
import { focusCamera, viewportAvailable } from "../viewport/cameraBridge";
|
||||
import { runClashAndStore, setClashSession, useClashSession } from "./clashSession";
|
||||
|
||||
/** Klick auf einen Treffer: Bauteile wählen, Kamera auf die Durchdringung. */
|
||||
export function focusClash(c: Clash, index: number): void {
|
||||
const s = getState();
|
||||
const sel = clashSelection(c);
|
||||
s.clearSelection();
|
||||
s.setSelectedWallIds(sel.wallIds);
|
||||
s.setSelectedCeilingIds(sel.ceilingIds);
|
||||
s.setSelectedExtrudedSolidIds(sel.extrudedSolidIds);
|
||||
s.setSelectedContextObjectIds(sel.contextObjectIds);
|
||||
setClashSession({ selected: index });
|
||||
const radius = Math.hypot(c.max[0] - c.min[0], c.max[1] - c.min[1], c.max[2] - c.min[2]) / 2;
|
||||
if (viewportAvailable()) focusCamera(c.center, radius);
|
||||
}
|
||||
|
||||
const itemText = (it: Clash["a"]) => `${t(`clash.kind.${it.kind}`)} ${it.id}`;
|
||||
|
||||
export function ClashPanel() {
|
||||
const session = useClashSession();
|
||||
return (
|
||||
<div className="bcf-panel">
|
||||
<div className="bcf-bar">
|
||||
<button type="button" className="bcf-btn" disabled={session.running} onClick={() => void runClashAndStore()}>
|
||||
{session.running ? t("clash.running") : t("clash.run")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="bcf-btn"
|
||||
disabled={session.clashes.length === 0}
|
||||
onClick={() => setClashSession({ clashes: [], selected: null })}
|
||||
>
|
||||
{t("clash.clear")}
|
||||
</button>
|
||||
</div>
|
||||
{session.clashes.length === 0 && <div className="bcf-empty">{t("clash.empty")}</div>}
|
||||
<ul className="bcf-list">
|
||||
{session.clashes.map((c, k) => (
|
||||
<li key={`${c.a.id}|${c.b.id}`}>
|
||||
<button type="button" className={`bcf-topic${k === session.selected ? " is-active" : ""}`} onClick={() => focusClash(c, k)}>
|
||||
<span className="bcf-status">{`K${k + 1}`}</span>
|
||||
<span className="bcf-topic-title">{`${itemText(c.a)} ↔ ${itemText(c.b)}`}</span>
|
||||
{c.volume !== null && <span className="bcf-count">{`${c.volume.toFixed(3)} m³`}</span>}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1461,6 +1461,13 @@ export function StairSection({
|
||||
value={stair.width}
|
||||
onCommit={(v) => host.onSetStairWidth(v)}
|
||||
/>
|
||||
{stair.shape === "spiral" && (
|
||||
<DimensionField
|
||||
label={t("objinfo.stair.column")}
|
||||
value={stair.centerColumn ?? 0}
|
||||
onCommit={(v) => host.onSetStairColumn(v)}
|
||||
/>
|
||||
)}
|
||||
<DimensionField
|
||||
label={t("objinfo.stair.steps")}
|
||||
value={stair.stepCount}
|
||||
@@ -2055,6 +2062,23 @@ export function WallSection({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* An Dach anschliessen ([G2]): automatisch endet die Wand an der Dach-Unterkante, "Ja"
|
||||
verlängert sie bis unter das Dach, "Nein" lässt die Dächer die Wand nicht schneiden. */}
|
||||
<div className="objinfo-field">
|
||||
<span className="objinfo-flabel">{t("objinfo.wall.roofAttach")}</span>
|
||||
<Dropdown
|
||||
value={wall.roofAttach}
|
||||
onChange={(v) => host.onSetWallRoofAttach(v as "auto" | "on" | "off")}
|
||||
options={[
|
||||
{ value: "auto", label: t("objinfo.wall.roofAttach.auto") },
|
||||
{ value: "on", label: t("objinfo.wall.roofAttach.on") },
|
||||
{ value: "off", label: t("objinfo.wall.roofAttach.off") },
|
||||
]}
|
||||
title={t("objinfo.wall.roofAttach.tip")}
|
||||
width={120}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Aufbau-Typ-Segment. */}
|
||||
<div className="objinfo-field">
|
||||
<span className="objinfo-flabel">{t("objinfo.wall.buildup")}</span>
|
||||
|
||||
+121
-2
@@ -13,7 +13,7 @@
|
||||
// Bezeichner englisch, UI-Text/Kommentare deutsch (CONVENTIONS.md). Alle sichtbaren
|
||||
// Texte über t(...).
|
||||
|
||||
import { useState } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { t } from "../i18n";
|
||||
import type { TranslationKey } from "../i18n";
|
||||
import { usePanelHost } from "./host";
|
||||
@@ -26,6 +26,7 @@ import { openContextImportWindowNative } from "../native/contextImportWindow";
|
||||
import { SunStudySection } from "./SunStudySection";
|
||||
import { SiteRulesSection } from "./SiteRulesSection";
|
||||
import { PointCloudSection } from "./PointCloudSection";
|
||||
import { excavationQuantities } from "../core";
|
||||
|
||||
/** Typ-spezifisches Badge-Label (i18n-Key) je Kontext-Objekt-Art. */
|
||||
function typeBadgeKey(obj: ContextObject): TranslationKey {
|
||||
@@ -38,6 +39,8 @@ function typeBadgeKey(obj: ContextObject): TranslationKey {
|
||||
return "site.type.terrain";
|
||||
case "image":
|
||||
return "site.type.image";
|
||||
case "excavation":
|
||||
return "site.type.excavation";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,9 +56,42 @@ function layerOf(obj: ContextObject): string {
|
||||
return t("site.group.contours");
|
||||
case "image":
|
||||
return t("site.group.image");
|
||||
case "excavation":
|
||||
return t("site.group.terrain");
|
||||
}
|
||||
}
|
||||
|
||||
/** Zahl-Eingabe für ein Feld eines Kontext-Objekts (leer = Standard, ungültig = keine Änderung). */
|
||||
function NumField(props: {
|
||||
label: string;
|
||||
value: number | undefined;
|
||||
step: number;
|
||||
min?: number;
|
||||
placeholder?: string;
|
||||
onChange: (v: number | undefined) => void;
|
||||
}) {
|
||||
return (
|
||||
<label className="site-prop">
|
||||
<span>{props.label}</span>
|
||||
<input
|
||||
type="number"
|
||||
step={props.step}
|
||||
min={props.min}
|
||||
placeholder={props.placeholder}
|
||||
value={props.value ?? ""}
|
||||
onChange={(e) => {
|
||||
const raw = e.target.value.trim();
|
||||
if (raw === "") return props.onChange(undefined);
|
||||
const v = Number(raw);
|
||||
if (Number.isFinite(v)) props.onChange(v);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
const fmt1 = (v: number) => v.toLocaleString("de-CH", { maximumFractionDigits: 1, minimumFractionDigits: 1 });
|
||||
|
||||
/** Gruppiert Kontext-Objekte nach Ebene, Reihenfolge des ersten Auftretens. */
|
||||
function groupByLayer(objects: ContextObject[]): { layer: string; items: ContextObject[] }[] {
|
||||
const order: string[] = [];
|
||||
@@ -73,6 +109,15 @@ function groupByLayer(objects: ContextObject[]): { layer: string; items: Context
|
||||
return order.map((layer) => ({ layer, items: byLayer.get(layer)! }));
|
||||
}
|
||||
|
||||
function ExcavationQty({ q }: { q: { cut: number; fill: number; backfill: number } | undefined }) {
|
||||
if (!q) return <div className="site-qty">{t("site.excavation.noTerrain")}</div>;
|
||||
return (
|
||||
<div className="site-qty">
|
||||
{t("site.excavation.qty", { cut: fmt1(q.cut), fill: fmt1(q.fill), backfill: fmt1(q.backfill) })}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SitePanel() {
|
||||
const host = usePanelHost();
|
||||
const notify = useStore((s) => s.notify);
|
||||
@@ -89,9 +134,16 @@ export function SitePanel() {
|
||||
? selectedSet
|
||||
: (contourSets[0]?.id ?? "");
|
||||
|
||||
// [T6] Glätten beim Erzeugen (Bruchkanten werden immer erzwungen).
|
||||
const [smooth, setSmooth] = useState(true);
|
||||
// [68] Mengen der Baugruben (Kern), nur neu, wenn sich das Projekt ändert.
|
||||
const quantities = useMemo(() => excavationQuantities(host.project), [host.project]);
|
||||
const patch = (id: string, field: string) => (v: number | undefined) =>
|
||||
host.onPatchContextObject(id, { [field]: v }, `site-${id}-${field}`);
|
||||
|
||||
const onGenerate = () => {
|
||||
if (!effectiveSet) return;
|
||||
const id = host.onGenerateTerrain(effectiveSet);
|
||||
const id = host.onGenerateTerrain(effectiveSet, { smooth: smooth ? 2 : 0 });
|
||||
if (id === null) {
|
||||
// Kein sinnvolles TIN — ruhiger Hinweis als Toast (keine harte Fehlerbox;
|
||||
// window.alert wäre im Tauri-WKWebView ohnehin wirkungslos).
|
||||
@@ -153,11 +205,22 @@ export function SitePanel() {
|
||||
{contourSets[0].name}
|
||||
</span>
|
||||
)}
|
||||
<label className="site-check" title={t("site.smooth.hint")}>
|
||||
<input type="checkbox" checked={smooth} onChange={(e) => setSmooth(e.target.checked)} />
|
||||
{t("site.smooth")}
|
||||
</label>
|
||||
<button type="button" className="site-btn" onClick={onGenerate}>
|
||||
{t("site.generateTerrain")}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{objects.some((o) => o.type === "terrainMesh") && (
|
||||
<div className="site-actions">
|
||||
<button type="button" className="site-btn" title={t("site.excavation.hint")} onClick={() => host.onStartExcavation()}>
|
||||
{t("site.excavation.draw")}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="site-sep" />
|
||||
<SunStudySection />
|
||||
@@ -213,6 +276,62 @@ export function SitePanel() {
|
||||
>
|
||||
×
|
||||
</button>
|
||||
{obj.type === "terrainMesh" && (
|
||||
<div className="site-props">
|
||||
<NumField
|
||||
label={t("site.contourInterval")}
|
||||
value={obj.contourInterval}
|
||||
step={0.5}
|
||||
min={0}
|
||||
placeholder="—"
|
||||
onChange={patch(obj.id, "contourInterval")}
|
||||
/>
|
||||
<NumField
|
||||
label={t("site.contourIndexEvery")}
|
||||
value={obj.contourIndexEvery}
|
||||
step={1}
|
||||
min={1}
|
||||
placeholder="5"
|
||||
onChange={patch(obj.id, "contourIndexEvery")}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{obj.type === "excavation" && (
|
||||
<div className="site-props">
|
||||
<NumField
|
||||
label={t("site.excavation.bottom")}
|
||||
value={obj.bottom}
|
||||
step={0.05}
|
||||
onChange={(v) => v !== undefined && patch(obj.id, "bottom")(v)}
|
||||
/>
|
||||
<NumField label={t("site.excavation.slope")} value={obj.slope} step={5} min={5} placeholder="45" onChange={patch(obj.id, "slope")} />
|
||||
<NumField
|
||||
label={t("site.excavation.fillSlope")}
|
||||
value={obj.fillSlope}
|
||||
step={5}
|
||||
min={5}
|
||||
placeholder="33.7"
|
||||
onChange={patch(obj.id, "fillSlope")}
|
||||
/>
|
||||
<NumField
|
||||
label={t("site.excavation.bermWidth")}
|
||||
value={obj.bermWidth}
|
||||
step={0.25}
|
||||
min={0}
|
||||
placeholder="—"
|
||||
onChange={patch(obj.id, "bermWidth")}
|
||||
/>
|
||||
<NumField
|
||||
label={t("site.excavation.bermHeight")}
|
||||
value={obj.bermHeight}
|
||||
step={0.5}
|
||||
min={0}
|
||||
placeholder="—"
|
||||
onChange={patch(obj.id, "bermHeight")}
|
||||
/>
|
||||
<ExcavationQty q={quantities.find((x) => x.id === obj.id)} />
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -84,11 +84,14 @@ export function SiteRulesSection() {
|
||||
{rules.maxHeight !== undefined && check.maxTop !== null && (
|
||||
<div>
|
||||
{t(check.heightExceeded ? "siteRules.heightOver" : "siteRules.heightOk", {
|
||||
top: fmt(check.maxTop, 2),
|
||||
top: fmt(check.heightAboveTerrain ?? check.maxTop, 2),
|
||||
max: fmt(rules.maxHeight, 2),
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{check.terrainMin !== null && (
|
||||
<div>{t("siteRules.terrainAtFacade", { z: fmt(check.terrainMin, 2) })}</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -253,6 +253,17 @@ export function ToolIcon({ id }: { id: ToolId }) {
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
case "grid":
|
||||
// Achsraster: zwei Achsen mit Blasen.
|
||||
return (
|
||||
<svg {...common}>
|
||||
<line x1="5" y1="5" x2="5" y2="15" strokeDasharray="2 1" />
|
||||
<line x1="11" y1="5" x2="11" y2="15" strokeDasharray="2 1" />
|
||||
<line x1="1" y1="10" x2="15" y2="10" strokeDasharray="2 1" />
|
||||
<circle cx="5" cy="3" r="2" fill="none" />
|
||||
<circle cx="11" cy="3" r="2" fill="none" />
|
||||
</svg>
|
||||
);
|
||||
case "pointmarker":
|
||||
// Kreuz-in-Kreis (Punkt-/Knotenmarker).
|
||||
return (
|
||||
@@ -347,6 +358,7 @@ const TOOLS_2D: ToolId[] = [
|
||||
"scalebar",
|
||||
"revcloud",
|
||||
"pointmarker",
|
||||
"grid",
|
||||
"wipeout",
|
||||
"text",
|
||||
"leader",
|
||||
@@ -355,7 +367,7 @@ const TOOLS_2D: ToolId[] = [
|
||||
"image",
|
||||
];
|
||||
const TOOLS_3D: ToolId[] = ["wall", "ceiling", "window", "door", "stair", "room"];
|
||||
const COMMANDS_3D = ["column", "ceilingopening", "roof", "roofhole", "roofwindow", "dormer", "extrude", "solid", "solidbool", "sectionline", "viewline", "autodim"];
|
||||
const COMMANDS_3D = ["column", "ceilingopening", "roof", "roofhole", "roofwindow", "dormer", "extrude", "revolve", "loft", "solid", "solidbool", "sectionline", "viewline", "autodim", "excavation"];
|
||||
const COMMANDS_EDIT = ["move", "copy", "array", "rotate", "mirror", "offset", "multiline", "trim", "break", "extend", "fillet", "chamfer", "join", "defblock", "measure"];
|
||||
|
||||
type ToolsView = "list" | "icons";
|
||||
|
||||
@@ -26,6 +26,7 @@ import { ElementTreePanel, ElementsTabIcon } from "./ElementTreePanel";
|
||||
import { ViewSnapshotsPanel, ViewSnapshotsTabIcon } from "./ViewSnapshotsPanel";
|
||||
import { LayoutsPanel, LayoutsTabIcon } from "./LayoutsPanel";
|
||||
import { BcfPanel } from "./BcfPanel";
|
||||
import { ClashPanel } from "./ClashPanel";
|
||||
import { HistoryPanel } from "./HistoryPanel";
|
||||
import {
|
||||
ToolsTabIcon,
|
||||
@@ -52,6 +53,7 @@ export const BUILTIN_PANEL_IDS = {
|
||||
viewSnapshots: "view-snapshots",
|
||||
layouts: "layouts",
|
||||
bcf: "bcf",
|
||||
clash: "clash",
|
||||
history: "history",
|
||||
} as const;
|
||||
|
||||
@@ -162,6 +164,16 @@ registerPanel({
|
||||
render: () => <BcfPanel />,
|
||||
});
|
||||
|
||||
// Kollisionen ([T8]) — Treffer der Kollisionsprüfung, Klick zoomt im 3D auf die Durchdringung. Nicht im
|
||||
// Standard-Layout; öffnet sich beim Prüflauf („Modell > Kollisionsprüfung") bzw. über „Fenster > Panels".
|
||||
registerPanel({
|
||||
id: BUILTIN_PANEL_IDS.clash,
|
||||
title: "nav.clash",
|
||||
icon: <BcfTabIcon />,
|
||||
hasDisplayMode: false,
|
||||
render: () => <ClashPanel />,
|
||||
});
|
||||
|
||||
// Verlauf ([84]) — Undo-Schritte als Liste, Klick springt zum Schritt. Nicht im Standard-Layout,
|
||||
// erreichbar über „Bearbeiten > Verlauf" bzw. „Fenster > Panels".
|
||||
registerPanel({
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// Sitzungszustand der Kollisionsprüfung ([T8]): die Ergebnisse der letzten Prüfung leben ausserhalb des
|
||||
// Projekts (Marker im Grundriss kommen weiterhin als Zeichnungs-Elemente), damit Liste (ClashPanel) und
|
||||
// 3D-Hervorhebung (viewportContent) dieselben Treffer zeigen. Kleiner Modul-Speicher wie `bcfSession`.
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { clashMarkerOps, runClashCheck, type Clash } from "../analysis/clash";
|
||||
import { t } from "../i18n";
|
||||
import { getState } from "../state/appStore";
|
||||
|
||||
export interface ClashSession {
|
||||
clashes: Clash[];
|
||||
/** Index des gewählten Treffers (Liste/Zoom) oder null. */
|
||||
selected: number | null;
|
||||
/** Prüfung läuft. */
|
||||
running: boolean;
|
||||
}
|
||||
|
||||
let state: ClashSession = { clashes: [], selected: null, running: false };
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
export const getClashSession = (): ClashSession => state;
|
||||
|
||||
export function setClashSession(patch: Partial<ClashSession>): void {
|
||||
state = { ...state, ...patch };
|
||||
for (const l of listeners) l();
|
||||
}
|
||||
|
||||
export function useClashSession(): ClashSession {
|
||||
return useSyncExternalStore(
|
||||
(cb) => {
|
||||
listeners.add(cb);
|
||||
return () => listeners.delete(cb);
|
||||
},
|
||||
getClashSession,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüfung ausführen: Ergebnis in die Sitzung (Liste + 3D-Hervorhebung), Marker in den Grundriss, Meldung.
|
||||
* Läuft auf dem aktuellen Projektstand des Stores.
|
||||
*/
|
||||
export async function runClashAndStore(): Promise<void> {
|
||||
if (state.running) return;
|
||||
const st = getState();
|
||||
setClashSession({ running: true });
|
||||
try {
|
||||
const clashes = await runClashCheck(st.project);
|
||||
st.applyChange((p) => clashMarkerOps(p, clashes, st.activeCategoryCode));
|
||||
setClashSession({ clashes, selected: null, running: false });
|
||||
// window.alert ist im Tauri-WKWebView wirkungslos → Toast.
|
||||
st.notify(
|
||||
clashes.length === 0
|
||||
? t("clash.none")
|
||||
: `${t("clash.found")}: ${clashes.length} — ` +
|
||||
clashes
|
||||
.slice(0, 5)
|
||||
.map((c, k) => `K${k + 1} ${c.a.kind}↔${c.b.kind}${c.volume !== null ? ` ${c.volume.toFixed(3)} m³` : ""}`)
|
||||
.join(", "),
|
||||
clashes.length === 0 ? "info" : "warning",
|
||||
);
|
||||
} catch (err) {
|
||||
setClashSession({ running: false });
|
||||
st.notify(`${t("clash.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error");
|
||||
}
|
||||
}
|
||||
+15
-1
@@ -40,6 +40,7 @@ import type {
|
||||
WallType,
|
||||
} from "../model/types";
|
||||
import type { MeasurementReadout, SnapSettings, ToolId } from "../tools/types";
|
||||
import type { TerrainOptions } from "../model/terrain";
|
||||
import type { Selection } from "../state/selectionInfo";
|
||||
import type { TextStylePreset } from "../text/richText";
|
||||
import type { ScheduleKind } from "../export/exportSchedule";
|
||||
@@ -296,6 +297,11 @@ export interface PanelHostValue {
|
||||
drawingId: string,
|
||||
patch: { start?: EndMark; end?: EndMark; sizeMm?: number },
|
||||
) => void;
|
||||
/** Achsraster ([112]): Blasenseite, Überstand (m), Blasen-Ø (Papier-mm), Geschosse (leer = alle). */
|
||||
onSetGridProps: (
|
||||
drawingId: string,
|
||||
patch: { bubbles?: "start" | "end" | "both"; extend?: number; bubbleMm?: number; levels?: string[] | undefined; show3d?: boolean },
|
||||
) => void;
|
||||
onSetDimensionStyle: (
|
||||
drawingId: string,
|
||||
patch: {
|
||||
@@ -397,6 +403,8 @@ export interface PanelHostValue {
|
||||
* "both" = heutiges Verhalten, "below"/"above" = die Wand endet an der Decke.
|
||||
*/
|
||||
onSetWallSliceTermination: (termination: SliceTermination) => void;
|
||||
/** An Dach anschliessen ([G2]): "auto" = Default (Wand endet an der Dach-Unterkante). */
|
||||
onSetWallRoofAttach: (attach: "auto" | "on" | "off") => void;
|
||||
/** Ansichtsschraffur ([100]) an der gewählten Wand bzw. am gewählten Dach drehen/versetzen. */
|
||||
onSetSurfacePatternPlacement?: (patch: { surfacePatternAngle?: number; surfacePatternOffset?: { x: number; y: number } }) => void;
|
||||
/** Weist der Wand einen Wandtyp-Preset (mehrschichtiger Aufbau) zu. */
|
||||
@@ -527,6 +535,8 @@ export interface PanelHostValue {
|
||||
onSetStairArrowStyle: (style: "line" | "filled") => void;
|
||||
/** Setzt den Referenzpunkt der Laufbreite (links/mitte/rechts). */
|
||||
onSetStairReferenz: (referenz: "links" | "mitte" | "rechts") => void;
|
||||
/** Radius der Mittelsäule (Wendel) in Metern; ≤ 0 entfernt sie. */
|
||||
onSetStairColumn: (radius: number) => void;
|
||||
/** Weist der Treppe einen Treppentyp (Bibliothek) zu; "" löst die Zuweisung. */
|
||||
onSetStairType: (typeId: string) => void;
|
||||
|
||||
@@ -581,7 +591,11 @@ export interface PanelHostValue {
|
||||
* Erzeugt aus einem ContourSet (per ID) ein Gelände-TIN. Liefert die neue
|
||||
* TerrainMesh-ID oder null (unbekannte ID / kein sinnvolles TIN).
|
||||
*/
|
||||
onGenerateTerrain: (contourSetId: string) => string | null;
|
||||
onGenerateTerrain: (contourSetId: string, opts?: TerrainOptions) => string | null;
|
||||
/** [T6]/[68] Ändert Felder eines Kontext-Objekts (Äquidistanz, Baugruben-Sohle …). */
|
||||
onPatchContextObject: (id: string, patch: Record<string, unknown>, coalesceKey?: string) => void;
|
||||
/** [68] Startet den Befehl „Baugrube" (Umriss zeichnen). */
|
||||
onStartExcavation: () => void;
|
||||
/**
|
||||
* Setzt/ersetzt den Georeferenzierungs-Bezug (`Project.geoAnchor`) — welcher
|
||||
* Modell-Punkt welcher realen LV95-Koordinate entspricht. `undefined` löscht
|
||||
|
||||
@@ -119,12 +119,14 @@ export function levelArg(level: DrawingLevel) {
|
||||
export function generateSectionPlan(
|
||||
output: SectionOutput,
|
||||
mono = false,
|
||||
opts: { hiddenLines?: boolean; visibleCodes?: Set<string>; categoryDisplay?: CategoryDisplayResolver; openings?: boolean } = {},
|
||||
opts: { hiddenLines?: boolean; visibleCodes?: Set<string>; categoryDisplay?: CategoryDisplayResolver; openings?: boolean; scaleDenominator?: number } = {},
|
||||
): Plan {
|
||||
const { project, level } = output;
|
||||
const text = JSON.stringify({
|
||||
level: levelArg(level),
|
||||
hiddenLines: !!opts.hiddenLines,
|
||||
// Massstabsnenner für die Achsblasen des Rasters ([112]); Default 100.
|
||||
scale: opts.scaleDenominator ?? 100,
|
||||
...visibilityArgs(project, opts.visibleCodes, opts.categoryDisplay),
|
||||
});
|
||||
const args = output.bodies.slice();
|
||||
|
||||
@@ -104,6 +104,11 @@ export interface RWall {
|
||||
* Nur für Boxen ohne Löcher/Öffnungen (render3d `WallInput::top_drop`).
|
||||
*/
|
||||
topDrop?: [number, number];
|
||||
/**
|
||||
* Ebene Oberkante unter einer Dachfläche ([G2]): `[z am Anfang, dz/dx, dz/dy]` (Grundriss-Meter);
|
||||
* übersteuert `topDrop` (render3d `WallInput::top_plane`). Fehlt = waagrecht.
|
||||
*/
|
||||
topPlane?: [number, number, number];
|
||||
color: RRgb;
|
||||
/**
|
||||
* Immer leer: die Schichten werden TS-seitig in eigene Voll-Boxen zerlegt
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
// [112]/[38] Achsraster und Bemassung im Store: eine Bemassung zwischen zwei Achsen folgt der verschobenen
|
||||
// Achse (Kern führt `pts` im selben Undo-Schritt nach); Rundmass folgt dem Kreis; Achsfang im Kern.
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { getState, setState } from "./appStore";
|
||||
import { emptyProject } from "../model/sampleProject";
|
||||
import { addItems, cmdMutation, patchItem } from "../core";
|
||||
import type { Drawing2D } from "../model/types";
|
||||
|
||||
const dims = (): Drawing2D[] => getState().project.drawings2d.filter((d) => d.geom.shape === "dimension");
|
||||
const xs = (d: Drawing2D): number[] => (d.geom.shape === "dimension" ? d.geom.pts.map((q) => q.x) : []);
|
||||
|
||||
beforeEach(() => {
|
||||
setState({ project: emptyProject, undoDepth: 0, redoDepth: 0, canUndo: false, canRedo: false });
|
||||
getState().clearHistory();
|
||||
getState().setProject(cmdMutation({ cmd: "grid", at: [2, 1], xs: "6 6", ys: "5", ctx: { level: "eg", cat: "20" }, stamp: "g" }));
|
||||
});
|
||||
|
||||
describe("Achsraster im Store", () => {
|
||||
it("Bemassung zwischen zwei Achsen: Achse verschieben → Mass folgt, ein Undo-Schritt", () => {
|
||||
const grid = getState().project.drawings2d.find((d) => d.geom.shape === "grid")!;
|
||||
expect(grid).toBeDefined();
|
||||
// Achse 1 bei x = 2, Achse 2 bei x = 8, Kette auf y = 3 zwischen den gefangenen Achspunkten.
|
||||
getState().setProject(cmdMutation({ cmd: "dimension", pts: [[2, 3], [8, 3]], snaps: [[2, 3], [8, 3]], offset: 1, ctx: { level: "eg" }, stamp: "t" }));
|
||||
const d0 = dims()[0];
|
||||
expect(d0.geom.shape === "dimension" && d0.geom.refs?.map((r) => r?.feature)).toEqual(["axis", "axis"]);
|
||||
expect(xs(d0)).toEqual([2, 8]);
|
||||
|
||||
getState().applyChange((p) =>
|
||||
patchItem(p, "drawings2d", grid.id, (d) => (d.geom.shape === "grid" ? { ...d, geom: { ...d.geom, a: d.geom.a.map((x) => (x.label === "2" ? { ...x, pos: 7.5 } : x)) } } : d)),
|
||||
);
|
||||
expect(xs(dims()[0])).toEqual([2, 9.5]);
|
||||
getState().undo();
|
||||
expect(xs(dims()[0])).toEqual([2, 8]);
|
||||
getState().redo();
|
||||
expect(xs(dims()[0])).toEqual([2, 9.5]);
|
||||
});
|
||||
|
||||
it("Raster verschieben mit der Bemassung bleibt verbunden; Achsschnittpunkt hängt als axiscross an", () => {
|
||||
getState().setProject(cmdMutation({ cmd: "dimension", pts: [[2, 1], [8, 1]], snaps: [[2, 1], [8, 1]], offset: 1, ctx: { level: "eg" }, stamp: "t" }));
|
||||
const d = dims()[0];
|
||||
expect(d.geom.shape === "dimension" && d.geom.refs?.map((r) => r?.feature)).toEqual(["axiscross", "axiscross"]);
|
||||
// Ursprung des Rasters um (1, 0) verschieben → Punkte folgen.
|
||||
const grid = getState().project.drawings2d.find((x) => x.geom.shape === "grid")!;
|
||||
getState().applyChange((p) => patchItem(p, "drawings2d", grid.id, (x) => (x.geom.shape === "grid" ? { ...x, geom: { ...x.geom, origin: { x: 3, y: 1 } } } : x)));
|
||||
expect(xs(dims()[0])).toEqual([3, 9]);
|
||||
});
|
||||
|
||||
it("Radiusmass folgt dem Kreis", () => {
|
||||
getState().applyChange(
|
||||
addItems("drawings2d", [{ id: "K", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "circle", center: { x: 20, y: 20 }, r: 2 } } as Drawing2D]),
|
||||
);
|
||||
getState().setProject(cmdMutation({ cmd: "dimround", kind: "radius", pts: [[22, 20]], ctx: { level: "eg" }, stamp: "r" }));
|
||||
getState().applyChange((p) => patchItem(p, "drawings2d", "K", (x) => (x.geom.shape === "circle" ? { ...x, geom: { ...x.geom, center: { x: 30, y: 20 }, r: 3 } } : x)));
|
||||
const d = dims()[0];
|
||||
expect(d.geom.shape === "dimension" && d.geom.pts).toEqual([{ x: 30, y: 20 }, { x: 33, y: 20 }]);
|
||||
});
|
||||
});
|
||||
@@ -124,6 +124,8 @@ export interface WallInfo {
|
||||
layerBoundaries: LayerBoundaryChoice[];
|
||||
/** Terminierungs-Regel am Deckenanschluss (Default "both" = heutiges Verhalten). */
|
||||
sliceTermination: SliceTermination;
|
||||
/** An Dach anschliessen ([G2]): "auto" (Default), "on" (bis unter das Dach verlängern), "off". */
|
||||
roofAttach: "auto" | "on" | "off";
|
||||
wallTypeId: string;
|
||||
/** Aktuelle Gesamtdicke (Meter). */
|
||||
thickness: number;
|
||||
@@ -257,6 +259,8 @@ export interface StairInfo {
|
||||
arrowStyle?: "line" | "filled";
|
||||
/** Referenzpunkt der Laufbreite (links/mitte/rechts). Fehlt → "mitte". */
|
||||
referenz?: "links" | "mitte" | "rechts";
|
||||
/** Nur Wendel: Radius der Mittelsäule (Meter); fehlt → keine Säule. */
|
||||
centerColumn?: number;
|
||||
/** Zugewiesener Treppentyp (Bibliothek, `Stair.typeId`) oder undefined. */
|
||||
typeId?: string;
|
||||
/** Geschoss, dem die Treppe zugeordnet ist. */
|
||||
|
||||
+11
-6
@@ -9,9 +9,9 @@
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import { generateTerrainFromContours } from "../model/terrain";
|
||||
import { generateTerrainFromContours, type TerrainOptions } from "../model/terrain";
|
||||
import type { ContextObject, Project } from "../model/types";
|
||||
import { addItems, fieldOps, removeItems } from "../core/opsBuild";
|
||||
import { addItems, fieldOps, patchItem, removeItems } from "../core/opsBuild";
|
||||
import type { CoreOp } from "../core/ops";
|
||||
import { ensureContextCategories } from "../model/contextCategories";
|
||||
import type { StoreApi } from "./store";
|
||||
@@ -32,7 +32,9 @@ export interface SiteSlice {
|
||||
* weiteres Kontext-Objekt hinzu. Liefert die ID des neuen TerrainMesh, oder
|
||||
* null, wenn der ContourSet nicht existiert / kein Mesh entsteht.
|
||||
*/
|
||||
generateTerrain: (contourSetId: string) => string | null;
|
||||
generateTerrain: (contourSetId: string, opts?: TerrainOptions) => string | null;
|
||||
/** [T6]/[68] Ändert Felder eines Kontext-Objekts (Gelände, Baugrube) in einem Schritt; `coalesceKey` für Tippen. */
|
||||
patchContextObject: (id: string, patch: Record<string, unknown>, coalesceKey?: string) => void;
|
||||
/** Leert die gesamte Kontext-Schicht. */
|
||||
clearContext: () => void;
|
||||
}
|
||||
@@ -44,7 +46,7 @@ export interface SiteSlice {
|
||||
*/
|
||||
type SiteSliceDeps = {
|
||||
project: Project;
|
||||
applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[])) => void;
|
||||
applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[]), coalesceKey?: string) => void;
|
||||
};
|
||||
|
||||
export function createSiteSlice(
|
||||
@@ -81,13 +83,16 @@ export function createSiteSlice(
|
||||
get().applyChange((p) => removeItems(p, "context", ids));
|
||||
},
|
||||
|
||||
generateTerrain: (contourSetId) => {
|
||||
patchContextObject: (id, patch, coalesceKey) =>
|
||||
get().applyChange((p) => patchItem(p, "context", id, (o) => ({ ...o, ...patch }) as ContextObject), coalesceKey),
|
||||
|
||||
generateTerrain: (contourSetId, opts) => {
|
||||
const ctx = get().project.context ?? [];
|
||||
const set = ctx.find(
|
||||
(o) => o.id === contourSetId && o.type === "contourSet",
|
||||
);
|
||||
if (!set || set.type !== "contourSet") return null;
|
||||
const terrain = generateTerrainFromContours(set.contours);
|
||||
const terrain = generateTerrainFromContours(set.contours, opts);
|
||||
if (terrain.indices.length === 0) return null; // kein sinnvolles TIN
|
||||
addToContext([terrain]);
|
||||
return terrain.id;
|
||||
|
||||
@@ -169,6 +169,7 @@ export function usePanelHostBase(opts: {
|
||||
| "removeContextObject"
|
||||
| "removeContextObjects"
|
||||
| "generateTerrain"
|
||||
| "patchContextObject"
|
||||
| "commitTransformOn"
|
||||
| "setElementColor"
|
||||
| "setElementWeight"
|
||||
@@ -293,6 +294,7 @@ export function usePanelHostBase(opts: {
|
||||
removeContextObject,
|
||||
removeContextObjects,
|
||||
generateTerrain,
|
||||
patchContextObject,
|
||||
commitTransformOn,
|
||||
setElementColor,
|
||||
setElementWeight,
|
||||
@@ -600,6 +602,17 @@ export function usePanelHostBase(opts: {
|
||||
patchItem(p, "drawings2d", drawingId, (d) => ({ ...d, endMarks: { ...d.endMarks, ...patch } })),
|
||||
),
|
||||
),
|
||||
onSetGridProps: (drawingId, patch) =>
|
||||
setProject(
|
||||
opsMutation((p) =>
|
||||
patchItem(p, "drawings2d", drawingId, (d) => {
|
||||
if (d.geom.shape !== "grid") return d;
|
||||
const geom = { ...d.geom, ...patch };
|
||||
if (patch.levels === undefined && "levels" in patch) delete geom.levels;
|
||||
return { ...d, geom };
|
||||
}),
|
||||
),
|
||||
),
|
||||
onSetDimensionStyle: (drawingId, patch) =>
|
||||
setProject(
|
||||
opsMutation((p) =>
|
||||
@@ -800,6 +813,11 @@ export function usePanelHostBase(opts: {
|
||||
sliceTermination: termination === "both" ? undefined : termination,
|
||||
});
|
||||
},
|
||||
onSetWallRoofAttach: (attach) => {
|
||||
if (selection?.kind === "wall")
|
||||
// "auto" ist der Default ⇒ als undefined speichern.
|
||||
updateWall(selection.id, { roofAttach: attach === "auto" ? undefined : attach === "on" });
|
||||
},
|
||||
onSetWallType: (wallTypeId) => {
|
||||
if (selection?.kind === "wall")
|
||||
updateWall(selection.id, { wallTypeId });
|
||||
@@ -967,6 +985,10 @@ export function usePanelHostBase(opts: {
|
||||
onSetStairArrowStyle: (arrowStyle) => {
|
||||
if (selection?.kind === "stair") updateStair(selection.id, { arrowStyle });
|
||||
},
|
||||
onSetStairColumn: (radius) => {
|
||||
if (selection?.kind === "stair")
|
||||
updateStair(selection.id, { centerColumn: radius > 0 ? radius : undefined });
|
||||
},
|
||||
onSetStairReferenz: (referenz) => {
|
||||
if (selection?.kind === "stair") updateStair(selection.id, { referenz });
|
||||
},
|
||||
@@ -1083,6 +1105,8 @@ export function usePanelHostBase(opts: {
|
||||
onRemoveContextObject: removeContextObject,
|
||||
onRemoveContextObjects: removeContextObjects,
|
||||
onGenerateTerrain: generateTerrain,
|
||||
onPatchContextObject: patchContextObject,
|
||||
onStartExcavation: () => onRunCommand("excavation"),
|
||||
onSetGeoAnchor: (anchor) => {
|
||||
applyChange((p) => setFieldIfChanged(p, "geoAnchor", anchor));
|
||||
},
|
||||
|
||||
@@ -48,6 +48,8 @@ function contextObjectsBounds(objs: ContextObject[]): Vec2[] | null {
|
||||
} else if (obj.type === "image") {
|
||||
acc(obj.min.x, obj.min.y);
|
||||
acc(obj.max.x, obj.max.y);
|
||||
} else if (obj.type === "excavation") {
|
||||
for (const p of obj.outline) acc(p.x, p.y);
|
||||
} else {
|
||||
// importedMesh / terrainMesh: flaches (x,y,z…)-Array, Stride 3.
|
||||
const pos = obj.positions;
|
||||
@@ -351,6 +353,7 @@ export function useProjectActions(
|
||||
const removeContextObject = useStore((s) => s.removeContextObject);
|
||||
const removeContextObjects = useStore((s) => s.removeContextObjects);
|
||||
const generateTerrain = useStore((s) => s.generateTerrain);
|
||||
const patchContextObject = useStore((s) => s.patchContextObject);
|
||||
const moveGripOf = useStore((s) => s.moveGripOf);
|
||||
const moveElementByOf = useStore((s) => s.moveElementByOf);
|
||||
const moveEdgeOf = useStore((s) => s.moveEdgeOf);
|
||||
@@ -465,6 +468,7 @@ export function useProjectActions(
|
||||
removeContextObject,
|
||||
removeContextObjects,
|
||||
generateTerrain,
|
||||
patchContextObject,
|
||||
moveGripOf,
|
||||
moveElementByOf,
|
||||
moveEdgeOf,
|
||||
|
||||
@@ -4945,11 +4945,39 @@ body {
|
||||
}
|
||||
.site-panel .site-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 4px 6px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
/* [T6]/[68] Felder von Gelände und Baugrube unter der Zeile. */
|
||||
.site-panel .site-props {
|
||||
flex: 1 0 100%;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 4px 8px;
|
||||
font-size: 11px;
|
||||
}
|
||||
.site-panel .site-prop {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 4px;
|
||||
}
|
||||
.site-panel .site-prop input {
|
||||
width: 64px;
|
||||
}
|
||||
.site-panel .site-qty {
|
||||
grid-column: 1 / -1;
|
||||
color: var(--text-dim, inherit);
|
||||
}
|
||||
.site-panel .site-check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
font-size: 11px;
|
||||
}
|
||||
.site-panel .site-row:hover {
|
||||
background: var(--accent-dim);
|
||||
}
|
||||
|
||||
@@ -346,6 +346,18 @@ const pointmarkerTool: Tool = {
|
||||
onCancel: (s) => [s, { draft: null, done: true }],
|
||||
};
|
||||
|
||||
// Achsraster ([112]): Platzhalter-Werkzeug, gekoppelt an den `grid`-Befehl (Ursprung + Feldweiten).
|
||||
const gridTool: Tool = {
|
||||
id: "grid",
|
||||
labelKey: "tool.grid",
|
||||
hintKey: () => "tool.grid.hint",
|
||||
init: () => ({ phase: "idle" }),
|
||||
onClick: (s) => [s, { draft: null }],
|
||||
onMove: (s) => [s, { draft: null }],
|
||||
onCommitGesture: (s) => [s, { draft: null, done: true }],
|
||||
onCancel: (s) => [s, { draft: null, done: true }],
|
||||
};
|
||||
|
||||
// Wipeout/Maskenregion: Platzhalter-Werkzeug, gekoppelt an den
|
||||
// `wipeout`-Befehl (Punktfolge, schliesst automatisch → weisse Maskenfläche).
|
||||
// Freies 2D-Element (nicht floorOnly).
|
||||
@@ -456,6 +468,7 @@ const TOOLS: Record<ToolId, Tool> = {
|
||||
scalebar: scalebarTool,
|
||||
revcloud: revcloudTool,
|
||||
pointmarker: pointmarkerTool,
|
||||
grid: gridTool,
|
||||
wipeout: wipeoutTool,
|
||||
text: textTool,
|
||||
leader: leaderTool,
|
||||
|
||||
@@ -35,6 +35,7 @@ export type ToolId =
|
||||
| "scalebar"
|
||||
| "revcloud"
|
||||
| "pointmarker"
|
||||
| "grid"
|
||||
| "wipeout"
|
||||
| "text"
|
||||
| "leader"
|
||||
|
||||
@@ -182,6 +182,15 @@ export function CommandIcon({ name }: { name: string }) {
|
||||
<line x1="8" y1="3" x2="8" y2="9" strokeDasharray="1.5 1.5" />
|
||||
</svg>
|
||||
);
|
||||
case "excavation":
|
||||
// Baugrube: Geländelinie mit Grube, Böschungen schräg.
|
||||
return (
|
||||
<svg {...common}>
|
||||
<polyline points="1,5 4,5 6.5,11 9.5,11 12,5 15,5" />
|
||||
<line x1="4.8" y1="6.5" x2="3.6" y2="6.5" />
|
||||
<line x1="11.2" y1="6.5" x2="12.4" y2="6.5" />
|
||||
</svg>
|
||||
);
|
||||
case "roofhole":
|
||||
// Dachhof: Dach-Umriss mit ausgespartem Innenhof.
|
||||
return (
|
||||
@@ -225,6 +234,24 @@ export function CommandIcon({ name }: { name: string }) {
|
||||
<path d="M9.5 12.5 L12.5 9.5 L12.5 4.5" />
|
||||
</svg>
|
||||
);
|
||||
case "revolve":
|
||||
// Rotationskörper: Profil neben einer Achse, Drehbogen.
|
||||
return (
|
||||
<svg {...common}>
|
||||
<path d="M8 2.5 V13.5" strokeDasharray="1.4 1.2" />
|
||||
<path d="M9.5 4.5 H13 V11.5 H9.5 Z" />
|
||||
<path d="M6.5 4.5 H3 V11.5 H6.5" />
|
||||
</svg>
|
||||
);
|
||||
case "loft":
|
||||
// Loft: grosses Profil unten, kleines oben, verbunden.
|
||||
return (
|
||||
<svg {...common}>
|
||||
<rect x="2.5" y="9.5" width="11" height="3" />
|
||||
<rect x="5.5" y="3.5" width="5" height="2" />
|
||||
<path d="M2.5 9.5 L5.5 5.5 M13.5 9.5 L10.5 5.5" />
|
||||
</svg>
|
||||
);
|
||||
case "voidbox":
|
||||
// Durchbruch: Wand mit gestricheltem, durchkreuztem Ausschnitt.
|
||||
return (
|
||||
|
||||
@@ -5,6 +5,8 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import { projectToModel3d, sampleProject } from "../core";
|
||||
import {
|
||||
FOV_Y,
|
||||
focusCamera,
|
||||
focusedCamera,
|
||||
camera3dFromViewCamera,
|
||||
captureSnapshot,
|
||||
getCamera,
|
||||
@@ -153,6 +155,25 @@ describe("Schnittebene", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Fokus auf einen Punkt (Kollisionsliste)", () => {
|
||||
it("zentriert das Ziel auf den Modellpunkt, behält die Blickrichtung, Abstand folgt dem Radius", () => {
|
||||
const cam = orbitCamera({ yaw: 0.4, pitch: 0.3, dist: 15, target: [1, 2, 3], ortho: false, orthoHalfHeight: 8 });
|
||||
const f = focusedCamera(cam, [4, 5, 6], 2);
|
||||
close(f.target, modelToWorld([4, 5, 6]));
|
||||
const d = (c: Camera3d) => {
|
||||
const v = [c.target[0] - c.eye[0], c.target[1] - c.eye[1], c.target[2] - c.eye[2]];
|
||||
const l = Math.hypot(...v);
|
||||
return v.map((x) => x / l);
|
||||
};
|
||||
close(d(f), d(cam));
|
||||
const near = Math.hypot(...f.target.map((t, i) => t - f.eye[i]));
|
||||
expect(near).toBeGreaterThan(2);
|
||||
expect(near).toBeLessThan(15);
|
||||
const ortho = focusedCamera({ ...cam, perspective: false, orthoHalfHeight: 8 }, [0, 0, 0], 2);
|
||||
expect(ortho.orthoHalfHeight).toBeLessThan(8);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Registrierung", () => {
|
||||
function fakeViewport() {
|
||||
const state = { cam: orbitCamera({ yaw: 0.4, pitch: 0.3, dist: 15, target: [1, 2, 3], ortho: false, orthoHalfHeight: 8 }), written: null as Camera3d | null, section: undefined as unknown };
|
||||
@@ -181,6 +202,14 @@ describe("Registrierung", () => {
|
||||
expect(setCamera(vc)).toBe(false);
|
||||
});
|
||||
|
||||
it("focusCamera schreibt die fokussierte Kamera in den Viewport (false ohne Viewport)", () => {
|
||||
expect(focusCamera([1, 2, 3], 1)).toBe(false);
|
||||
const { state, a } = fakeViewport();
|
||||
registerViewportCamera(a);
|
||||
expect(focusCamera([5, 6, 7], 1)).toBe(true);
|
||||
close(state.written!.target, modelToWorld([5, 6, 7]));
|
||||
});
|
||||
|
||||
it("getCamera → setCamera am angemeldeten Viewport lässt die Kamera unverändert", () => {
|
||||
const { state, a } = fakeViewport();
|
||||
registerViewportCamera(a);
|
||||
|
||||
@@ -257,6 +257,29 @@ export function setCamera(cam: ViewCamera, opts: { animate?: boolean } = {}): bo
|
||||
return c3 ? api.write(c3, opts.animate === true) : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kamera, die einen Modellpunkt (x, y, Höhe) ins Ziel nimmt: gleiche Blickrichtung, Abstand so, dass eine
|
||||
* Kugel vom Radius `radius` (Meter) bequem ins Bild passt; orthografisch schrumpft die Sichthöhe.
|
||||
*/
|
||||
export function focusedCamera(cam: Camera3d, centerModel: readonly number[], radius: number): Camera3d {
|
||||
const target = modelToWorld(centerModel);
|
||||
const d = norm(sub(cam.target, cam.eye)) ?? ([0, 0, -1] as V3);
|
||||
const r = Math.max(radius, 0.5);
|
||||
const dist = Math.max((r * 2.2) / Math.tan((cam.fovY || FOV_Y) / 2), 1.5);
|
||||
return {
|
||||
...cam,
|
||||
target,
|
||||
eye: [target[0] - d[0] * dist, target[1] - d[1] * dist, target[2] - d[2] * dist],
|
||||
orthoHalfHeight: cam.perspective ? cam.orthoHalfHeight : r * 2.2,
|
||||
};
|
||||
}
|
||||
|
||||
/** Fokus der Live-Kamera auf einen Modellpunkt; `false` ohne Viewport. */
|
||||
export function focusCamera(centerModel: readonly number[], radius: number, opts: { animate?: boolean } = {}): boolean {
|
||||
const cur = api?.read();
|
||||
return api && cur ? api.write(focusedCamera(cur.camera, centerModel, radius), opts.animate !== false) : false;
|
||||
}
|
||||
|
||||
/** PNG des aktuellen 3D-Bildes, oder null (kein Viewport, leeres/nicht lesbares Bild). */
|
||||
export async function captureSnapshot(opts: { maxEdge?: number } = {}): Promise<Uint8Array | null> {
|
||||
if (!api) return null;
|
||||
|
||||
@@ -47,5 +47,6 @@ export function drawingMoveAnchor(d: Drawing2D, verts: Vec2[]): Vec2 | null {
|
||||
const g = d.geom;
|
||||
if (g.shape === "circle" || g.shape === "arc" || g.shape === "ellipse") return g.center;
|
||||
if (g.shape === "text" || g.shape === "kote" || g.shape === "detailref" || g.shape === "scalebar" || g.shape === "pointmarker") return g.at;
|
||||
if (g.shape === "grid") return g.origin;
|
||||
return null;
|
||||
}
|
||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user