From ef40091f6d7f566510bd8f1b176543ff8ab0ae1f Mon Sep 17 00:00:00 2001 From: Karim Date: Thu, 10 Sep 2026 15:40:04 +0200 Subject: [PATCH] =?UTF-8?q?Aufgestauter=20Arbeitsstand:=20Stifts=C3=A4tze,?= =?UTF-8?q?=20Bulge/B=C3=B6gen,=20neue=202D-Befehle,=20Geo/Import-Fixes,?= =?UTF-8?q?=20Dach-Schnittfugen=203D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sammel-Commit für mehrere Wochen Arbeit seit dem letzten Commit-Stand (22.8.) — Details je Fund/Feature stehen datiert in PENDENZEN.md. - Stiftsatz-System (ArchiCAD-Stiftsatz-Vorbild): Bauteile/Ebenen/Element- Overrides wahlweise auf freie Farbe oder Stift+Stärke gekoppelt, eigene Palette-UI, 255-Stift-Standardpalette. - Wand-"+"-Kreuzung: vierte Wand an einem Knoten wurde nicht mitverschnitten (model/joins.ts). - 2D-Grundriss: Schnitt-vs-Ansicht-Entscheidung berücksichtigt jetzt wall.bottom/top-Override statt nur der rohen Wandhöhe. - Bulge/Bogensegmente in Polylinien (geometry/bulge.ts) inkl. Trim/Extend/ Offset/Fillet-Unterstützung. - Neue 2D-Befehle: Block/Blockdefinition, Leader, Polygon, Textpfad, Xline. - Kontext-Objekt-Kategorien (Ebenen-Zuordnung für importierte Gebäude/ Terrain-Meshes). - Element-Zwischenablage (Kopieren/Einfügen) für alle 3D-Elementarten. - swissBUILDINGS3D/DXF-Import-Fixes (Polyface-Mesh-Absturz, Georeferenzierung, anwählbare Kontext-Meshes im 3D-Viewport). - Dach-Schnittfugen im 3D-Live-Schnitt (render3d: roof_cut.rs neu). - Diverse kleinere Fixes/Ergänzungen in Grundriss-, Schnitt-, Ansichts- und 3D-Pipeline (siehe PENDENZEN.md für Einzelheiten). Verifiziert: tsc --noEmit sauber, vitest run 117/1206 grün, cargo test --package render3d 96/96 grün. --- .gitignore | 4 + src-tauri/render3d/examples/section_svg.rs | 2 +- src-tauri/render3d/src/gpu.rs | 10 +- src-tauri/render3d/src/lib.rs | 1 + src-tauri/render3d/src/roof_cut.rs | 264 ++++++++++ src-tauri/render3d/src/section.rs | 110 +++- src-tauri/render3d/src/section_fill.rs | 62 ++- src-tauri/render3d/src/types.rs | 44 ++ src-tauri/render3d/src/web.rs | 32 +- src/App.tsx | 181 +++++-- src/DrawingTabs.tsx | 140 ++--- src/commands/cmds/block.test.ts | 80 +++ src/commands/cmds/block.ts | 87 ++++ src/commands/cmds/chamfer.ts | 4 +- src/commands/cmds/defblock.test.ts | 111 ++++ src/commands/cmds/defblock.ts | 90 ++++ src/commands/cmds/extend.test.ts | 110 ++++ src/commands/cmds/extend.ts | 88 +++- src/commands/cmds/fillet.test.ts | 23 + src/commands/cmds/fillet.ts | 44 +- src/commands/cmds/leader.test.ts | 72 +++ src/commands/cmds/leader.ts | 97 ++++ src/commands/cmds/offset.ts | 84 ++- src/commands/cmds/polygon.test.ts | 120 +++++ src/commands/cmds/polygon.ts | 157 ++++++ src/commands/cmds/textpath.test.ts | 80 +++ src/commands/cmds/textpath.ts | 137 +++++ src/commands/cmds/trim.test.ts | 108 ++++ src/commands/cmds/trim.ts | 93 +++- src/commands/cmds/xline.test.ts | 86 +++ src/commands/cmds/xline.ts | 136 +++++ src/commands/registry.ts | 25 + src/commands/types.ts | 1 - src/editors/elementClipboard.test.ts | 145 ++++++ src/editors/elementClipboard.ts | 236 +++++++++ src/editors/splitJoin.test.ts | 95 ++++ src/editors/splitJoin.ts | 74 ++- src/geometry/bulge.test.ts | 74 +++ src/geometry/bulge.ts | 141 +++++ src/geometry/kernel2d.extendBulge.test.ts | 70 +++ src/geometry/kernel2d.offsetBulge.test.ts | 77 +++ src/geometry/kernel2d.trimBulge.test.ts | 118 +++++ src/geometry/kernel2d.ts | 491 ++++++++++++++++++ src/i18n/de.ts | 74 ++- src/i18n/en.ts | 74 ++- src/io/dwgParser.test.ts | 186 +++++++ src/io/dwgParser.ts | 270 +++++++++- src/io/dxfParser.ts | 3 + src/io/geoContext.ts | 3 + src/io/projectFile.ts | 34 ++ src/io/stacApi.ts | 91 +++- src/io/swissBuildings3d.test.ts | 40 ++ src/io/swissBuildings3d.ts | 137 ++++- src/menus/contextMenu.tsx | 28 + src/model/contextCategories.test.ts | 110 ++++ src/model/contextCategories.ts | 175 +++++++ src/model/geoRebase.ts | 11 + src/model/joins.test.ts | 60 +++ src/model/joins.ts | 60 ++- src/model/penSets.test.ts | 352 +++++++++++++ src/model/penSets.ts | 253 +++++++++ src/model/sampleProject.ts | 23 +- src/model/terrain.ts | 27 +- src/model/types.ts | 239 ++++++++- src/native/appMenu.ts | 22 + src/panels/AttributesPanel.tsx | 109 +++- src/panels/ToolsPanel.tsx | 50 +- src/panels/ViewSnapshotsPanel.tsx | 31 +- src/panels/host.ts | 39 +- src/plan/PlanView.cssImageFilter.test.ts | 37 ++ src/plan/PlanView.tsx | 66 ++- src/plan/generatePlan.context.test.ts | 78 +++ src/plan/generatePlan.sectionLine.test.ts | 52 +- src/plan/generatePlan.ts | 139 ++++- src/plan/generatePlan.viewwall.test.ts | 33 ++ src/plan/generatePlan/context.ts | 22 +- src/plan/generatePlan/drawing2d.test.ts | 192 +++++++ src/plan/generatePlan/drawing2d.ts | 121 ++++- src/plan/generatePlan/sections.ts | 40 +- src/plan/generatePlan/shared.resolve.test.ts | 34 +- src/plan/generatePlan/shared.ts | 18 + src/plan/generateSectionPlan.category.test.ts | 95 ++++ src/plan/generateVisibleLevelsPlan.test.ts | 163 ++++++ src/plan/glPlan/glPlanCompile.ts | 12 +- src/plan/glPlan/glPlanHatch.test.ts | 33 ++ src/plan/glPlan/glPlanHatch.ts | 11 +- src/plan/planView/overlays.tsx | 9 +- src/plan/planView/primitives.tsx | 88 +++- src/plan/toElevation.test.ts | 144 ++++- src/plan/toElevation.ts | 93 +++- src/plan/toRenderScene.ts | 12 +- src/plan/toSection.ts | 16 +- src/plan/toWalls3d.test.ts | 274 +++++++++- src/plan/toWalls3d.ts | 6 +- src/plan/toWalls3d/bands.ts | 27 +- src/plan/toWalls3d/openings.ts | 56 ++ src/plan/toWalls3d/roofs.ts | 56 +- src/plan/toWalls3d/shared.ts | 29 ++ src/plan/toWalls3d/stairs.ts | 143 ++++- src/state/projectSlice.penSets.test.ts | 160 ++++++ src/state/projectSlice.polylineBulge.test.ts | 63 +++ src/state/projectSlice.ts | 293 ++++++++++- src/state/reorderDrawingLevels.test.ts | 78 +++ src/state/selectionInfo.contextImage.test.ts | 74 +++ src/state/selectionInfo.ts | 55 +- src/state/selectionSlice.ts | 14 +- src/state/siteSlice.ts | 27 +- src/state/useImportHandling.ts | 6 +- src/state/useKeyboardShortcuts.ts | 123 +++-- src/state/useMouseSelectionHandlers.ts | 76 ++- src/state/usePanelHostBase.ts | 117 ++++- src/state/useProjectActions.ts | 22 + src/state/useProjectFileActions.ts | 85 ++- src/state/useSelectionState.ts | 29 +- src/state/viewSnapshots.test.ts | 33 ++ src/state/viewSnapshots.ts | 21 +- src/styles.css | 313 ++++++++++- src/tools/snapping.ts | 14 + src/tools/tools.ts | 72 +++ src/tools/transform.test.ts | 42 ++ src/tools/transform.ts | 41 +- src/tools/types.ts | 5 + src/ui/AppMenuBar.tsx | 31 ++ src/ui/ContextImportDialog.tsx | 13 +- src/ui/ImportDialog.tsx | 8 +- src/ui/PenColorField.tsx | 312 +++++++++++ src/ui/ResourceManager.tsx | 36 +- src/ui/hatchPreview.tsx | 35 +- src/ui/resourceManager/ComponentsTab.tsx | 74 ++- src/ui/resourceManager/HatchesTab.tsx | 38 +- src/ui/resourceManager/PenSetsTab.tsx | 191 +++++++ src/ui/resourceManager/fields.tsx | 12 +- src/ui/ribbon/CommandIcon.tsx | 9 + src/viewport/Viewport3D.tsx | 27 +- src/viewport/viewport3d/meshBuilders.ts | 154 ++++++ src/views/viewportContent.tsx | 267 ++++++++-- 136 files changed, 11109 insertions(+), 665 deletions(-) create mode 100644 src-tauri/render3d/src/roof_cut.rs create mode 100644 src/commands/cmds/block.test.ts create mode 100644 src/commands/cmds/block.ts create mode 100644 src/commands/cmds/defblock.test.ts create mode 100644 src/commands/cmds/defblock.ts create mode 100644 src/commands/cmds/leader.test.ts create mode 100644 src/commands/cmds/leader.ts create mode 100644 src/commands/cmds/polygon.test.ts create mode 100644 src/commands/cmds/polygon.ts create mode 100644 src/commands/cmds/textpath.test.ts create mode 100644 src/commands/cmds/textpath.ts create mode 100644 src/commands/cmds/trim.test.ts create mode 100644 src/commands/cmds/xline.test.ts create mode 100644 src/commands/cmds/xline.ts create mode 100644 src/editors/elementClipboard.test.ts create mode 100644 src/editors/elementClipboard.ts create mode 100644 src/editors/splitJoin.test.ts create mode 100644 src/geometry/bulge.test.ts create mode 100644 src/geometry/bulge.ts create mode 100644 src/geometry/kernel2d.extendBulge.test.ts create mode 100644 src/geometry/kernel2d.offsetBulge.test.ts create mode 100644 src/geometry/kernel2d.trimBulge.test.ts create mode 100644 src/io/dwgParser.test.ts create mode 100644 src/model/contextCategories.test.ts create mode 100644 src/model/contextCategories.ts create mode 100644 src/model/penSets.test.ts create mode 100644 src/model/penSets.ts create mode 100644 src/plan/PlanView.cssImageFilter.test.ts create mode 100644 src/plan/generateSectionPlan.category.test.ts create mode 100644 src/plan/generateVisibleLevelsPlan.test.ts create mode 100644 src/state/projectSlice.penSets.test.ts create mode 100644 src/state/projectSlice.polylineBulge.test.ts create mode 100644 src/state/reorderDrawingLevels.test.ts create mode 100644 src/state/selectionInfo.contextImage.test.ts create mode 100644 src/ui/PenColorField.tsx create mode 100644 src/ui/resourceManager/PenSetsTab.tsx diff --git a/.gitignore b/.gitignore index 01b6e4c9..91d59d84 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,10 @@ scripts/*.png .DS_Store *.log +# Lokale Test-/Demo-Projektdateien (kein Quellcode) +*.obp +*.obp.lock + # Generierte native-Viewport-Szenen (aus sampleProject via scripts/dump-native-scene.mjs) src-tauri/assets/native2d_scene.json src-tauri/assets/native3d_walls.json diff --git a/src-tauri/render3d/examples/section_svg.rs b/src-tauri/render3d/examples/section_svg.rs index 6d444829..d3f906b0 100644 --- a/src-tauri/render3d/examples/section_svg.rs +++ b/src-tauri/render3d/examples/section_svg.rs @@ -176,7 +176,7 @@ fn main() { // section.rs-Tests). Zeigt also geschnittenes Material UND eine gemischte // sichtbar/verdeckt-Ansicht MIT Oeffnung in einem Bild. let plane = SectionPlane::looking_plus_x(-0.3); - let out = cut_section(&plane, &walls, &slabs); + let out = cut_section(&plane, &walls, &slabs, &[]); println!( "cut_polygons={}, visible_edges={}, hidden_edges={}", diff --git a/src-tauri/render3d/src/gpu.rs b/src-tauri/render3d/src/gpu.rs index 07a28a16..98a327ea 100644 --- a/src-tauri/render3d/src/gpu.rs +++ b/src-tauri/render3d/src/gpu.rs @@ -27,8 +27,8 @@ use crate::section_fill::{ }; use crate::shaders::{CAP_WGSL, GRID_WGSL, MESH_AERIAL_WGSL, MESH_TEXTURED_WGSL, MESH_WGSL}; use crate::types::{ - Camera, Mesh, MeshInput, SlabInput, TexturedMesh, WallInput, FLOATS_PER_VERTEX, - TEXTURED_FLOATS_PER_VERTEX, + Camera, Mesh, MeshInput, RoofLayerInput, SlabInput, TexturedMesh, WallInput, + FLOATS_PER_VERTEX, TEXTURED_FLOATS_PER_VERTEX, }; /// Darstellungsart des 3D-Renderers (Oberleiste: shaded/white/textured/ @@ -1296,6 +1296,7 @@ impl Renderer { /// Waenden/Decken neu bauen — bei `active == false` werden Uniform-Flag und /// Caps geloescht. Buendelt `set_section_plane` + `build_cut_caps` + /// `set_cut_caps`, damit `web.rs` nur EINEN Aufruf braucht. + #[allow(clippy::too_many_arguments)] pub fn update_section( &mut self, device: &wgpu::Device, @@ -1304,15 +1305,16 @@ impl Renderer { normal: [f32; 3], walls: &[WallInput], slabs: &[SlabInput], + roofs: &[RoofLayerInput], ) { self.set_section_plane(active, point, normal); if active { let plane = SectionPlane::new(point, normal); - let caps = build_cut_caps(&plane, walls, slabs); + let caps = build_cut_caps(&plane, walls, slabs, roofs); self.set_cut_caps(device, &caps); // P2: die Schnitt-Umrisslinien (Fugen-/Materiallinien) je ueberlebendem // Cut-Cap-Rechteck aus DERSELBEN, dominanz-verschnittenen Rechteck-Menge. - let lines = build_cut_cap_lines(&plane, walls, slabs); + let lines = build_cut_cap_lines(&plane, walls, slabs, roofs); self.set_cut_lines(device, &lines); } else { self.set_cut_caps(device, &[]); diff --git a/src-tauri/render3d/src/lib.rs b/src-tauri/render3d/src/lib.rs index 064c6adf..e3e39673 100644 --- a/src-tauri/render3d/src/lib.rs +++ b/src-tauri/render3d/src/lib.rs @@ -19,6 +19,7 @@ pub mod grid; pub mod math; pub mod mesh; pub(crate) mod openings; +pub mod roof_cut; pub mod section; pub mod section_boolean; pub mod section_fill; diff --git a/src-tauri/render3d/src/roof_cut.rs b/src-tauri/render3d/src/roof_cut.rs new file mode 100644 index 00000000..6ddd79f4 --- /dev/null +++ b/src-tauri/render3d/src/roof_cut.rs @@ -0,0 +1,264 @@ +//! Schnitt einer GENEIGTEN Dach-Schicht (`RoofLayerInput`) mit einer vertikalen +//! `SectionPlane` — der Dach-Ergänzungspfad zum Prisma-Ansatz in `section.rs`. +//! +//! ## Warum ein eigener Pfad (nicht `Prism`) +//! +//! `section.rs`s gesamte Herleitung ("jedes Bauteil ist ein 2D-Grundriss, +//! VERTIKAL extrudiert über `[z0,z1]`, daher ist der Schnitt mit einer +//! vertikalen Ebene immer ein Rechteck") gilt für Wand und Decke, aber NICHT +//! für ein Dach: eine Dachfläche ist ein Polygon, extrudiert entlang ihrer +//! EIGENEN (i. A. schrägen) Flächennormalen. Da die Extrusionsrichtung nicht +//! mehr parallel zur Höhenachse ist, ist der Schnitt mit einer vertikalen +//! Ebene kein Rechteck mehr, sondern ein allgemeineres Polygon (i. d. R. ein +//! Parallelogramm/Trapez) — der Rechteck-Kurzschluss aus `section.rs` trägt +//! hier nicht. +//! +//! ## Herleitung +//! +//! Die Schicht ist die Menge `{ p + s*d : p ∈ Polygon, s ∈ [0,1] }` für die +//! Extrusionsrichtung `d = -thickness * normal` (Schicht wächst nach INNEN, +//! weg von `normal`, s. `RoofLayerInput::normal`). Ein Punkt liegt GENAU DANN +//! auf der Schnittebene (Punkt `plane.point`, Normale `N`), wenn +//! +//! ```text +//! dot(p + s*d - plane.point, N) = 0 +//! <=> s(p) = -dot(p - plane.point, N) / dot(d, N) (*) +//! ``` +//! +//! `dot(p - plane.point, N)` ist LINEAR in `p` (das Polygon liegt in einer +//! Ebene), `dot(d, N)` eine Konstante — also ist `s(p)` eine AFFINE Funktion +//! von `p`. Der Schnitt-Querschnitt ist damit exakt die Teilmenge +//! `{ p ∈ Polygon : s(p) ∈ [0,1] }` — eine Poly-Clip-Aufgabe des Polygons +//! gegen ZWEI Halbebenen im eigenen Parameterraum (klassisches Sutherland- +//! Hodgman, hier direkt auf den 3D-Punkten mit dem Skalarfeld `s`). Jeder +//! resultierende Clip-Punkt `p_i` liefert über (*) sein `s(p_i)`, und +//! `p_i + s(p_i)*d` ist der tatsächliche 3D-Schnittpunkt (liegt exakt auf der +//! Ebene, keine weitere „Kappung" nötig — Clip und Schnitt fallen zusammen). +//! +//! Degeneriert, wenn `dot(d, N) ≈ 0` (Extrusionsrichtung [nahezu] parallel +//! zur Schnittebene — die Dachfläche wird „auf Kante" geschnitten): `s(p)` +//! ist dann nicht sinnvoll bestimmbar, `cut_roof_layer` liefert konservativ +//! `None` (kein Cut-Polygon), analog zur Wand-Sonderbehandlung „hinreichend +//! parallel" in `section.rs`. +//! +//! ANNAHME: die Eingabe-Polygone (Dachflächen aus `roofGeometry`) sind +//! EINFACH und (praktisch immer) KONVEX — bei einem nicht-konvexen Polygon +//! könnte der Schnitt in mehrere getrennte Stücke zerfallen, was ein +//! einzelner Sutherland-Hodgman-Durchlauf nicht korrekt abbildet. Für die in +//! dieser App erzeugten Dachformen (flach/pult/sattel/walm/mansarde/zelt, +//! stets Rechtecke/Trapeze) ist das gegeben. + +use crate::math; +use crate::section::{ComponentKind, ComponentRef, CutPolygon, SectionPlane}; +use crate::types::RoofLayerInput; + +/// Sutherland-Hodgman-Clip eines (räumlichen) Polygons gegen EINE Halbebene im +/// Sinne eines Skalarfelds `f`: behält die Punkte mit `f(p) >= threshold`. +/// Kanten, die die Grenze `f(p) = threshold` queren, werden per LINEARER +/// Interpolation geschnitten — exakt, weil `f` laut Konstruktion AFFIN +/// entlang jeder Kante ist (s. Moduldoc). +fn clip_half_plane(pts: &[[f32; 3]], f: impl Fn([f32; 3]) -> f32, threshold: f32) -> Vec<[f32; 3]> { + let n = pts.len(); + if n == 0 { + return Vec::new(); + } + let inside = |p: [f32; 3]| f(p) - threshold >= -1e-6; + let intersect = |a: [f32; 3], b: [f32; 3]| -> [f32; 3] { + let fa = f(a) - threshold; + let fb = f(b) - threshold; + let denom = fa - fb; + let t = if denom.abs() > 1e-9 { fa / denom } else { 0.0 }; + [ + a[0] + (b[0] - a[0]) * t, + a[1] + (b[1] - a[1]) * t, + a[2] + (b[2] - a[2]) * t, + ] + }; + let mut out = Vec::with_capacity(n + 2); + for i in 0..n { + let prev = pts[(i + n - 1) % n]; + let cur = pts[i]; + let prev_in = inside(prev); + let cur_in = inside(cur); + if prev_in && cur_in { + out.push(cur); + } else if prev_in && !cur_in { + out.push(intersect(prev, cur)); + } else if !prev_in && cur_in { + out.push(intersect(prev, cur)); + out.push(cur); + } + } + out +} + +/// Modell `(x, y, z=Höhe)` -> Welt `(x, z, y)` — dieselbe Konvention wie +/// `MeshInput`/`mesh.rs` (s. `types.rs`-Moduldoc). `RoofLayerInput::polygon`/ +/// `normal` kommen UNVERÄNDERT aus der TS-seitigen Dachflächen-Berechnung +/// (`toWalls3d/roofs.ts::planeNormalUp`/`g.planes`, dieselben Modell-Punkte, +/// aus denen auch das Render-Mesh gebaut wird) — die TS-Seite rechnet also +/// NICHT selbst nach Welt um (anders als ursprünglich entworfen), sondern +/// reicht die Rohdaten 1:1 durch, konsistent mit `WallInput`/`SlabInput`/ +/// `MeshInput`, die den Modell->Welt-Wechsel ebenfalls Rust-seitig machen. +fn to_world(p: [f32; 3]) -> [f32; 3] { + [p[0], p[2], p[1]] +} + +/// Schneidet EINE Dach-Schicht mit einer Schnittebene. `None`, wenn die Ebene +/// die Schicht nicht trifft, das Polygon entartet ist (<3 Punkte, Dicke ≈ 0) +/// oder die Extrusion (fast) parallel zur Ebene liegt (s. Moduldoc). +pub fn cut_roof_layer(layer: &RoofLayerInput, plane: &SectionPlane) -> Option { + if layer.polygon.len() < 3 || layer.thickness.abs() < 1e-6 { + return None; + } + let polygon: Vec<[f32; 3]> = layer.polygon.iter().map(|&p| to_world(p)).collect(); + let normal = to_world(layer.normal); + let d = [ + -normal[0] * layer.thickness, + -normal[1] * layer.thickness, + -normal[2] * layer.thickness, + ]; + let dn = math::dot(d, plane.normal); + if dn.abs() < 1e-6 { + return None; + } + let s_of = |p: [f32; 3]| -> f32 { -math::dot(math::sub(p, plane.point), plane.normal) / dn }; + + let clipped = clip_half_plane(&polygon, &s_of, 0.0); + // Zweiter Clip gegen s <= 1: als "-s >= -1", damit dieselbe `inside`- + // Konvention (>= threshold) wiederverwendet werden kann. + let clipped = clip_half_plane(&clipped, |p| -s_of(p), -1.0); + if clipped.len() < 3 { + return None; + } + + let pts: Vec<[f32; 2]> = clipped + .iter() + .map(|&p| { + let s = s_of(p).clamp(0.0, 1.0); + let cut_p = [p[0] + d[0] * s, p[1] + d[1] * s, p[2] + d[2] * s]; + plane.project(cut_p) + }) + .collect(); + + Some(CutPolygon { + component: ComponentRef { + kind: ComponentKind::Roof, + index: 0, // vom Aufrufer (`cut_section`) auf den echten Array-Index gesetzt + }, + color: layer.color, + hatch: layer.hatch, + pts, + cut: layer.cut.clone(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::types::CutBandMeta; + + /// Pultdach-artige Fläche, in MODELL-Metern `(x, y, z=Höhe)` — wie + /// `RoofLayerInput` es erwartet (`cut_roof_layer` macht den Modell->Welt- + /// Wechsel selbst, s. `to_world`). Traufe bei Modell-X=0/Höhe=0, First bei + /// Modell-X=4/Höhe=3, First läuft entlang Modell-Y (Grundriss-Tiefe) — nach + /// dem Wechsel `(x,y,z)->world(x,z,y)` entsteht exakt die Fläche + /// `P0=(0,0,0), P1=(0,0,5)‥First entlang Welt-Z` aus einer früheren Version + /// dieses Tests (per Hand nachgerechnet): ein ebenes Rechteck, das eine + /// vertikale Schnittebene entlang Welt-X (z. B. `looking_plus_x`) ECHT quert + /// (Welt-X- UND Welt-Y-Komponente der Normalen ungleich null) — anders als + /// eine Ebene, die nur die Firstrichtung variiert (die wäre parallel zur + /// Extrusion, s. `extrusion_parallel_zur_ebene_liefert_none_statt_panik`). + fn sloped_layer(thickness: f32, cut: Option) -> RoofLayerInput { + RoofLayerInput { + polygon: vec![ + [0.0, 0.0, 0.0], + [0.0, 5.0, 0.0], + [4.0, 5.0, 3.0], + [4.0, 0.0, 3.0], + ], + normal: math::normalize([-15.0, 0.0, 20.0]), + thickness, + color: [0.7, 0.4, 0.3], + hatch: None, + cut, + } + } + + #[test] + fn schnitt_mittig_liefert_ein_viereck_auf_der_ebene() { + let layer = sloped_layer(0.1, None); + // Vertikale Schnittebene bei Grundriss-X = 2 (Blick +X) — schneidet die + // Dachfläche in der Mitte (X läuft 0..4 über die Flächenbreite). + let plane = SectionPlane::looking_plus_x(2.0); + let poly = cut_roof_layer(&layer, &plane).expect("Ebene trifft die Schicht"); + assert_eq!(poly.pts.len(), 4, "Schnitt eines Quaders/Prismas ist ein Viereck"); + // Alle Punkte liegen wirklich AUF der Ebene (u,v -> Welt -> Tiefe 0 pruefen). + for &[u, v] in &poly.pts { + let world = [ + plane.point[0] + u * plane.u_axis()[0], + v, + plane.point[2] + u * plane.u_axis()[2], + ]; + assert!(plane.depth(world).abs() < 1e-4, "Punkt muss auf der Ebene liegen"); + } + } + + #[test] + fn schnitt_ausserhalb_der_flaeche_liefert_none() { + let layer = sloped_layer(0.1, None); + let plane = SectionPlane::looking_plus_x(10.0); // weit ausserhalb X in [0,4] + assert!(cut_roof_layer(&layer, &plane).is_none()); + } + + #[test] + fn dickere_schicht_liefert_ein_breiteres_schnitt_viereck() { + // Dicke wirkt entlang der (schrägen) Normalen -> bei gleicher X-Schnittposition + // deckt eine dickere Schicht eine groessere (u,v)-Spanne ab. + let plane = SectionPlane::looking_plus_x(2.0); + let thin = cut_roof_layer(&sloped_layer(0.05, None), &plane).unwrap(); + let thick = cut_roof_layer(&sloped_layer(0.3, None), &plane).unwrap(); + let spread = |poly: &CutPolygon| -> f32 { + let vs: Vec = poly.pts.iter().map(|p| p[1]).collect(); + vs.iter().cloned().fold(f32::MIN, f32::max) - vs.iter().cloned().fold(f32::MAX, f32::min) + }; + assert!(spread(&thick) > spread(&thin)); + } + + #[test] + fn schnittstil_und_farbe_wandern_ins_cutpolygon() { + let cut = CutBandMeta { + join_priority: None, + component_id: None, + line_color: Some([0.1, 0.2, 0.3]), + line_weight: Some(0.5), + }; + let layer = sloped_layer(0.1, Some(cut)); + let plane = SectionPlane::looking_plus_x(2.0); + let poly = cut_roof_layer(&layer, &plane).unwrap(); + assert_eq!(poly.color, [0.7, 0.4, 0.3]); + let meta = poly.cut.expect("cut-Metadaten muessen erhalten bleiben"); + assert_eq!(meta.line_color, Some([0.1, 0.2, 0.3])); + assert_eq!(meta.line_weight, Some(0.5)); + // Bewusst KEINE join_priority -> nimmt nicht an subtract_dominant_bands teil. + assert_eq!(meta.join_priority, None); + } + + #[test] + fn extrusion_parallel_zur_ebene_liefert_none_statt_panik() { + // Degenerierter Fall: die Schnittebene so waehlen, dass ihre Normale + // senkrecht auf der (WELT-)Extrusionsrichtung `d = -normal*thickness` + // steht (dot(d, plane.normal) ~ 0) -> `s(p)` waere nicht bestimmbar. + // `layer.normal` ist Modell-Raum -> erst `to_world`, wie `cut_roof_layer` + // es intern auch macht. + let layer = sloped_layer(0.1, None); + let world_normal = to_world(layer.normal); + let d = [-world_normal[0], -world_normal[1], -world_normal[2]]; + // `n` per Kreuzprodukt aus `d` und der Weltvertikalen konstruiert: per + // Definition senkrecht zu `d`, ausserdem vertikal-frei genug fuer eine + // sinnvolle Schnittebene (Moduldoc: nur vertikale Ebenen). + let n = math::cross([0.0, 1.0, 0.0], d); + let plane = SectionPlane::new([2.0, 0.0, 0.0], n); + assert!(cut_roof_layer(&layer, &plane).is_none()); + } +} diff --git a/src-tauri/render3d/src/section.rs b/src-tauri/render3d/src/section.rs index 467f4741..d60fc0ae 100644 --- a/src-tauri/render3d/src/section.rs +++ b/src-tauri/render3d/src/section.rs @@ -130,7 +130,7 @@ use serde::{Deserialize, Serialize}; use crate::math; -use crate::types::{CutBandMeta, Hatch, Opening, Point2, Rgb, SlabInput, WallInput}; +use crate::types::{CutBandMeta, Hatch, Opening, Point2, Rgb, RoofLayerInput, SlabInput, WallInput}; /// Toleranz fuer "naeher an der Ebene" / Grenzwert-Vergleiche (Meter, Tiefe/Hoehe). const EPS: f32 = 1e-4; @@ -248,6 +248,9 @@ fn to_world(p: Point2, height: f32) -> [f32; 3] { pub enum ComponentKind { Wall, Slab, + /// Dach-Schicht (`RoofLayerInput`) — läuft NICHT über `Prism` (s. dortige + /// Moduldoc), sondern über `roof_cut::cut_roof_layer`. + Roof, } /// Referenz auf das Ursprungs-Bauteil eines Cut-Polygons/einer Kante: Art + @@ -967,8 +970,19 @@ fn compute_view_edges( // ───────────────────────────────────────────────────────────────────────────── /// Fuehrt einen Schnitt/eine Ansicht entlang `plane` gegen das Modell (Waende + -/// Decken) aus. Siehe Moduldoc fuer Format/Konventionen. -pub fn cut_section(plane: &SectionPlane, walls: &[WallInput], slabs: &[SlabInput]) -> SectionOutput { +/// Decken + optional Dach-Schichten) aus. Siehe Moduldoc fuer Format/ +/// Konventionen. Dach-Schichten (`roofs`) laufen NICHT ueber die `Prism`- +/// Pipeline (kein vertikales Prisma, s. `roof_cut.rs`-Moduldoc) — ihre +/// Cut-Polygone werden separat berechnet und additiv angehaengt; sie tragen +/// bewusst keine `join_priority`, nehmen also nicht an der Boolean-Dominanz +/// (`section_boolean::subtract_dominant_bands`, aufgerufen in `section_fill.rs`) +/// teil. +pub fn cut_section( + plane: &SectionPlane, + walls: &[WallInput], + slabs: &[SlabInput], + roofs: &[RoofLayerInput], +) -> SectionOutput { let mut prisms: Vec = Vec::new(); // Gehrte Wand-Fussabdruecke einmalig ueber die gesamte Wandkonnektivitaet // (dieselbe Verschneidung wie das 3D-Mesh, siehe `mesh::wall_mitered_footprints`). @@ -1006,6 +1020,14 @@ pub fn cut_section(plane: &SectionPlane, walls: &[WallInput], slabs: &[SlabInput } } + // Dach-Schichten: separater Pfad (kein Prisma), additiv angehaengt. + for (i, layer) in roofs.iter().enumerate() { + if let Some(mut poly) = crate::roof_cut::cut_roof_layer(layer, plane) { + poly.component.index = i; + cut_polygons.push(poly); + } + } + let (visible_edges, hidden_edges) = compute_view_edges(plane, &prisms); SectionOutput { @@ -1125,7 +1147,7 @@ mod tests { // (Achse x in [0,3]), aber ausserhalb von Schenkel A (Band x in // [-0.1,0.1]) und schneidet die volle Bodenplatte (x in [-0.5,3.5]). let plane = SectionPlane::looking_plus_x(1.5); - let out = cut_section(&plane, &walls, &slabs); + let out = cut_section(&plane, &walls, &slabs, &[]); assert_eq!( out.cut_polygons.len(), @@ -1168,7 +1190,7 @@ mod tests { let (walls, slabs) = l_wall_scene(); // x = 10 liegt weit ausserhalb aller Fussabdruecke. let plane = SectionPlane::looking_plus_x(10.0); - let out = cut_section(&plane, &walls, &slabs); + let out = cut_section(&plane, &walls, &slabs, &[]); assert!(out.cut_polygons.is_empty()); } @@ -1180,7 +1202,7 @@ mod tests { // Ebene bei x = -2, Blick nach +X: das gesamte Modell liegt dahinter // (kleinste Fussabdruck-X ist -0.5 bei der Bodenplatte). let plane = SectionPlane::looking_plus_x(-2.0); - let out = cut_section(&plane, &walls, &slabs); + let out = cut_section(&plane, &walls, &slabs, &[]); assert!( out.cut_polygons.is_empty(), @@ -1249,7 +1271,7 @@ mod tests { let (walls, _) = l_wall_scene(); let wall_a = vec![walls[0].clone()]; let plane = SectionPlane::looking_plus_x(-2.0); - let out = cut_section(&plane, &wall_a, &[]); + let out = cut_section(&plane, &wall_a, &[], &[]); assert_eq!(out.visible_edges.len(), 4, "Vorderseite: 2 vertikale + Boden + Deckel"); assert_eq!(out.hidden_edges.len(), 4, "Rueckseite: 2 vertikale + Boden + Deckel"); // Alle sichtbaren Kanten liegen bei der naeheren Tiefe (kleinerer @@ -1271,7 +1293,7 @@ mod tests { // sauber aneinander, ohne Ueberlappung. let (walls, _) = l_wall_scene(); let plane = SectionPlane::looking_plus_x(0.05); - let out = cut_section(&plane, &walls, &[]); + let out = cut_section(&plane, &walls, &[], &[]); let wall_cuts: Vec<&CutPolygon> = out .cut_polygons @@ -1333,7 +1355,7 @@ mod tests { // entstehen: Bruestung (0..1.0) und Sturz (2.0..2.5). let wall = wall_with_window(); let plane = SectionPlane::looking_plus_x(2.0); - let out = cut_section(&plane, &[wall], &[]); + let out = cut_section(&plane, &[wall], &[], &[]); assert_eq!(out.cut_polygons.len(), 2, "Bruestung + Sturz statt Vollrechteck"); @@ -1377,7 +1399,7 @@ mod tests { // (1.5..2.5) -> Regressionsfall, unveraendert ein Vollrechteck. let wall = wall_with_window(); let plane = SectionPlane::looking_plus_x(0.5); - let out = cut_section(&plane, &[wall], &[]); + let out = cut_section(&plane, &[wall], &[], &[]); assert_eq!(out.cut_polygons.len(), 1, "kein Fenster an dieser Stelle -> ein Vollrechteck"); let c = &out.cut_polygons[0]; @@ -1415,7 +1437,7 @@ mod tests { }; // Blick von y = -2 nach +Y: beide Waende (y=0 bzw. y=1) liegen dahinter. let plane = SectionPlane::looking_plus_y(-2.0); - let out = cut_section(&plane, &[w0, w1], &[]); + let out = cut_section(&plane, &[w0, w1], &[], &[]); // -- Fensterrahmen (Wand 0) ist vollstaendig sichtbar (nichts davor). -- // Leibungen bei u=-1.5 und u=-2.5 (Fenster-Enden), v von 1.0 (Bruestung) @@ -1509,4 +1531,70 @@ mod tests { }); assert!(!w1_closed_wall_visible, "u=-4.0 (hinter geschlossener Wand) darf nicht sichtbar sein"); } + + /// Integrationstest: `cut_section` mit Wand + Dach-Schicht zusammen — deckt + /// die eigentliche Verdrahtung ab (nicht nur die isolierte Geometrie in + /// `roof_cut.rs`s eigenen Tests): das Dach-Cut-Polygon landet im selben + /// `cut_polygons`, unter `ComponentKind::Roof`, mit korrektem Array-Index, + /// UNBEEINFLUSST von einer gleichzeitig geschnittenen Wand. + #[test] + fn cut_section_mit_wand_und_dach_liefert_beide_cut_polygone() { + let wall = WallInput { + start: [2.0, -1.0], + end: [2.0, 1.0], + thickness: 0.3, + height: 2.5, + base_elevation: 0.0, + color: [0.8, 0.8, 0.8], + openings: vec![], + layers: None, + holes: vec![], + material_index: None, + hatch: None, + cut: None, + }; + // Pultdach-Flaeche wie in roof_cut.rs-Tests: First entlang Welt-Z, + // steigt von X=0 (Traufe) zu X=4 (First) an. + let roof = RoofLayerInput { + // Modell-Meter (x,y,z=Höhe) — `cut_roof_layer` macht den + // Modell->Welt-Wechsel selbst (s. `roof_cut::to_world`). + polygon: vec![ + [0.0, 0.0, 3.0], + [0.0, 5.0, 3.0], + [4.0, 5.0, 6.0], + [4.0, 0.0, 6.0], + ], + normal: crate::math::normalize([-15.0, 0.0, 20.0]), + thickness: 0.2, + color: [0.7, 0.4, 0.3], + hatch: None, + cut: Some(CutBandMeta { + join_priority: None, + component_id: None, + line_color: Some([0.2, 0.1, 0.05]), + line_weight: Some(0.4), + }), + }; + let plane = SectionPlane::looking_plus_x(2.0); + let out = cut_section(&plane, &[wall], &[], &[roof]); + + let wall_polys: Vec<_> = out + .cut_polygons + .iter() + .filter(|p| p.component.kind == ComponentKind::Wall) + .collect(); + let roof_polys: Vec<_> = out + .cut_polygons + .iter() + .filter(|p| p.component.kind == ComponentKind::Roof) + .collect(); + assert!(!wall_polys.is_empty(), "Wand muss weiterhin ihr Cut-Polygon liefern"); + assert_eq!(roof_polys.len(), 1, "genau ein Dach-Cut-Polygon"); + assert_eq!(roof_polys[0].component.index, 0); + assert_eq!(roof_polys[0].pts.len(), 4); + // Der Fugenlinien-Stil aus `RoofLayerInput::cut` bleibt erhalten. + let meta = roof_polys[0].cut.as_ref().expect("cut-Metadaten erwartet"); + assert_eq!(meta.line_color, Some([0.2, 0.1, 0.05])); + assert_eq!(meta.line_weight, Some(0.4)); + } } diff --git a/src-tauri/render3d/src/section_fill.rs b/src-tauri/render3d/src/section_fill.rs index 0cad882a..d86bf361 100644 --- a/src-tauri/render3d/src/section_fill.rs +++ b/src-tauri/render3d/src/section_fill.rs @@ -34,8 +34,8 @@ //! Rechteck (4 Ecken, siehe `section.rs`) — Fan-Triangulierung genuegt. use crate::section::{cut_section, CutPolygon, SectionPlane}; -use crate::section_boolean::{rect_of_poly, subtract_dominant_bands}; -use crate::types::{SlabInput, WallInput}; +use crate::section_boolean::subtract_dominant_bands; +use crate::types::{RoofLayerInput, SlabInput, WallInput}; /// f32 pro Cap-Vertex: [pos.x, pos.y, pos.z, u, v, pattern, angle_rad, scale, /// line_weight_mm]. Spiegel des Vertex-Layouts der `cap_pipeline` (gpu.rs) und des @@ -99,8 +99,13 @@ const FALLBACK_PATTERN: f32 = 2.0; /// (`toSection.ts::attachCutStyles` Phase 2). Gemeinsame Basis der Cut-Cap-Flaechen /// (`build_cut_caps`) UND der Cut-Umrisslinien (`build_cut_cap_lines`), damit beide /// auf DERSELBEN, ueberlappungsfreien Rechteck-Menge arbeiten. -fn cut_cap_polys(plane: &SectionPlane, walls: &[WallInput], slabs: &[SlabInput]) -> Vec { - let out = cut_section(plane, walls, slabs); +fn cut_cap_polys( + plane: &SectionPlane, + walls: &[WallInput], + slabs: &[SlabInput], + roofs: &[RoofLayerInput], +) -> Vec { + let out = cut_section(plane, walls, slabs, roofs); subtract_dominant_bands(out.cut_polygons) } @@ -108,8 +113,9 @@ pub fn build_cut_caps( plane: &SectionPlane, walls: &[WallInput], slabs: &[SlabInput], + roofs: &[RoofLayerInput], ) -> Vec { - let polys = cut_cap_polys(plane, walls, slabs); + let polys = cut_cap_polys(plane, walls, slabs, roofs); let point = plane.point; let u_axis = plane.u_axis(); // (u, v) -> Welt: horizontale Lage aus point + u*u_axis, Hoehe = v. @@ -155,8 +161,8 @@ pub fn build_cut_caps( verts } -/// Erzeugt die Schnitt-UMRISSLINIEN (P2): fuer JEDES ueberlebende Cut-Cap-Rechteck -/// seine vier Kanten als flache Ribbon-Dreiecke auf der Schnittebene, in Welt- +/// Erzeugt die Schnitt-UMRISSLINIEN (P2): fuer JEDES ueberlebende Cut-Cap-Polygon +/// seine Kanten als flache Ribbon-Dreiecke auf der Schnittebene, in Welt- /// Koordinaten (dieselbe (u,v)->Welt-Ruecktransformation wie `build_cut_caps`). /// Rueckgabe = interleaved `[px,py,pz, r,g,b]` (`CUT_LINE_FLOATS_PER_VERTEX`, /// TriangleList), leer wenn die Ebene das Modell nicht schneidet. @@ -169,12 +175,21 @@ pub fn build_cut_caps( /// (2 Dreiecke) um ihre Mittellinie gelegt, mit der Ribbon-Breite senkrecht zur /// Kante IN der Ebene; alle Ribbons um `CUT_LINE_LIFT` zur Kamera versetzt, damit /// sie nicht an der Ebene weggeclippt werden und vor den Caps liegen. +/// +/// Laeuft ueber `poly.pts` DIREKT (nicht mehr ueber dessen achsparallele +/// Bounding-Box, `rect_of_poly`) — fuer Wand-/Decken-Baender identisch (deren +/// `pts` SIND bereits genau die vier Bbox-Ecken in derselben Reihenfolge, siehe +/// `section.rs`/`poly_from_rect`), aber notwendig fuer NICHT achsparallele +/// Polygone (Dach-Schichten, `roof_cut::cut_roof_layer` — ein Dach wird von einer +/// vertikalen Schnittebene i. A. als schiefes Parallelogramm/Trapez getroffen, +/// dessen Bbox-Rechteck die Kanten falsch wiedergeben wuerde). pub fn build_cut_cap_lines( plane: &SectionPlane, walls: &[WallInput], slabs: &[SlabInput], + roofs: &[RoofLayerInput], ) -> Vec { - let polys = cut_cap_polys(plane, walls, slabs); + let polys = cut_cap_polys(plane, walls, slabs, roofs); let point = plane.point; let u_axis = plane.u_axis(); let normal = plane.normal; @@ -194,9 +209,10 @@ pub fn build_cut_cap_lines( let mut verts: Vec = Vec::new(); for poly in &polys { - let Some(r) = rect_of_poly(poly) else { + let n = poly.pts.len(); + if n < 2 { continue; - }; + } // Stil aus den Band-Metadaten (oder Default). let (color, weight_mm) = match &poly.cut { Some(meta) => ( @@ -207,16 +223,10 @@ pub fn build_cut_cap_lines( }; let half_w = (weight_mm.max(0.0) * CUT_LINE_MM_TO_WORLD * 0.5).max(1e-4); - // Die vier Rechteck-Ecken (u,v) im Umlauf; je Kante ein Ribbon. - let corners = [ - [r.u_min, r.v_min], - [r.u_max, r.v_min], - [r.u_max, r.v_max], - [r.u_min, r.v_max], - ]; - for k in 0..4 { - let a = to_world(corners[k]); - let b = to_world(corners[(k + 1) % 4]); + // Die tatsaechlichen Polygon-Ecken (u,v) im Umlauf; je Kante ein Ribbon. + for k in 0..n { + let a = to_world(poly.pts[k]); + let b = to_world(poly.pts[(k + 1) % n]); push_line_ribbon(&mut verts, a, b, normal, half_w, color); } } @@ -298,7 +308,7 @@ mod tests { cut: None, }; let plane = SectionPlane::looking_plus_x(1.5); - let verts = build_cut_caps(&plane, &[wall], &[]); + let verts = build_cut_caps(&plane, &[wall], &[], &[]); assert!(!verts.is_empty(), "Schnitt liefert Cap-Geometrie"); assert_eq!( @@ -338,7 +348,7 @@ mod tests { cut: None, }; let plane = SectionPlane::looking_plus_x(1.5); - let verts = build_cut_caps(&plane, &[wall], &[]); + let verts = build_cut_caps(&plane, &[wall], &[], &[]); assert!(!verts.is_empty()); assert_eq!(verts[5], FALLBACK_PATTERN, "Fallback = Diagonale (2)"); assert_eq!(verts[6], 0.0, "Fallback-Winkel 0"); @@ -391,7 +401,7 @@ mod tests { }), }; let plane = SectionPlane::looking_plus_x(1.5); - let verts = build_cut_caps(&plane, &[wall], &[slab]); + let verts = build_cut_caps(&plane, &[wall], &[slab], &[]); assert!(!verts.is_empty()); // Die Wand-Caps tragen pattern==2 (diagonal), die Beton-Caps pattern==1 @@ -478,7 +488,7 @@ mod tests { }), }; let plane = SectionPlane::looking_plus_x(1.5); - let verts = build_cut_caps(&plane, &[wall], &[screed, insulation]); + let verts = build_cut_caps(&plane, &[wall], &[screed, insulation], &[]); assert!(!verts.is_empty()); // Wand-u-Intervall (=y) ist [-0.2,0.2]. Fuer JEDES Estrich- (Muster 3) oder @@ -529,7 +539,7 @@ mod tests { }), }; let plane = SectionPlane::looking_plus_x(1.5); - let verts = build_cut_cap_lines(&plane, &[wall.clone()], &[]); + let verts = build_cut_cap_lines(&plane, &[wall.clone()], &[], &[]); assert!(!verts.is_empty()); assert_eq!( verts.len() % CUT_LINE_FLOATS_PER_VERTEX, @@ -573,7 +583,7 @@ mod tests { line_color: Some(color), line_weight: Some(0.2), }); - let thin_verts = build_cut_cap_lines(&plane, &[thin], &[]); + let thin_verts = build_cut_cap_lines(&plane, &[thin], &[], &[]); assert!( bbox_y(&verts) > bbox_y(&thin_verts) + 1e-4, "dickere Strichstaerke -> groessere v-Ausdehnung der Ribbons" diff --git a/src-tauri/render3d/src/types.rs b/src-tauri/render3d/src/types.rs index 1af8f502..364b9d70 100644 --- a/src-tauri/render3d/src/types.rs +++ b/src-tauri/render3d/src/types.rs @@ -268,6 +268,50 @@ pub struct SlabInput { pub cut: Option, } +/// EINE Dachflächen-Schicht für den 3D-Live-Schnitt (`crate::roof_cut`). +/// +/// Anders als `WallInput`/`SlabInput` ist das KEIN vertikales Prisma (2D- +/// Grundriss extrudiert über `[z0,z1]`) — eine Dachfläche ist ein GENEIGTES +/// Polygon, extrudiert entlang ihrer EIGENEN Flächennormalen (nicht vertikal). +/// `section.rs`s gesamter Ansatz ("jedes Bauteil ist ein vertikales Prisma, +/// daher ist der Schnitt mit einer vertikalen Ebene immer ein Rechteck") +/// funktioniert für ein geneigtes Bauteil nicht — daher ein eigener, +/// paralleler Pfad (`roof_cut::cut_roof_layer`) statt Wiederverwendung von +/// `Prism`. Das Ergebnis landet trotzdem im selben `CutPolygon`-Format +/// (`section::CutPolygon`, `component.kind = ComponentKind::Roof`) und läuft +/// durch dieselbe Cap-/Linien-Pipeline (`section_fill.rs`) wie Wand/Decke. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RoofLayerInput { + /// Eckpunkte der OBERSEITE dieser Schicht (näher am First/aussen), planar, + /// in MODELL-Metern `(x, y, z=Höhe)` — dieselbe Konvention wie + /// `MeshInput::positions` (NICHT vorab nach Welt umgerechnet; `roof_cut:: + /// cut_roof_layer` macht den Modell->Welt-Wechsel `(x,y,z)->(x,z,y)` + /// selbst, wie `mesh.rs` es für Meshes tut). Schlusspunkt NICHT dupliziert. + pub polygon: Vec<[f32; 3]>, + /// Nach AUSSEN/OBEN zeigende Flächennormale (normalisiert, MODELL-Meter, + /// dieselbe `(x,y,z)`-Konvention wie `polygon`) — exakt dieselbe wie + /// `toWalls3d/roofs.ts::planeNormalUp` (dort TS-seitig berechnet und 1:1 + /// mitgegeben, statt hier erneut hergeleitet — vermeidet ein Konventions-/ + /// Vorzeichen-Auseinanderlaufen zwischen Render-Mesh und Schnitt-Geometrie). + pub normal: [f32; 3], + /// Schichtdicke (Meter), Extrusion entlang `-normal` (nach INNEN, wie + /// `pushRoofSlab`: `bottom = top - normal*thickness`). + pub thickness: f32, + /// Albedo-Farbe dieser Schicht. + pub color: Rgb, + /// Optionale Schnitt-Schraffur (siehe `WallInput::hatch`). + #[serde(default)] + pub hatch: Option, + /// Schnitt-Verschneidungs-/Linienstil-Metadaten (siehe `WallInput::cut`). + /// `join_priority`/`component_id` bleiben für Dach-Schichten bewusst + /// `None` (keine Teilnahme an `section_boolean::subtract_dominant_bands` + /// — ein nicht-achsparalleles Cut-Polygon als Bounding-Box zu behandeln + /// wäre falsch; die Dominanz-Subtraktion bleibt Wand/Decke vorbehalten). + /// `line_color`/`line_weight` (aus `jointLineStyleId`) wirken trotzdem. + #[serde(default)] + pub cut: Option, +} + fn default_slab_color() -> Rgb { [0.86, 0.86, 0.88] } diff --git a/src-tauri/render3d/src/web.rs b/src-tauri/render3d/src/web.rs index 76c8c324..47330ed8 100644 --- a/src-tauri/render3d/src/web.rs +++ b/src-tauri/render3d/src/web.rs @@ -33,7 +33,7 @@ use web_sys::HtmlCanvasElement; use crate::gpu::Renderer; use crate::math::preset_camera; use crate::section::{cut_section, SectionPlane}; -use crate::types::{Camera, CameraPreset, MeshInput, Projection, SlabInput, WallInput}; +use crate::types::{Camera, CameraPreset, MeshInput, Projection, RoofLayerInput, SlabInput, WallInput}; /// JSON-Eingabe des Modells: Waende (bereits in Teilquader zerlegt, siehe /// `projectToWalls3d`) + Deckenplatten. `slabs` optional (leeres Modell ohne @@ -47,6 +47,13 @@ struct ModelInput { /// haelt aeltere Payloads ohne `meshes` gueltig. #[serde(default)] meshes: Vec, + /// Dach-Schichten fuer den Live-Schnitt (`section::cut_section`/ + /// `roof_cut::cut_roof_layer`) — separat von `meshes` (die reine + /// Render-Geometrie, kein Prisma-kompatibles Format). `#[serde(default)]` + /// haelt aeltere Payloads ohne `roofLayers` gueltig (Daecher zeigen dann + /// im Live-Schnitt weiterhin keine Cut-Flaeche/-Fugenlinien, wie bisher). + #[serde(default, rename = "roofLayers")] + roof_layers: Vec, } /// Berechnet einen Schnitt/eine Ansicht (`section::cut_section`) gegen das Modell @@ -79,7 +86,7 @@ pub fn cut_section_json( let model: ModelInput = serde_json::from_str(model_json) .map_err(|e| JsValue::from_str(&format!("Modell parsen: {e}")))?; let plane = SectionPlane::new([px, py, pz], [nx, ny, nz]); - let out = cut_section(&plane, &model.walls, &model.slabs); + let out = cut_section(&plane, &model.walls, &model.slabs, &model.roof_layers); serde_json::to_string(&out) .map_err(|e| JsValue::from_str(&format!("SectionOutput serialisieren: {e}"))) } @@ -105,6 +112,9 @@ pub struct WebModelRenderer { /// Cut-Cap-Geometrie neu berechnen koennen muss (GPU-frei, `cut_section`). walls: Vec, slabs: Vec, + /// Gecachte Dach-Schichten (analog `walls`/`slabs`) fuer denselben Zweck — + /// der Live-Schnitt braucht sie bei jedem `set_section_plane`/`set_model`. + roof_layers: Vec, /// Aktueller Live-Schnitt-Zustand: aktiv? + Ebene (point/normal). Gemerkt, /// damit ein `set_model` bei aktivem Schnitt die Caps automatisch neu baut. section: Option<([f32; 3], [f32; 3])>, @@ -251,6 +261,7 @@ impl WebModelRenderer { bounds: None, walls: Vec::new(), slabs: Vec::new(), + roof_layers: Vec::new(), section: None, }) } @@ -265,10 +276,11 @@ impl WebModelRenderer { self.bounds = model_bounds(&model.walls, &model.slabs, &model.meshes); self.renderer .upload_model(&self.device, &model.walls, &model.slabs, &model.meshes); - // Wand-/Decken-Eingabe fuer den Live-Schnitt cachen (Klon, da der Renderer - // sie nur zu GPU-Puffern verarbeitet und verwirft). + // Wand-/Decken-/Dach-Eingabe fuer den Live-Schnitt cachen (Klon, da der + // Renderer sie nur zu GPU-Puffern verarbeitet und verwirft). self.walls = model.walls; self.slabs = model.slabs; + self.roof_layers = model.roof_layers; // Ist der Schnitt aktiv, die Caps am neuen Modell neu aufbauen. if let Some((point, normal)) = self.section { self.renderer.update_section( @@ -278,6 +290,7 @@ impl WebModelRenderer { normal, &self.walls, &self.slabs, + &self.roof_layers, ); } Ok(()) @@ -304,8 +317,15 @@ impl WebModelRenderer { let point = [px, py, pz]; let normal = [nx, ny, nz]; self.section = if active { Some((point, normal)) } else { None }; - self.renderer - .update_section(&self.device, active, point, normal, &self.walls, &self.slabs); + self.renderer.update_section( + &self.device, + active, + point, + normal, + &self.walls, + &self.slabs, + &self.roof_layers, + ); Ok(()) } diff --git a/src/App.tsx b/src/App.tsx index 5a78c38d..23147380 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -31,6 +31,8 @@ import type { Vec2, Wall, } from "./model/types"; +import { activePenSet, resolvePenColor, resolvePenWeight } from "./model/penSets"; +import { PenColorField } from "./ui/PenColorField"; import { generatePlan } from "./plan/generatePlan"; import type { CategoryDisplayResolver } from "./plan/generatePlan"; import { sectionPlaneFromLevel } from "./plan/toSection"; @@ -45,7 +47,7 @@ import { ExportSaveDialog } from "./ui/ExportSaveDialog"; import { PromptDialog } from "./ui/PromptDialog"; import { LockConflictDialog } from "./ui/LockConflictDialog"; import { Toast } from "./ui/Toast"; -import { isTauriRuntime } from "./io/projectFile"; +import { isTauriRuntime, PROJECT_TEMPLATE_EXT } from "./io/projectFile"; import { checkForUpdate } from "./update/checkForUpdate"; import type { PlanViewHandle } from "./plan/PlanView"; import type { DisplayResolver } from "./viewport/Viewport3D"; @@ -122,7 +124,7 @@ import { useProjectActions } from "./state/useProjectActions"; import { useActiveToolKeys, useBooleanOpsShortcut, - useDrawingClipboardShortcut, + useElementClipboardShortcut, useGroupShortcut, useSelectAllAndDeleteShortcut, useSplitJoinShortcut, @@ -190,10 +192,8 @@ import { } from "./state/viewSnapshots"; // Seiteneffekt: registriert die zwei dockbaren Kern-Panels in der Registry. import { BUILTIN_PANEL_IDS } from "./panels/builtinPanels"; -import { deriveDrawings } from "./DrawingTabs"; import { SplashScreen } from "./ui/SplashScreen"; import { StartScreen } from "./ui/StartScreen"; -import { emptyProject } from "./model/sampleProject"; /** * Offenes Kontextmenü — genau eine Quelle. `x/y` sind Viewport-Pixel (clientX/Y). @@ -218,16 +218,21 @@ const TOOL_COMMAND: Partial> = { stair: "stair", room: "room", line: "line", + xline: "xline", polyline: "polyline", rect: "rect", circle: "circle", arc: "arc", ellipse: "ellipse", + polygon: "polygon", + block: "block", spline: "spline", bezier: "bezier", dimension: "dimension", kote: "kote", text: "text", + leader: "leader", + textpath: "textpath", textbox: "textbox", }; /** Befehlsname für ein gekoppeltes Werkzeug (oder null, wenn keiner). */ @@ -378,8 +383,8 @@ export default function App() { setSelectedDrawingIds, selectedDrawingId, setSelectedDrawingId, - drawingClipboard, - setDrawingClipboard, + elementClipboard, + setElementClipboard, selectedWallId, selectedCeilingIds, setSelectedCeilingIds, @@ -387,8 +392,9 @@ export default function App() { selectedRoofIds, setSelectedRoofIds, selectedRoofId, + selectedSectionLineIds, + setSelectedSectionLineIds, selectedSectionLineId, - setSelectedSectionLineId, section3dCutId, setSection3dCutId, updateRoof, @@ -456,7 +462,7 @@ export default function App() { setSelectedExtrudedSolidIds([]); setSelectedColumnIds([]); setSelectedRoofIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); setMenu(null); setEditor(null); }, [activeLevelId]); @@ -836,7 +842,7 @@ export default function App() { setSelectedColumnIds([]); setSelectedRoofIds([]); setSelectedContextObjectIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); setSelectedDrawingId(id); setEditTextMinHeightM(minHeightM ?? null); setEditTextId(id); @@ -1014,7 +1020,7 @@ export default function App() { // Tastatur-Handler unten und dem Menüpunkt „Bearbeiten > Löschen" (AppMenuBar). const hasSelectionToDelete = () => !!( - selectedSectionLineId || + selectedSectionLineIds.length || selectedDrawingIds.length || selectedWallIds.length || selectedCeilingIds.length || @@ -1030,11 +1036,12 @@ export default function App() { // Löscht die AKTUELLE Auswahl (alle Kanäle) — geteilte Logik zwischen dem // Entf-Tastatur-Handler und dem Menüpunkt „Bearbeiten > Löschen". const deleteSelection = () => { - // Schnittlinie: Entf löscht NUR ihre Linie (linePoints), die Ebene bleibt. - if (selectedSectionLineId) { - patchLevel(selectedSectionLineId, { linePoints: undefined }); - setSelectedSectionLineId(null); - return; + // Schnittlinie(n): Entf löscht NUR ihre Linie (linePoints), die Ebene + // bleibt — ADDITIV zu den übrigen Kanälen unten (nicht mehr exklusiv: + // seit Cmd/Ctrl+A Schnittlinien zusammen mit Wänden/etc. mitselektiert, + // würde ein frühes `return` hier die übrigen Kanäle stumm überspringen). + if (selectedSectionLineIds.length) { + for (const id of selectedSectionLineIds) patchLevel(id, { linePoints: undefined }); } const dids = new Set(selectedDrawingIds); const wids = new Set(selectedWallIds); @@ -1073,7 +1080,7 @@ export default function App() { setSelectedColumnIds([]); setSelectedRoofIds([]); setSelectedContextObjectIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); }; // Tastatur im Auswahl-Werkzeug: Ctrl/Cmd+A = alles wählen, Entf/Backspace = @@ -1093,14 +1100,18 @@ export default function App() { selectedColumnIds, selectedRoofIds, selectedContextObjectIds, - selectedSectionLineId, + selectedSectionLineIds, setSelectedWallIds, setSelectedDrawingIds, setSelectedCeilingIds, + setSelectedOpeningIds, setSelectedStairIds, setSelectedRoomIds, setSelectedExtrudedSolidIds, setSelectedColumnIds, + setSelectedRoofIds, + setSelectedContextObjectIds, + setSelectedSectionLineIds, hasSelectionToDelete, deleteSelection, }); @@ -1326,6 +1337,16 @@ export default function App() { patchLineStyle, addLineStyle, deleteLineStyle, + addPen, + renamePen, + deletePen, + addPenSet, + renamePenSet, + deletePenSet, + setActivePenSet, + patchPenSetColor, + patchPenSetWeight, + seedStandardPenSet, patchWallType, setOverrideRules, patchCeilingType, @@ -1365,6 +1386,7 @@ export default function App() { setElementBackground, updateDrawing2D, reorderDrawings, + reorderDrawingLevels, resizeElement, updateWall, setWallThickness, @@ -1473,16 +1495,36 @@ export default function App() { } : null; - // Ctrl/Cmd+C / Ctrl/Cmd+V = 2D-Zeichenelemente kopieren/einfügen — siehe - // state/useKeyboardShortcuts.ts. - useDrawingClipboardShortcut( - selectedDrawingIds, - drawingClipboard, - setDrawingClipboard, + // Ctrl/Cmd+C / Ctrl/Cmd+V = Bauteile kopieren/einfügen (alle 9 Auswahl-Kanäle, + // nicht nur 2D-Zeichenelemente) — siehe state/useKeyboardShortcuts.ts. + useElementClipboardShortcut( + { + wallIds: selectedWallIds, + drawingIds: selectedDrawingIds, + ceilingIds: selectedCeilingIds, + roofIds: selectedRoofIds, + openingIds: selectedOpeningIds, + stairIds: selectedStairIds, + roomIds: selectedRoomIds, + extrudedSolidIds: selectedExtrudedSolidIds, + columnIds: selectedColumnIds, + }, + elementClipboard, + setElementClipboard, activeLevelId, - project.drawings2d, - importDrawings, - setSelectedDrawingIds, + project, + setProject, + { + wallIds: setSelectedWallIds, + drawingIds: setSelectedDrawingIds, + ceilingIds: setSelectedCeilingIds, + roofIds: setSelectedRoofIds, + openingIds: setSelectedOpeningIds, + stairIds: setSelectedStairIds, + roomIds: setSelectedRoomIds, + extrudedSolidIds: setSelectedExtrudedSolidIds, + columnIds: setSelectedColumnIds, + }, ); // Projektdatei-I/O (Speichern/Öffnen/Lock), Schnellexport (CSV/IFC/OBJ/STL) @@ -1490,10 +1532,15 @@ export default function App() { // useProjectFileActions(), siehe dort. const { projectFileInputRef, + projectTemplateFileInputRef, lockConflict, setLockConflict, openImportForFile, onSaveProject, + onNewProject, + onNewProjectFromSample, + onNewProjectFromTemplate, + onProjectTemplateFileChosen, applyOpenedProjectFile, projectFileName, runExport, @@ -1833,6 +1880,9 @@ export default function App() { // von Tauri (isTauriRuntime-Guard steckt im Hook selbst). useNativeAppMenu( { + onNewProject, + onNewProjectFromSample, + onNewProjectFromTemplate, onOpenProject, onSaveProject, onImport: () => dxfInputRef.current?.click(), @@ -1988,6 +2038,16 @@ export default function App() { onImportLineStyles: importLineStyles, onImportHatches: importHatches, onSetOverrideRules: setOverrideRules, + onAddPen: addPen, + onRenamePen: renamePen, + onDeletePen: deletePen, + onAddPenSet: addPenSet, + onRenamePenSet: renamePenSet, + onDeletePenSet: deletePenSet, + onSetActivePenSet: setActivePenSet, + onPatchPenSetColor: patchPenSetColor, + onPatchPenSetWeight: patchPenSetWeight, + onSeedStandardPenSet: seedStandardPenSet, }; // Ressourcen-Manager als eigenes natives Fenster (Tauri) statt Overlay im @@ -2046,7 +2106,7 @@ export default function App() { // Resolver: je Geschoss-ID die Render-Entscheidung (aktiv = Arbeitsfokus). // Memoisiert, damit Plan/3D nicht bei jedem Render neu rechnen. - const floorDisplay: DisplayResolver = useMemo(() => { + const floorDisplay: CategoryDisplayResolver & DisplayResolver = useMemo(() => { const visible = new Map( project.drawingLevels.map((z) => [z.id, z.visible]), ); @@ -2068,14 +2128,6 @@ export default function App() { // referenzstabil → triggert sonst keinen Neuaufbau). const displayKey = `${drawingLevelsMode}|${layersMode}|${activeLevelId}|${activeCategoryCode}`; - // Dokument-Tabs der Zeichenflächen-Kopfzeile — ein Tab je Geschoss- - // Grundriss (siehe DrawingTabs.tsx). Teilt sich `activeLevelId`/ - // `setActiveLevelId` mit dem Panel „Zeichnungsebenen". - const drawings = useMemo( - () => deriveDrawings(project.drawingLevels), - [project.drawingLevels], - ); - // ── Ableitungen für Oberleiste + Status-Leiste ──────────────────────────── // Eine zoom-/cursor-fähige Plan-Ansicht ist nur im Grundriss eines Geschosses // aktiv. Sonst sind Cursor/Zoom bedeutungslos (PlanView ist nicht montiert → @@ -2398,6 +2450,7 @@ export default function App() { activeLevelId: activeLevel.id, visibleCodes, categoryDisplay, + floorDisplay, selectionState: { selectedWallIds, setSelectedWallIds, @@ -2420,8 +2473,8 @@ export default function App() { setSelectedRoofIds, selectedContextObjectIds, setSelectedContextObjectIds, - selectedSectionLineId, - setSelectedSectionLineId, + selectedSectionLineIds, + setSelectedSectionLineIds, selectedGroupIds, setSelectedGroupIds, groupPath, @@ -2446,7 +2499,7 @@ export default function App() { setSelectedColumnIds, setSelectedRoofIds, setSelectedContextObjectIds, - setSelectedSectionLineId, + setSelectedSectionLineIds, }); // App-weites Drag & Drop einer DXF/DWG-Datei — siehe state/useImportHandling.ts. @@ -2546,7 +2599,7 @@ export default function App() { setSelectedRoofIds, setSelectedContextObjectIds, selectedSectionLineId, - setSelectedSectionLineId, + setSelectedSectionLineIds, section3dCutId, }, toolState: { @@ -2581,7 +2634,7 @@ export default function App() { return ( { - setProject(emptyProject); + onNewProject(); setBootPhase("editor"); }} onOpenProject={() => { @@ -2642,6 +2695,18 @@ export default function App() { e.target.value = ""; }} /> + {/* Verstecktes Vorlagen-Datei-Input („Neu aus Vorlage" → Datei wählen). */} + { + const f = e.target.files?.[0]; + if (f) onProjectTemplateFileChosen(f); + e.target.value = ""; + }} + /> {/* Schmale globale Leiste: Marke/Menü · Datei/Export/Einstellungen. Ansichts-/Zoom-/Darstellungs-Steuerung folgt direkt darunter (ViewRibbonTab, permanent — kein Tab-Umschalter mehr). */} @@ -2672,6 +2737,12 @@ export default function App() { menuBar={ isTauriRuntime() ? undefined : ( dxfInputRef.current?.click()} onUndo={undo} onRedo={redo} canUndo={canUndo} @@ -2855,7 +2926,12 @@ export default function App() { section3d={section3dPlane} onClearSection3d={() => setSection3dCutId(null)} mono={planColorMode === "mono"} - drawings={drawings} + viewSnapshotTabs={{ + selectedId: baseHost.selectedViewSnapshotId, + onApply: baseHost.onApplyViewSnapshot, + onCaptureAuto: baseHost.onCaptureViewSnapshotAuto, + onDelete: baseHost.onDeleteViewSnapshot, + }} onSelectLevel={setActiveLevelId} floorDisplay={floorDisplay} categoryDisplay={categoryDisplay} @@ -2873,7 +2949,7 @@ export default function App() { selectedRoomIds={selectedRoomIds} selectedRoofIds={selectedRoofIds} selectedContextObjectIds={selectedContextObjectIds} - selectedSectionLineId={selectedSectionLineId} + selectedSectionLineIds={selectedSectionLineIds} roomStamp={roomStamp} onStampMove={moveRoomStamp} onStampEdit={onOpenStampEditor} @@ -3316,6 +3392,7 @@ export default function App() { bringForward: () => reorderDrawings(selectedDrawingIds, "forward"), sendBackward: () => reorderDrawings(selectedDrawingIds, "backward"), sendToBack: () => reorderDrawings(selectedDrawingIds, "back"), + reorderLevel: (id, op) => reorderDrawingLevels([id], op), })} onClose={() => setMenu(null)} /> @@ -3345,11 +3422,20 @@ export default function App() { /> - - patchCategory(cat.code, { color: e.target.value }) + patchCategory(cat.code, { color, colorPenId: undefined })} + onPenChange={(colorPenId) => + patchCategory(cat.code, { + colorPenId, + ...(colorPenId + ? { color: resolvePenColor(project, colorPenId), lw: resolvePenWeight(project, colorPenId) } + : {}), + }) } /> @@ -3360,6 +3446,7 @@ export default function App() { step={0.01} min={0.01} value={cat.lw} + disabled={!!cat.colorPenId} onChange={(e) => patchCategory(cat.code, { lw: Number(e.target.value) }) } diff --git a/src/DrawingTabs.tsx b/src/DrawingTabs.tsx index c9208dd1..8f768c9f 100644 --- a/src/DrawingTabs.tsx +++ b/src/DrawingTabs.tsx @@ -1,90 +1,100 @@ -// Dokument-Tabs „Zeichnungen/Blätter" — Kopfzeile über der Zeichenfläche. +// Ausschnitt-Tab-Leiste — Kopfzeile über der Zeichenfläche. // -// Ersetzt die frühere Kopfzeile mit Geschosshöhe/Schnitthöhe (diese Werte -// werden jetzt ausschliesslich in den Geschoss-Einstellungen gepflegt, siehe -// den Editor `editor.floorHeight`/`editor.cutHeight` in App.tsx). Ein Tab -// entspricht heute immer dem Grundriss eines Geschosses; ein Klick aktiviert -// dessen Zeichnungsebene über denselben State, den auch das Panel -// „Zeichnungsebenen" (DrawingLevelsPanel) verwendet — beide bleiben so -// zwangsläufig synchron. +// Jeder Tab ist ein gespeicherter Ausschnitt (ViewSnapshot, DOSSIER A2, +// s. state/viewSnapshots.ts + panels/ViewSnapshotsPanel.tsx): aktive +// Zeichnungsebene + Ebenen-/Zeichnungsebenen-Sichtbarkeit + Overrides + Ansicht. +// Ein Klick lädt ihn — identisch zum Panel „Ausschnitte" (dieselben Handler). +// „+" sichert den aktuellen Stand als neuen Tab; der Name wird automatisch +// bestimmt (aktive Zeichnungskombination, falls ihre Sichtbarkeits-Map exakt +// passt, sonst das aktive Blatt) — kein Tipp-Dialog, wie ein Browser-Tab. +// „×" löscht einen Tab; mindestens einer bleibt immer erhalten (fehlt der +// letzte, wird beim nächsten Mount automatisch einer aus dem aktuellen Stand +// nachgezogen). // -// Der Typ `Drawing` ist bewusst schlank gehalten, damit künftige Arten -// (Schnitt-Blatt, Layout) sich später einhängen können, ohne dass die -// Tab-Leiste selbst umgebaut werden muss — siehe `activate()` unten. +// Ersetzt die frühere Ein-Tab-je-Geschoss-Leiste: ein Ausschnitt kann JEDE +// Zeichnungsebenen-Art referenzieren (Geschoss, Schnitt, Ansicht, Zeichnung), +// nicht nur Geschosse — man kann also in einem Tab im Schnitt arbeiten und im +// nächsten im Grundriss, jeweils mit eigener Ebenen-/Zeichnungssichtbarkeit. // // Bezeichner englisch, UI-Text/Kommentare deutsch (CONVENTIONS.md). -import type { DrawingLevel } from "./model/types"; +import { useEffect } from "react"; +import type { Project } from "./model/types"; import { t } from "./i18n"; -/** Art einer Dokument-Zeichnung. Heute nur der Grundriss eines Geschosses; - * Platz für künftige Arten (z. B. "section", "layout") bleibt offen. */ -export type DrawingKind = "plan"; - -/** Ein Tab der Dokument-Leiste — leichtgewichtiger Verweis auf die Quelle - * (aktuell immer eine Zeichnungsebene vom Typ "floor"). */ -export interface Drawing { - id: string; - title: string; - kind: DrawingKind; - /** Geschoss/Zeichnungsebene, deren Grundriss dieser Tab zeigt. */ - levelId: string; -} - -/** Leitet die Dokument-Tabs aus den Geschossen des Projekts ab — ein Tab je - * Geschoss. Schnitte/Ansichten und freie Zeichnungen bleiben vorerst aussen - * vor (weiterhin nur über das Panel „Zeichnungsebenen" erreichbar). */ -export function deriveDrawings(levels: DrawingLevel[]): Drawing[] { - return levels - .filter((level): level is DrawingLevel & { kind: "floor" } => level.kind === "floor") - .map((level) => ({ - id: level.id, - title: level.name, - kind: "plan", - levelId: level.id, - })); +/** Handler-Bündel der Ausschnitt-Tab-Leiste — identische Semantik wie die + * gleichnamigen Host-Handler in panels/host.ts (dieselbe Quelle der Wahrheit). */ +export interface ViewSnapshotTabsHandlers { + /** Id des aktuell angewählten Ausschnitts (aktiver Tab) oder `null`, wenn + * der Live-Zustand von jedem gespeicherten Ausschnitt abweicht. */ + selectedId: string | null; + /** Lädt einen Ausschnitt (Klick auf einen Tab). */ + onApply: (id: string) => void; + /** Sichert den aktuellen Stand als neuen Ausschnitt (automatischer Name); + * liefert dessen Id. */ + onCaptureAuto: () => string; + /** Löscht einen Ausschnitt. */ + onDelete: (id: string) => void; } export function DrawingTabs({ - drawings, - activeLevelId, - onSelectLevel, + project, + handlers, }: { - drawings: Drawing[]; - /** Aktuell aktive Zeichnungsebene (globaler App-State, siehe App.tsx). */ - activeLevelId: string; - /** Setter derselben Zeichnungsebene — identisch mit dem, den das Panel - * „Zeichnungsebenen" verwendet (kein paralleler State). */ - onSelectLevel: (id: string) => void; + project: Project; + handlers: ViewSnapshotTabsHandlers; }) { - if (drawings.length === 0) return null; + const snapshots = project.viewSnapshots ?? []; + const { selectedId, onApply, onCaptureAuto, onDelete } = handlers; - // Aktivierung nach Art dispatchen. Heute gibt es nur "plan" (→ Geschoss - // aktivieren); künftige Arten hängen hier ihr eigenes Ziel ein, ohne dass - // sich an der Tab-Leiste selbst etwas ändert. - const activate = (drawing: Drawing) => { - switch (drawing.kind) { - case "plan": - onSelectLevel(drawing.levelId); - break; - } - }; + // Es muss immer mindestens ein Tab existieren (Nutzer-Vorgabe): ein frisches + // oder altes Projekt ohne einen einzigen Ausschnitt bekommt beim ersten + // Mount automatisch einen aus dem aktuellen Stand. + useEffect(() => { + if (snapshots.length === 0) onCaptureAuto(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [snapshots.length]); + + if (snapshots.length === 0) return null; return (
- {drawings.map((d) => ( + {snapshots.map((s) => ( ))} +
); } diff --git a/src/commands/cmds/block.test.ts b/src/commands/cmds/block.test.ts new file mode 100644 index 00000000..0dc81177 --- /dev/null +++ b/src/commands/cmds/block.test.ts @@ -0,0 +1,80 @@ +/** + * `blockCommand` — Einfügepunkt → neue `{shape:"block"}`-Instanz, die auf + * die aktuell per Option gewählte `BlockDef` zeigt. Ohne Definitionen: No-Op. + */ + +import { describe, it, expect } from "vitest"; +import { blockCommand } from "./block"; +import type { CommandContext, Project } from "../types"; +import type { BlockDef } from "../../model/types"; + +function project(blockDefs: BlockDef[] = []): 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: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + blockDefs, + }; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +describe("blockCommand", () => { + it("ohne definierte Blöcke: Klick committet nichts", () => { + const p = project([]); + const ctx = makeCtx(p); + const [, result] = blockCommand.onInput( + blockCommand.init(), + { kind: "point", point: { x: 1, y: 1 } }, + ctx, + ); + expect(result.commit).toBeUndefined(); + expect(result.done).toBe(true); + }); + + it("mit einer Definition: Klick platziert eine Instanz an der Klickposition, rotation 0", () => { + const def: BlockDef = { id: "blk1", name: "Stuhl", geom2d: [{ shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } }] }; + const p = project([def]); + const ctx = makeCtx(p); + const [, result] = blockCommand.onInput( + blockCommand.init(), + { kind: "point", point: { x: 3, y: 4 } }, + ctx, + ); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + expect(next.drawings2d.length).toBe(1); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("block"); + if (g.shape === "block") { + expect(g.blockDefId).toBe("blk1"); + expect(g.at).toEqual({ x: 3, y: 4 }); + expect(g.rotation).toBe(0); + } + }); +}); diff --git a/src/commands/cmds/block.ts b/src/commands/cmds/block.ts new file mode 100644 index 00000000..22bd9979 --- /dev/null +++ b/src/commands/cmds/block.ts @@ -0,0 +1,87 @@ +// Block einfügen — platziert eine Instanz einer vorhandenen Block-Definition +// (`Project.blockDefs`, s. `defblock`). Welche Definition aktiv ist, zyklt +// über eine Inline-Option (persistent über Aufrufe, wie `count` bei +// Multiline); Rotation läuft NICHT über dieses Werkzeug, sondern über den +// bestehenden `rotate`-Transform (v1 bewusst nur Position). Schritte: +// 1) „Einfügepunkt:" → Punkt → commit. Ohne definierte Blöcke: No-Op. + +import type { Drawing2D } from "../../model/types"; +import { uniqueId } from "../../tools/types"; +import type { + CmdOption, + Command, + CommandContext, + CommandResult, + CommandState, + Project, + Vec2, +} from "../types"; + +let lastDefIndex = 0; + +interface BlockState extends CommandState { + phase: "point"; + defIds: string[]; + defNames: string[]; +} + +const DEF_OPTION: CmdOption = { id: "def", labelKey: "cmd.block.def" }; + +function readDefs(ctx: CommandContext): { ids: string[]; names: string[] } { + const defs = ctx.project.blockDefs ?? []; + return { ids: defs.map((d) => d.id), names: defs.map((d) => d.name) }; +} + +function appendInstance(p: Project, blockDefId: string, at: Vec2, ctx: CommandContext): Project { + const d: Drawing2D = { + id: uniqueId("dr2d"), + type: "drawing2d", + levelId: ctx.level.id, + categoryCode: ctx.defaultCategoryCode, + geom: { shape: "block", blockDefId, at, rotation: 0 }, + }; + return { ...p, drawings2d: [...p.drawings2d, d] }; +} + +const idle = (): [CommandState, CommandResult] => [ + { phase: "point", lastPoint: null, defIds: [], defNames: [] } as BlockState, + { draft: null, done: true }, +]; + +export const blockCommand: Command = { + name: "block", + labelKey: "cmd.block.label", + prompt: () => "cmd.block.point", + accepts: () => ["point", "option"], + options: (state) => { + const s = state as BlockState; + const i = s.defIds.length ? lastDefIndex % s.defIds.length : 0; + return s.defIds.length ? [{ ...DEF_OPTION, value: s.defNames[i] }] : []; + }, + init: (): BlockState => ({ phase: "point", lastPoint: null, defIds: [], defNames: [] }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as BlockState; + const { ids, names } = readDefs(ctx); + const ns: BlockState = { ...s, defIds: ids, defNames: names }; + if (input.kind === "option") { + if (input.id === "def" && ids.length) lastDefIndex = (lastDefIndex + 1) % ids.length; + return [ns, { draft: null }]; + } + if (input.kind !== "point") return [ns, { draft: null }]; + if (ids.length === 0) return idle(); + const blockDefId = ids[lastDefIndex % ids.length]; + const at = input.point; + return [idle()[0], { draft: null, done: true, commit: (p) => appendInstance(p, blockDefId, at, ctx) }]; + }, + + onMove: (state, _point, _snap, ctx): [CommandState, CommandResult] => { + const s = state as BlockState; + const { ids, names } = readDefs(ctx); + const ns: BlockState = { ...s, defIds: ids, defNames: names }; + return [ns, { draft: null }]; + }, + + onConfirm: (): [CommandState, CommandResult] => idle(), + onCancel: (): [CommandState, CommandResult] => idle(), +}; diff --git a/src/commands/cmds/chamfer.ts b/src/commands/cmds/chamfer.ts index 9cb3f83b..3bc8544e 100644 --- a/src/commands/cmds/chamfer.ts +++ b/src/commands/cmds/chamfer.ts @@ -9,6 +9,7 @@ // ist von Natur aus gerade, also ein exaktes (nicht approximiertes) Ergebnis. import type { Drawing2D, Drawing2DGeom } from "../../model/types"; +import { hasRealBulge } from "../../geometry/bulge"; import { chamferCorner, type Chamfer } from "../../geometry/kernel2d"; import type { Command, @@ -34,7 +35,8 @@ interface Curve { /** Wandelt eine chamfer-fähige 2D-Form (polyline/rect) in eine Punktliste oder null. */ function geomToCurve(g: Drawing2DGeom): Curve | null { - if (g.shape === "polyline") return { pts: g.pts, closed: g.closed }; + // Bogen-Segmente (bulge) hier noch nicht unterstützt, s. fillet.ts/offset.ts. + if (g.shape === "polyline" && !hasRealBulge(g.bulge)) return { pts: g.pts, closed: g.closed }; if (g.shape === "rect") { return { pts: [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }], diff --git a/src/commands/cmds/defblock.test.ts b/src/commands/cmds/defblock.test.ts new file mode 100644 index 00000000..bf6c672d --- /dev/null +++ b/src/commands/cmds/defblock.test.ts @@ -0,0 +1,111 @@ +/** + * `defblockCommand` — Mehrfachauswahl + Basispunkt → neue `BlockDef` (lokale + * Geometrie relativ zum Basispunkt) + eine ersetzende `{shape:"block"}`- + * Instanz; Quell-Elemente verschwinden aus `drawings2d`. + */ + +import { describe, it, expect } from "vitest"; +import { defblockCommand } from "./defblock"; +import type { CommandContext, Project } from "../types"; +import type { Drawing2D } from "../../model/types"; + +function project(drawings: 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: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: drawings, + context: [], + }; +} + +function makeCtx(p: Project, drawingIds: string[]): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: drawingIds[0] ?? null, drawingIds }, + }; +} + +describe("defblockCommand", () => { + it("erzeugt eine BlockDef aus der Auswahl (lokal relativ zum Basispunkt) + eine ersetzende Instanz", () => { + const line: Drawing2D = { id: "d1", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: 5, y: 5 }, b: { x: 8, y: 5 } } }; + const circle: Drawing2D = { id: "d2", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "circle", center: { x: 6, y: 6 }, r: 1 } }; + const p = project([line, circle]); + const ctx = makeCtx(p, ["d1", "d2"]); + const [, result] = defblockCommand.onInput( + defblockCommand.init(), + { kind: "point", point: { x: 5, y: 5 } }, + ctx, + ); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + + expect(next.drawings2d.find((d) => d.id === "d1")).toBeUndefined(); + expect(next.drawings2d.find((d) => d.id === "d2")).toBeUndefined(); + expect(next.drawings2d.length).toBe(1); + const inst = next.drawings2d[0]; + expect(inst.geom.shape).toBe("block"); + + expect(next.blockDefs?.length).toBe(1); + const def = next.blockDefs![0]; + expect(def.name).toBe("Block 1"); + expect(def.geom2d.length).toBe(2); + const localLine = def.geom2d.find((g) => g.shape === "line"); + if (localLine?.shape === "line") { + // Basispunkt (5,5) wird zum lokalen Ursprung → a rückt auf (0,0). + expect(localLine.a).toEqual({ x: 0, y: 0 }); + expect(localLine.b).toEqual({ x: 3, y: 0 }); + } + if (inst.geom.shape === "block") { + expect(inst.geom.blockDefId).toBe(def.id); + expect(inst.geom.at).toEqual({ x: 5, y: 5 }); + expect(inst.geom.rotation).toBe(0); + } + }); + + it("leere Auswahl committet nichts", () => { + const p = project([]); + const ctx = makeCtx(p, []); + const [, result] = defblockCommand.onInput( + defblockCommand.init(), + { kind: "point", point: { x: 0, y: 0 } }, + ctx, + ); + expect(result.commit).toBeUndefined(); + }); + + it("schliesst bereits platzierte Block-Instanzen aus der Auswahl aus (keine verschachtelten Blöcke)", () => { + const inst: Drawing2D = { id: "b1", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "block", blockDefId: "x", at: { x: 0, y: 0 }, rotation: 0 } }; + const p = project([inst]); + const ctx = makeCtx(p, ["b1"]); + const [, result] = defblockCommand.onInput( + defblockCommand.init(), + { kind: "point", point: { x: 0, y: 0 } }, + ctx, + ); + // ids.length > 0 am Eingang (die Auswahl ist nicht leer) → commit ist gesetzt, + // aber defineAndReplace filtert die Block-Quelle innen raus → No-Op-Ergebnis. + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + expect(next.blockDefs ?? []).toEqual([]); + expect(next.drawings2d.length).toBe(1); + }); +}); diff --git a/src/commands/cmds/defblock.ts b/src/commands/cmds/defblock.ts new file mode 100644 index 00000000..2c4bcaaf --- /dev/null +++ b/src/commands/cmds/defblock.ts @@ -0,0 +1,90 @@ +// Block definieren — macht aus der aktuellen 2D-Mehrfachauswahl ein +// wiederverwendbares Symbol (`Project.blockDefs`, s. `model/types.ts`): +// die Quell-Elemente werden ENTFERNT und durch EINE `{shape:"block"}`-Instanz +// ersetzt, die auf die neue, gemeinsame Definition zeigt. Schritte: +// 1) „Basispunkt:" → Punkt (wird zum lokalen Ursprung der Definition UND +// zum Einfügepunkt der ersetzenden Instanz — die Symbolgeometrie +// verschiebt sich beim Commit relativ dazu, sieht also unverändert aus). +// +// Enthält die Auswahl bereits eine Block-Instanz, wird sie ignoriert (keine +// verschachtelten Blöcke, v1 — s. `BlockDef`-Kopfkommentar in model/types.ts). +// Leere/rein-block-Auswahl → No-Op (kein Commit). + +import type { BlockDef, Drawing2D } from "../../model/types"; +import { mvGeom } from "../../tools/transform"; +import { uniqueId } from "../../tools/types"; +import type { + Command, + CommandContext, + CommandResult, + CommandSelection, + CommandState, + Project, + Vec2, +} from "../types"; + +function selectedDrawingIds(sel: CommandSelection): string[] { + if (sel.drawingIds && sel.drawingIds.length) return sel.drawingIds; + return sel.drawingId ? [sel.drawingId] : []; +} + +function nextBlockName(p: Project): string { + return `Block ${(p.blockDefs?.length ?? 0) + 1}`; +} + +function defineAndReplace(p: Project, ids: string[], at: Vec2, ctx: CommandContext): Project { + const idSet = new Set(ids); + // Block-Instanzen als Quelle ausschliessen (keine verschachtelten Blöcke). + const srcs = p.drawings2d.filter((d) => idSet.has(d.id) && d.geom.shape !== "block"); + if (srcs.length === 0) return p; + const toLocal = (pt: Vec2): Vec2 => ({ x: pt.x - at.x, y: pt.y - at.y }); + const def: BlockDef = { + id: uniqueId("blk"), + name: nextBlockName(p), + geom2d: srcs.map((d) => mvGeom(d.geom, toLocal)), + }; + const instance: Drawing2D = { + id: uniqueId("dr2d"), + type: "drawing2d", + levelId: ctx.level.id, + categoryCode: ctx.defaultCategoryCode, + geom: { shape: "block", blockDefId: def.id, at, rotation: 0 }, + }; + const srcIds = new Set(srcs.map((d) => d.id)); + const rest = p.drawings2d.filter((d) => !srcIds.has(d.id)); + return { + ...p, + blockDefs: [...(p.blockDefs ?? []), def], + drawings2d: [...rest, instance], + }; +} + +interface DefblockState extends CommandState { + phase: "base"; +} + +const idle = (): [CommandState, CommandResult] => [ + { phase: "base", lastPoint: null } as DefblockState, + { draft: null, done: true }, +]; + +export const defblockCommand: Command = { + name: "defblock", + labelKey: "cmd.defblock.label", + prompt: () => "cmd.defblock.base", + accepts: () => ["point"], + options: () => [], + init: (): DefblockState => ({ phase: "base", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + if (input.kind !== "point") return [state, { draft: null }]; + const ids = selectedDrawingIds(ctx.selection); + if (ids.length === 0) return idle(); + const at = input.point; + return [idle()[0], { draft: null, done: true, commit: (p) => defineAndReplace(p, ids, at, ctx) }]; + }, + + onMove: (state): [CommandState, CommandResult] => [state, { draft: null }], + onConfirm: (): [CommandState, CommandResult] => idle(), + onCancel: (): [CommandState, CommandResult] => idle(), +}; diff --git a/src/commands/cmds/extend.test.ts b/src/commands/cmds/extend.test.ts index 84929a64..5c0cf2a3 100644 --- a/src/commands/cmds/extend.test.ts +++ b/src/commands/cmds/extend.test.ts @@ -6,6 +6,7 @@ import { describe, it, expect } from "vitest"; import { extendCommand } from "./extend"; +import { bulgeArc } from "../../geometry/bulge"; import type { CommandContext, Project } from "../types"; function project(): Project { @@ -83,3 +84,112 @@ describe("extendCommand", () => { expect(next).toBe(p); // unverändert (No-op) }); }); + +/** + * `extendBulgeSegment` — ist das äusserste Segment ein echter Bogen (bulge), + * muss die Verlängerung DENSELBEN Kreis weiterschwenken (Mittelpunkt/Radius + * unverändert), nicht die Sehne zur Geraden verlängern. + */ +function bulgeProject(): 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: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [ + // Cutter: waagrechte Linie bei y=-1 — tangential an den Einheitskreis unten (0,-1). + { id: "cutter", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: -10, y: -1 }, b: { x: 10, y: -1 } } }, + // Ziel: oberer Halbkreis von (-1,0) nach (1,0), bulge=1 (Apex bei (0,1)). + { id: "target", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "polyline", pts: [{ x: -1, y: 0 }, { x: 1, y: 0 }], closed: false, bulge: [1] } }, + ], + context: [], + }; +} + +describe("extendCommand — Bogen-Enden (bulge)", () => { + it("verlängert das Ende-Segment (Bogen) auf DEMSELBEN Kreis bis zum Cutter", () => { + const p = bulgeProject(); + const ctx = makeCtx(p); + const [, result] = extendCommand.onInput( + extendCommand.init(), + { kind: "point", point: { x: 1, y: 0 } }, // nahe am Ende (1,0) + ctx, + ); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + const target = next.drawings2d.find((d) => d.id === "target")!; + expect(target.geom.shape).toBe("polyline"); + if (target.geom.shape !== "polyline") return; + expect(target.geom.pts[0]).toEqual({ x: -1, y: 0 }); // unverändertes Ende bleibt stehen + // Neuer Endpunkt: der Bogen wächst über die obere Hälfte hinaus bis zur + // Tangente y=-1 — trifft exakt den Berührpunkt (0,-1). + expect(target.geom.pts[1].x).toBeCloseTo(0, 6); + expect(target.geom.pts[1].y).toBeCloseTo(-1, 6); + // Der neue bulge-Wert muss wieder DENSELBEN Kreis (Mittelpunkt/Radius) ergeben. + const bulge = target.geom.bulge?.[0]; + expect(bulge).toBeDefined(); + const arc = bulgeArc(target.geom.pts[0], target.geom.pts[1], bulge!); + expect(arc).not.toBeNull(); + expect(arc!.center.x).toBeCloseTo(0, 6); + expect(arc!.center.y).toBeCloseTo(0, 6); + expect(arc!.r).toBeCloseTo(1, 6); + }); + + it("verlängert das Start-Segment (Bogen) symmetrisch, wenn das nähere Ende der Kurvenanfang ist", () => { + const p = bulgeProject(); + // Zusätzliches gerades Segment ab (1,0), damit das Bogen-Segment (Index 0) + // NICHT mehr das letzte, sondern weiterhin das erste (Start-)Segment ist. + const target = p.drawings2d.find((d) => d.id === "target")!; + if (target.geom.shape === "polyline") { + target.geom.pts.push({ x: 2, y: 0 }); + target.geom.bulge = [1, 0]; + } + const ctx = makeCtx(p); + const [, result] = extendCommand.onInput( + extendCommand.init(), + { kind: "point", point: { x: -1, y: 0 } }, // nahe am Kurvenanfang (-1,0) + ctx, + ); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + const out = next.drawings2d.find((d) => d.id === "target")!; + expect(out.geom.shape).toBe("polyline"); + if (out.geom.shape !== "polyline") return; + expect(out.geom.pts[out.geom.pts.length - 1]).toEqual({ x: 2, y: 0 }); // anderes Ende unverändert + expect(out.geom.pts[0].x).toBeCloseTo(0, 6); + expect(out.geom.pts[0].y).toBeCloseTo(-1, 6); + const bulge = out.geom.bulge?.[0]; + expect(bulge).toBeDefined(); + const arc = bulgeArc(out.geom.pts[0], out.geom.pts[1], bulge!); + expect(arc).not.toBeNull(); + expect(arc!.center.x).toBeCloseTo(0, 6); + expect(arc!.center.y).toBeCloseTo(0, 6); + expect(arc!.r).toBeCloseTo(1, 6); + }); + + it("kein Cutter auf dem Bogen getroffen → No-op", () => { + const p = bulgeProject(); + p.drawings2d = p.drawings2d.filter((d) => d.id !== "cutter"); + const ctx = makeCtx(p); + const [, result] = extendCommand.onInput( + extendCommand.init(), + { kind: "point", point: { x: 1, y: 0 } }, + ctx, + ); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + expect(next).toBe(p); + }); +}); diff --git a/src/commands/cmds/extend.ts b/src/commands/cmds/extend.ts index 23705b86..ca1a58b6 100644 --- a/src/commands/cmds/extend.ts +++ b/src/commands/cmds/extend.ts @@ -12,13 +12,20 @@ // // Geschlossene Formen (rect, geschlossene polyline) und reine Punktformen // (circle/arc/text) sind nicht extend-fähig — ein geschlossener Ring hat kein -// "Ende". Reine Geometrie liegt im Kernel (`extendSegment`); hier nur -// Treffer-Bestimmung, Drawing2D ↔ {pts,closed} und der Commit. +// "Ende". Reine Geometrie liegt im Kernel (`extendSegment`/`extendBulgeSegment`); +// hier nur Treffer-Bestimmung, Drawing2D ↔ {pts,closed,bulge} und der Commit. +// +// Bogen-Enden: ist das äusserste Segment ein echter Bogen (bulge), verlängert +// `extendBulgeSegment` denselben Kreis (Mittelpunkt/Radius unverändert, nur +// die Schwenk-Spanne wächst) bis zum nächsten Schneider — Cutter bleiben +// bewusst GERADE (wie überall bei Trim/Extend, s. `cuttersFor`). // // Bezeichner englisch, Kommentare/UI deutsch (CONVENTIONS.md). import type { Drawing2D, Drawing2DGeom } from "../../model/types"; +import { bulgeArcPoints, hasRealBulge } from "../../geometry/bulge"; import { + extendBulgeSegment, extendSegment, pointSegmentDistance, polylineEdges, @@ -37,15 +44,33 @@ const HIT_TOL = 0.25; // Modell-Meter: Pick-Toleranz für die Kurvenwahl interface Curve { pts: Vec2[]; closed: boolean; + bulge?: number[]; } /** Wandelt eine extend-fähige 2D-Form (offen) in eine Punktliste oder null. */ function geomToOpenCurve(g: Drawing2DGeom): Curve | null { if (g.shape === "line") return { pts: [g.a, g.b], closed: false }; - if (g.shape === "polyline" && !g.closed) return { pts: g.pts, closed: false }; + if (g.shape === "polyline" && !g.closed) return { pts: g.pts, closed: false, bulge: g.bulge }; return null; // rect/geschlossene polyline/circle/arc/text: kein Ende zum Verlängern } +/** + * Treffer-Kanten einer (evtl. bulge-tragenden) Kurve für Pick/Preview: bei + * echten Bogen-Segmenten wird tesselliert (Kreisbogen ≠ Sehne), sonst bleiben + * es die rohen Polylinien-Kanten. Wortgetreu wie `offset.ts`/`trim.ts`. + */ +function curveHitEdges(curve: Curve): [Vec2, Vec2][] { + if (!hasRealBulge(curve.bulge)) return polylineEdges(curve.pts, curve.closed); + const n = curve.pts.length; + const edgeCount = curve.closed ? n : n - 1; + const chain: Vec2[] = [curve.pts[0]]; + for (let i = 0; i < edgeCount; i++) { + const seg = bulgeArcPoints(curve.pts[i], curve.pts[(i + 1) % n], curve.bulge?.[i]); + chain.push(...seg.slice(1)); + } + return polylineEdges(chain, false); +} + /** Alle trim/extend-fähigen Drawing2D der Ebene als Cutter-Kurven (auch geschlossene). */ function cuttersFor(project: Project, levelId: string, exceptId: string): Curve[] { const out: Curve[] = []; @@ -54,7 +79,9 @@ function cuttersFor(project: Project, levelId: string, exceptId: string): Curve[ if (d.levelId !== levelId) continue; const g = d.geom; if (g.shape === "line") out.push({ pts: [g.a, g.b], closed: false }); - else if (g.shape === "polyline") out.push({ pts: g.pts, closed: g.closed }); + // Als Cutter würde eine Bogen-Polylinie fälschlich als Gerade behandelt + // (falscher Schnittpunkt) — lieber als Cutter ignorieren als falsch rechnen. + else if (g.shape === "polyline" && !hasRealBulge(g.bulge)) out.push({ pts: g.pts, closed: g.closed }); else if (g.shape === "rect") { out.push({ pts: [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }], @@ -73,7 +100,7 @@ function pickOpenCurveAt(project: Project, levelId: string, pt: Vec2): Drawing2D if (d.levelId !== levelId) continue; const curve = geomToOpenCurve(d.geom); if (!curve) continue; - for (const [a, b] of polylineEdges(curve.pts, curve.closed)) { + for (const [a, b] of curveHitEdges(curve)) { const dd = pointSegmentDistance(pt, a, b); if (dd < bestD) { bestD = dd; @@ -87,21 +114,44 @@ function pickOpenCurveAt(project: Project, levelId: string, pt: Vec2): Drawing2D /** * Verlängert die Kurve am Ende, das dem Klickpunkt am nächsten liegt, bis zum * nächsten Schnitt mit den Cuttern (jenseits dieses Endes). Liefert die neuen - * Punkte, oder `null`, wenn kein Cutter getroffen wird (kein Effekt). + * Punkte (+ ggf. bulge-Array), oder `null`, wenn kein Cutter getroffen wird + * (kein Effekt). Ist das betroffene ÄUSSERSTE Segment ein echter Bogen, läuft + * die Verlängerung über `extendBulgeSegment` (gleicher Kreis, grössere + * Schwenk-Spanne) statt über die Geraden-Variante. */ -function extendCurve(curve: Curve, cutters: Curve[], pick: Vec2): Vec2[] | null { +function extendCurve(curve: Curve, cutters: Curve[], pick: Vec2): Curve | null { const n = curve.pts.length; if (n < 2) return null; const distStart = Math.hypot(pick.x - curve.pts[0].x, pick.y - curve.pts[0].y); const distEnd = Math.hypot(pick.x - curve.pts[n - 1].x, pick.y - curve.pts[n - 1].y); const extendStart = distStart <= distEnd; + const segIdx = extendStart ? 0 : n - 2; // bulge-Index des äussersten Segments + const bulgeVal = curve.bulge?.[segIdx] ?? 0; + + if (Math.abs(bulgeVal) > 1e-9) { + const a = curve.pts[segIdx]; + const b = curve.pts[segIdx + 1]; + const result = extendBulgeSegment(a, b, bulgeVal, extendStart ? "start" : "end", cutters); + if (!result) return null; + const nextPts = [...curve.pts]; + const nextBulge = curve.bulge ? [...curve.bulge] : new Array(n - 1).fill(0); + if (extendStart) { + nextPts[0] = result.point; + nextBulge[0] = result.bulge; + } else { + nextPts[n - 1] = result.point; + nextBulge[n - 2] = result.bulge; + } + return { pts: nextPts, closed: false, bulge: nextBulge }; + } + const idxA = extendStart ? 1 : n - 2; const idxB = extendStart ? 0 : n - 1; const result = extendSegment(curve.pts[idxA], curve.pts[idxB], "end", cutters); if (!result) return null; const next = [...curve.pts]; next[idxB] = result[1]; - return next; + return { pts: next, closed: false, bulge: curve.bulge }; } /** Wendet Extend auf das Projekt an: ersetzt die getroffene Kurve durch ihre verlängerte Form. */ @@ -112,23 +162,35 @@ function applyExtend(p: Project, target: Drawing2D, pick: Vec2): Project { const next = extendCurve(curve, cutters, pick); if (!next) return p; const geom: Drawing2DGeom = - next.length === 2 && target.geom.shape === "line" - ? { shape: "line", a: next[0], b: next[1] } - : { shape: "polyline", pts: next, closed: false }; + next.pts.length === 2 && target.geom.shape === "line" && !hasRealBulge(next.bulge) + ? { shape: "line", a: next.pts[0], b: next.pts[1] } + : { + shape: "polyline", + pts: next.pts, + closed: false, + ...(hasRealBulge(next.bulge) ? { bulge: next.bulge } : {}), + }; return { ...p, drawings2d: p.drawings2d.map((d) => (d.id === target.id ? { ...d, geom } : d)), }; } -/** Vorschau-Form der verlängerten Kurve (für den Draft). */ +/** Vorschau-Form der verlängerten Kurve (für den Draft — Bogen tesselliert, s. `curveHitEdges`). */ function extendPreview(project: Project, target: Drawing2D, pick: Vec2): DraftShape[] { const curve = geomToOpenCurve(target.geom); if (!curve) return []; const cutters = cuttersFor(project, target.levelId, target.id); const next = extendCurve(curve, cutters, pick); if (!next) return []; - return [{ kind: "poly", pts: next, closed: false }]; + const pts = hasRealBulge(next.bulge) + ? curveHitEdges(next).reduce((acc, [a, b], i) => { + if (i === 0) acc.push(a); + acc.push(b); + return acc; + }, []) + : next.pts; + return [{ kind: "poly", pts, closed: false }]; } // ── Zustand ─────────────────────────────────────────────────────────────────── diff --git a/src/commands/cmds/fillet.test.ts b/src/commands/cmds/fillet.test.ts index 377cbc76..2b37cc9e 100644 --- a/src/commands/cmds/fillet.test.ts +++ b/src/commands/cmds/fillet.test.ts @@ -86,6 +86,29 @@ describe("filletCommand", () => { pts.some((p) => Math.hypot(p.x - x, p.y - y) < 1e-6); expect(hasNear(1.5, 0)).toBe(true); // Tangente auf dem ersten Schenkel expect(hasNear(2, 0.5)).toBe(true); // Tangente auf dem zweiten Schenkel + // Echter Bogen (kein tessellierter Punkthaufen): genau 4 Punkte, mit + // einem von 0 verschiedenen bulge-Wert an der Tangente↔Tangente-Kante. + expect(pts.length).toBe(4); + expect(poly.geom.bulge?.[1]).toBeDefined(); + expect(Math.abs(poly.geom.bulge![1])).toBeGreaterThan(0.1); + }); + + it("Polylinie mit echtem bulge-Segment gilt als nicht fillet-fähig (Datenverlust-Schutz)", () => { + const p = project(); + p.drawings2d[0].geom = { + shape: "polyline", + pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 2 }], + closed: false, + bulge: [0.4, 0], + }; + const ctx = makeCtx(p); + const [state, result] = filletCommand.onInput( + filletCommand.init(), + { kind: "point", point: { x: 2, y: 0 } }, + ctx, + ); + expect(result.commit).toBeUndefined(); + expect((state as { phase: string }).phase).toBe("pick"); }); it("daneben geklickt → Befehl bleibt im pick-Zustand (kein Treffer)", () => { diff --git a/src/commands/cmds/fillet.ts b/src/commands/cmds/fillet.ts index fb747d75..79025551 100644 --- a/src/commands/cmds/fillet.ts +++ b/src/commands/cmds/fillet.ts @@ -6,14 +6,16 @@ // wird gewählt; ein einzelnes `line`-Element hat keine eigene Ecke) // 2) „Radius:" → Punkt (Abstand von der Ecke) ODER getippte Zahl → commit // -// EINSCHRÄNKUNG (ehrlich, nicht verschwiegen): Polylinien kennen im Modell -// bisher keine Bogen-Segmente (kein „Bulge" — siehe PENDENZEN.md, 2D- -// Vervollständigung). Die Verrundung wird daher als kurze Punktfolge entlang -// des Bogens TESSELLIERT (approximiert), nicht als echtes Arc-Segment -// gespeichert — optisch rund, aber kein editierbares Bogen-Objekt. Ein rect -// wird beim ersten Fillet zu einer polyline (kein reines Rechteck mehr). +// Die Verrundung wird als ECHTES Bogen-Segment gespeichert (`bulge`, s. +// `geometry/bulge.ts`), nicht mehr tesselliert — editierbar wie jeder andere +// Bulge-Bogen (Griff zieht die Krümmung, Rendering bleibt exakt rund unabhängig +// vom Massstab). Quellkurven, die an der gewählten Ecke bereits ein Bogen- +// Segment tragen, bleiben ausgenommen (`geomToCurve`) — die Tangenten-Setback- +// Rechnung geht von geraden Schenkeln aus. Ein rect wird beim ersten Fillet zu +// einer polyline (kein reines Rechteck mehr). import type { Drawing2D, Drawing2DGeom } from "../../model/types"; +import { bulgeFromSagittaPoint, hasRealBulge } from "../../geometry/bulge"; import { filletCorner, type Fillet } from "../../geometry/kernel2d"; import type { Command, @@ -39,14 +41,18 @@ interface Curve { /** Wandelt eine fillet-fähige 2D-Form (polyline/rect) in eine Punktliste oder null. */ function geomToCurve(g: Drawing2DGeom): Curve | null { - if (g.shape === "polyline") return { pts: g.pts, closed: g.closed }; + // Bogen-Segmente (bulge) hier noch nicht unterstützt — der Fillet-Commit + // baut die Polylinie komplett neu aus reinen Punkten auf und würde ein + // bestehendes bulge-Array an anderen Segmenten sonst stillschweigend + // verlieren, s. offset.ts. + if (g.shape === "polyline" && !hasRealBulge(g.bulge)) return { pts: g.pts, closed: g.closed }; if (g.shape === "rect") { return { pts: [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }], closed: true, }; } - return null; // line (keine eigene Ecke), circle/arc/text: nicht fillet-fähig + return null; // line (keine eigene Ecke), circle/arc/text/Bogen-Polylinie: nicht fillet-fähig } /** Ein Treffer: das Element + der Eckpunkt-Index (mit gültigen beiden Nachbarn). */ @@ -101,16 +107,27 @@ function tessellateFillet(f: Fillet, segments = 12): Vec2[] { return pts; } -/** Ersetzt den Eckpunkt durch die tessellierte Bogen-Punktfolge (Tangente↔Tangente). */ +/** Ersetzt den Eckpunkt durch die beiden Tangentenpunkte (Tangente↔Tangente). */ function applyFilletPoints(hit: CornerHit, f: Fillet): Vec2[] { - const arc = tessellateFillet(f); return [ ...hit.curve.pts.slice(0, hit.index), - ...arc, + f.tangentA, + f.tangentB, ...hit.curve.pts.slice(hit.index + 1), ]; } +/** Bulge-Wert des Verrundungs-Bogens (tangentA→tangentB), aus einem echten Bogenpunkt hergeleitet. */ +function filletBulge(f: Fillet): number { + const TAU = Math.PI * 2; + let delta = f.endAngle - f.startAngle; + while (delta > Math.PI) delta -= TAU; + while (delta < -Math.PI) delta += TAU; + const mid = f.startAngle + delta / 2; + const apex: Vec2 = { x: f.center.x + f.radius * Math.cos(mid), y: f.center.y + f.radius * Math.sin(mid) }; + return bulgeFromSagittaPoint(f.tangentA, f.tangentB, apex); +} + function filletDraft(hit: CornerHit, r: number, at: Vec2 | null): ToolDraft { const f = r > EPS ? filletFor(hit, r) : null; const preview: DraftShape[] = f @@ -125,7 +142,10 @@ function commitFillet(p: Project, hit: CornerHit, r: number): Project { const f = filletFor(hit, r); if (!f) return p; // Radius zu gross für die Schenkellänge, oder Ecke (fast) gerade → No-op const pts = applyFilletPoints(hit, f); - const geom: Drawing2DGeom = { shape: "polyline", pts, closed: hit.curve.closed }; + const edgeCount = hit.curve.closed ? pts.length : pts.length - 1; + const bulge = new Array(edgeCount).fill(0); + bulge[hit.index] = filletBulge(f); // Kante tangentA→tangentB (an Position hit.index) + const geom: Drawing2DGeom = { shape: "polyline", pts, closed: hit.curve.closed, bulge }; return { ...p, drawings2d: p.drawings2d.map((d) => (d.id === hit.drawing.id ? { ...d, geom } : d)), diff --git a/src/commands/cmds/leader.test.ts b/src/commands/cmds/leader.test.ts new file mode 100644 index 00000000..c2917569 --- /dev/null +++ b/src/commands/cmds/leader.test.ts @@ -0,0 +1,72 @@ +/** + * `leaderCommand` — Zielpunkt + Textanker → leeres `text`-Element mit + * `leaderTarget` gesetzt, meldet `focusDrawingId` (öffnet den Inline-Editor). + */ + +import { describe, it, expect } from "vitest"; +import { leaderCommand } from "./leader"; +import type { CommandContext, Project } from "../types"; + +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: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + }; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +describe("leaderCommand", () => { + it("Zielpunkt + Anker → leeres Text-Element mit leaderTarget, focusDrawingId gesetzt", () => { + const p = project(); + const ctx = makeCtx(p); + const [afterTarget] = leaderCommand.onInput( + leaderCommand.init(), + { kind: "point", point: { x: 10, y: 10 } }, + ctx, + ); + const [, result] = leaderCommand.onInput( + afterTarget, + { kind: "point", point: { x: 2, y: 2 } }, + ctx, + ); + expect(result.commit).toBeDefined(); + expect(result.focusDrawingId).toBeDefined(); + const next = result.commit!(p); + expect(next.drawings2d.length).toBe(1); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("text"); + if (g.shape === "text") { + expect(g.text).toBe(""); + expect(g.at).toEqual({ x: 2, y: 2 }); + expect(g.leaderTarget).toEqual({ x: 10, y: 10 }); + } + expect(next.drawings2d[0].id).toBe(result.focusDrawingId); + }); +}); diff --git a/src/commands/cmds/leader.ts b/src/commands/cmds/leader.ts new file mode 100644 index 00000000..3b3eb4d5 --- /dev/null +++ b/src/commands/cmds/leader.ts @@ -0,0 +1,97 @@ +// Leader (Legenden-/Vorführungspfeil) — wie `text`, aber mit vorangestelltem +// Zielpunkt: Schritte: +// 1) „Zielpunkt:" → Punkt (Pfeilspitze, zeigt auf das referenzierte Detail) +// 2) „Textanker:" → Punkt (Textposition) +// Committet SOFORT ein leeres Text-Element mit `leaderTarget` gesetzt und +// meldet `focusDrawingId` — dieselbe Inline-Editor-Infrastruktur wie beim +// `text`-Befehl (kein neuer Shape, s. `Drawing2DGeom["text"].leaderTarget`). + +import type { Drawing2D } from "../../model/types"; +import { uniqueId } from "../../tools/types"; +import type { + Command, + CommandContext, + CommandResult, + CommandState, + DraftShape, + Project, + ToolDraft, + Vec2, +} from "../types"; + +const DEFAULT_TEXT_HEIGHT_M = 0.25; +const EPS = 1e-6; + +interface LeaderTarget extends CommandState { + phase: "target"; +} +interface LeaderAnchor extends CommandState { + phase: "anchor"; + target: Vec2; + cursor: Vec2 | null; +} +type LeaderState = LeaderTarget | LeaderAnchor; + +function appendEmptyLeaderText(p: Project, id: string, at: Vec2, target: Vec2, ctx: CommandContext): Project { + const d: Drawing2D = { + id, + type: "drawing2d", + levelId: ctx.level.id, + categoryCode: ctx.defaultCategoryCode, + geom: { shape: "text", at, text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0, leaderTarget: target }, + }; + return { ...p, drawings2d: [...p.drawings2d, d] }; +} + +const idle = (): [CommandState, CommandResult] => [ + { phase: "target", lastPoint: null } as LeaderTarget, + { draft: null, done: true }, +]; + +function anchorDraft(target: Vec2, cursor: Vec2 | null): ToolDraft { + if (!cursor || Math.hypot(cursor.x - target.x, cursor.y - target.y) < EPS) { + return { preview: [], vertices: [target] }; + } + const preview: DraftShape[] = [{ kind: "line", a: cursor, b: target }]; + return { preview, vertices: [target] }; +} + +export const leaderCommand: Command = { + name: "leader", + labelKey: "cmd.leader.label", + prompt: (s) => ((s as LeaderState).phase === "anchor" ? "cmd.leader.anchor" : "cmd.leader.target"), + accepts: () => ["point"], + options: () => [], + init: (): LeaderTarget => ({ phase: "target", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as LeaderState; + if (input.kind !== "point") return [s, { draft: null }]; + if (s.phase !== "anchor") { + const next: LeaderAnchor = { phase: "anchor", target: input.point, cursor: input.point, lastPoint: input.point }; + return [next, { draft: anchorDraft(input.point, input.point) }]; + } + const id = uniqueId("dr2d"); + const at = input.point; + const target = s.target; + return [ + idle()[0], + { + draft: null, + done: true, + commit: (p) => appendEmptyLeaderText(p, id, at, target, ctx), + focusDrawingId: id, + }, + ]; + }, + + onMove: (state, point): [CommandState, CommandResult] => { + const s = state as LeaderState; + if (s.phase !== "anchor") return [s, { draft: null }]; + const ns: LeaderAnchor = { ...s, cursor: point }; + return [ns, { draft: anchorDraft(s.target, point) }]; + }, + + onConfirm: (): [CommandState, CommandResult] => idle(), + onCancel: (): [CommandState, CommandResult] => idle(), +}; diff --git a/src/commands/cmds/offset.ts b/src/commands/cmds/offset.ts index 6effa2e1..94afc245 100644 --- a/src/commands/cmds/offset.ts +++ b/src/commands/cmds/offset.ts @@ -14,10 +14,12 @@ // Vorzeichen, wenn negativ getippt. import type { Drawing2D, Drawing2DGeom } from "../../model/types"; +import { bulgeArcPoints, hasRealBulge } from "../../geometry/bulge"; import { uniqueId } from "../../tools/types"; import { leftNormal, normalize, sub } from "../../model/geometry"; import { offsetPolyline, + offsetPolylineWithBulge, offsetSegment, pointSegmentDistance, polylineEdges, @@ -51,12 +53,14 @@ let lastSign = 1; interface Curve { pts: Vec2[]; closed: boolean; + /** Bogen-Segmente (DXF-bulge, s. `geometry/bulge.ts`) — nur bei polyline. */ + bulge?: number[]; } -/** Wandelt eine offset-fähige 2D-Form in eine Punktliste (+closed) oder null. */ +/** Wandelt eine offset-fähige 2D-Form in eine Punktliste (+closed[/bulge]) oder null. */ function geomToCurve(g: Drawing2DGeom): Curve | null { if (g.shape === "line") return { pts: [g.a, g.b], closed: false }; - if (g.shape === "polyline") return { pts: g.pts, closed: g.closed }; + if (g.shape === "polyline") return { pts: g.pts, closed: g.closed, bulge: g.bulge }; if (g.shape === "rect") { // Rechteck als geschlossene 4-Punkt-Polylinie offsetten (Task). return { @@ -74,7 +78,8 @@ function geomToCurve(g: Drawing2DGeom): Curve | null { /** Ist diese Form offset-fähig (line/polyline/rect)? */ function isOffsetable(d: Drawing2D): boolean { - return d.geom.shape === "line" || d.geom.shape === "polyline" || d.geom.shape === "rect"; + const g = d.geom; + return g.shape === "line" || g.shape === "polyline" || g.shape === "rect"; } /** Genau ein passendes Drawing2D vorselektiert? Dann liefere es. */ @@ -85,6 +90,25 @@ function singleSelectedCurve(project: Project, sel: CommandSelection): Drawing2D return null; } +/** + * Kanten für Klick-Trefftests/Vorschau: bei Bogen-Segmenten (bulge) wird die + * Kurve zu Geradenstücken tesselliert (`bulgeArcPoints`), damit Klick-/Seiten- + * Tests entlang der TATSÄCHLICHEN (runden) Kontur funktionieren statt entlang + * der geraden Sehne. Die eigentliche Offset-Geometrie bleibt exakt (bulge- + * erhaltend, s. `offsetPolylineWithBulge`) — nur diese Hilfsfunktion approximiert. + */ +function curveHitEdges(curve: Curve): [Vec2, Vec2][] { + if (!hasRealBulge(curve.bulge)) return polylineEdges(curve.pts, curve.closed); + const n = curve.pts.length; + const edgeCount = curve.closed ? n : n - 1; + const chain: Vec2[] = [curve.pts[0]]; + for (let i = 0; i < edgeCount; i++) { + const seg = bulgeArcPoints(curve.pts[i], curve.pts[(i + 1) % n], curve.bulge?.[i]); + chain.push(...seg.slice(1)); + } + return polylineEdges(chain, false); // Schlusskante (falls closed) ist bereits mit-tesselliert +} + /** Nächstes offset-fähiges Drawing2D zum Klickpunkt (innerhalb Toleranz). */ function pickCurveAt(project: Project, levelId: string, pt: Vec2): Drawing2D | null { let best: Drawing2D | null = null; @@ -93,7 +117,7 @@ function pickCurveAt(project: Project, levelId: string, pt: Vec2): Drawing2D | n if (d.levelId !== levelId) continue; const curve = geomToCurve(d.geom); if (!curve) continue; - for (const [a, b] of polylineEdges(curve.pts, curve.closed)) { + for (const [a, b] of curveHitEdges(curve)) { const dd = pointSegmentDistance(pt, a, b); if (dd < bestD) { bestD = dd; @@ -113,7 +137,7 @@ function pickCurveAt(project: Project, levelId: string, pt: Vec2): Drawing2D | n function sideSign(curve: Curve, pt: Vec2): number { let bestD = Infinity; let sign = lastSign; - for (const [a, b] of polylineEdges(curve.pts, curve.closed)) { + for (const [a, b] of curveHitEdges(curve)) { const mid: Vec2 = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; const dd = pointSegmentDistance(pt, a, b); if (dd < bestD) { @@ -128,38 +152,46 @@ function sideSign(curve: Curve, pt: Vec2): number { return sign; } -/** Offset einer Kurve um die vorzeichenbehaftete Distanz `d` → neue Punktliste. */ -function offsetCurve(curve: Curve, d: number): Vec2[] { - if (!curve.closed && curve.pts.length === 2) { +/** Offset einer Kurve um die vorzeichenbehaftete Distanz `d` → neue Geometrie (bulge-erhaltend). */ +function offsetCurveGeom(curve: Curve, d: number): { pts: Vec2[]; bulge?: number[] } { + if (!curve.closed && curve.pts.length === 2 && !hasRealBulge(curve.bulge)) { const [a, b] = offsetSegment(curve.pts[0], curve.pts[1], d); - return [a, b]; + return { pts: [a, b] }; } - return offsetPolyline(curve.pts, d, curve.closed); + if (hasRealBulge(curve.bulge)) { + return offsetPolylineWithBulge(curve.pts, curve.bulge, d, curve.closed); + } + return { pts: offsetPolyline(curve.pts, d, curve.closed) }; } /** Versetzte Form als neues Drawing2D (gleiche Attribute, neue ID/Geometrie). */ function offsetGeom(src: Drawing2D, d: number): Drawing2DGeom | null { - const g = src.geom; - if (g.shape === "line") { - const [a, b] = offsetSegment(g.a, g.b, d); - return { shape: "line", a, b }; + const curve = geomToCurve(src.geom); + if (!curve) return null; + const { pts, bulge } = offsetCurveGeom(curve, d); + if (src.geom.shape === "line" && pts.length === 2) { + return { shape: "line", a: pts[0], b: pts[1] }; } - if (g.shape === "polyline") { - return { shape: "polyline", pts: offsetPolyline(g.pts, d, g.closed), closed: g.closed }; - } - if (g.shape === "rect") { - const curve = geomToCurve(g)!; - return { shape: "polyline", pts: offsetPolyline(curve.pts, d, true), closed: true }; - } - return null; + const geom: Drawing2DGeom = { shape: "polyline", pts, closed: curve.closed }; + if (bulge && hasRealBulge(bulge)) geom.bulge = bulge; + return geom; } -/** Vorschau-Formen der versetzten Kurve (für den Draft). */ +/** Vorschau-Formen der versetzten Kurve (für den Draft — tesselliert, s. `DraftShape`). */ function offsetDraftShapes(curve: Curve, d: number): DraftShape[] { - const pts = offsetCurve(curve, d); + const { pts, bulge } = offsetCurveGeom(curve, d); if (pts.length < 2) return []; - if (!curve.closed && pts.length === 2) return [{ kind: "line", a: pts[0], b: pts[1] }]; - return [{ kind: "poly", pts, closed: curve.closed }]; + if (!curve.closed && pts.length === 2 && !hasRealBulge(bulge)) { + return [{ kind: "line", a: pts[0], b: pts[1] }]; + } + const tess = hasRealBulge(bulge) + ? curveHitEdges({ pts, closed: curve.closed, bulge }).reduce((out, [a, b], i) => { + if (i === 0) out.push(a); + out.push(b); + return out; + }, []) + : pts; + return [{ kind: "poly", pts: tess, closed: curve.closed }]; } function appendOffset(p: Project, src: Drawing2D, d: number): Project { diff --git a/src/commands/cmds/polygon.test.ts b/src/commands/cmds/polygon.test.ts new file mode 100644 index 00000000..f75bb89d --- /dev/null +++ b/src/commands/cmds/polygon.test.ts @@ -0,0 +1,120 @@ +/** + * `polygonCommand` — Mittelpunkt + Radius → geschlossene `polyline` mit N + * (Default 6) gleichmässig verteilten Eckpunkten auf dem Umkreis. + */ + +import { describe, it, expect } from "vitest"; +import { polygonCommand } from "./polygon"; +import type { CommandContext, Project } from "../types"; + +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: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + }; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +const dist = (a: { x: number; y: number }, b: { x: number; y: number }) => + Math.hypot(b.x - a.x, b.y - a.y); + +describe("polygonCommand", () => { + it("Mittelpunkt + Radius-Punkt → geschlossene Polylinie mit 6 Eckpunkten auf dem Umkreis", () => { + const p = project(); + const ctx = makeCtx(p); + const [afterCenter] = polygonCommand.onInput( + polygonCommand.init(), + { kind: "point", point: { x: 0, y: 0 } }, + ctx, + ); + const [, result] = polygonCommand.onInput( + afterCenter, + { kind: "point", point: { x: 5, y: 0 } }, + ctx, + ); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + expect(next.drawings2d.length).toBe(1); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("polyline"); + if (g.shape === "polyline") { + expect(g.closed).toBe(true); + expect(g.pts.length).toBe(6); + // Erste Ecke exakt in Klickrichtung (+X) im Klickabstand. + expect(g.pts[0].x).toBeCloseTo(5, 6); + expect(g.pts[0].y).toBeCloseTo(0, 6); + // Alle Eckpunkte liegen auf dem Umkreis mit Radius 5. + for (const pt of g.pts) expect(dist({ x: 0, y: 0 }, pt)).toBeCloseTo(5, 6); + } + }); + + it("Ecken-Zahl per Option zyklt 3..12 und zurück zu 3", () => { + const p = project(); + const ctx = makeCtx(p); + let [state] = polygonCommand.onInput( + polygonCommand.init(), + { kind: "point", point: { x: 0, y: 0 } }, + ctx, + ); + // Von Default 6 hoch bis 12, dann Wrap auf 3. + let opts = polygonCommand.options(state); + expect(opts[0].value).toBe("6"); + for (let i = 0; i < 6; i++) { + [state] = polygonCommand.onInput(state, { kind: "option", id: "sides" }, ctx); + } + opts = polygonCommand.options(state); + expect(opts[0].value).toBe("12"); + [state] = polygonCommand.onInput(state, { kind: "option", id: "sides" }, ctx); + opts = polygonCommand.options(state); + expect(opts[0].value).toBe("3"); + + const [, result] = polygonCommand.onInput(state, { kind: "point", point: { x: 4, y: 0 } }, ctx); + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + if (g.shape === "polyline") expect(g.pts.length).toBe(3); + }); + + it("entarteter Radius (Punkt=Mittelpunkt) committet nichts", () => { + const p = project(); + const ctx = makeCtx(p); + const [afterCenter] = polygonCommand.onInput( + polygonCommand.init(), + { kind: "point", point: { x: 2, y: 2 } }, + ctx, + ); + const [, result] = polygonCommand.onInput( + afterCenter, + { kind: "point", point: { x: 2, y: 2 } }, + ctx, + ); + const next = result.commit!(p); + expect(next.drawings2d.length).toBe(0); + }); +}); diff --git a/src/commands/cmds/polygon.ts b/src/commands/cmds/polygon.ts new file mode 100644 index 00000000..8ee2a4e1 --- /dev/null +++ b/src/commands/cmds/polygon.ts @@ -0,0 +1,157 @@ +// Regelmässiges Vieleck — Mittelpunkt + Radius (umschriebener Kreis), Anzahl +// Ecken zyklt über eine Inline-Option (3..12, Default 6), analog zum +// `count`-Zyklus bei Multiline. Committet als geschlossene `polyline` — kein +// neuer Shape-Typ nötig, erbt dadurch Rendering/Snapping/Griffe/Export +// komplett vom bestehenden Polylinien-Pfad. Schritte: +// 1) „Mittelpunkt:" → Punkt +// 2) „Radius:" → Punkt (Abstand+Richtung des ersten Eckpunkts) ODER +// getippte Zahl (Radius, Richtung +X) → commit. Ecken-Zahl per Option. + +import type { Drawing2D } from "../../model/types"; +import { uniqueId } from "../../tools/types"; +import type { + CmdOption, + Command, + CommandContext, + CommandField, + CommandResult, + CommandState, + DraftShape, + Project, + ToolDraft, + Vec2, +} from "../types"; + +const EPS = 1e-6; +const MIN_SIDES = 3; +const MAX_SIDES = 12; + +let lastSides = 6; + +interface PolyIdle extends CommandState { + phase: "center"; +} +interface PolyDrawing extends CommandState { + phase: "radius"; + center: Vec2; + cursor: Vec2 | null; +} +type PolyState = PolyIdle | PolyDrawing; + +const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); + +const RADIUS_FIELDS: CommandField[] = [{ id: "radius", labelKey: "cmd.field.radius" }]; +const SIDES_OPTION: CmdOption = { id: "sides", labelKey: "cmd.polygon.sides" }; + +/** Eckpunkte des umschriebenen regelmässigen Vielecks (erste Ecke Richtung `dir`). */ +function polygonPts(center: Vec2, r: number, sides: number, dir: Vec2 | null): Vec2[] { + const t0 = dir && dist(center, dir) > EPS ? Math.atan2(dir.y - center.y, dir.x - center.x) : 0; + const pts: Vec2[] = []; + for (let i = 0; i < sides; i++) { + const t = t0 + (i / sides) * Math.PI * 2; + pts.push({ x: center.x + r * Math.cos(t), y: center.y + r * Math.sin(t) }); + } + return pts; +} + +function polygonDraft(center: Vec2, r: number, dir: Vec2 | null, at: Vec2 | null): ToolDraft { + if (r < EPS) return { preview: [], vertices: [center] }; + const preview: DraftShape[] = [{ kind: "poly", pts: polygonPts(center, r, lastSides, dir), closed: true }]; + const draft: ToolDraft = { preview, vertices: [center] }; + if (at) draft.hud = { at, text: `R: ${r.toFixed(3)}m × ${lastSides}` }; + return draft; +} + +function appendPolygon(p: Project, center: Vec2, r: number, dir: Vec2 | null, ctx: CommandContext): Project { + if (r < EPS) return p; + const d: Drawing2D = { + id: uniqueId("dr2d"), + type: "drawing2d", + levelId: ctx.level.id, + categoryCode: ctx.defaultCategoryCode, + geom: { shape: "polyline", pts: polygonPts(center, r, lastSides, dir), closed: true }, + }; + return { ...p, drawings2d: [...p.drawings2d, d] }; +} + +const idle = (): [CommandState, CommandResult] => [ + { phase: "center", lastPoint: null } as PolyIdle, + { draft: null, done: true }, +]; + +export const polygonCommand: Command = { + name: "polygon", + labelKey: "cmd.polygon.label", + prompt: (s) => ((s as PolyState).phase === "radius" ? "cmd.polygon.radius" : "cmd.polygon.center"), + accepts: (s) => ((s as PolyState).phase === "radius" ? ["point", "number", "option"] : ["point"]), + options: (s) => + (s as PolyState).phase === "radius" ? [{ ...SIDES_OPTION, value: String(lastSides) }] : [], + init: (): PolyIdle => ({ phase: "center", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as PolyState; + if (s.phase !== "radius") { + if (input.kind !== "point") return [s, { draft: null }]; + const ns: PolyDrawing = { phase: "radius", center: input.point, cursor: input.point, lastPoint: input.point }; + return [ns, { draft: polygonDraft(input.point, 0, null, null) }]; + } + if (input.kind === "option") { + if (input.id === "sides") { + lastSides = lastSides >= MAX_SIDES ? MIN_SIDES : lastSides + 1; + const r = s.cursor ? dist(s.center, s.cursor) : 0; + return [s, { draft: polygonDraft(s.center, r, s.cursor, s.cursor) }]; + } + return [s, { draft: null }]; + } + let r: number; + let dir: Vec2 | null; + if (input.kind === "number") { + r = input.value; + dir = s.cursor; + } else if (input.kind === "point") { + r = dist(s.center, input.point); + dir = input.point; + } else { + const rr = s.cursor ? dist(s.center, s.cursor) : 0; + return [s, { draft: polygonDraft(s.center, rr, s.cursor, s.cursor) }]; + } + const center = s.center; + return [ + idle()[0], + { draft: null, done: true, commit: (p) => appendPolygon(p, center, r, dir, ctx) }, + ]; + }, + + onMove: (state, point): [CommandState, CommandResult] => { + const s = state as PolyState; + if (s.phase !== "radius") return [s, { draft: null }]; + const r = dist(s.center, point); + const ns: PolyDrawing = { ...s, cursor: point }; + return [ns, { draft: polygonDraft(s.center, r, point, point) }]; + }, + + onConfirm: (): [CommandState, CommandResult] => idle(), + onCancel: (): [CommandState, CommandResult] => idle(), + + fields: (state) => ((state as PolyState).phase === "radius" ? RADIUS_FIELDS : []), + fieldValues: (state, _locks, cursor): Record => { + const s = state as PolyState; + if (s.phase !== "radius" || !cursor) return {}; + return { radius: dist(s.center, cursor) }; + }, + pointFromFields: (state, locks, cursor) => { + const s = state as PolyState; + if (s.phase !== "radius") return null; + const r = "radius" in locks ? Math.abs(locks.radius) : cursor ? dist(s.center, cursor) : 0; + if (cursor) { + const d = dist(s.center, cursor); + if (d > EPS) { + return { + x: s.center.x + ((cursor.x - s.center.x) / d) * r, + y: s.center.y + ((cursor.y - s.center.y) / d) * r, + }; + } + } + return { x: s.center.x + r, y: s.center.y }; + }, +}; diff --git a/src/commands/cmds/textpath.test.ts b/src/commands/cmds/textpath.test.ts new file mode 100644 index 00000000..d305170f --- /dev/null +++ b/src/commands/cmds/textpath.test.ts @@ -0,0 +1,80 @@ +/** + * `textpathCommand` — mind. 2 Pfadpunkte + Enter → leeres `text`-Element mit + * `pathPts` gesetzt, meldet `focusDrawingId` (öffnet den Inline-Editor). + */ + +import { describe, it, expect } from "vitest"; +import { textpathCommand } from "./textpath"; +import type { CommandContext, Project } from "../types"; + +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: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + }; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +describe("textpathCommand", () => { + it("2 Punkte + Enter → leeres Text-Element mit pathPts, focusDrawingId gesetzt", () => { + const p = project(); + const ctx = makeCtx(p); + const [afterA] = textpathCommand.onInput( + textpathCommand.init(), + { kind: "point", point: { x: 0, y: 0 } }, + ctx, + ); + const [afterB] = textpathCommand.onInput(afterA, { kind: "point", point: { x: 3, y: 2 } }, ctx); + const [, result] = textpathCommand.onConfirm(afterB, ctx); + expect(result.commit).toBeDefined(); + expect(result.focusDrawingId).toBeDefined(); + const next = result.commit!(p); + expect(next.drawings2d.length).toBe(1); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("text"); + if (g.shape === "text") { + expect(g.text).toBe(""); + expect(g.pathPts).toEqual([{ x: 0, y: 0 }, { x: 3, y: 2 }]); + expect(g.at).toEqual({ x: 0, y: 0 }); + } + }); + + it("Enter mit nur 1 Punkt committet nichts", () => { + const p = project(); + const ctx = makeCtx(p); + const [afterA] = textpathCommand.onInput( + textpathCommand.init(), + { kind: "point", point: { x: 0, y: 0 } }, + ctx, + ); + const [, result] = textpathCommand.onConfirm(afterA, ctx); + expect(result.commit).toBeUndefined(); + }); +}); diff --git a/src/commands/cmds/textpath.ts b/src/commands/cmds/textpath.ts new file mode 100644 index 00000000..0b1b2079 --- /dev/null +++ b/src/commands/cmds/textpath.ts @@ -0,0 +1,137 @@ +// Text-entlang-Pfad — wie `polyline` beim Punkte-Sammeln (≥2 Stützpunkte, +// Enter/Rechtsklick beendet), aber committet SOFORT ein leeres Text-Element +// mit `pathPts` gesetzt und meldet `focusDrawingId` — dieselbe Inline-Editor- +// Infrastruktur wie `text`/`leader` (kein neuer Shape, s. `Drawing2DGeom +// ["text"].pathPts`). Schritte: +// 1) „Pfadpunkt:" → Punkt +// 2) „Nächster Pfadpunkt ( Fertig ):" → Punkt … Enter beendet (≥2 Punkte nötig) + +import type { Drawing2D } from "../../model/types"; +import { segmentHud, uniqueId } from "../../tools/types"; +import type { + Command, + CommandContext, + CommandField, + CommandResult, + CommandState, + DraftShape, + Project, + ToolDraft, + Vec2, +} from "../types"; + +const EPS = 1e-6; +const DEG = Math.PI / 180; +const DEFAULT_TEXT_HEIGHT_M = 0.25; +const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); +const segAngleDeg = (a: Vec2, b: Vec2): number => + (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI; + +const PATH_FIELDS: CommandField[] = [ + { id: "length", labelKey: "cmd.field.length" }, + { id: "angle", labelKey: "cmd.field.angle" }, +]; + +function nextFromFields(last: Vec2, locks: Record, cursor: Vec2 | null): Vec2 { + const ref = cursor ?? last; + const length = "length" in locks ? locks.length : segLen(last, ref); + const angleDeg = "angle" in locks ? locks.angle : segAngleDeg(last, ref); + const ang = angleDeg * DEG; + return { x: last.x + Math.cos(ang) * length, y: last.y + Math.sin(ang) * length }; +} + +interface TpIdle extends CommandState { + phase: "start"; +} +interface TpNext extends CommandState { + phase: "next"; + points: Vec2[]; + cursor: Vec2 | null; +} +type TpState = TpIdle | TpNext; + +function pathDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { + const pts = cursor ? [...points, cursor] : points; + const preview: DraftShape[] = pts.length >= 2 ? [{ kind: "poly", pts, closed: false }] : []; + const draft: ToolDraft = { preview, vertices: points }; + const last = points[points.length - 1]; + if (cursor && last && segLen(last, cursor) >= EPS) draft.hud = segmentHud(last, cursor); + return draft; +} + +function appendEmptyTextPath(p: Project, id: string, pts: Vec2[], ctx: CommandContext): Project { + const d: Drawing2D = { + id, + type: "drawing2d", + levelId: ctx.level.id, + categoryCode: ctx.defaultCategoryCode, + geom: { shape: "text", at: pts[0], text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0, pathPts: pts }, + }; + return { ...p, drawings2d: [...p.drawings2d, d] }; +} + +const idle = (): [CommandState, CommandResult] => [ + { phase: "start", lastPoint: null } as TpIdle, + { draft: null, done: true }, +]; + +function commitPath(pts: Vec2[], ctx: CommandContext): CommandResult { + const id = uniqueId("dr2d"); + return { draft: null, done: true, commit: (p) => appendEmptyTextPath(p, id, pts, ctx), focusDrawingId: id }; +} + +export const textpathCommand: Command = { + name: "textpath", + labelKey: "cmd.textpath.label", + prompt: (s) => ((s as TpState).phase === "next" ? "cmd.textpath.next" : "cmd.textpath.start"), + accepts: () => ["point", "number"], + options: () => [], + init: (): TpIdle => ({ phase: "start", lastPoint: null }), + + onInput: (state, input): [CommandState, CommandResult] => { + const s = state as TpState; + if (input.kind !== "point") { + return [s, { draft: s.phase === "next" ? pathDraft(s.points, s.cursor) : null }]; + } + const pt = input.point; + if (s.phase !== "next") { + const ns: TpNext = { phase: "next", points: [pt], cursor: pt, lastPoint: pt }; + return [ns, { draft: pathDraft([pt], pt) }]; + } + const points = [...s.points, pt]; + const ns: TpNext = { phase: "next", points, cursor: pt, lastPoint: pt }; + return [ns, { draft: pathDraft(points, pt) }]; + }, + + onMove: (state, point): [CommandState, CommandResult] => { + const s = state as TpState; + if (s.phase !== "next") return [s, { draft: null }]; + const ns: TpNext = { ...s, cursor: point }; + return [ns, { draft: pathDraft(s.points, point) }]; + }, + + onConfirm: (state, ctx): [CommandState, CommandResult] => { + const s = state as TpState; + if (s.phase === "next" && s.points.length >= 2) { + return [idle()[0], commitPath(s.points, ctx)]; + } + return idle(); + }, + onCancel: (): [CommandState, CommandResult] => idle(), + + fields: (state) => ((state as TpState).phase === "next" ? PATH_FIELDS : []), + pointFromFields: (state, locks, cursor) => { + const s = state as TpState; + if (s.phase !== "next" || s.points.length === 0) return null; + return nextFromFields(s.points[s.points.length - 1], locks, cursor); + }, + fieldValues: (state, _locks, cursor): Record => { + const s = state as TpState; + if (s.phase !== "next" || s.points.length === 0 || !cursor) return {}; + const last = s.points[s.points.length - 1]; + return { + length: segLen(last, cursor), + angle: ((segAngleDeg(last, cursor) % 360) + 360) % 360, + }; + }, +}; diff --git a/src/commands/cmds/trim.test.ts b/src/commands/cmds/trim.test.ts new file mode 100644 index 00000000..02daca42 --- /dev/null +++ b/src/commands/cmds/trim.test.ts @@ -0,0 +1,108 @@ +/** + * `trimCommand` — Integrationstest für den Bogen-Fall (`trimPolylineWithBulge`, + * s. Kernel-Tests in `geometry/kernel2d.trimBulge.test.ts` für die reine + * Geometrie). Deckt die Verdrahtung ab: Klick-Trefftest auf einem Bogen- + * Segment (tesselliert, s. `curveHitEdges`) + committete Geometrie behält + * bulge — sowohl als Ziel-Kurve als auch als Schneider (Bogen-Cutter). + */ + +import { describe, it, expect } from "vitest"; +import { trimCommand } from "./trim"; +import type { CommandContext, Project } from "../types"; + +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: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [ + // Cutter: senkrechte Linie bei x=0. + { id: "cutter", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: 0, y: -5 }, b: { x: 0, y: 5 } } }, + // Ziel: Halbkreis (-1,0)→(1,0), bulge=1 (center=(0,0), r=1). + { id: "target", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "polyline", pts: [{ x: -1, y: 0 }, { x: 1, y: 0 }], closed: false, bulge: [1] } }, + ], + context: [], + }; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +describe("trimCommand — Bogen-Segmente (bulge)", () => { + it("Klick auf den rechten Viertelbogen trifft ihn (tessellierter Trefftest) und schneidet ihn weg", () => { + const p = project(); + const ctx = makeCtx(p); + // Klick auf dem rechten Viertelbogen (45°: (√2/2, √2/2)) — liegt weit von + // der geraden Sehne (-1,0)-(1,0) entfernt, ein reiner Sehnen-Trefftest + // würde hier fehlschlagen. + const pick = { x: Math.SQRT1_2, y: Math.SQRT1_2 }; + const [, result] = trimCommand.onInput(trimCommand.init(), { kind: "point", point: pick }, ctx); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + const rest = next.drawings2d.filter((d) => d.id !== "cutter"); + expect(rest.length).toBe(1); + const g = rest[0].geom; + expect(g.shape).toBe("polyline"); + if (g.shape !== "polyline") return; + // Nur der linke Viertelbogen bleibt: (-1,0) → (0,1), mit echtem bulge. + expect(g.pts[0].x).toBeCloseTo(-1, 6); + expect(g.pts[1].x).toBeCloseTo(0, 6); + expect(g.pts[1].y).toBeCloseTo(1, 6); + expect(g.bulge?.[0]).toBeDefined(); + expect(Math.abs(g.bulge![0])).toBeGreaterThan(0.01); + }); + + it("ein Bogen-CUTTER schneidet jetzt echt (Kreis↔Kreis-Schnitt), statt ignoriert zu werden", () => { + const p = project(); + // Geraden-Cutter entfernen, nur der Bogen-Cutter soll hier wirken. + p.drawings2d = p.drawings2d.filter((d) => d.id !== "cutter"); + // Bogen-Cutter: oberer Halbkreis von center=(1,0), r=1 (a=(0,0)→b=(2,0), + // bulge=1) — kreuzt das Ziel (oberer Halbkreis center=(0,0), r=1) exakt + // bei (0.5, √3/2) ("Vesica Piscis", s. kernel2d.trimBulge.test.ts). + p.drawings2d.push({ + id: "arcCutter", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }], closed: false, bulge: [1] }, + }); + const ctx = makeCtx(p); + // Klick bei 120° (vor dem Schnitt bei 60° in Schwenkrichtung). + const pick = { x: Math.cos((2 * Math.PI) / 3), y: Math.sin((2 * Math.PI) / 3) }; + const [, result] = trimCommand.onInput(trimCommand.init(), { kind: "point", point: pick }, ctx); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + const rest = next.drawings2d.filter((d) => d.id !== "arcCutter"); + expect(rest.length).toBe(1); + const g = rest[0].geom; + expect(g.shape).toBe("polyline"); + if (g.shape !== "polyline") return; + // Übrig bleibt der rechte Teilbogen: Schnittpunkt (0.5,√3/2) → b=(1,0). + expect(g.pts[0].x).toBeCloseTo(0.5, 6); + expect(g.pts[0].y).toBeCloseTo(Math.sqrt(3) / 2, 6); + expect(g.pts[g.pts.length - 1]).toEqual({ x: 1, y: 0 }); + expect(Math.abs(g.bulge?.[0] ?? 0)).toBeGreaterThan(0.01); + }); +}); diff --git a/src/commands/cmds/trim.ts b/src/commands/cmds/trim.ts index 717518b5..c7908603 100644 --- a/src/commands/cmds/trim.ts +++ b/src/commands/cmds/trim.ts @@ -11,17 +11,20 @@ // // Linie → wird gekürzt/aufgeteilt; Polylinie → der getroffene Abschnitt fällt // raus (kann die Polylinie in Stücke teilen). Reine Geometrie liegt im Kernel -// (`trimPolyline`); hier nur Treffer-Bestimmung, Drawing2D ↔ {pts,closed} und der -// Commit. Wände sind ausgenommen (nur Drawing2D). +// (`trimPolylineWithBulge`, auch für reine Geraden-Ziele — s. Kopfkommentar +// bei `trimCurve`); hier nur Treffer-Bestimmung, Drawing2D ↔ {pts,closed, +// bulge} und der Commit. Wände sind ausgenommen (nur Drawing2D). Sowohl +// Ziel-Kurve als auch Schneider dürfen Bogen-Segmente (bulge) tragen. // // Bezeichner englisch, Kommentare/UI deutsch (CONVENTIONS.md). import type { Drawing2D, Drawing2DGeom } from "../../model/types"; +import { bulgeArcPoints, hasRealBulge } from "../../geometry/bulge"; import { uniqueId } from "../../tools/types"; import { pointSegmentDistance, polylineEdges, - trimPolyline, + trimPolylineWithBulge, vecEqual, } from "../../geometry/kernel2d"; import type { @@ -40,12 +43,14 @@ const HIT_TOL = 0.25; // Modell-Meter: Pick-Toleranz für die Kurvenwahl interface Curve { pts: Vec2[]; closed: boolean; + /** Bogen-Segmente (DXF-bulge, s. `geometry/bulge.ts`) — nur bei polyline. */ + bulge?: number[]; } -/** Wandelt eine trim-fähige 2D-Form in eine Punktliste (+closed) oder null. */ +/** Wandelt eine trim-fähige 2D-Form in eine Punktliste (+closed[/bulge]) oder null. */ function geomToCurve(g: Drawing2DGeom): Curve | null { if (g.shape === "line") return { pts: [g.a, g.b], closed: false }; - if (g.shape === "polyline") return { pts: g.pts, closed: g.closed }; + if (g.shape === "polyline") return { pts: g.pts, closed: g.closed, bulge: g.bulge }; if (g.shape === "rect") { return { pts: [ @@ -57,16 +62,31 @@ function geomToCurve(g: Drawing2DGeom): Curve | null { closed: true, }; } - return null; // circle/arc/text: hier nicht trim-fähig (offener Punkt) + return null; // circle/arc/text: hier nicht trim-fähig } /** Ist diese Form trim-fähig (line/polyline/rect)? */ function isTrimmable(d: Drawing2D): boolean { - return ( - d.geom.shape === "line" || - d.geom.shape === "polyline" || - d.geom.shape === "rect" - ); + const g = d.geom; + return g.shape === "line" || g.shape === "polyline" || g.shape === "rect"; +} + +/** + * Kanten für Klick-Trefftests: bei Bogen-Segmenten (bulge) wird die Kurve zu + * Geradenstücken tesselliert, damit der Trefftest entlang der TATSÄCHLICHEN + * (runden) Kontur funktioniert statt entlang der geraden Sehne — s. gleiches + * Vorgehen in offset.ts (`curveHitEdges`). + */ +function curveHitEdges(curve: Curve): [Vec2, Vec2][] { + if (!hasRealBulge(curve.bulge)) return polylineEdges(curve.pts, curve.closed); + const n = curve.pts.length; + const edgeCount = curve.closed ? n : n - 1; + const chain: Vec2[] = [curve.pts[0]]; + for (let i = 0; i < edgeCount; i++) { + const seg = bulgeArcPoints(curve.pts[i], curve.pts[(i + 1) % n], curve.bulge?.[i]); + chain.push(...seg.slice(1)); + } + return polylineEdges(chain, false); } /** Nächstes trim-fähiges Drawing2D der Ebene zum Klickpunkt (innerhalb Toleranz). */ @@ -82,7 +102,7 @@ function pickCurveAt( if (!isTrimmable(d)) continue; const curve = geomToCurve(d.geom); if (!curve) continue; - for (const [a, b] of polylineEdges(curve.pts, curve.closed)) { + for (const [a, b] of curveHitEdges(curve)) { const dd = pointSegmentDistance(pt, a, b); if (dd < bestD) { bestD = dd; @@ -93,7 +113,11 @@ function pickCurveAt( return best; } -/** Alle anderen trim-fähigen Drawing2D der Ebene als Cutter-Kurven. */ +/** + * Alle anderen trim-fähigen Drawing2D der Ebene als Cutter-Kurven — Bogen- + * Segmente (bulge) sind als Schneider zugelassen (`trimPolylineWithBulge` + * schneidet Kreis↔Gerade UND Kreis↔Kreis, s. `edgeIntersectTs`). + */ function cuttersFor( project: Project, levelId: string, @@ -119,17 +143,33 @@ function sameChain(a: { pts: Vec2[]; closed: boolean }, b: Curve): boolean { } /** Eine getrimmte Rest-Kette als passende Drawing2D-Geometrie. */ -function chainToGeom(chain: { pts: Vec2[]; closed: boolean }): Drawing2DGeom { - if (chain.pts.length === 2 && !chain.closed) { +function chainToGeom(chain: { pts: Vec2[]; closed: boolean; bulge?: number[] }): Drawing2DGeom { + if (chain.pts.length === 2 && !chain.closed && !hasRealBulge(chain.bulge)) { return { shape: "line", a: chain.pts[0], b: chain.pts[1] }; } - return { shape: "polyline", pts: chain.pts, closed: chain.closed }; + const geom: Drawing2DGeom = { shape: "polyline", pts: chain.pts, closed: chain.closed }; + if (hasRealBulge(chain.bulge)) geom.bulge = chain.bulge; + return geom; } /** * Wendet einen Trim auf das Projekt an: ersetzt das getroffene Element durch * seine Rest-Ketten (Attribute geerbt). Bleibt nichts übrig, fällt es weg. */ +/** + * Trimmt eine Kurve gegen ihre Schneider (bulge-erhaltend). Läuft IMMER über + * `trimPolylineWithBulge` — sie ist eine echte Obermenge von `trimPolyline` + * (Gerade-only ist der Sonderfall bulge=undefined) und wird jetzt auch für + * reine Geraden-Ziele gebraucht, sobald ein Bogen-CUTTER im Spiel ist. + */ +function trimCurve( + curve: Curve, + cutters: { pts: Vec2[]; closed: boolean; bulge?: number[] }[], + pick: Vec2, +): { pts: Vec2[]; closed: boolean; bulge?: number[] }[] { + return trimPolylineWithBulge(curve.pts, curve.bulge, curve.closed, cutters, pick); +} + function applyTrim( p: Project, target: Drawing2D, @@ -140,8 +180,9 @@ function applyTrim( const cutters = cuttersFor(p, target.levelId, target.id).map((c) => ({ pts: c.pts, closed: c.closed, + bulge: c.bulge, })); - const rest = trimPolyline(curve.pts, curve.closed, cutters, pick); + const rest = trimCurve(curve, cutters, pick); // Echtes No-op: genau eine Kette, identisch (gleiche Punkte) zur Quelle → // nichts wurde weggeschnitten (kein Schnitt mit Cuttern). if (rest.length === 1 && sameChain(rest[0], curve)) return p; @@ -152,7 +193,7 @@ function applyTrim( return { ...p, drawings2d: [...others, ...replacements] }; } -/** Vorschau-Formen der NACH dem Trim verbleibenden Ketten (für den Draft). */ +/** Vorschau-Formen der NACH dem Trim verbleibenden Ketten (für den Draft — tesselliert, s. `DraftShape`). */ function trimPreview( project: Project, target: Drawing2D, @@ -163,15 +204,23 @@ function trimPreview( const cutters = cuttersFor(project, target.levelId, target.id).map((c) => ({ pts: c.pts, closed: c.closed, + bulge: c.bulge, })); - const rest = trimPolyline(curve.pts, curve.closed, cutters, pick); + const rest = trimCurve(curve, cutters, pick); const out: DraftShape[] = []; for (const c of rest) { if (c.pts.length < 2) continue; - if (c.pts.length === 2 && !c.closed) { - out.push({ kind: "line", a: c.pts[0], b: c.pts[1] }); + const pts = hasRealBulge(c.bulge) + ? curveHitEdges({ pts: c.pts, closed: c.closed, bulge: c.bulge }).reduce((acc, [a, b], i) => { + if (i === 0) acc.push(a); + acc.push(b); + return acc; + }, []) + : c.pts; + if (pts.length === 2 && !c.closed) { + out.push({ kind: "line", a: pts[0], b: pts[1] }); } else { - out.push({ kind: "poly", pts: c.pts, closed: c.closed }); + out.push({ kind: "poly", pts, closed: c.closed }); } } return out; diff --git a/src/commands/cmds/xline.test.ts b/src/commands/cmds/xline.test.ts new file mode 100644 index 00000000..87d1db7b --- /dev/null +++ b/src/commands/cmds/xline.test.ts @@ -0,0 +1,86 @@ +/** + * `xlineCommand` — zwei Punkte → `Drawing2DGeom["xline"]` (nur a/b + * gespeichert; die „unendliche" Verlängerung passiert beim Rendern). + */ + +import { describe, it, expect } from "vitest"; +import { xlineCommand } from "./xline"; +import type { CommandContext, Project } from "../types"; + +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: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + }; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +describe("xlineCommand", () => { + it("zwei Punkte → shape:'xline' mit exakt a/b (keine Verlängerung im Modell)", () => { + const p = project(); + const ctx = makeCtx(p); + const [afterStart] = xlineCommand.onInput( + xlineCommand.init(), + { kind: "point", point: { x: 0, y: 0 } }, + ctx, + ); + const [, result] = xlineCommand.onInput( + afterStart, + { kind: "point", point: { x: 4, y: 0 } }, + ctx, + ); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + expect(next.drawings2d.length).toBe(1); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("xline"); + if (g.shape === "xline") { + expect(g.a).toEqual({ x: 0, y: 0 }); + expect(g.b).toEqual({ x: 4, y: 0 }); + } + }); + + it("Null-Strecke (gleicher Punkt) committet nichts", () => { + const p = project(); + const ctx = makeCtx(p); + const [afterStart] = xlineCommand.onInput( + xlineCommand.init(), + { kind: "point", point: { x: 1, y: 1 } }, + ctx, + ); + const [, result] = xlineCommand.onInput( + afterStart, + { kind: "point", point: { x: 1, y: 1 } }, + ctx, + ); + expect(result.commit).toBeUndefined(); + expect(result.done).toBe(true); + }); +}); diff --git a/src/commands/cmds/xline.ts b/src/commands/cmds/xline.ts new file mode 100644 index 00000000..3f415185 --- /dev/null +++ b/src/commands/cmds/xline.ts @@ -0,0 +1,136 @@ +// Konstruktionslinie (Hilfslinie) — wie `line`, aber committet `shape:"xline"` +// (unendliche Ausrichtungslinie, s. `Drawing2DGeom["xline"]`). Zwei Punkte +// legen nur die Richtung fest; Rendering/Snapping verlängern weit darüber +// hinaus. Schritte: +// 1) „Startpunkt:" → Punkt +// 2) „Richtungspunkt:" → Punkt (Tab-Felder Länge/Winkel wie bei Line) → commit + +import type { Drawing2D } from "../../model/types"; +import { segmentHud, uniqueId } from "../../tools/types"; +import type { + Command, + CommandContext, + CommandField, + CommandResult, + CommandState, + DraftShape, + Project, + ToolDraft, + Vec2, +} from "../types"; + +const EPS = 1e-6; +const DEG = Math.PI / 180; +const XLINE_PREVIEW_EXT_M = 30; // nur für die Live-Vorschau — echte Länge kommt aus generatePlan +const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); +const segAngleDeg = (a: Vec2, b: Vec2): number => + (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI; + +const LINE_FIELDS: CommandField[] = [ + { id: "length", labelKey: "cmd.field.length" }, + { id: "angle", labelKey: "cmd.field.angle" }, +]; + +function lineEndFromFields(a: Vec2, locks: Record, cursor: Vec2 | null): Vec2 { + const ref = cursor ?? a; + const length = "length" in locks ? locks.length : segLen(a, ref); + const angleDeg = "angle" in locks ? locks.angle : segAngleDeg(a, ref); + const ang = angleDeg * DEG; + return { x: a.x + Math.cos(ang) * length, y: a.y + Math.sin(ang) * length }; +} + +interface XlineIdle extends CommandState { + phase: "start"; +} +interface XlineDrawing extends CommandState { + phase: "end"; + a: Vec2; + cursor: Vec2 | null; +} +type XlineState = XlineIdle | XlineDrawing; + +/** Vorschau: kurzes Segment PLUS Verlängerung in beide Richtungen (deutet „unendlich" an). */ +function xlineDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { + const preview: DraftShape[] = []; + if (cursor && segLen(a, cursor) >= EPS) { + const ux = (cursor.x - a.x) / segLen(a, cursor); + const uy = (cursor.y - a.y) / segLen(a, cursor); + preview.push({ + kind: "line", + a: { x: a.x - ux * XLINE_PREVIEW_EXT_M, y: a.y - uy * XLINE_PREVIEW_EXT_M }, + b: { x: cursor.x + ux * XLINE_PREVIEW_EXT_M, y: cursor.y + uy * XLINE_PREVIEW_EXT_M }, + }); + } + const draft: ToolDraft = { preview, vertices: [a] }; + if (cursor && segLen(a, cursor) >= EPS) draft.hud = segmentHud(a, cursor); + return draft; +} + +function appendXline(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project { + const d: Drawing2D = { + id: uniqueId("dr2d"), + type: "drawing2d", + levelId: ctx.level.id, + categoryCode: ctx.defaultCategoryCode, + geom: { shape: "xline", a, b }, + }; + return { ...p, drawings2d: [...p.drawings2d, d] }; +} + +export const xlineCommand: Command = { + name: "xline", + labelKey: "cmd.xline.label", + prompt: (s) => ((s as XlineState).phase === "end" ? "cmd.xline.end" : "cmd.xline.start"), + accepts: () => ["point", "number"], + options: () => [], + init: (): XlineIdle => ({ phase: "start", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as XlineState; + if (input.kind !== "point") return [s, { draft: s.phase === "end" ? xlineDraft(s.a, s.cursor) : null }]; + const pt = input.point; + if (s.phase !== "end") { + const next: XlineDrawing = { phase: "end", a: pt, cursor: pt, lastPoint: pt }; + return [next, { draft: xlineDraft(pt, pt) }]; + } + if (segLen(s.a, pt) < EPS) { + return [{ phase: "start", lastPoint: null }, { draft: null, done: true }]; + } + const a = s.a; + return [ + { phase: "start", lastPoint: null }, + { draft: null, done: true, commit: (p) => appendXline(p, a, pt, ctx) }, + ]; + }, + + onMove: (state, point): [CommandState, CommandResult] => { + const s = state as XlineState; + if (s.phase !== "end") return [s, { draft: null }]; + const next: XlineDrawing = { ...s, cursor: point }; + return [next, { draft: xlineDraft(s.a, point) }]; + }, + + onConfirm: (): [CommandState, CommandResult] => [ + { phase: "start", lastPoint: null }, + { draft: null, done: true }, + ], + onCancel: (): [CommandState, CommandResult] => [ + { phase: "start", lastPoint: null }, + { draft: null, done: true }, + ], + + fields: (state) => ((state as XlineState).phase === "end" ? LINE_FIELDS : []), + pointFromFields: (state, locks, cursor) => { + const s = state as XlineState; + if (s.phase !== "end") return null; + return lineEndFromFields(s.a, locks, cursor); + }, + fieldValues: (state, _locks, cursor): Record => { + const s = state as XlineState; + if (s.phase !== "end" || !cursor) return {}; + return { + length: segLen(s.a, cursor), + angle: ((segAngleDeg(s.a, cursor) % 360) + 360) % 360, + }; + }, +}; diff --git a/src/commands/registry.ts b/src/commands/registry.ts index 055e4311..d90d110b 100644 --- a/src/commands/registry.ts +++ b/src/commands/registry.ts @@ -6,6 +6,7 @@ import type { Command } from "./types"; import { lineCommand } from "./cmds/line"; import { polylineCommand } from "./cmds/polyline"; +import { xlineCommand } from "./cmds/xline"; import { wallCommand } from "./cmds/wall"; import { ceilingCommand } from "./cmds/ceiling"; import { openingCommand, fensterCommand, tuerCommand } from "./cmds/opening"; @@ -18,11 +19,14 @@ import { rectCommand } from "./cmds/rect"; import { circleCommand } from "./cmds/circle"; import { arcCommand } from "./cmds/arc"; import { ellipseCommand } from "./cmds/ellipse"; +import { polygonCommand } from "./cmds/polygon"; import { splineCommand } from "./cmds/spline"; import { bezierCommand } from "./cmds/bezier"; import { dimensionCommand } from "./cmds/dimension"; import { koteCommand } from "./cmds/kote"; import { textCommand } from "./cmds/text"; +import { leaderCommand } from "./cmds/leader"; +import { textpathCommand } from "./cmds/textpath"; import { textboxCommand } from "./cmds/textbox"; import { moveCommand } from "./cmds/move"; import { mirrorCommand } from "./cmds/mirror"; @@ -41,6 +45,8 @@ import { terrainCommand } from "./cmds/terrain"; import { measureCommand } from "./cmds/measure"; import { sectionLineCommand, viewLineCommand } from "./cmds/sectionline"; import { georefCommand } from "./cmds/georef"; +import { blockCommand } from "./cmds/block"; +import { defblockCommand } from "./cmds/defblock"; /** Alle bekannten Befehle, Schlüssel = Befehlsname (lowercase). */ export const COMMANDS: Record = { @@ -56,15 +62,19 @@ export const COMMANDS: Record = { room: roomCommand, line: lineCommand, polyline: polylineCommand, + xline: xlineCommand, rect: rectCommand, circle: circleCommand, arc: arcCommand, ellipse: ellipseCommand, + polygon: polygonCommand, spline: splineCommand, bezier: bezierCommand, dimension: dimensionCommand, kote: koteCommand, text: textCommand, + leader: leaderCommand, + textpath: textpathCommand, textbox: textboxCommand, move: moveCommand, mirror: mirrorCommand, @@ -84,6 +94,8 @@ export const COMMANDS: Record = { sectionline: sectionLineCommand, viewline: viewLineCommand, georef: georefCommand, + block: blockCommand, + defblock: defblockCommand, }; /** @@ -112,11 +124,20 @@ export const ALIASES: Record = { rm: "room", l: "line", pl: "polyline", + xl: "xline", + hilfslinie: "xline", + konstruktionslinie: "xline", + bl: "block", + symbol: "block", + db: "defblock", + blockdef: "defblock", rec: "rect", c: "circle", a: "arc", bogen: "arc", el: "ellipse", + vg: "polygon", + vieleck: "polygon", sp: "spline", dim: "dimension", bemassung: "dimension", @@ -126,6 +147,10 @@ export const ALIASES: Record = { tx: "text", txt: "text", beschriftung: "text", + ld: "leader", + vorführer: "leader", + txp: "textpath", + pfadtext: "textpath", m: "move", s: "mirror", spiegeln: "mirror", diff --git a/src/commands/types.ts b/src/commands/types.ts index 6e28cb58..52772a29 100644 --- a/src/commands/types.ts +++ b/src/commands/types.ts @@ -15,7 +15,6 @@ import type { DrawingLevel } from "../model/types"; import type { SnapResult, ToolDraft } from "../tools/types"; export type { DraftShape, SnapResult, ToolDraft } from "../tools/types"; -export { segmentHud, angleDegOf } from "../tools/types"; // ── Eingabe-Arten ──────────────────────────────────────────────────────────── diff --git a/src/editors/elementClipboard.test.ts b/src/editors/elementClipboard.test.ts new file mode 100644 index 00000000..dce9e0ea --- /dev/null +++ b/src/editors/elementClipboard.test.ts @@ -0,0 +1,145 @@ +/** + * `elementClipboard` — Kopieren/Einfügen für ALLE Bauteil-Arten (Wand/Decke/ + * Dach/Öffnung/Treppe/Raum/Extrusion/Stütze), nicht nur 2D-Zeichenelemente. + * Deckt insbesondere die Öffnung↔Wand-Paarkopplung ab (s. Kopfkommentar in + * `elementClipboard.ts`). + */ +import { describe, it, expect } from "vitest"; +import { collectElementClipboard, pasteElementClipboard, isClipboardEmpty } from "./elementClipboard"; +import type { ElementSelectionIds } from "./elementClipboard"; +import type { Project, Wall, Opening, Ceiling } from "../model/types"; + +function emptySel(): ElementSelectionIds { + return { + wallIds: [], + drawingIds: [], + ceilingIds: [], + roofIds: [], + openingIds: [], + stairIds: [], + roomIds: [], + extrudedSolidIds: [], + columnIds: [], + }; +} + +function wall(id: string, floorId = "eg"): Wall { + return { + id, + type: "wall", + floorId, + categoryCode: "20", + start: { x: 0, y: 0 }, + end: { x: 5, y: 0 }, + wallTypeId: "wt1", + height: 2.6, + }; +} + +function opening(id: string, hostWallId: string): Opening { + return { + id, + type: "opening", + hostWallId, + categoryCode: "21", + kind: "window", + position: 1, + width: 1.2, + height: 1.2, + sillHeight: 0.9, + }; +} + +function ceiling(id: string, floorId = "eg"): Ceiling { + return { + id, + type: "ceiling", + floorId, + categoryCode: "30", + outline: [{ x: 0, y: 0 }, { x: 5, y: 0 }, { x: 5, y: 5 }, { x: 0, y: 5 }], + wallTypeId: "wt1", + thickness: 0.24, + }; +} + +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 }, + { id: "og", name: "OG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 2.6 }, + ], + layers: [{ code: "20", name: "Wand", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [wall("w1")], + doors: [], + openings: [opening("o1", "w1")], + ceilings: [ceiling("c1")], + stairs: [], + rooms: [], + context: [], + drawings2d: [], + }; +} + +describe("collectElementClipboard", () => { + it("liefert null, wenn nichts gewählt ist", () => { + const p = project(); + expect(collectElementClipboard(p, emptySel())).toBeNull(); + }); + + it("kopiert eine gewählte Wand samt ihrer Öffnung automatisch mit (Kaskade)", () => { + const p = project(); + const sel = { ...emptySel(), wallIds: ["w1"] }; + const clip = collectElementClipboard(p, sel)!; + expect(clip.walls.length).toBe(1); + expect(clip.openings.length).toBe(1); + expect(clip.openings[0].hostWallId).toBe("w1"); + }); + + it("überspringt eine Öffnung, deren Wirtswand NICHT mitkopiert wird", () => { + const p = project(); + const sel = { ...emptySel(), openingIds: ["o1"] }; // nur Öffnung, nicht die Wand + const clip = collectElementClipboard(p, sel); + // Ohne Wirtswand: leere Zwischenablage (isClipboardEmpty → null). + expect(clip).toBeNull(); + }); + + it("kopiert eine gewählte Decke unabhängig von Wänden", () => { + const p = project(); + const sel = { ...emptySel(), ceilingIds: ["c1"] }; + const clip = collectElementClipboard(p, sel)!; + expect(clip.ceilings.length).toBe(1); + expect(isClipboardEmpty(clip)).toBe(false); + }); +}); + +describe("pasteElementClipboard", () => { + it("fügt Wand + Öffnung mit NEUEN, verknüpften IDs auf dem aktiven Geschoss ein", () => { + const p = project(); + const clip = collectElementClipboard(p, { ...emptySel(), wallIds: ["w1"] })!; + const { project: next, pastedIds } = pasteElementClipboard(p, clip, "og"); + expect(next.walls.length).toBe(2); + expect(next.openings!.length).toBe(2); + const newWall = next.walls.find((w) => w.id === pastedIds.wallIds[0])!; + expect(newWall.floorId).toBe("og"); + expect(newWall.id).not.toBe("w1"); + const newOpening = next.openings!.find((o) => o.id === pastedIds.openingIds[0])!; + expect(newOpening.hostWallId).toBe(newWall.id); // umgehängt, nicht mehr "w1" + // Koordinaten bleiben identisch (Einfügen „in place", wie beim 2D-Verhalten). + expect(newWall.start).toEqual({ x: 0, y: 0 }); + expect(newWall.end).toEqual({ x: 5, y: 0 }); + }); + + it("Originale bleiben unverändert (immutabel)", () => { + const p = project(); + const clip = collectElementClipboard(p, { ...emptySel(), wallIds: ["w1"] })!; + pasteElementClipboard(p, clip, "og"); + expect(p.walls.length).toBe(1); + expect(p.walls[0].id).toBe("w1"); + }); +}); diff --git a/src/editors/elementClipboard.ts b/src/editors/elementClipboard.ts new file mode 100644 index 00000000..8e141eac --- /dev/null +++ b/src/editors/elementClipboard.ts @@ -0,0 +1,236 @@ +// Kopieren/Einfügen (Ctrl/Cmd+C/V) für ALLE Bauteil-Arten, nicht nur 2D- +// Zeichenelemente (die das schon länger konnten, s. `useKeyboardShortcuts.ts`). +// Reine Funktionen; die Tastatur-Verdrahtung bleibt in `useKeyboardShortcuts.ts` +// (`useElementClipboardShortcut`), analog zum bisherigen 2D-only-Mechanismus. +// +// Einfügen legt Klone mit NEUEN IDs auf dem AKTIVEN Geschoss an, an denselben +// Modell-Koordinaten wie beim Kopieren (Nutzer verschiebt danach bei Bedarf) — +// exakt dasselbe Verhalten wie das bestehende 2D-Kopieren. +// +// Öffnungen (Fenster/Türen) sind an eine Wand gebunden (`hostWallId`) — eine +// Öffnung ohne gültige Wirtswand ist im Modell nicht vorgesehen (dieselbe +// Invariante wie beim Löschen einer Zeichnungsebene, s. `projectSlice.ts` +// `deleteLevel`). Eine Öffnung wird daher NUR mitkopiert, wenn ihre Wirtswand +// ebenfalls Teil der Kopie ist (Paar-Kopie, `hostWallId` wird auf die neue +// Wand-ID umgehängt); eine isoliert gewählte Öffnung ohne ihre Wand hat kein +// sinnvolles Einfüge-Ziel und wird beim Kopieren stillschweigend übersprungen +// — bewusste, dokumentierte Scope-Entscheidung statt eines rätselhaften No-ops. +// +// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). + +import type { + Ceiling, + Column, + Drawing2D, + ExtrudedSolid, + Opening, + Project, + Roof, + Room, + Stair, + Wall, +} from "../model/types"; +import { uniqueId } from "../tools/types"; + +/** Auswahl-IDs je Bauteil-Art, wie sie die 9 Auswahl-Kanäle des Stores liefern. */ +export interface ElementSelectionIds { + wallIds: string[]; + drawingIds: string[]; + ceilingIds: string[]; + roofIds: string[]; + openingIds: string[]; + stairIds: string[]; + roomIds: string[]; + extrudedSolidIds: string[]; + columnIds: string[]; +} + +/** Tiefe Kopie der gewählten Elemente über alle Bauteil-Arten hinweg. */ +export interface ElementClipboard { + walls: Wall[]; + drawings: Drawing2D[]; + ceilings: Ceiling[]; + roofs: Roof[]; + openings: Opening[]; + stairs: Stair[]; + rooms: Room[]; + extrudedSolids: ExtrudedSolid[]; + columns: Column[]; +} + +const EMPTY_CLIPBOARD: ElementClipboard = { + walls: [], + drawings: [], + ceilings: [], + roofs: [], + openings: [], + stairs: [], + rooms: [], + extrudedSolids: [], + columns: [], +}; + +/** Ist die Zwischenablage leer (nichts zum Einfügen)? */ +export function isClipboardEmpty(c: ElementClipboard): boolean { + return ( + c.walls.length === 0 && + c.drawings.length === 0 && + c.ceilings.length === 0 && + c.roofs.length === 0 && + c.openings.length === 0 && + c.stairs.length === 0 && + c.rooms.length === 0 && + c.extrudedSolids.length === 0 && + c.columns.length === 0 + ); +} + +/** + * Sammelt die gewählten Elemente (über alle 9 Auswahl-Kanäle) tief kopiert in + * eine Zwischenablage. `null`, wenn NICHTS gewählt ist (Aufrufer lässt dann + * das native Browser-Copy laufen statt `preventDefault`, s. bisheriges + * 2D-Verhalten). + */ +export function collectElementClipboard( + project: Project, + sel: ElementSelectionIds, +): ElementClipboard | null { + const wallIds = new Set(sel.wallIds); + const walls = project.walls.filter((w) => wallIds.has(w.id)); + const drawings = project.drawings2d.filter((d) => sel.drawingIds.includes(d.id)); + const ceilingIds = new Set(sel.ceilingIds); + const ceilings = (project.ceilings ?? []).filter((c) => ceilingIds.has(c.id)); + const roofIds = new Set(sel.roofIds); + const roofs = (project.roofs ?? []).filter((r) => roofIds.has(r.id)); + // Öffnungen: automatisch mitkopiert, wenn ihre Wirtswand mitkopiert wird + // (kaskadiert wie beim Löschen einer Wand/Ebene, unabhängig davon, ob die + // Öffnung selbst zusätzlich explizit markiert war, s. Kopfkommentar). + const openings = (project.openings ?? []).filter((o) => wallIds.has(o.hostWallId)); + const stairIds = new Set(sel.stairIds); + const stairs = (project.stairs ?? []).filter((s) => stairIds.has(s.id)); + const roomIds = new Set(sel.roomIds); + const rooms = (project.rooms ?? []).filter((r) => roomIds.has(r.id)); + const extrudedSolidIds = new Set(sel.extrudedSolidIds); + const extrudedSolids = (project.extrudedSolids ?? []).filter((s) => extrudedSolidIds.has(s.id)); + const columnIds = new Set(sel.columnIds); + const columns = (project.columns ?? []).filter((c) => columnIds.has(c.id)); + + const clip: ElementClipboard = { + walls: walls.map((w) => structuredClone(w)), + drawings: drawings.map((d) => structuredClone(d)), + ceilings: ceilings.map((c) => structuredClone(c)), + roofs: roofs.map((r) => structuredClone(r)), + openings: openings.map((o) => structuredClone(o)), + stairs: stairs.map((s) => structuredClone(s)), + rooms: rooms.map((r) => structuredClone(r)), + extrudedSolids: extrudedSolids.map((s) => structuredClone(s)), + columns: columns.map((c) => structuredClone(c)), + }; + return isClipboardEmpty(clip) ? null : clip; +} + +/** Neue IDs je Bauteil-Art (für die Nachauswahl nach dem Einfügen). */ +export interface PastedIds { + wallIds: string[]; + drawingIds: string[]; + ceilingIds: string[]; + roofIds: string[]; + openingIds: string[]; + stairIds: string[]; + roomIds: string[]; + extrudedSolidIds: string[]; + columnIds: string[]; +} + +/** + * Fügt eine Zwischenablage ins Projekt ein: Klone mit neuen IDs auf dem + * AKTIVEN Geschoss (`activeLevelId`), an denselben Modell-Koordinaten. Liefert + * das neue Projekt + die neuen IDs (für die Nachauswahl). + */ +export function pasteElementClipboard( + project: Project, + clip: ElementClipboard, + activeLevelId: string, +): { project: Project; pastedIds: PastedIds } { + const wallIdMap = new Map(); + const newWalls: Wall[] = clip.walls.map((w) => { + const id = uniqueId("W"); + wallIdMap.set(w.id, id); + return { ...w, id, floorId: activeLevelId }; + }); + const newDrawings: Drawing2D[] = clip.drawings.map((d) => ({ + ...d, + id: uniqueId("dr2d"), + levelId: activeLevelId, + })); + const newCeilings: Ceiling[] = clip.ceilings.map((c) => ({ + ...c, + id: uniqueId("C"), + floorId: activeLevelId, + })); + const newRoofs: Roof[] = clip.roofs.map((r) => ({ + ...r, + id: uniqueId("RF"), + floorId: activeLevelId, + })); + // Nur Öffnungen mit einer erfolgreich mitkopierten Wirtswand ergeben eine + // gültige neue Öffnung (sollte durch `collectElementClipboard` immer + // gegeben sein — Map-Miss defensiv übersprungen statt eine kaputte + // Öffnung ohne Wirt zu erzeugen). + const newOpenings: Opening[] = []; + for (const o of clip.openings) { + const hostWallId = wallIdMap.get(o.hostWallId); + if (!hostWallId) continue; + newOpenings.push({ ...o, id: uniqueId("O"), hostWallId }); + } + const newStairs: Stair[] = clip.stairs.map((s) => ({ + ...s, + id: uniqueId("ST"), + floorId: activeLevelId, + })); + const newRooms: Room[] = clip.rooms.map((r) => ({ + ...r, + id: uniqueId("RM"), + floorId: activeLevelId, + })); + const newExtrudedSolids: ExtrudedSolid[] = clip.extrudedSolids.map((s) => ({ + ...s, + id: uniqueId("extrude"), + levelId: activeLevelId, + })); + const newColumns: Column[] = clip.columns.map((c) => ({ + ...c, + id: uniqueId("column"), + floorId: activeLevelId, + })); + + const next: Project = { + ...project, + walls: [...project.walls, ...newWalls], + drawings2d: [...project.drawings2d, ...newDrawings], + ceilings: [...(project.ceilings ?? []), ...newCeilings], + roofs: [...(project.roofs ?? []), ...newRoofs], + openings: [...(project.openings ?? []), ...newOpenings], + stairs: [...(project.stairs ?? []), ...newStairs], + rooms: [...(project.rooms ?? []), ...newRooms], + extrudedSolids: [...(project.extrudedSolids ?? []), ...newExtrudedSolids], + columns: [...(project.columns ?? []), ...newColumns], + }; + + return { + project: next, + pastedIds: { + wallIds: newWalls.map((w) => w.id), + drawingIds: newDrawings.map((d) => d.id), + ceilingIds: newCeilings.map((c) => c.id), + roofIds: newRoofs.map((r) => r.id), + openingIds: newOpenings.map((o) => o.id), + stairIds: newStairs.map((s) => s.id), + roomIds: newRooms.map((r) => r.id), + extrudedSolidIds: newExtrudedSolids.map((s) => s.id), + columnIds: newColumns.map((c) => c.id), + }, + }; +} + +export { EMPTY_CLIPBOARD }; diff --git a/src/editors/splitJoin.test.ts b/src/editors/splitJoin.test.ts new file mode 100644 index 00000000..32f5d059 --- /dev/null +++ b/src/editors/splitJoin.test.ts @@ -0,0 +1,95 @@ +/** + * `joinDrawings` — Bogen-Segmente (bulge) müssen beim Verbinden erhalten + * bleiben (nicht mehr stillschweigend zu Geraden entarten, s. Kopfkommentar + * bei `toPolyFormAllowBulge`). + */ +import { describe, it, expect } from "vitest"; +import { cutSegment, joinDrawings, nearestEdgeIndex } from "./splitJoin"; +import type { Drawing2D } from "../model/types"; + +function poly(id: string, pts: { x: number; y: number }[], bulge?: number[]): Drawing2D { + return { + id, + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "polyline", pts, closed: false, ...(bulge ? { bulge } : {}) }, + }; +} + +describe("joinDrawings — bulge-Erhalt", () => { + it("zwei offene Ketten (eine mit Bogen) werden verbunden, der Bogen bleibt erhalten", () => { + const a = poly("a", [{ x: -1, y: 0 }, { x: 1, y: 0 }], [1]); // Halbkreis + const b = poly("b", [{ x: 1, y: 0 }, { x: 3, y: 0 }]); // gerade, schliesst an a's Ende an + const out = joinDrawings([a, b]); + expect(out.length).toBe(1); + const g = out[0].geom; + expect(g.shape).toBe("polyline"); + if (g.shape !== "polyline") return; + expect(g.pts.length).toBe(3); + expect(g.bulge?.[0]).toBeCloseTo(1, 6); // erste Kante (a's Bogen) unverändert + expect(g.bulge?.[1] ?? 0).toBeCloseTo(0, 6); // zweite Kante (b, gerade) + }); + + it("wird eine bulge-Kette beim Verbinden umgedreht, kehrt sich das Vorzeichen um", () => { + // b's Startpunkt trifft a's Startpunkt → b muss umgedreht werden, um anzuschliessen. + const a = poly("a", [{ x: -1, y: 0 }, { x: 1, y: 0 }], [1]); + const b = poly("b", [{ x: -1, y: 0 }, { x: -3, y: 0 }]); + const out = joinDrawings([a, b]); + expect(out.length).toBe(1); + const g = out[0].geom; + if (g.shape !== "polyline") return; + // Kette läuft jetzt b(umgedreht) → a: [-3,0] → [-1,0] → [1,0]. + expect(g.pts[0]).toEqual({ x: -3, y: 0 }); + expect(g.pts[2]).toEqual({ x: 1, y: 0 }); + expect(g.bulge?.[0] ?? 0).toBeCloseTo(0, 6); // b's (gerade) Kante zuerst + expect(g.bulge?.[1]).toBeCloseTo(1, 6); // a's Bogen unverändert (nicht umgedreht) + }); + + it("nicht-verbindbare Elemente (kein gemeinsamer Endpunkt) bleiben unverändert", () => { + const a = poly("a", [{ x: 0, y: 0 }, { x: 1, y: 0 }], [0.5]); + const b = poly("b", [{ x: 10, y: 10 }, { x: 11, y: 10 }]); + const out = joinDrawings([a, b]); + expect(out.length).toBe(2); + // Neue IDs (inherit() vergibt immer frische IDs) — über den bulge-Wert + // finden statt über die ursprüngliche ID. + const withBulge = out.find((d) => d.geom.shape === "polyline" && d.geom.bulge); + expect(withBulge).toBeDefined(); + if (withBulge?.geom.shape === "polyline") expect(withBulge.geom.bulge?.[0]).toBeCloseTo(0.5, 6); + }); +}); + +describe("cutSegment / nearestEdgeIndex — bulge-Erhalt", () => { + it("Segment-Löschen an einer GERADEN Kante lässt den Bogen der Nachbarkante unangetastet (offen)", () => { + // 4 Kanten: Bogen(0->1), gerade(1->2), gerade(2->3), gerade(3->4). Löscht Kante 1 + // (das längere, punktreichere Reststück rechts wird behalten, s. removeSegmentWithBulge). + const src = poly( + "a", + [{ x: -1, y: 0 }, { x: 1, y: 0 }, { x: 2, y: 0 }, { x: 3, y: 0 }, { x: 4, y: 0 }], + [1, 0, 0, 0], + ); + const out = cutSegment(src, 1); + expect(out).not.toBeNull(); + if (!out || out.geom.shape !== "polyline") return; + // Rechtes (längeres) Stück bleibt: [2,0] -> [3,0] -> [4,0], keine Kante mehr mit Bogen. + expect(out.geom.pts).toEqual([{ x: 2, y: 0 }, { x: 3, y: 0 }, { x: 4, y: 0 }]); + // fromPolyForm lässt das bulge-Feld ganz weg, wenn kein echter Bogen mehr übrig ist. + expect(out.geom.bulge).toBeUndefined(); + }); + + it("Segment-Löschen an der BOGEN-Kante selbst entfernt genau diesen Bogen", () => { + const src = poly("a", [{ x: -1, y: 0 }, { x: 1, y: 0 }, { x: 2, y: 0 }], [1, 0]); + const out = cutSegment(src, 0); + expect(out).not.toBeNull(); + if (!out || out.geom.shape !== "polyline") return; + expect(out.geom.pts).toEqual([{ x: 1, y: 0 }, { x: 2, y: 0 }]); + expect(out.geom.bulge?.[0] ?? 0).toBeCloseTo(0, 6); + }); + + it("nearestEdgeIndex trifft die Bogen-Kante auch, wenn der Klickpunkt neben der Sehne liegt (auf dem Bogen)", () => { + // Halbkreis von (-1,0) nach (1,0), bulge=1 -> Apex bei (0,1). + const src = poly("a", [{ x: -1, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 2 }], [1, 0]); + const idx = nearestEdgeIndex(src.geom, { x: 0, y: 0.95 }); + expect(idx).toBe(0); // Bogen-Kante, nicht die gerade Kante 1 + }); +}); diff --git a/src/editors/splitJoin.ts b/src/editors/splitJoin.ts index dae5958f..5e4d2788 100644 --- a/src/editors/splitJoin.ts +++ b/src/editors/splitJoin.ts @@ -7,18 +7,22 @@ import type { Drawing2D, Drawing2DGeom, Vec2 } from "../model/types"; import { - joinChains, + joinChainsWithBulge, removeSegment, + removeSegmentWithBulge, splitAtIntersections, splitClosedByChord, splitPolylineAtParam, vecEqual, } from "../geometry/kernel2d"; +import { bulgeArcPoints, hasRealBulge } from "../geometry/bulge"; /** Eine Polylinien-Darstellung eines Drawing2D (für die Kernel-Funktionen). */ export interface PolyForm { pts: Vec2[]; closed: boolean; + /** Bogen-Segmente (DXF-bulge, s. `geometry/bulge.ts`) — nur bei `toPolyFormAllowBulge`. */ + bulge?: number[]; } /** @@ -30,6 +34,11 @@ export function toPolyForm(geom: Drawing2DGeom): PolyForm | null { case "line": return { pts: [geom.a, geom.b], closed: false }; case "polyline": + // Bogen-Segmente (bulge) hier noch nicht unterstützt — Split/Segment- + // Löschen bauen pts komplett neu auf und würden bestehende Bögen + // stillschweigend zu Geraden entarten lassen, s. offset.ts. (Join hat + // eine eigene, bulge-erhaltende Variante, s. `toPolyFormAllowBulge`.) + if (hasRealBulge(geom.bulge)) return null; return { pts: geom.pts.slice(), closed: geom.closed }; case "rect": return { @@ -46,6 +55,16 @@ export function toPolyForm(geom: Drawing2DGeom): PolyForm | null { } } +/** + * Wie {@link toPolyForm}, aber lässt Bogen-Segmente (bulge) durch — nur für + * Join (`joinDrawings`), das die Kette per {@link joinChainsWithBulge} bulge- + * erhaltend verkettet statt sie geometrisch neu aufzubauen. + */ +function toPolyFormAllowBulge(geom: Drawing2DGeom): PolyForm | null { + if (geom.shape === "polyline") return { pts: geom.pts.slice(), closed: geom.closed, bulge: geom.bulge }; + return toPolyForm(geom); +} + /** * Baut aus einer Polylinien-Form die passende Drawing2D-Geometrie. Zwei Punkte + * offen → `line`; sonst `polyline` (geschlossen oder offen). Rechtecke werden @@ -53,10 +72,12 @@ export function toPolyForm(geom: Drawing2DGeom): PolyForm | null { */ export function fromPolyForm(form: PolyForm): Drawing2DGeom { const pts = form.pts; - if (pts.length === 2 && !form.closed) { + if (pts.length === 2 && !form.closed && !hasRealBulge(form.bulge)) { return { shape: "line", a: pts[0], b: pts[1] }; } - return { shape: "polyline", pts, closed: form.closed }; + const geom: Drawing2DGeom = { shape: "polyline", pts, closed: form.closed }; + if (hasRealBulge(form.bulge)) geom.bulge = form.bulge; + return geom; } let counter = 0; @@ -205,16 +226,16 @@ export function joinDrawings(srcs: Drawing2D[]): Drawing2D[] { const joinable: { form: PolyForm; src: Drawing2D }[] = []; const passthrough: Drawing2D[] = []; for (const d of srcs) { - const form = toPolyForm(d.geom); + const form = toPolyFormAllowBulge(d.geom); if (form) joinable.push({ form, src: d }); else passthrough.push(d); } if (joinable.length === 0) return srcs; - const chains = joinChains(joinable.map((j) => j.form)); + const chains = joinChainsWithBulge(joinable.map((j) => j.form)); const template = joinable[0].src; const joined = chains.map((c) => - inherit(template, fromPolyForm({ pts: c.pts, closed: c.closed })), + inherit(template, fromPolyForm({ pts: c.pts, closed: c.closed, bulge: c.bulge })), ); return [...joined, ...passthrough]; } @@ -223,12 +244,15 @@ export function joinDrawings(srcs: Drawing2D[]): Drawing2D[] { * Segment-Löschen (Schere): entfernt das Segment `edgeIndex` aus einem * Drawing2D. Geschlossene Form → offene Polylinie. Liefert das geänderte * Drawing2D, oder `null`, wenn weniger als 2 Punkte übrig blieben (Element - * komplett löschen) bzw. die Form nicht unterstützt wird. + * komplett löschen) bzw. die Form nicht unterstützt wird. Bogen-Segmente + * (bulge) bleiben dabei an ihrem Punktepaar erhalten (s. `removeSegmentWithBulge`). */ export function cutSegment(src: Drawing2D, edgeIndex: number): Drawing2D | null { - const form = toPolyForm(src.geom); + const form = toPolyFormAllowBulge(src.geom); if (!form) return src; // nicht unterstützte Form unverändert lassen - const res = removeSegment(form.pts, form.closed, edgeIndex); + const res = hasRealBulge(form.bulge) + ? removeSegmentWithBulge(form.pts, form.bulge!, form.closed, edgeIndex) + : removeSegment(form.pts, form.closed, edgeIndex); if (res.pts.length < 2) return null; return inherit(src, fromPolyForm(res)); } @@ -236,26 +260,28 @@ export function cutSegment(src: Drawing2D, edgeIndex: number): Drawing2D | null /** * Liefert den Index der Kante eines Drawing2D, die dem Modellpunkt `p` am * nächsten liegt (für Alt+Klick = Segment-Löschen). `null`, wenn die Form keine - * Kanten hat (circle/arc/text) oder zu wenige Punkte. Reuse: Polyline-Form + - * Punkt-Strecke-Distanz. + * Kanten hat (circle/arc/text) oder zu wenige Punkte. Bei Bogen-Segmenten + * (bulge) wird der Abstand gegen die tessellierte Bogenkurve gemessen (nicht + * gegen die Sehne), der Index bleibt aber der der ORIGINAL-Kante — wichtig, + * da `cutSegment` denselben Index gegen das bulge-Array auflöst. */ export function nearestEdgeIndex(geom: Drawing2DGeom, p: Vec2): number | null { - const form = toPolyForm(geom); + const form = toPolyFormAllowBulge(geom); if (!form || form.pts.length < 2) return null; - const edges: [number, Vec2, Vec2][] = []; - for (let i = 0; i < form.pts.length - 1; i++) { - edges.push([i, form.pts[i], form.pts[i + 1]]); - } - if (form.closed && form.pts.length > 2) { - edges.push([form.pts.length - 1, form.pts[form.pts.length - 1], form.pts[0]]); - } + const n = form.pts.length; + const edgeCount = form.closed ? n : n - 1; let best: number | null = null; let bestD = Infinity; - for (const [i, a, b] of edges) { - const d = segDist(p, a, b); - if (d < bestD) { - bestD = d; - best = i; + for (let i = 0; i < edgeCount; i++) { + const a = form.pts[i]; + const b = form.pts[(i + 1) % n]; + const arcPts = hasRealBulge(form.bulge) ? bulgeArcPoints(a, b, form.bulge?.[i]) : [a, b]; + for (let k = 0; k < arcPts.length - 1; k++) { + const d = segDist(p, arcPts[k], arcPts[k + 1]); + if (d < bestD) { + bestD = d; + best = i; + } } } return best; diff --git a/src/geometry/bulge.test.ts b/src/geometry/bulge.test.ts new file mode 100644 index 00000000..ff06eaad --- /dev/null +++ b/src/geometry/bulge.test.ts @@ -0,0 +1,74 @@ +/** + * `geometry/bulge.ts` — Kreisbogen-Segmente in Polylinien (DXF-Bulge- + * Konvention). Reine Geometrie-Tests, kein Modellbezug. + */ + +import { describe, it, expect } from "vitest"; +import { bulgeArc, bulgeArcPoints, bulgeFromSagittaPoint } from "./bulge"; + +describe("bulgeArc / bulgeArcPoints", () => { + it("bulge 0 (oder fehlend) → Gerade, keine Bogen-Tessellation", () => { + const a = { x: 0, y: 0 }, b = { x: 4, y: 2 }; + expect(bulgeArc(a, b, 0)).toBeNull(); + expect(bulgeArcPoints(a, b, undefined)).toEqual([a, b]); + expect(bulgeArcPoints(a, b, 0)).toEqual([a, b]); + }); + + it("bulge 1 (Halbkreis) über a=(0,0) b=(2,0): Apex bei (1,1), Radius 1, Zentrum (1,0)", () => { + const a = { x: 0, y: 0 }, b = { x: 2, y: 0 }; + const arc = bulgeArc(a, b, 1); + expect(arc).not.toBeNull(); + if (arc) { + expect(arc.center.x).toBeCloseTo(1, 6); + expect(arc.center.y).toBeCloseTo(0, 6); + expect(arc.r).toBeCloseTo(1, 6); + } + const pts = bulgeArcPoints(a, b, 1); + expect(pts[0].x).toBeCloseTo(0, 6); + expect(pts[0].y).toBeCloseTo(0, 6); + expect(pts[pts.length - 1].x).toBeCloseTo(2, 6); + expect(pts[pts.length - 1].y).toBeCloseTo(0, 6); + // Der mittlere Tessellations-Punkt (Apex) liegt bei (1,1) — links von a→b, + // wie es die positive Bulge-Konvention definiert. + const mid = pts[Math.round((pts.length - 1) / 2)]; + expect(mid.x).toBeCloseTo(1, 3); + expect(mid.y).toBeCloseTo(1, 3); + // Alle Punkte liegen exakt auf dem Kreis um (1,0) mit r=1. + for (const p of pts) { + expect(Math.hypot(p.x - 1, p.y - 0)).toBeCloseTo(1, 6); + } + }); + + it("negativer bulge bulgt auf die andere Seite (rechts von a→b)", () => { + const a = { x: 0, y: 0 }, b = { x: 2, y: 0 }; + const pts = bulgeArcPoints(a, b, -1); + const mid = pts[Math.round((pts.length - 1) / 2)]; + expect(mid.x).toBeCloseTo(1, 3); + expect(mid.y).toBeCloseTo(-1, 3); + }); + + it("kleiner bulge (flacher Bogen) bleibt nahe der Sehne", () => { + const a = { x: 0, y: 0 }, b = { x: 10, y: 0 }; + const pts = bulgeArcPoints(a, b, 0.1); + const mid = pts[Math.round((pts.length - 1) / 2)]; + // Sagitta = h*bulge = 5*0.1 = 0.5 + expect(mid.y).toBeCloseTo(0.5, 1); + }); +}); + +describe("bulgeFromSagittaPoint — Umkehrung für die Griff-Interaktion", () => { + it("Apex-Punkt eines bekannten Bogens liefert exakt den ursprünglichen bulge zurück (Rundtrip)", () => { + const a = { x: 0, y: 0 }, b = { x: 6, y: 0 }; + for (const b0 of [0.3, -0.5, 1, -1, 2]) { + const pts = bulgeArcPoints(a, b, b0); + const apex = pts[Math.round((pts.length - 1) / 2)]; + const back = bulgeFromSagittaPoint(a, b, apex); + expect(back).toBeCloseTo(b0, 1); + } + }); + + it("Punkt exakt auf der Sehne → bulge 0", () => { + const a = { x: 0, y: 0 }, b = { x: 4, y: 0 }; + expect(bulgeFromSagittaPoint(a, b, { x: 2, y: 0 })).toBeCloseTo(0, 9); + }); +}); diff --git a/src/geometry/bulge.ts b/src/geometry/bulge.ts new file mode 100644 index 00000000..5216cbcf --- /dev/null +++ b/src/geometry/bulge.ts @@ -0,0 +1,141 @@ +// Bulge — DXF-Konvention für Bogen-Segmente in Polylinien: `bulge = tan(Δ/4)` +// (Δ = Öffnungswinkel des Kreisbogens von a nach b). Reine Geometrie, keine +// Abhängigkeit vom Modell — s. Kopfkommentar bei `Drawing2DGeom["polyline"]. +// bulge` (model/types.ts) für die Feld-Semantik. +// +// Herleitung (Sehnen-Pfeilhöhen-Beziehung, exakt, ohne Kreisbogen-Trigonometrie +// im Radius): für eine Sehne der halben Länge h mit Pfeilhöhe (Sagitta) s gilt +// die Kreissegment-Identität r = (h²+s²) / (2s). Die Bulge-Definition liefert +// zusätzlich exakt s = h·bulge (Standard-Identität (1−cosX)/sinX = tan(X/2) +// mit X = Δ/2). Damit lässt sich der komplette Bogen (Zentrum/Radius) ohne +// eine einzige inverse Winkelfunktion aus bulge ableiten. + +import type { Vec2 } from "../model/types"; + +const EPS = 1e-9; + +/** Trägt dieses `bulge`-Array mindestens ein echtes Bogen-Segment (≠0)? */ +export function hasRealBulge(bulge: number[] | undefined): boolean { + return !!bulge && bulge.some((b) => Math.abs(b) > EPS); +} + +interface BulgeArc { + center: Vec2; + r: number; + a0: number; + a1: number; + /** Bogenmass der Schwenkrichtung von a0 nach a1 (positiv = CCW), inkl. Vorzeichen. */ + sweep: number; +} + +/** Kreisbogen-Parameter aus zwei Endpunkten + `bulge`, oder `null` bei (nahezu) 0 (Gerade). */ +export function bulgeArc(a: Vec2, b: Vec2, bulge: number): BulgeArc | null { + if (Math.abs(bulge) < EPS) return null; + const dx = b.x - a.x, dy = b.y - a.y; + const chord = Math.hypot(dx, dy); + if (chord < EPS) return null; + const ux = dx / chord, uy = dy / chord; + const nx = -uy, ny = ux; // Links-Normale von a→b + const h = chord / 2; + const s = h * bulge; // Sagitta (Pfeilhöhe), Vorzeichen wie bulge + const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2; + const rSigned = (h * h + s * s) / (2 * s); + const cx = mx + nx * (s - rSigned); + const cy = my + ny * (s - rSigned); + const r = Math.abs(rSigned); + const apexX = mx + nx * s, apexY = my + ny * s; + const a0 = Math.atan2(a.y - cy, a.x - cx); + const a1 = Math.atan2(b.y - cy, b.x - cx); + const aApex = Math.atan2(apexY - cy, apexX - cx); + const TAU = Math.PI * 2; + const norm = (x: number) => ((x % TAU) + TAU) % TAU; + // Die Sehnenmitte (Apex) liegt per Konstruktion auf dem Bogen — die Schwenk- + // richtung (CCW oder CW von a0 nach a1) ist genau die, die den Apex-Winkel + // unterwegs passiert. Robust gegen Vorzeichenfehler in der Herleitung oben: + // wird direkt gegen den bekannten Apex-Punkt geprüft statt abstrakt hergeleitet. + const ccwSweep = norm(a1 - a0); + const ccwPassesApex = norm(aApex - a0) <= ccwSweep + 1e-7; + const sweep = ccwPassesApex ? ccwSweep : -(TAU - ccwSweep); + return { center: { x: cx, y: cy }, r, a0, a1, sweep }; +} + +/** + * Tessellierte Bogenpunkte von a nach b (inkl. beider Endpunkte) — für + * Rendering/Fläche/Hit-Test/Export, die nur Geradensegmente kennen (analog + * `circlePts`/`ellipsePts`). `null`-Bulge (Gerade) liefert `[a, b]`. + */ +export function bulgeArcPoints(a: Vec2, b: Vec2, bulge: number | undefined): Vec2[] { + const arc = bulge !== undefined ? bulgeArc(a, b, bulge) : null; + if (!arc) return [a, b]; + const { center, r, a0, sweep } = arc; + // Auflösung: ~1 Segment je 12° reicht für Plan-Massstäbe (analog `circlePts` + // N=48 bei vollem Kreis ⇒ 7.5°/Segment; hier etwas gröber, dafür adaptiv zur + // tatsächlichen Bogenlänge statt immer 48 Punkte für jedes kleine Bögchen). + // Gerade Segmentzahl erzwingen, damit der exakte Apex-Punkt (t=0.5) immer + // als echter Tessellations-Punkt in der Mitte des Arrays landet (wichtig + // für den Bulge-Griff, s. `bulgePointAt`). + let N = Math.max(2, Math.ceil(Math.abs(sweep) / (Math.PI / 15))); + if (N % 2 !== 0) N += 1; + const pts: Vec2[] = []; + for (let i = 0; i <= N; i++) { + const t = a0 + sweep * (i / N); + pts.push({ x: center.x + r * Math.cos(t), y: center.y + r * Math.sin(t) }); + } + return pts; +} + +/** + * Bulge aus einem gezogenen Punkt `p` relativ zur Sehne a-b ableiten (Griff- + * Interaktion: Segment-Mitte senkrecht zur Sehne ziehen). Exakt die Umkehrung + * der `s = h·bulge`-Identität oben — kein Winkel involviert. + */ +export function bulgeFromSagittaPoint(a: Vec2, b: Vec2, p: Vec2): number { + const dx = b.x - a.x, dy = b.y - a.y; + const chord = Math.hypot(dx, dy); + if (chord < EPS) return 0; + const ux = dx / chord, uy = dy / chord; + const nx = -uy, ny = ux; + const h = chord / 2; + const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2; + const s = (p.x - mx) * nx + (p.y - my) * ny; + return s / h; +} + +/** Punkt auf dem aktuellen Bogen bei Parameter t∈[0,1] (0=a, 1=b, 0.5=Apex) — für den Bulge-Griff. */ +export function bulgePointAt(a: Vec2, b: Vec2, bulge: number, t: number): Vec2 { + const pts = bulgeArcPoints(a, b, bulge); + if (pts.length <= 2) return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }; + const idx = Math.round(t * (pts.length - 1)); + return pts[Math.max(0, Math.min(pts.length - 1, idx))]; +} + +/** Punkt auf einem Kreis (center, r) beim Winkel `a` (Radiant). */ +export function pointOnCircle(center: Vec2, r: number, a: number): Vec2 { + return { x: center.x + r * Math.cos(a), y: center.y + r * Math.sin(a) }; +} + +/** + * Bulge-Wert für den Teilbogen desselben Kreises (center, r) von Winkel `aFrom` + * zu `aTo`, in der durch `sweepSign` vorgegebenen Schwenkrichtung (+1 = CCW, + * −1 = CW — dieselbe Richtung wie der Eltern-Bogen, aus dem dieser Teilbogen + * stammt, z. B. beim Zuschneiden/Offsetten eines Bogen-Segments). Statt die + * Vorzeichen-Herleitung erneut zu machen (fehleranfällig), wird ein echter + * Punkt AUF dem Teilbogen (bei der Winkel-Mitte) konstruiert und darüber + * `bulgeFromSagittaPoint` (bereits getestet, s. `bulgeArc`) wiederverwendet. + */ +export function bulgeBetweenAngles( + center: Vec2, + r: number, + aFrom: number, + aTo: number, + sweepSign: 1 | -1, +): number { + const TAU = Math.PI * 2; + const norm = (x: number) => ((x % TAU) + TAU) % TAU; + const delta = sweepSign > 0 ? norm(aTo - aFrom) : -norm(aFrom - aTo); + const mid = aFrom + delta / 2; + const P = pointOnCircle(center, r, aFrom); + const Q = pointOnCircle(center, r, aTo); + const M = pointOnCircle(center, r, mid); + return bulgeFromSagittaPoint(P, Q, M); +} diff --git a/src/geometry/kernel2d.extendBulge.test.ts b/src/geometry/kernel2d.extendBulge.test.ts new file mode 100644 index 00000000..f9f6d3c1 --- /dev/null +++ b/src/geometry/kernel2d.extendBulge.test.ts @@ -0,0 +1,70 @@ +/** + * `extendBulgeSegment` — Verlängerung eines Bogen-Endsegments (DXF-bulge) + * über einen Endpunkt hinaus, entlang DESSELBEN Kreises (Mittelpunkt/Radius + * unverändert, nur die Schwenk-Spanne wächst) bis zum nächsten geraden + * Schneider. Gegenstück zu `extendSegment` (Geraden-only). + */ +import { describe, it, expect } from "vitest"; +import { bulgeArc } from "./bulge"; +import { extendBulgeSegment } from "./kernel2d"; +import type { Vec2 } from "../model/types"; + +// Halbkreis a=(-1,0) → b=(1,0), bulge=1 ⇒ center=(0,0), r=1, Apex bei (0,1). +const A: Vec2 = { x: -1, y: 0 }; +const B: Vec2 = { x: 1, y: 0 }; +const BULGE = 1; + +describe("extendBulgeSegment", () => { + it("verlängert über `b` hinaus (end='end') bis zum tangentialen Schneider y=-1", () => { + const cutter = { pts: [{ x: -10, y: -1 }, { x: 10, y: -1 }], closed: false }; + const res = extendBulgeSegment(A, B, BULGE, "end", [cutter]); + expect(res).not.toBeNull(); + expect(res!.point.x).toBeCloseTo(0, 6); + expect(res!.point.y).toBeCloseTo(-1, 6); + // Derselbe Kreis: Rückwärtsprobe über bulgeArc(a, neuer-Endpunkt, neuer bulge). + const arc = bulgeArc(A, res!.point, res!.bulge); + expect(arc).not.toBeNull(); + expect(arc!.center.x).toBeCloseTo(0, 6); + expect(arc!.center.y).toBeCloseTo(0, 6); + expect(arc!.r).toBeCloseTo(1, 6); + }); + + it("verlängert über `a` hinaus (end='start') symmetrisch, `b` bleibt fest", () => { + const cutter = { pts: [{ x: -10, y: -1 }, { x: 10, y: -1 }], closed: false }; + const res = extendBulgeSegment(A, B, BULGE, "start", [cutter]); + expect(res).not.toBeNull(); + expect(res!.point.x).toBeCloseTo(0, 6); + expect(res!.point.y).toBeCloseTo(-1, 6); + const arc = bulgeArc(res!.point, B, res!.bulge); + expect(arc).not.toBeNull(); + expect(arc!.center.x).toBeCloseTo(0, 6); + expect(arc!.center.y).toBeCloseTo(0, 6); + expect(arc!.r).toBeCloseTo(1, 6); + }); + + it("kein Schneider trifft den Kreis → null (kein Effekt)", () => { + // Gerade weit ausserhalb des Einheitskreises, trifft ihn nie. + const cutter = { pts: [{ x: -10, y: 5 }, { x: 10, y: 5 }], closed: false }; + const res = extendBulgeSegment(A, B, BULGE, "end", [cutter]); + expect(res).toBeNull(); + }); + + it("Gerade (bulge≈0) liefert null — Aufrufer soll auf extendSegment ausweichen", () => { + const cutter = { pts: [{ x: -10, y: -1 }, { x: 10, y: -1 }], closed: false }; + const res = extendBulgeSegment(A, B, 0, "end", [cutter]); + expect(res).toBeNull(); + }); + + it("wählt den NÄCHSTGELEGENEN Schneider in Schwenkrichtung, nicht irgendeinen Treffer", () => { + // Zwei Schneider unterhalb: einer nah (Tangente y=-1, delta=π/2 ab b), + // einer weiter weg (Gerade x=-3, schneidet den Kreis gar nicht — Kontrolle), + // plus ein echter zweiter Treffer weiter entlang der Schwenkrichtung (y=0.999, + // sehr nah an a selbst — muss NICHT gewählt werden, da a0 rausgefiltert wird + // und der Kreis dort ohnehin nicht geschnitten wird ausserhalb [-1,1]). + const near = { pts: [{ x: -10, y: -1 }, { x: 10, y: -1 }], closed: false }; + const outside = { pts: [{ x: -3, y: -10 }, { x: -3, y: 10 }], closed: false }; // x=-3, ausserhalb r=1 + const res = extendBulgeSegment(A, B, BULGE, "end", [outside, near]); + expect(res).not.toBeNull(); + expect(res!.point.y).toBeCloseTo(-1, 6); // der einzig echte Treffer (Tangente) + }); +}); diff --git a/src/geometry/kernel2d.offsetBulge.test.ts b/src/geometry/kernel2d.offsetBulge.test.ts new file mode 100644 index 00000000..67f5618f --- /dev/null +++ b/src/geometry/kernel2d.offsetBulge.test.ts @@ -0,0 +1,77 @@ +/** + * `offsetPolylineWithBulge` — Offset einer Polylinie mit Bogen-Segmenten + * (DXF-bulge). Deckt genau die Fälle ab, die `offsetPolyline` (Geraden-only) + * nicht kann: konzentrischer Radius-Offset eines Bogens, und Gehrung + * (miter) zwischen Bogen↔Gerade bzw. Bogen↔Bogen. + */ +import { describe, it, expect } from "vitest"; +import { offsetPolylineWithBulge } from "./kernel2d"; + +describe("offsetPolylineWithBulge", () => { + it("Halbkreis (bulge=1): Offset nach links (+d) vergrössert den Radius, bulge bleibt gleich", () => { + // a=(-1,0) → b=(1,0), bulge=1 ⇒ Halbkreis, center=(0,0), r=1 (s. bulge.test.ts). + const res = offsetPolylineWithBulge( + [{ x: -1, y: 0 }, { x: 1, y: 0 }], + [1], + 0.3, + false, + ); + expect(res.pts.length).toBe(2); + // Neuer Radius r'=1.3 ⇒ neue Endpunkte bei (±1.3, 0). + expect(res.pts[0].x).toBeCloseTo(-1.3, 6); + expect(res.pts[0].y).toBeCloseTo(0, 6); + expect(res.pts[1].x).toBeCloseTo(1.3, 6); + expect(res.pts[1].y).toBeCloseTo(0, 6); + // bulge kodiert nur den Öffnungswinkel (unverändert bei gleichem Winkelbereich). + expect(res.bulge[0]).toBeCloseTo(1, 6); + }); + + it("Halbkreis: Offset nach rechts (−d) verkleinert den Radius", () => { + const res = offsetPolylineWithBulge( + [{ x: -1, y: 0 }, { x: 1, y: 0 }], + [1], + -0.3, + false, + ); + expect(res.pts[0].x).toBeCloseTo(-0.7, 6); + expect(res.pts[1].x).toBeCloseTo(0.7, 6); + expect(res.bulge[0]).toBeCloseTo(1, 6); + }); + + it("Gerade ohne bulge bleibt exakt wie offsetPolyline (Geraden-only Fallback deckungsgleich)", () => { + const res = offsetPolylineWithBulge( + [{ x: 0, y: 0 }, { x: 2, y: 0 }], + undefined, + 0.5, + false, + ); + expect(res.pts).toEqual([{ x: 0, y: 0.5 }, { x: 2, y: 0.5 }]); + expect(res.bulge).toEqual([0]); + }); + + it("Gerade → Bogen → Gerade: die Gehrung an der Bogen-Naht liegt auf dem Bogen-Kreis", () => { + // Gerade (0,0)→(2,0), Viertelkreisbogen (2,0)→(2,2) mit bulge=tan(45°/2)... + // einfacher: Viertelkreis ⇒ Δ=π/2 ⇒ bulge=tan(π/8). + const bulge = Math.tan(Math.PI / 8); + const pts = [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 2 }]; + const res = offsetPolylineWithBulge(pts, [0, bulge], 0.2, false); + expect(res.pts.length).toBe(3); + expect(res.bulge.length).toBe(2); + // Erste Kante bleibt gerade. + expect(res.bulge[0]).toBeCloseTo(0, 6); + // Zweite Kante bleibt ein echter Bogen (nicht 0). + expect(Math.abs(res.bulge[1])).toBeGreaterThan(0.01); + // Der mittlere (Naht-)Punkt muss näher am Bogen-Zentrum (2,0)... je nach + // Seite verschoben, aber jedenfalls NICHT mehr exakt der rohe Eck-Punkt (2,0). + expect(res.pts[1]).not.toEqual({ x: 2, y: 0 }); + }); + + it("geschlossene Form (Kreis-artiges Polygon mit einem Bogen-Segment) bleibt geschlossen", () => { + // Dreieck mit einer verrundeten Ecke (wie ein Fillet-Ergebnis). + const pts = [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }]; + const bulge = [0, 0, 0, 0]; + const res = offsetPolylineWithBulge(pts, bulge, 0.2, true); + expect(res.pts.length).toBe(4); + expect(res.bulge).toEqual([0, 0, 0, 0]); + }); +}); diff --git a/src/geometry/kernel2d.trimBulge.test.ts b/src/geometry/kernel2d.trimBulge.test.ts new file mode 100644 index 00000000..e1cb0a2d --- /dev/null +++ b/src/geometry/kernel2d.trimBulge.test.ts @@ -0,0 +1,118 @@ +/** + * `trimPolylineWithBulge` — Quick-Trim einer Ziel-Kurve mit Bogen-Segmenten + * (bulge). Deckt sowohl GERADE als auch BOGEN-Schneider ab (Kreis↔Gerade UND + * Kreis↔Kreis, s. `edgeIntersectTs` im Kernel): ein Bogen-Segment wird korrekt + * zerschnitten, der verbleibende Teilbogen behält seine Krümmung (neu + * hergeleiteter bulge-Wert). + */ +import { describe, it, expect } from "vitest"; +import { bulgeArc } from "./bulge"; +import { trimPolylineWithBulge } from "./kernel2d"; + +describe("trimPolylineWithBulge", () => { + it("Halbkreis, gegen eine senkrechte Gerade am Apex getrimmt: die geklickte Hälfte fällt weg", () => { + // a=(-1,0) → b=(1,0), bulge=1 ⇒ Halbkreis, center=(0,0), r=1. + const pts = [{ x: -1, y: 0 }, { x: 1, y: 0 }]; + const bulge = [1]; + const cutter = { pts: [{ x: 0, y: -5 }, { x: 0, y: 5 }], closed: false }; + // Klick im rechten Viertelbogen (zwischen Apex (0,1) und b=(1,0)). + const pick = { x: Math.SQRT1_2, y: Math.SQRT1_2 }; + const rest = trimPolylineWithBulge(pts, bulge, false, [cutter], pick); + expect(rest.length).toBe(1); + const [chain] = rest; + expect(chain.pts.length).toBe(2); + expect(chain.pts[0].x).toBeCloseTo(-1, 6); + expect(chain.pts[0].y).toBeCloseTo(0, 6); + expect(chain.pts[1].x).toBeCloseTo(0, 6); + expect(chain.pts[1].y).toBeCloseTo(1, 6); + // Der verbleibende Viertelbogen muss geometrisch exakt auf demselben Kreis + // liegen (center=(0,0), r=1) — bulge kodiert weiterhin einen echten Bogen. + const arc = bulgeArc(chain.pts[0], chain.pts[1], chain.bulge[0]); + expect(arc).not.toBeNull(); + expect(arc!.center.x).toBeCloseTo(0, 5); + expect(arc!.center.y).toBeCloseTo(0, 5); + expect(arc!.r).toBeCloseTo(1, 5); + }); + + it("kein Schnitt mit dem Cutter → Kurve bleibt unverändert (inkl. bulge)", () => { + const pts = [{ x: -1, y: 0 }, { x: 1, y: 0 }]; + const bulge = [1]; + const cutter = { pts: [{ x: 10, y: -5 }, { x: 10, y: 5 }], closed: false }; + const rest = trimPolylineWithBulge(pts, bulge, false, [cutter], { x: 0, y: 1 }); + expect(rest.length).toBe(1); + expect(rest[0].pts).toEqual(pts); + expect(rest[0].bulge).toEqual([1]); + }); + + it("gerade Kanten in einer gemischten Kurve bleiben unangetastet (bulge=0)", () => { + // Gerade (0,0)→(2,0), dann Halbkreis (2,0)→(4,0) mit bulge=1 (center=(3,0),r=1). + const pts = [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 4, y: 0 }]; + const bulge = [0, 1]; + const cutter = { pts: [{ x: 1, y: -5 }, { x: 1, y: 5 }], closed: false }; + const rest = trimPolylineWithBulge(pts, bulge, false, [cutter], { x: 0.5, y: 0 }); + // Der Schnitt liegt auf der GERADEN ersten Kante bei x=1 → das linke Stück + // (0,0)→(1,0), angeklickt, fällt weg; das rechte Stück bleibt (gerade + // Restkante + unverändertem Bogen). + expect(rest.length).toBe(1); + expect(rest[0].pts[0].x).toBeCloseTo(1, 6); + expect(rest[0].bulge[0]).toBeCloseTo(0, 6); // Rest der geraden Kante + expect(rest[0].bulge[1]).toBeCloseTo(1, 6); // Bogen unverändert + }); + + it("GERADES Ziel gegen einen BOGEN-Schneider: der Kreis-Schnitt zählt als Cut-Knoten", () => { + // Ziel: waagrechte Gerade y=0 von x=-5 bis x=5. + const pts = [{ x: -5, y: 0 }, { x: 5, y: 0 }]; + // Schneider: Bogen von (0,-2) nach (0,2) mit bulge=1 ⇒ center=(0,0), r=2, + // bulgt nach LINKS (Apex bei (-2,0)) — kreuzt die Ziel-Gerade exakt einmal + // bei (-2,0) (Apex liegt genau auf der Geraden). + const cutter = { pts: [{ x: 0, y: -2 }, { x: 0, y: 2 }], closed: false, bulge: [1] }; + // Klick LINKS vom Schnittpunkt → das linke Stück [-5,-2] fällt weg. + const rest = trimPolylineWithBulge(pts, undefined, false, [cutter], { x: -3, y: 0 }); + expect(rest.length).toBe(1); + expect(rest[0].pts[0].x).toBeCloseTo(-2, 6); + expect(rest[0].pts[0].y).toBeCloseTo(0, 6); + expect(rest[0].pts[1]).toEqual({ x: 5, y: 0 }); + }); + + it("BOGEN-Ziel gegen BOGEN-Schneider: Kreis↔Kreis-Schnitt, Treffer nur innerhalb BEIDER Spannen", () => { + // Ziel: oberer Halbkreis, center=(0,0), r=1 (a=(-1,0)→b=(1,0), bulge=1). + const targetPts = [{ x: -1, y: 0 }, { x: 1, y: 0 }]; + const targetBulge = [1]; + // Schneider: oberer Halbkreis von center=(1,0), r=1 (a=(0,0)→b=(2,0), bulge=1, + // per Translationssymmetrie zum Ziel — ebenfalls die obere Hälfte). + // Klassischer "Vesica Piscis"-Schnitt zweier Einheitskreise im Abstand 1: + // (0.5, ±√3/2) — nur der OBERE Punkt liegt in BEIDEN oberen Halbkreis-Spannen. + const cutter = { pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }], closed: false, bulge: [1] }; + // Klick nahe a=(-1,0) (vor dem Schnittpunkt in Schwenkrichtung) → das + // Stück von a bis zum Schnittpunkt fällt weg, der Rest (Schnittpunkt→b) bleibt. + const pick = { x: Math.cos((2 * Math.PI) / 3), y: Math.sin((2 * Math.PI) / 3) }; // 120°, vor dem Schnitt bei 60° + const rest = trimPolylineWithBulge(targetPts, targetBulge, false, [cutter], pick); + expect(rest.length).toBe(1); + const [chain] = rest; + expect(chain.pts[0].x).toBeCloseTo(0.5, 6); + expect(chain.pts[0].y).toBeCloseTo(Math.sqrt(3) / 2, 6); + expect(chain.pts[chain.pts.length - 1]).toEqual({ x: 1, y: 0 }); + // Der verbleibende Bogen liegt weiterhin exakt auf dem ZIEL-Kreis (0,0)/r=1, + // NICHT auf dem Schneider-Kreis. + const arc = bulgeArc(chain.pts[0], chain.pts[chain.pts.length - 1], chain.bulge[0]); + expect(arc).not.toBeNull(); + expect(arc!.center.x).toBeCloseTo(0, 5); + expect(arc!.center.y).toBeCloseTo(0, 5); + expect(arc!.r).toBeCloseTo(1, 5); + }); + + it("Bogen-Schneider ausserhalb seiner eigenen Spanne zählt NICHT als Treffer", () => { + // Gleiche Kreis-Geometrie wie oben (Vesica Piscis, Schnitt bei (0.5, ±√3/2)), + // aber der Schneider deckt nur den UNTEREN Halbkreis seines Kreises ab + // (a=(0,0)→b=(2,0), bulge=-1) — der relevante obere Schnittpunkt (0.5,√3/2) + // liegt dann ausserhalb der Schneider-Spanne → kein Cut, Ziel bleibt ganz. + const targetPts = [{ x: -1, y: 0 }, { x: 1, y: 0 }]; + const targetBulge = [1]; + const cutter = { pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }], closed: false, bulge: [-1] }; + const pick = { x: 0, y: 1 }; // Apex des Ziel-Bogens + const rest = trimPolylineWithBulge(targetPts, targetBulge, false, [cutter], pick); + expect(rest.length).toBe(1); + expect(rest[0].pts).toEqual(targetPts); + expect(rest[0].bulge).toEqual([1]); + }); +}); diff --git a/src/geometry/kernel2d.ts b/src/geometry/kernel2d.ts index 3ba26196..53814e80 100644 --- a/src/geometry/kernel2d.ts +++ b/src/geometry/kernel2d.ts @@ -20,6 +20,7 @@ import { scale, sub, } from "../model/geometry"; +import { bulgeArc, bulgeBetweenAngles } from "./bulge"; /** Numerische Toleranz (Meter) für Schnitt-/Gleichheitstests. */ export const EPS = 1e-7; @@ -204,6 +205,117 @@ export function offsetPolyline(pts: Vec2[], d: number, closed: boolean): Vec2[] return result; } +// ── Offset MIT Bogen-Segmenten (bulge) ────────────────────────────────────── + +/** Eine rohe Offset-Kante: Gerade (`arc: null`) oder konzentrischer Bogen. */ +interface OffsetEdge { + a: Vec2; + b: Vec2; + arc: { center: Vec2; r: number; sweepSign: 1 | -1 } | null; +} + +/** Offset einer einzelnen Kante (Gerade ODER Bogen-Segment) um `d`. */ +function offsetEdgeFor(a: Vec2, b: Vec2, bulgeVal: number | undefined, d: number): OffsetEdge { + const arc = bulgeVal !== undefined ? bulgeArc(a, b, bulgeVal) : null; + if (!arc) { + const [oa, ob] = offsetSegment(a, b, d); + return { a: oa, b: ob, arc: null }; + } + const sweepSign: 1 | -1 = arc.sweep >= 0 ? 1 : -1; + // Tangentenrichtung d/dθ(cosθ,sinθ) = (−sinθ,cosθ) ist bei steigendem θ (CCW, + // sweepSign=+1) exakt die um 90° CCW gedrehte Radius-Richtung ⇒ „links" (+d) + // zeigt nach INNEN (Radius sinkt). Bei CW (sweepSign=−1) ist es umgekehrt. + const newR = Math.max(0.001, arc.r - d * sweepSign); + const oa = { x: arc.center.x + newR * Math.cos(arc.a0), y: arc.center.y + newR * Math.sin(arc.a0) }; + const ob = { x: arc.center.x + newR * Math.cos(arc.a1), y: arc.center.y + newR * Math.sin(arc.a1) }; + return { a: oa, b: ob, arc: { center: arc.center, r: newR, sweepSign } }; +} + +/** Kandidat aus `cands`, der `fallback` am nächsten liegt (oder `null`, wenn leer). */ +function nearestTo(cands: Vec2[], fallback: Vec2): Vec2 | null { + if (cands.length === 0) return null; + let best = cands[0]; + let bestD = dist(best, fallback); + for (let i = 1; i < cands.length; i++) { + const dd = dist(cands[i], fallback); + if (dd < bestD) { bestD = dd; best = cands[i]; } + } + return best; +} + +/** Schnittpunkt zweier Offset-Kanten (Gerade↔Gerade/Gerade↔Bogen/Bogen↔Bogen) für die Gehrung. */ +function joinOffsetEdges(e1: OffsetEdge, e2: OffsetEdge, fallback: Vec2): Vec2 { + if (!e1.arc && !e2.arc) { + const d1 = sub(e1.b, e1.a); + const d2 = sub(e2.b, e2.a); + return lineIntersect(e1.a, d1, e2.a, d2) ?? fallback; + } + if (e1.arc && !e2.arc) { + return nearestTo(lineCircleIntersect(e2.a, e2.b, e1.arc.center, e1.arc.r), fallback) ?? fallback; + } + if (!e1.arc && e2.arc) { + return nearestTo(lineCircleIntersect(e1.a, e1.b, e2.arc.center, e2.arc.r), fallback) ?? fallback; + } + return nearestTo(circleCircleIntersect(e1.arc!.center, e1.arc!.r, e2.arc!.center, e2.arc!.r), fallback) ?? fallback; +} + +const angleOf = (center: Vec2, p: Vec2): number => Math.atan2(p.y - center.y, p.x - center.x); + +/** + * Offset einer Polylinie MIT Bogen-Segmenten (`bulge`, s. `geometry/bulge.ts`) + * um `d` (links positiv). Ein Bogen-Segment bleibt konzentrisch (gleicher + * Mittelpunkt/Winkelbereich, s. `offsetEdgeFor`) — nur der Radius ändert sich; + * der bulge-WERT selbst bleibt beim reinen Offsetten unverändert (er kodiert + * nur den Öffnungswinkel, nicht den Radius) — wird aber an den Nahtstellen aus + * den TATSÄCHLICHEN (durch die Gehrung ggf. verschobenen) Endpunkt-Winkeln neu + * hergeleitet (`bulgeBetweenAngles`), sonst stimmt die Krümmung nicht mehr exakt. + * Nachbar-Kanten werden wie bei `offsetPolyline` auf Gehrung (miter) geschnitten + * (`joinOffsetEdges`, bei Bogen-Beteiligung per Geraden↔Kreis-/Kreis↔Kreis- + * Schnitt, nächstgelegener Kandidat zum Fallback-Punkt gewinnt). + */ +export function offsetPolylineWithBulge( + pts: Vec2[], + bulge: (number | undefined)[] | undefined, + d: number, + closed: boolean, +): { pts: Vec2[]; bulge: number[] } { + const n = pts.length; + if (n < 2) return { pts: pts.slice(), bulge: [] }; + const edgeCount = closed ? n : n - 1; + const edges: OffsetEdge[] = []; + for (let i = 0; i < edgeCount; i++) { + edges.push(offsetEdgeFor(pts[i], pts[(i + 1) % n], bulge?.[i], d)); + } + + const verts: Vec2[] = []; + if (!closed) { + verts.push(edges[0].a); + for (let i = 0; i < edges.length - 1; i++) { + verts.push(joinOffsetEdges(edges[i], edges[i + 1], edges[i].b)); + } + verts.push(edges[edges.length - 1].b); + } else { + for (let i = 0; i < edges.length; i++) { + const prev = edges[(i - 1 + edges.length) % edges.length]; + const curr = edges[i]; + verts.push(joinOffsetEdges(prev, curr, curr.a)); + } + } + + const outBulge: number[] = new Array(edgeCount).fill(0); + for (let i = 0; i < edgeCount; i++) { + const e = edges[i]; + if (!e.arc) continue; + const vStart = verts[i]; + const vEnd = closed ? verts[(i + 1) % edgeCount] : verts[i + 1]; + const aFrom = angleOf(e.arc.center, vStart); + const aTo = angleOf(e.arc.center, vEnd); + outBulge[i] = bulgeBetweenAngles(e.arc.center, e.arc.r, aFrom, aTo, e.arc.sweepSign); + } + + return { pts: verts, bulge: outBulge }; +} + // ── Trim / Split ───────────────────────────────────────────────────────────── /** @@ -410,6 +522,224 @@ function nearestParamOnChain(edges: [Vec2, Vec2][], p: Vec2): number { return best; } +// ── Trim MIT Bogen-Segmenten (Ziel-Kurve UND Schneider dürfen bulge tragen) ─ +// Gleicher Algorithmus wie `trimPolyline` oben (Cut-Knoten sammeln → Bogen um +// den Pick entfernen), aber sowohl die Ziel-Kurve als auch die Schneider +// dürfen Bogen-Segmente (`bulge`) tragen — Kreis↔Gerade- UND Kreis↔Kreis- +// Schnitt beim Cut-Sammeln (s. `edgeIntersectTs`). `extend.ts` hält an der +// Cutter-müssen-gerade-sein-Einschränkung fest (Verlängerung eines Bogens +// gegen einen Bogen-Cutter bräuchte eine andere Kandidatenwahl als „kleinstes +// delta"; eigener, separater Umfang). + +interface BulgeEdge { + a: Vec2; + b: Vec2; + arc: { center: Vec2; r: number; a0: number; sweep: number } | null; +} + +function buildBulgeEdges(pts: Vec2[], bulge: (number | undefined)[] | undefined, closed: boolean): BulgeEdge[] { + const n = pts.length; + const edgeCount = closed ? n : n - 1; + const edges: BulgeEdge[] = []; + for (let i = 0; i < edgeCount; i++) { + const a = pts[i]; + const b = pts[(i + 1) % n]; + const bv = bulge?.[i]; + const arc = bv !== undefined ? bulgeArc(a, b, bv) : null; + edges.push({ a, b, arc: arc ? { center: arc.center, r: arc.r, a0: arc.a0, sweep: arc.sweep } : null }); + } + return edges; +} + +/** Punkt einer BulgeEdge bei Parameter t∈[0,1] (0=a, 1=b). */ +function pointOnBulgeEdgeAtT(e: BulgeEdge, t: number): Vec2 { + if (!e.arc) return add(e.a, scale(sub(e.b, e.a), t)); + const { center, r, a0, sweep } = e.arc; + return { x: center.x + r * Math.cos(a0 + sweep * t), y: center.y + r * Math.sin(a0 + sweep * t) }; +} + +/** Nächster Punkt + Parameter t∈[0,1] einer BulgeEdge zu `p` (für die Pick-Lokalisierung). */ +function closestOnBulgeEdge(e: BulgeEdge, p: Vec2): { point: Vec2; t: number } { + if (!e.arc) { + const t = Math.max(0, Math.min(1, projectParam(p, e.a, e.b))); + return { point: add(e.a, scale(sub(e.b, e.a), t)), t }; + } + const { center, a0, sweep } = e.arc; + const TAU = Math.PI * 2; + const norm = (x: number) => ((x % TAU) + TAU) % TAU; + const angleP = Math.atan2(p.y - center.y, p.x - center.x); + const raw = sweep >= 0 ? norm(angleP - a0) : -norm(a0 - angleP); + const t = sweep !== 0 ? Math.max(0, Math.min(1, raw / sweep)) : 0; + return { point: pointOnBulgeEdgeAtT(e, t), t }; +} + +/** Winkel-Parameter t (nicht auf [0,1] geklemmt) eines Punktes AUF dem Vollkreis der BulgeEdge. */ +function tOnArc(arc: { center: Vec2; r: number; a0: number; sweep: number }, p: Vec2): number { + const TAU = Math.PI * 2; + const norm = (x: number) => ((x % TAU) + TAU) % TAU; + const angleP = Math.atan2(p.y - arc.center.y, p.x - arc.center.x); + const raw = arc.sweep >= 0 ? norm(angleP - arc.a0) : -norm(arc.a0 - angleP); + return arc.sweep !== 0 ? raw / arc.sweep : 0; +} + +/** Liegt ein (bereits AUF dem Vollkreis liegender) Punkt innerhalb der TATSÄCHLICHEN Bogen-Spanne? */ +function onArcSpan(arc: { center: Vec2; r: number; a0: number; sweep: number }, p: Vec2): boolean { + const t = tOnArc(arc, p); + return t >= -EPS && t <= 1 + EPS; +} + +/** + * t-Parameter(e) ∈(0,1) auf `target`, an denen `cutter` (GERADE ODER BOGEN) + * sie trifft — Kreuzprodukt aus vier Fällen (Gerade×Gerade, Bogen×Gerade, + * Gerade×Bogen, Bogen×Bogen). Schneidet ein Bogen-Schneider, wird der Treffer + * IMMER gegen dessen tatsächliche Spanne geprüft (nicht nur den vollen + * Kreis) — sonst würde ein kurzer Bogen-Cutter wie ein Vollkreis wirken. + */ +function edgeIntersectTs(target: BulgeEdge, cutter: BulgeEdge): number[] { + if (!target.arc && !cutter.arc) { + const h = segmentIntersect(target.a, target.b, cutter.a, cutter.b); + return h ? [h.t] : []; + } + if (target.arc && !cutter.arc) { + return segmentCircleIntersect(cutter.a, cutter.b, target.arc.center, target.arc.r).map((p) => + tOnArc(target.arc!, p), + ); + } + if (!target.arc && cutter.arc) { + return segmentCircleIntersect(target.a, target.b, cutter.arc.center, cutter.arc.r) + .filter((p) => onArcSpan(cutter.arc!, p)) + .map((p) => projectParam(p, target.a, target.b)); + } + return circleCircleIntersect(target.arc!.center, target.arc!.r, cutter.arc!.center, cutter.arc!.r) + .filter((p) => onArcSpan(cutter.arc!, p)) + .map((p) => tOnArc(target.arc!, p)); +} + +/** bulge-Wert des Teilbogens t0..t1 einer BulgeEdge (Gerade → 0; volle Kante → `orig` unverändert). */ +function subBulge(edge: BulgeEdge, orig: number, t0: number, t1: number): number { + if (!edge.arc) return 0; + if (t0 <= EPS && t1 >= 1 - EPS) return orig; + const { center, r, a0, sweep } = edge.arc; + const sweepSign: 1 | -1 = sweep >= 0 ? 1 : -1; + return bulgeBetweenAngles(center, r, a0 + sweep * t0, a0 + sweep * t1, sweepSign); +} + +function nearestParamOnBulgeChain(edges: BulgeEdge[], p: Vec2): number { + let best = 0; + let bestD = Infinity; + for (let ei = 0; ei < edges.length; ei++) { + const { point, t } = closestOnBulgeEdge(edges[ei], p); + const d = dist(p, point); + if (d < bestD) { bestD = d; best = ei + t; } + } + return best; +} + +/** + * Wie {@link trimPolyline}, aber die Ziel-Kurve `pts`/`bulge` darf Bogen- + * Segmente tragen (Schneider bleiben gerade, s. Kopfkommentar oben). Liefert + * die verbleibenden Ketten inkl. ihres jeweiligen `bulge`-Arrays. + */ +export function trimPolylineWithBulge( + pts: Vec2[], + bulge: (number | undefined)[] | undefined, + closed: boolean, + cutters: { pts: Vec2[]; closed: boolean; bulge?: (number | undefined)[] }[], + pick: Vec2, +): { pts: Vec2[]; closed: boolean; bulge: number[] }[] { + const edges = buildBulgeEdges(pts, bulge, closed); + const bulgeFull: number[] = edges.map((e, i) => (e.arc ? (bulge?.[i] ?? 0) : 0)); + if (edges.length === 0) return [{ pts: pts.slice(), closed, bulge: [] }]; + + interface CutN { edge: number; t: number; point: Vec2; } + const rawCuts: CutN[] = []; + for (let ei = 0; ei < edges.length; ei++) { + for (const c of cutters) { + for (const ce of buildBulgeEdges(c.pts, c.bulge, c.closed)) { + for (const t of edgeIntersectTs(edges[ei], ce)) { + if (t > EPS && t < 1 - EPS) rawCuts.push({ edge: ei, t, point: pointOnBulgeEdgeAtT(edges[ei], t) }); + } + } + } + } + rawCuts.sort((p, q) => (p.edge - q.edge) || (p.t - q.t)); + const cut: CutN[] = []; + for (const h of rawCuts) { + const prev = cut[cut.length - 1]; + if (prev && prev.edge === h.edge && Math.abs(prev.t - h.t) < 1e-6) continue; + cut.push(h); + } + if (cut.length === 0) return [{ pts: pts.slice(), closed, bulge: bulgeFull }]; + + // Materialisiert die Kette von (fromEdge,fromT,fromPoint) bis (toEdge,toT,toPoint) + // entlang der Kantenfolge (vorwärts, mit Wrap für geschlossene Ketten). + const spanBulge = ( + fromEdge: number, fromT: number, fromPoint: Vec2, + toEdge: number, toT: number, toPoint: Vec2, + ): { pts: Vec2[]; bulge: number[] } => { + const total = edges.length; + const outPts: Vec2[] = [fromPoint]; + const outBulge: number[] = []; + const pushPoint = (p: Vec2, segBulge: number) => { + const last = outPts[outPts.length - 1]; + if (dist(last, p) <= EPS) return; // degenerierte Nullstrecke überspringen + outPts.push(p); + outBulge.push(segBulge); + }; + let e = fromEdge; + let curT = fromT; + let steps = 0; + while (steps <= total && e !== toEdge) { + pushPoint(edges[e].b, subBulge(edges[e], bulgeFull[e], curT, 1)); + curT = 0; + e = (e + 1) % total; + steps++; + } + pushPoint(toPoint, subBulge(edges[toEdge], bulgeFull[toEdge], curT, toT)); + return { pts: outPts, bulge: outBulge }; + }; + + if (!closed) { + const pickPos = nearestParamOnBulgeChain(edges, pick); + const cutPos = cut.map((c) => c.edge + c.t); + let loIdx = -1; + let hiIdx = cut.length; + for (let i = 0; i < cut.length; i++) { + if (cutPos[i] <= pickPos) loIdx = i; + else { hiIdx = i; break; } + } + const result: { pts: Vec2[]; closed: boolean; bulge: number[] }[] = []; + if (loIdx >= 0) { + const c = cut[loIdx]; + const s = spanBulge(0, 0, pts[0], c.edge, c.t, c.point); + if (s.pts.length >= 2) result.push({ pts: s.pts, closed: false, bulge: s.bulge }); + } + if (hiIdx < cut.length) { + const c = cut[hiIdx]; + const s = spanBulge(c.edge, c.t, c.point, edges.length - 1, 1, pts[pts.length - 1]); + if (s.pts.length >= 2) result.push({ pts: s.pts, closed: false, bulge: s.bulge }); + } + return result; + } + + if (cut.length === 1) return [{ pts: pts.slice(), closed: true, bulge: bulgeFull }]; + const pickPos = nearestParamOnBulgeChain(edges, pick); + const cutPos = cut.map((c) => c.edge + c.t); + let seg = -1; + for (let i = 0; i < cut.length; i++) { + const a = cutPos[i]; + const b = cutPos[(i + 1) % cut.length]; + const inside = i === cut.length - 1 ? pickPos >= a || pickPos <= b : pickPos >= a && pickPos <= b; + if (inside) { seg = i; break; } + } + if (seg < 0) seg = 0; + const from = cut[(seg + 1) % cut.length]; + const to = cut[seg]; + const chain = spanBulge(from.edge, from.t, from.point, to.edge, to.t, to.point); + if (chain.pts.length < 2) return []; + return [{ pts: chain.pts, closed: false, bulge: chain.bulge }]; +} + // ── Extend ─────────────────────────────────────────────────────────────────── /** @@ -444,6 +774,57 @@ export function extendSegment( return end === "end" ? [a1, hitPoint] : [hitPoint, a2]; } +/** + * Wie {@link extendSegment}, aber für ein Bogen-Segment (`a`→`b` mit `bulge`, + * DXF-Konvention): verlängert den Kreisbogen über das gewählte Ende hinaus + * (gleicher Mittelpunkt/Radius, nur die Schwenk-Spanne wächst) bis zur + * nächstgelegenen Schneider-Kante. Schneider bleiben bewusst GERADE (wie bei + * `extendSegment`/Trim — Bogen-Cutter sind ein eigenes, grösseres Vorhaben), + * daher genügt die Kreis-Strecken-Schnittfunktion. `end: "end"` verlängert + * über `b` hinaus (a bleibt fest), `end: "start"` über `a` hinaus (b bleibt + * fest) — jeweils in derselben Schwenkrichtung wie das Original, nicht + * rückwärts. Liefert `null` bei Geraden (bulge≈0) oder ohne Treffer. + */ +export function extendBulgeSegment( + a: Vec2, + b: Vec2, + bulge: number, + end: "start" | "end", + cutters: { pts: Vec2[]; closed: boolean }[], +): { point: Vec2; bulge: number } | null { + const arc = bulgeArc(a, b, bulge); + if (!arc) return null; + const { center, r, a0, a1, sweep } = arc; + const sweepSign: 1 | -1 = sweep >= 0 ? 1 : -1; + const TAU = Math.PI * 2; + const norm = (x: number) => ((x % TAU) + TAU) % TAU; + let bestDelta: number | null = null; + let bestAngle = 0; + for (const c of cutters) { + for (const [b1, b2] of polylineEdges(c.pts, c.closed)) { + for (const p of segmentCircleIntersect(b1, b2, center, r)) { + const theta = Math.atan2(p.y - center.y, p.x - center.x); + const delta = + end === "end" + ? sweepSign > 0 ? norm(theta - a1) : norm(a1 - theta) + : sweepSign > 0 ? norm(a0 - theta) : norm(theta - a0); + if (delta < EPS) continue; // trifft den Endpunkt selbst + if (bestDelta === null || delta < bestDelta) { + bestDelta = delta; + bestAngle = theta; + } + } + } + } + if (bestDelta === null) return null; + const point = { x: center.x + r * Math.cos(bestAngle), y: center.y + r * Math.sin(bestAngle) }; + const newBulge = + end === "end" + ? bulgeBetweenAngles(center, r, a0, bestAngle, sweepSign) + : bulgeBetweenAngles(center, r, bestAngle, a1, sweepSign); + return { point, bulge: newBulge }; +} + // ── Kreis-Schnitte (für Circle/Arc, 2P/3P/Tangenten) ──────────────────────── /** Schnittpunkte einer unendlichen GERADE a→b mit einem Kreis (0/1/2 Punkte). */ @@ -752,6 +1133,43 @@ export function removeSegment( return { pts: left.length >= right.length ? left : right, closed: false }; } +/** + * Wie {@link removeSegment}, aber trägt ein `bulge`-Array (Bogen-Segmente, + * DXF-Konvention, s. `geometry/bulge.ts`) mit durch die Operation. Dieselbe + * Index-Regel wie überall: `bulge[i]` gehört zur Kante `pts[i]→pts[i+1]` + * (bzw. `pts[n-1]→pts[0]` bei geschlossenen Polylinien) — die entfernte Kante + * nimmt ihren bulge-Eintrag mit, alle übrigen wandern unverändert mit ihrem + * Punktepaar mit. (Dedup identischer Nachbarpunkte wie bei `removeSegment` + * bewusst ausgelassen — würde bulge-Indizes gegenüber pts verschieben; bei + * bulge-Polylinien treten doppelte Punkte praktisch nicht auf.) + */ +export function removeSegmentWithBulge( + pts: Vec2[], + bulge: number[], + closed: boolean, + edgeIndex: number, +): { pts: Vec2[]; closed: boolean; bulge: number[] } { + const n = pts.length; + if (closed) { + const outPts: Vec2[] = []; + const outBulge: number[] = []; + for (let k = 1; k <= n; k++) outPts.push(pts[(edgeIndex + k) % n]); + for (let k = 1; k <= n - 1; k++) outBulge.push(bulge[(edgeIndex + k) % n]); + return { pts: outPts, closed: false, bulge: outBulge }; + } + if (edgeIndex <= 0) return { pts: pts.slice(1), closed: false, bulge: bulge.slice(1) }; + if (edgeIndex >= n - 1) { + return { pts: pts.slice(0, n - 1), closed: false, bulge: bulge.slice(0, -1) }; + } + const leftPts = pts.slice(0, edgeIndex + 1); + const leftBulge = bulge.slice(0, edgeIndex); + const rightPts = pts.slice(edgeIndex + 1); + const rightBulge = bulge.slice(edgeIndex + 1); + return leftPts.length >= rightPts.length + ? { pts: leftPts, closed: false, bulge: leftBulge } + : { pts: rightPts, closed: false, bulge: rightBulge }; +} + /** Ein Schnitt-Treffer auf einer Ziel-Kante: Kantenindex + Parameter + Punkt. */ interface EdgeHit { edge: number; @@ -922,3 +1340,76 @@ export function joinChains( } return out; } + +/** Kehrt ein bulge-Array um (Reihenfolge + Vorzeichen), für eine rückwärts gelaufene Kette. */ +function reverseBulge(b: number[]): number[] { + return b.slice().reverse().map((v) => -v); +} + +/** + * Wie {@link joinChains}, aber trägt pro Kette ein optionales `bulge`-Array + * (Bogen-Segmente, DXF-Konvention, s. `geometry/bulge.ts`) mit durch die + * Verkettung. Beim Verbinden ZWEIER Ketten am Endpunkt bleibt die Kanten- + * Reihenfolge/-Richtung jeder Kette erhalten → deren bulge-Werte werden einfach + * aneinandergehängt. Muss eine Kette dafür UMGEDREHT werden (ihr Start- statt + * Endpunkt trifft den Anschluss), kehrt sich pro Kante sowohl die Reihenfolge + * als auch das VORZEICHEN um (dieselbe Konvention wie bei Spiegelung, s. + * `tools/transform.ts::mvGeom`, Fall `"polyline"`) — bulge kodiert die Krümmung + * relativ zur Laufrichtung, die sich beim Umdrehen umkehrt. + */ +export function joinChainsWithBulge( + polylines: { pts: Vec2[]; closed: boolean; bulge?: number[] }[], +): { pts: Vec2[]; closed: boolean; bulge: number[] }[] { + const closedOut: { pts: Vec2[]; closed: boolean; bulge: number[] }[] = []; + const open: { pts: Vec2[]; bulge: number[] }[] = []; + for (const pl of polylines) { + const bulge = pl.bulge ?? new Array(Math.max(0, pl.pts.length - 1)).fill(0); + if (pl.closed) closedOut.push({ pts: pl.pts.slice(), closed: true, bulge }); + else if (pl.pts.length >= 1) open.push({ pts: pl.pts.slice(), bulge }); + } + + let merged = true; + while (merged) { + merged = false; + outer: for (let i = 0; i < open.length; i++) { + for (let j = i + 1; j < open.length; j++) { + const A = open[i]; + const B = open[j]; + const aS = A.pts[0], aE = A.pts[A.pts.length - 1]; + const bS = B.pts[0], bE = B.pts[B.pts.length - 1]; + let combined: { pts: Vec2[]; bulge: number[] } | null = null; + if (vecEqual(aE, bS)) { + combined = { pts: [...A.pts, ...B.pts.slice(1)], bulge: [...A.bulge, ...B.bulge] }; + } else if (vecEqual(aE, bE)) { + combined = { + pts: [...A.pts, ...B.pts.slice(0, -1).reverse()], + bulge: [...A.bulge, ...reverseBulge(B.bulge.slice(0, -1))], + }; + } else if (vecEqual(aS, bE)) { + combined = { pts: [...B.pts, ...A.pts.slice(1)], bulge: [...B.bulge, ...A.bulge] }; + } else if (vecEqual(aS, bS)) { + combined = { + pts: [...B.pts.slice().reverse(), ...A.pts.slice(1)], + bulge: [...reverseBulge(B.bulge), ...A.bulge], + }; + } + if (combined) { + open.splice(j, 1); + open.splice(i, 1, combined); + merged = true; + break outer; + } + } + } + } + + const out = [...closedOut]; + for (const chain of open) { + if (chain.pts.length > 2 && vecEqual(chain.pts[0], chain.pts[chain.pts.length - 1])) { + out.push({ pts: chain.pts.slice(0, -1), closed: true, bulge: chain.bulge }); + } else { + out.push({ pts: chain.pts, closed: false, bulge: chain.bulge }); + } + } + return out; +} diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 56224c4a..03eb2b10 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -128,6 +128,10 @@ export const de = { // ausser Bearbeiten/Ansicht/Fenster (oben) auch Datei/Export/Transformieren // zeigt, was die In-App-AppMenuBar nicht hat. ───────────────────────────── "menu.native.file": "Datei", + "menu.native.new": "Neu", + "menu.native.newFromTemplate": "Neu aus Vorlage", + "menu.native.newFromSample": "Musterhaus", + "menu.native.newFromTemplateFile": "Vorlagendatei wählen …", "menu.native.open": "Öffnen …", "menu.native.saveAs": "Speichern unter …", "menu.native.import": "Importieren …", @@ -172,6 +176,10 @@ export const de = { "tool.door": "Tür", "tool.stair": "Treppe", "tool.line": "Linie", + "tool.xline": "Konstruktionslinie", + "tool.xline.hint": "Konstruktionslinie: zwei Punkte legen die Richtung fest (unendlich verlängert)", + "tool.block": "Block einfügen", + "tool.block.hint": "Block einfügen: aktive Definition per Option wählen, dann Einfügepunkt klicken", "tool.polyline": "Polylinie", "tool.rect": "Rechteck", "tool.circle": "Kreis", @@ -180,6 +188,8 @@ export const de = { "tool.arc.hint": "Bogen: Mittelpunkt, Startpunkt, dann Endpunkt (CCW)", "tool.ellipse": "Ellipse", "tool.ellipse.hint": "Ellipse: zwei gegenüberliegende Ecken der Bounding-Box", + "tool.polygon": "Vieleck", + "tool.polygon.hint": "Vieleck: Mittelpunkt, dann Radius (Ecken-Zahl per Option)", "tool.spline": "Spline", "tool.spline.hint": "Spline: Wegpunkte klicken, Enter beendet (glatte Kurve durch die Punkte)", "tool.bezier": "Bezier", @@ -190,6 +200,10 @@ export const de = { "tool.kote.hint": "Höhenkote: Punkt setzen, dann Höhenwert eintippen (Art umschaltbar: OK/UK, fertig/roh)", "tool.text": "Text", "tool.text.hint": "Text: Ankerpunkt setzen, dann Text eintippen", + "tool.leader": "Vorführungspfeil", + "tool.leader.hint": "Vorführungspfeil: Zielpunkt setzen, dann Textanker, dann Text eintippen", + "tool.textpath": "Text entlang Pfad", + "tool.textpath.hint": "Text entlang Pfad: mindestens zwei Pfadpunkte setzen (Enter beendet), dann Text eintippen", "tool.textbox": "Textspalte", "tool.textbox.hint": "Textspalte: Anker, dann Spaltenbreite ziehen, dann Text eintippen", "tool.image": "Bild/PDF", @@ -305,6 +319,8 @@ export const de = { // ── Dokument-Tabs (Zeichnungen/Blätter) ───────────────────────────────── "tabs.drawings": "Zeichnungen", + "tabs.add": "Neuer Ausschnitt-Tab", + "tabs.delete": "Ausschnitt-Tab löschen", // ── Navigator-Panels ───────────────────────────────────────────────────── "nav.drawingLevels": "Zeichnungsebenen", @@ -321,6 +337,10 @@ export const de = { "attr.color": "Farbe", "attr.weight": "Strichstärke (mm)", "attr.opacity": "Deckkraft", + "attr.saturation": "Sättigung", + "attr.brightness": "Helligkeit", + "attr.contrast": "Kontrast", + "attr.grayscale": "Graustufen", "attr.lineStyle": "Linienstil", "attr.lineStyle.none": "Standard", "attr.fill": "Füllung", @@ -373,6 +393,7 @@ export const de = { "objinfo.contextObject.type.importedMesh": "Importiertes Mesh", "objinfo.contextObject.type.terrainMesh": "Gelände", "objinfo.contextObject.type.contourSet": "Höhenlinien", + "objinfo.contextObject.type.image": "Luftbild", "objinfo.contextObject.lv95E": "LV95 Ost (E)", "objinfo.contextObject.lv95N": "LV95 Nord (N)", "objinfo.contextObject.noAnchor": "Kein Standort-Bezug im Projekt", @@ -712,6 +733,7 @@ export const de = { "editor.layerTitle": "Ebene {code}", "editor.name": "Name", "editor.color": "Farbe", + "editor.pen": "Stift", "editor.lineWeight": "Linienstärke", "editor.hatch": "Schraffur", "editor.floorHeight": "Geschosshöhe", @@ -766,9 +788,12 @@ export const de = { "default.doorTypeName": "Neuer Türtyp", "default.windowTypeName": "Neuer Fenstertyp", "default.stairTypeName": "Neuer Treppentyp", + "default.penName": "Neuer Stift", + "default.penSetName": "Neuer Stiftsatz", // ── Warnungen (Lösch-Schutz) ───────────────────────────────────────────── "alert.layerInUse": "Ebene „{code} {name}\" wird von Bauteilen verwendet und kann nicht gelöscht werden.", + "alert.penSetIsActive": "Stiftsatz „{name}\" ist aktiv und kann nicht gelöscht werden — zuerst einen anderen Stiftsatz aktivieren.", "alert.componentInUse": "Bauteil „{name}\" wird von einem Wandtyp verwendet und kann nicht gelöscht werden.", "alert.hatchInUse": "Schraffur „{name}\" wird von einem Bauteil verwendet und kann nicht gelöscht werden.", "alert.lineStyleInUse": "Linienstil „{name}\" wird von einer Schraffur verwendet und kann nicht gelöscht werden.", @@ -795,6 +820,22 @@ export const de = { "resources.tab.stairStyles": "Treppentypen", "resources.tab.materials": "Materialien", "resources.tab.overrides": "Overrides", + "resources.tab.pens": "Stifte", + + // Stiftsätze (ArchiCAD-Stiftsatz-Muster). + "resources.pens.hint": "Ein Bauteil oder eine Ebene kann statt einer freien Farbe an einen Stift gekoppelt werden. Stifte selbst tragen keine Farbe — die liefert der AKTIVE Stiftsatz. Mehrere Stiftsätze umschalten färbt alle gekoppelten Bauteile/Ebenen sofort um.", + "resources.pens.setPlaceholder": "Name des Stiftsatzes", + "resources.pens.isActive": "Dieser Stiftsatz ist aktiv.", + "resources.pens.activate": "Als aktiv setzen", + "resources.pens.activeBadge": "aktiv", + "resources.pens.empty": "Noch keine Stifte — mit „+ Stift\" anlegen.", + "resources.pens.emptySets": "Noch keine Stiftsätze.", + "resources.pens.addPen": "Stift", + "resources.pens.addSet": "Stiftsatz", + "resources.pens.seedStandard": "255 Standard-Stifte laden", + "resources.pens.seedStandard.hint": "Ersetzt die Stift-Liste durch 255 prozedural erzeugte Stifte (klassische CAD-Nummerierung: 1-9 Grundfarben, 10-249 Farbtonstufen, 250-255 Graukeil) + einen neuen aktiven Stiftsatz mit diesen Farben.", + "resources.delete.penSet": "Stiftsatz „{name}\" löschen", + "resources.delete.pen": "Stift „{name}\" löschen", // Grafische Overrides (Regel-Engine). "resources.overrides.hint": @@ -954,12 +995,21 @@ export const de = { "resources.col.prio.hint": "Höhere Priorität läuft am Stoß durch", "resources.col.texture": "Textur", "resources.col.material": "Material", + "resources.col.color.hint": "Grundfarbe — 3D-Diffusfarbe + Fallback für Vorder-/Hintergrund, falls dort keine eigene Farbe gesetzt ist", "resources.col.foreground": "Vordergrund", "resources.col.foreground.hint": "Farbe der Muster-/Schraffurlinien (Vordergrund)", "resources.col.background": "Hintergrund", "resources.col.background.hint": "Füllfarbe (Poché/Hintergrund)", "resources.delete.component": "Bauteil „{name}\" löschen", + // Stift-Kopplung (ArchiCAD-Stiftsatz-Muster) — Dropdown neben Farbfeldern. + "pen.free": "Frei", + "pen.byPen": "Stift", + "pen.numberHint": "Stift-Nummer", + "pen.weightHint": "Stärke: {weight} mm", + "pen.customColor": "Andere Farbe …", + "pen.hexHint": "Hex-Farbwert (#rrggbb)", + // 3D-Material (PBR) — Bibliotheks-Auswahl + Upload. "material.assign": "Material …", "material.none": "— ohne —", @@ -1061,6 +1111,7 @@ export const de = { "pattern.insulation": "Wärmedämmung", "pattern.diagonal": "Diagonal", "pattern.crosshatch": "Kreuzschraffur", + "pattern.custom": "Eigenes Motiv", // Linien. "resources.lines.hint": "Strichstärke in Millimetern (Paper-Space). Strichmuster: durchgezogen, gestrichelt oder gepunktet.", @@ -1133,6 +1184,14 @@ export const de = { "cmd.line.label": "Linie", "cmd.line.start": "Startpunkt der Linie:", "cmd.line.end": "Endpunkt der Linie:", + "cmd.xline.label": "Konstruktionslinie", + "cmd.xline.start": "Startpunkt:", + "cmd.xline.end": "Richtungspunkt:", + "cmd.block.label": "Block einfügen", + "cmd.block.point": "Einfügepunkt:", + "cmd.block.def": "Symbol", + "cmd.defblock.label": "Block definieren", + "cmd.defblock.base": "Basispunkt:", "cmd.polyline.label": "Polylinie", "cmd.polyline.start": "Startpunkt:", "cmd.polyline.next": "Nächster Punkt:", @@ -1157,6 +1216,10 @@ export const de = { "cmd.ellipse.label": "Ellipse", "cmd.ellipse.corner1": "Erste Ecke:", "cmd.ellipse.corner2": "Gegenüberliegende Ecke:", + "cmd.polygon.label": "Vieleck", + "cmd.polygon.center": "Mittelpunkt:", + "cmd.polygon.radius": "Radius:", + "cmd.polygon.sides": "Ecken", "cmd.spline.label": "Spline", "cmd.spline.start": "Startpunkt:", "cmd.spline.next": "Nächster Punkt ( Schliessen Zurück ):", @@ -1182,6 +1245,12 @@ export const de = { "cmd.field.offset": "Abstand", "cmd.text.label": "Text", "cmd.text.point": "Ankerpunkt:", + "cmd.leader.label": "Vorführungspfeil", + "cmd.leader.target": "Zielpunkt:", + "cmd.leader.anchor": "Textanker:", + "cmd.textpath.label": "Text entlang Pfad", + "cmd.textpath.start": "Pfadpunkt:", + "cmd.textpath.next": "Nächster Pfadpunkt (Enter = fertig):", "cmd.textbox.label": "Textspalte", "cmd.textbox.first": "Erste Ecke:", "cmd.textbox.second": "Gegenecke (Breite × Höhe):", @@ -1356,6 +1425,9 @@ export const de = { // ── Datei-Menü (Burger, ganz rechts der Oberleiste) ────────────────────── "file.menu": "Datei", + "file.new": "Neues Projekt", + "file.newFromSample": "Neu aus Vorlage: Musterhaus", + "file.newFromTemplateFile": "Neu aus Vorlage: Datei wählen …", "file.save": "Projekt speichern", "file.open": "Projekt öffnen", "file.import": "DXF/DWG importieren…", @@ -1475,7 +1547,7 @@ export const de = { "ctxImport.buildings.off": "Aus", "ctxImport.buildings.flach": "Vereinfacht (Umriss, schnell)", "ctxImport.buildings.v2": "Echt 2.0 (stabil)", - "ctxImport.buildings.v3": "Echt 3.0 (Beta)", + "ctxImport.buildings.v3": "Echt 3.0 (Beta, Dach getrennt)", "ctxImport.src.swissTerrain": "Swisstopo-Gelände", "ctxImport.src.swissImage": "SWISSIMAGE-Luftbild (2D-Hintergrund)", "ctxImport.src.swissImageDrape": "Luftbild aufs Gelände legen (3D)", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 278fb127..8aefd9a0 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -126,6 +126,10 @@ export const en: Record = { // Native macOS system menu bar (appMenu.ts) — separate namespace since it // also shows File/Export/Transform, unlike the in-app AppMenuBar. "menu.native.file": "File", + "menu.native.new": "New", + "menu.native.newFromTemplate": "New From Template", + "menu.native.newFromSample": "Sample House", + "menu.native.newFromTemplateFile": "Choose Template File…", "menu.native.open": "Open…", "menu.native.saveAs": "Save As…", "menu.native.import": "Import…", @@ -170,6 +174,10 @@ export const en: Record = { "tool.door": "Door", "tool.stair": "Stair", "tool.line": "Line", + "tool.xline": "Construction Line", + "tool.xline.hint": "Construction line: two points set the direction (extended infinitely)", + "tool.block": "Insert Block", + "tool.block.hint": "Insert block: pick the active definition via the option, then click the insertion point", "tool.polyline": "Polyline", "tool.rect": "Rectangle", "tool.circle": "Circle", @@ -178,6 +186,8 @@ export const en: Record = { "tool.arc.hint": "Arc: center, start point, then end point (CCW)", "tool.ellipse": "Ellipse", "tool.ellipse.hint": "Ellipse: two opposite corners of the bounding box", + "tool.polygon": "Polygon", + "tool.polygon.hint": "Polygon: center, then radius (sides via option)", "tool.spline": "Spline", "tool.spline.hint": "Spline: click waypoints, Enter finishes (smooth curve through the points)", "tool.bezier": "Bezier", @@ -188,6 +198,10 @@ export const en: Record = { "tool.kote.hint": "Elevation mark: set a point, then type the height value (type toggle: top/bottom, finished/raw)", "tool.text": "Text", "tool.text.hint": "Text: set anchor point, then type the text", + "tool.leader": "Leader", + "tool.leader.hint": "Leader: set target point, then text anchor, then type the text", + "tool.textpath": "Text on Path", + "tool.textpath.hint": "Text on path: set at least two path points (Enter to finish), then type the text", "tool.textbox": "Text column", "tool.textbox.hint": "Text column: anchor, drag column width, then type the text", "tool.image": "Image/PDF", @@ -303,6 +317,8 @@ export const en: Record = { // Document tabs (drawings/sheets). "tabs.drawings": "Drawings", + "tabs.add": "New view-snapshot tab", + "tabs.delete": "Delete view-snapshot tab", // Navigator panels. "nav.drawingLevels": "Drawing levels", @@ -319,6 +335,10 @@ export const en: Record = { "attr.color": "Color", "attr.weight": "Line weight (mm)", "attr.opacity": "Opacity", + "attr.saturation": "Saturation", + "attr.brightness": "Brightness", + "attr.contrast": "Contrast", + "attr.grayscale": "Grayscale", "attr.lineStyle": "Line style", "attr.lineStyle.none": "Default", "attr.fill": "Fill", @@ -371,6 +391,7 @@ export const en: Record = { "objinfo.contextObject.type.importedMesh": "Imported mesh", "objinfo.contextObject.type.terrainMesh": "Terrain", "objinfo.contextObject.type.contourSet": "Contours", + "objinfo.contextObject.type.image": "Aerial image", "objinfo.contextObject.lv95E": "LV95 East (E)", "objinfo.contextObject.lv95N": "LV95 North (N)", "objinfo.contextObject.noAnchor": "No location reference in project", @@ -706,6 +727,7 @@ export const en: Record = { "editor.layerTitle": "Layer {code}", "editor.name": "Name", "editor.color": "Color", + "editor.pen": "Pen", "editor.lineWeight": "Line weight", "editor.hatch": "Hatch", "editor.floorHeight": "Floor height", @@ -760,9 +782,12 @@ export const en: Record = { "default.doorTypeName": "New door type", "default.windowTypeName": "New window type", "default.stairTypeName": "New stair type", + "default.penName": "New pen", + "default.penSetName": "New pen set", // Alerts. "alert.layerInUse": "Layer “{code} {name}” is used by components and cannot be deleted.", + "alert.penSetIsActive": "Pen set “{name}” is active and cannot be deleted — activate another pen set first.", "alert.componentInUse": "Component “{name}” is used by a wall type and cannot be deleted.", "alert.hatchInUse": "Hatch “{name}” is used by a component and cannot be deleted.", "alert.lineStyleInUse": "Line style “{name}” is used by a hatch and cannot be deleted.", @@ -789,6 +814,22 @@ export const en: Record = { "resources.tab.stairStyles": "Stair types", "resources.tab.materials": "Materials", "resources.tab.overrides": "Overrides", + "resources.tab.pens": "Pens", + + // Pen sets (ArchiCAD pen-set pattern). + "resources.pens.hint": "A component or layer can be linked to a pen instead of a free color. Pens themselves carry no color — that comes from the ACTIVE pen set. Switching between pen sets instantly recolors everything linked to a pen.", + "resources.pens.setPlaceholder": "Pen set name", + "resources.pens.isActive": "This pen set is active.", + "resources.pens.activate": "Set as active", + "resources.pens.activeBadge": "active", + "resources.pens.empty": "No pens yet — add one with “+ Pen”.", + "resources.pens.emptySets": "No pen sets yet.", + "resources.pens.addPen": "Pen", + "resources.pens.addSet": "Pen set", + "resources.pens.seedStandard": "Load 255 standard pens", + "resources.pens.seedStandard.hint": "Replaces the pen list with 255 procedurally generated pens (classic CAD numbering: 1-9 base colors, 10-249 hue steps, 250-255 grey wedge) plus a new active pen set with these colors.", + "resources.delete.penSet": "Delete pen set “{name}”", + "resources.delete.pen": "Delete pen “{name}”", // Graphic overrides (rule engine). "resources.overrides.hint": @@ -947,12 +988,21 @@ export const en: Record = { "resources.col.prio.hint": "Higher priority runs through at the join", "resources.col.texture": "Texture", "resources.col.material": "Material", + "resources.col.color.hint": "Base color — 3D diffuse color + fallback for foreground/background when they have no color of their own", "resources.col.foreground": "Foreground", "resources.col.foreground.hint": "Color of the pattern/hatch lines (foreground)", "resources.col.background": "Background", "resources.col.background.hint": "Fill color (poché/background)", "resources.delete.component": "Delete component “{name}”", + // Pen linking (ArchiCAD pen-set pattern) — dropdown next to color fields. + "pen.free": "Free", + "pen.byPen": "Pen", + "pen.numberHint": "Pen number", + "pen.weightHint": "Weight: {weight} mm", + "pen.customColor": "Other color …", + "pen.hexHint": "Hex color value (#rrggbb)", + // 3D material (PBR) — built-in library + upload. "material.assign": "Material …", "material.none": "— none —", @@ -1052,6 +1102,7 @@ export const en: Record = { "pattern.insulation": "Insulation", "pattern.diagonal": "Diagonal", "pattern.crosshatch": "Crosshatch", + "pattern.custom": "Custom motif", "resources.lines.hint": "Line weight in millimetres (paper space). Stroke: solid, dashed or dotted.", "resources.lines.empty": "No line styles yet.", @@ -1122,6 +1173,14 @@ export const en: Record = { "cmd.line.label": "Line", "cmd.line.start": "Start of line:", "cmd.line.end": "End of line:", + "cmd.xline.label": "Construction Line", + "cmd.xline.start": "Start point:", + "cmd.xline.end": "Direction point:", + "cmd.block.label": "Insert Block", + "cmd.block.point": "Insertion point:", + "cmd.block.def": "Symbol", + "cmd.defblock.label": "Define Block", + "cmd.defblock.base": "Base point:", "cmd.polyline.label": "Polyline", "cmd.polyline.start": "Start point:", "cmd.polyline.next": "Next point:", @@ -1146,6 +1205,10 @@ export const en: Record = { "cmd.ellipse.label": "Ellipse", "cmd.ellipse.corner1": "First corner:", "cmd.ellipse.corner2": "Opposite corner:", + "cmd.polygon.label": "Polygon", + "cmd.polygon.center": "Center:", + "cmd.polygon.radius": "Radius:", + "cmd.polygon.sides": "Sides", "cmd.spline.label": "Spline", "cmd.spline.start": "Start point:", "cmd.spline.next": "Next point ( Close Undo ):", @@ -1171,6 +1234,12 @@ export const en: Record = { "cmd.field.offset": "Offset", "cmd.text.label": "Text", "cmd.text.point": "Anchor point:", + "cmd.leader.label": "Leader", + "cmd.leader.target": "Target point:", + "cmd.leader.anchor": "Text anchor:", + "cmd.textpath.label": "Text on Path", + "cmd.textpath.start": "Path point:", + "cmd.textpath.next": "Next path point (Enter to finish):", "cmd.textbox.label": "Text column", "cmd.textbox.first": "First corner:", "cmd.textbox.second": "Opposite corner (width × height):", @@ -1344,6 +1413,9 @@ export const en: Record = { // File menu (burger, far right of the top bar). "file.menu": "File", + "file.new": "New Project", + "file.newFromSample": "New From Template: Sample House", + "file.newFromTemplateFile": "New From Template: Choose File…", "file.save": "Save project", "file.open": "Open project", "file.import": "Import DXF/DWG…", @@ -1462,7 +1534,7 @@ export const en: Record = { "ctxImport.buildings.off": "Off", "ctxImport.buildings.flach": "Simplified (footprint, fast)", "ctxImport.buildings.v2": "Real 2.0 (stable)", - "ctxImport.buildings.v3": "Real 3.0 (Beta)", + "ctxImport.buildings.v3": "Real 3.0 (Beta, roof separated)", "ctxImport.src.swissTerrain": "Swisstopo terrain", "ctxImport.src.swissImage": "SWISSIMAGE aerial (2D backdrop)", "ctxImport.src.swissImageDrape": "Drape aerial onto terrain (3D)", diff --git a/src/io/dwgParser.test.ts b/src/io/dwgParser.test.ts new file mode 100644 index 00000000..e5e817d3 --- /dev/null +++ b/src/io/dwgParser.test.ts @@ -0,0 +1,186 @@ +// `extractPfaceMeshesByLayer` liest POLYLINE_PFACE-Entities (DWG-Typ 29, Polyface- +// Mesh) über die LOW-LEVEL-LibreDWG-API, weil `convert()` diesen Typ nachweislich +// NICHT auf `.entities` abbildet (leeres Ergebnis an jedem betroffenen +// BLOCK_RECORD — empirisch gegen echte swissBUILDINGS3D-v3-„separated"-Kacheln +// verifiziert). Die Ableitungskette (Pointer→TIO→parent→layer/owner-Handle, +// Vertex-Array→Punkte/Face-Records) ist fehleranfällig genug, um eine echte +// Regressionsabsicherung zu verdienen — dieser Test baut eine handgeschriebene +// Fake-`LibreDwgApi` nach exakt dem Schema, das gegen echte Daten verifiziert +// wurde (s. Moduldoc in dwgParser.ts), statt echtes WASM zu laden. + +import { describe, it, expect } from "vitest"; +import { + extractPfaceMeshesByLayer, + type LibreDwgApi, + type DwgDynapiResult, + type DwgObjectRefLike, +} from "./dwgParser"; + +/** Baut eine Fake-API mit genau EINEM Polyface-Mesh: 3 Punkte + 1 Dreieck-Face, + * Layer + Owner-Block wählbar (für Mehr-Layer-Tests). Punkte sind block-lokal + * bei (0,0,z)/(1,0,z)/(0,1,z); die INSERT-Transform verschiebt sie um `insert`. */ +function fakeApi(opts: { + layerHandle: string; + layerName: string; + blockHandle: string; + blockName: string; + insert: { x: number; y: number; z: number }; +}): LibreDwgApi { + const pfaceTio = 1; + const entityPtr = 2; + const vertexArrPtr = 3; + // Vertex-Ref-Objekte: 3 Punkte (10/11/12) + 1 Face-Record (13). + const refs: DwgObjectRefLike[] = [ + { obj: 10, absolute_ref: 0 }, + { obj: 11, absolute_ref: 0 }, + { obj: 12, absolute_ref: 0 }, + { obj: 13, absolute_ref: 0 }, + ]; + const tioOf = (objPtr: number): number => objPtr * 100; // 10->1000, 13->1300 … + const points: Record = { + [tioOf(10)]: { x: 0, y: 0, z: 1808.7 }, + [tioOf(11)]: { x: 1, y: 0, z: 1809 }, + [tioOf(12)]: { x: 0, y: 1, z: 1810 }, + }; + const VERTIND_OFFSET = 8; + + return { + dwg_read_data: () => undefined, + convert: () => ({ + entities: [ + { + type: "INSERT", + name: opts.blockName, + layer: opts.layerName, + insertionPoint: opts.insert, + rotation: 0, + xScale: 1, + yScale: 1, + zScale: 1, + }, + ], + tables: { + LAYER: { entries: [{ name: opts.layerName, handle: opts.layerHandle }] }, + BLOCK_RECORD: { entries: [{ name: opts.blockName, handle: opts.blockHandle }] }, + }, + }), + dwg_free: () => {}, + dwg_getall_entity_by_type: () => [pfaceTio], + dwg_dynapi_entity_value: (objOrTio: number, field: string): DwgDynapiResult => { + if (objOrTio === pfaceTio) { + if (field === "num_owned") return { success: true, data: refs.length }; + if (field === "vertex") return { success: true, data: vertexArrPtr }; + if (field === "parent") return { success: true, data: entityPtr }; + } + if (field === "point") { + const p = points[objOrTio]; + return p ? { success: true, data: p } : { success: false }; + } + return { success: false }; + }, + dwg_object_to_entity_tio: (objPtr: number) => tioOf(objPtr), + dwg_object_entity_get_layer_object_ref: () => ({ + obj: 0, + absolute_ref: Number.parseInt(opts.layerHandle, 16), + }), + dwg_object_entity_get_ownerhandle_object: () => ({ + obj: 0, + absolute_ref: Number.parseInt(opts.blockHandle, 16), + }), + dwg_ptr_to_object_ref_array: (ptr: number) => (ptr === vertexArrPtr ? refs : []), + dwg_dynapi_entity_field_offset: (tio: number, field: string) => + field === "vertind" && tio === tioOf(13) ? VERTIND_OFFSET : 0, + dwg_ptr_to_int16_t_array: (ptr: number) => + ptr === tioOf(13) + VERTIND_OFFSET ? [1, 2, 3, 0] : [], + }; +} + +describe("extractPfaceMeshesByLayer", () => { + it("liest Punkte + Dreieck-Face eines Polyface-Meshes und ordnet sie dem DXF-Layer zu", () => { + const api = fakeApi({ + layerHandle: "5E", + layerName: "Roof", + blockHandle: "60", + blockName: "FMEBLOCK1", + insert: { x: 2739334.4, y: 1176965.2, z: 0 }, + }); + const db = api.convert(0); + const result = extractPfaceMeshesByLayer(api, 0, db, db.entities as never); + + expect([...result.keys()]).toEqual(["Roof"]); + const bucket = result.get("Roof")!; + // 3 Punkte, je um die INSERT-Insertion verschoben (Skalierung 1, Rotation 0). + expect(bucket.positions).toEqual([ + 2739334.4, 1176965.2, 1808.7, + 2739335.4, 1176965.2, 1809, + 2739334.4, 1176966.2, 1810, + ]); + // Ein Dreieck (vertind [1,2,3,0] -> 0-basiert [0,1,2], 4. Slot ungenutzt). + expect(bucket.indices).toEqual([0, 1, 2]); + }); + + it("gruppiert mehrere Polyface-Meshes nach ihrem jeweiligen Layer getrennt", () => { + const roofApi = fakeApi({ + layerHandle: "5E", + layerName: "Roof", + blockHandle: "60", + blockName: "B1", + insert: { x: 0, y: 0, z: 0 }, + }); + // Zweite Fake-Instanz mit Layer "Wall" statt "Roof" — dieselbe Struktur, + // andere Handle-Zuordnung, um die Gruppierung (nicht nur den Einzelfall) zu prüfen. + const wallApi = fakeApi({ + layerHandle: "E3C", + layerName: "Wall", + blockHandle: "8C6", + blockName: "B2", + insert: { x: 0, y: 0, z: 0 }, + }); + const roofDb = roofApi.convert(0); + const wallDb = wallApi.convert(0); + const roofResult = extractPfaceMeshesByLayer(roofApi, 0, roofDb, roofDb.entities as never); + const wallResult = extractPfaceMeshesByLayer(wallApi, 0, wallDb, wallDb.entities as never); + + expect([...roofResult.keys()]).toEqual(["Roof"]); + expect([...wallResult.keys()]).toEqual(["Wall"]); + }); + + it("überspringt ein Polyface-Mesh ohne auflösbares num_owned/vertex statt zu werfen", () => { + const api = fakeApi({ + layerHandle: "5E", + layerName: "Roof", + blockHandle: "60", + blockName: "FMEBLOCK1", + insert: { x: 0, y: 0, z: 0 }, + }); + const broken: LibreDwgApi = { + ...api, + dwg_dynapi_entity_value: (objOrTio, field) => + field === "num_owned" || field === "vertex" + ? { success: false } + : api.dwg_dynapi_entity_value(objOrTio, field), + }; + const db = broken.convert(0); + const result = extractPfaceMeshesByLayer(broken, 0, db, db.entities as never); + expect(result.size).toBe(0); + }); + + it("liefert eine leere Map, wenn dwg_getall_entity_by_type nicht verfügbar ist (kein Absturz)", () => { + const api = fakeApi({ + layerHandle: "5E", + layerName: "Roof", + blockHandle: "60", + blockName: "FMEBLOCK1", + insert: { x: 0, y: 0, z: 0 }, + }); + const unsupported: LibreDwgApi = { + ...api, + dwg_getall_entity_by_type: () => { + throw new Error("nicht in diesem WASM-Build kompiliert"); + }, + }; + const db = unsupported.convert(0); + const result = extractPfaceMeshesByLayer(unsupported, 0, db, db.entities as never); + expect(result.size).toBe(0); + }); +}); diff --git a/src/io/dwgParser.ts b/src/io/dwgParser.ts index 5542f4ee..d4d4ab4d 100644 --- a/src/io/dwgParser.ts +++ b/src/io/dwgParser.ts @@ -21,6 +21,12 @@ // Unterstützte Entities (Modellraum + expandierte Blöcke): // • 3DFACE → Dreiecks-Mesh (3 bzw. 4 Ecken → 1–2 Tri). // • POLYLINE2D (Polyface, Flag 64) → Dreiecks-Mesh (Polyface-Faces). +// • POLYLINE_PFACE (DWG-Typ 29) → Dreiecks-Mesh, NACH DXF-LAYER GRUPPIERT +// (s. `extractPfaceMeshesByLayer` — eigener +// Low-Level-Pfad, da `convert()` diesen Typ +// nicht auf `.entities` abbildet; verifiziert +// gegen swissBUILDINGS3D-v3-„separated"- +// Kacheln, dort „Roof"/„Wall"/„Floor"). // • LWPOLYLINE / POLYLINE2D / 3D → Kontur (z aus elevation/Vertex-Z). // • LINE → Kontur (zwei-Punkt-Linienzug). // • ARC → Kontur (Bogen, ~6° je Segment, offen). @@ -39,6 +45,7 @@ import type { Contour, ContourSet, ImportedMesh, Vec2 } from "../model/types"; import type { DxfImportResult, ImportDiagnostics } from "./dxfParser"; +import { GENERIC_IMPORT_CATEGORY } from "../model/contextCategories"; // Lose getippte Sicht auf die libredwg-web-Entities (wir greifen tolerant auf die // Felder zu, die wir brauchen; alle Punkte sind {x,y,z}). @@ -89,21 +96,58 @@ interface DwgEntityLike { } // Block-Record-Tabelleneintrag: Block-Name → Entities (siehe blockRecord.d.ts). -interface DwgBlockRecordLike { +// `handle` (Hex-String, z. B. "5E") wird für die POLYLINE_PFACE-Owner-Auflösung +// gebraucht (s. {@link extractPfaceMeshesByLayer}) — dieselbe Form wie bei +// {@link DwgLayerEntry}. +export interface DwgBlockRecordLike { name?: string; + handle?: string; entities?: DwgEntityLike[]; } +/** LAYER-Tabelleneintrag (Name + Hex-Handle) — für die Layer-Namensauflösung + * von POLYLINE_PFACE-Entities (s. {@link extractPfaceMeshesByLayer}). */ +export interface DwgLayerEntry { + name?: string; + handle?: string; +} + +/** Rückgabeform von `dwg_dynapi_entity_value`/`dwg_dynapi_entity_data` + * (generische Feld-Introspektion) — `data` ist je Feldtyp verschieden geformt + * (Zahl, `{x,y,z}`-Punkt, roher Heap-Pointer bei Array-/Handle-Feldern). */ +export interface DwgDynapiResult { + success: boolean; + data?: unknown; +} + +/** Aufgelöste Handle-Referenz (`Dwg_Object_Ref`) — `obj` ist der aufgelöste + * Objekt-Pointer (0/null = nicht auflösbar), `absolute_ref` das Handle selbst + * (Zahl ODER BigInt, je nach WASM-Build). */ +export interface DwgObjectRefLike { + obj: number; + absolute_ref: number | bigint; +} + // Schmale Sicht auf die LibreDWG-Instanz (nur die Methoden, die wir nutzen). -interface LibreDwgApi { +export interface LibreDwgApi { dwg_read_data(data: ArrayBuffer, fileType: number): number | undefined; convert(ptr: number): { entities?: unknown[]; tables?: { BLOCK_RECORD?: { entries?: DwgBlockRecordLike[] }; + LAYER?: { entries?: DwgLayerEntry[] }; }; }; dwg_free(ptr: number): void; + // ── Low-Level-API für POLYLINE_PFACE (s. Moduldoc bei {@link extractPfaceMeshesByLayer}) ── + dwg_getall_entity_by_type(dwgPtr: number, type: number): number[]; + dwg_dynapi_entity_value(objOrTio: number, field: string): DwgDynapiResult; + dwg_object_to_entity_tio(objPtr: number): number; + dwg_object_entity_get_layer_object_ref(entityPtr: number): DwgObjectRefLike; + dwg_object_entity_get_ownerhandle_object(entityPtr: number): DwgObjectRefLike; + dwg_ptr_to_object_ref_array(ptr: number, size: number): DwgObjectRefLike[]; + dwg_dynapi_entity_field_offset(tio: number, field: string): number; + dwg_ptr_to_int16_t_array(ptr: number, size: number): number[]; } // Singleton der WASM-Instanz (einmal laden, dann wiederverwenden). @@ -246,15 +290,185 @@ function insertTransform(e: DwgEntityLike): Transform2D { }; } +/** Positions-/Indexpuffer EINER Mesh-Gruppe (s. {@link Accum.meshesByLayer}). */ +interface MeshBucket { + positions: number[]; + indices: number[]; +} + // Aufnahme-Kontext für ein Mapping-Durchlauf (Meshes + Konturen + Histogramm). +// Meshes werden NACH DXF-LAYER-NAMEN gruppiert (statt in einem einzigen Puffer) +// — swissBUILDINGS3D v3 „separated" liefert z. B. „Roof"/„Wall"/„Floor" als +// eigene Layer je Gebäudefläche; damit sich das (Nutzer-Wunsch: Dach als eigene, +// ausblendbare Sub-Ebene) im Ergebnis widerspiegelt, MUSS die Gruppierung schon +// hier beim Parsen erhalten bleiben statt in einem Layer-losen Blob zu verschwinden. +// Ein DWG ohne (oder mit nur einem) Layer ergibt weiterhin genau EIN Mesh — die +// Gruppierung ist rein additiv, kein Verhaltensbruch für den generischen Fall. interface Accum { - meshTriangles: number[]; - meshIndices: number[]; + meshesByLayer: Map; contours: Contour[]; entityCounts: Record; total: number; } +/** Liefert (und legt bei Bedarf an) den Mesh-Puffer für einen DXF-Layernamen; + * leerer/fehlender Layername fällt auf `"0"` zurück (AutoCAD-Konvention für + * „kein eigener Layer"). */ +function meshBucket(acc: Accum, layer: string | undefined): MeshBucket { + const key = layer && layer.length > 0 ? layer : "0"; + let b = acc.meshesByLayer.get(key); + if (!b) { + b = { positions: [], indices: [] }; + acc.meshesByLayer.set(key, b); + } + return b; +} + +// DWG_TYPE_POLYLINE_PFACE (29) — Polyface-Mesh, wie in libredwgs `dwg.h` +// (`_dwg_entity_POLYLINE_PFACE`) benannt. Literal (statt Enum-Import), damit +// kein zusätzlicher Typ-Import den lazy WASM-Chunk aufbläht — analog zu +// `FILE_TYPE_DWG` oben. +const DWG_TYPE_POLYLINE_PFACE = 29; + +/** Baut eine Hex-Handle → Name-Map aus einer Tabelle (LAYER oder BLOCK_RECORD). + * `handle`/`absolute_ref` sind teils `number`, teils `bigint` (je WASM-Build) + * — als `BigInt` normalisiert, damit der Vergleich unabhängig davon stimmt. */ +function handleToNameMap( + entries: { name?: string; handle?: string }[] | undefined, +): Map { + const map = new Map(); + for (const e of entries ?? []) { + if (!e.name || !e.handle) continue; + const h = Number.parseInt(e.handle, 16); + if (Number.isFinite(h)) map.set(BigInt(h), e.name); + } + return map; +} + +/** Baut Blockname → Einfüge-Transform aus den Modellraum-INSERT-Entities + * (bereits von `convert()` korrekt geliefert, inkl. `layer`) — s. Moduldoc + * bei {@link extractPfaceMeshesByLayer}: jeder anonyme FME-Block wird genau + * EINMAL per INSERT platziert, dessen Transform auf die Block-lokalen + * POLYLINE_PFACE-Punktkoordinaten angewendet werden muss. */ +function buildInsertTransformsByBlockName( + modelSpaceEntities: DwgEntityLike[], +): Map { + const map = new Map(); + for (const e of modelSpaceEntities) { + if ((e.type ?? "").toUpperCase() !== "INSERT" || !e.name) continue; + map.set(e.name, insertTransform(e)); + } + return map; +} + +/** + * Extrahiert POLYLINE_PFACE-Entities (Polyface-Mesh, DWG-Typ 29) NACH LAYER + * GRUPPIERT — direkt über die Low-Level-LibreDWG-API, weil `convert()` diesen + * Entity-Typ NICHT auf `Dwg_Entity`-Objekte abbildet (leeres `.entities` an + * jedem betroffenen `BLOCK_RECORD`, empirisch verifiziert gegen echte + * swissBUILDINGS3D-v3-„separated"-Kacheln — nicht dokumentiert, kein Bug-Report + * dazu gefunden). Die für den Zugriff nötige Ableitungskette (an echten Daten + * durchgetestet, jeder Schritt reproduzierbar): + * 1. `dwg_getall_entity_by_type(dwgPtr, 29)` → TIO-Pointer je Polyface-Mesh. + * 2. `dwg_dynapi_entity_value(tio, "num_owned"/"vertex")` → Anzahl + Pointer + * auf das Handle-Array der referenzierten VERTEX_PFACE/_FACE-Kinder. + * 3. `dwg_dynapi_entity_value(tio, "parent")` → `Dwg_Object_Entity*` (NICHT + * mit dem TIO identisch — TIO ist ein weiterer Zeiger-Schritt tiefer). + * 4. Über `parent`: `dwg_object_entity_get_layer_object_ref`/ + * `..._get_ownerhandle_object` → Layer- bzw. Owner-Block-Handle, gegen die + * LAYER-/BLOCK_RECORD-Tabelle aufgelöst (Schritt 3 ist zwingend — dieselben + * Funktionen mit dem TIO direkt aufgerufen liefern nur Nullen). + * 5. `dwg_ptr_to_object_ref_array(vertexPtr, numOwned)` löst das Handle-Array + * zu `{obj}`-Objekten auf; `dwg_object_to_entity_tio(ref.obj)` + erneutes + * `dwg_dynapi_entity_value(..., "point")` liefert je nach Kind entweder + * einen Geometriepunkt (VERTEX_PFACE) ODER (Erfolg `false`) eine Face. + * 6. Für Faces ist `vertind` (4× int16, DXF 71–74) ein FESTES C-Array — weder + * `dwg_dynapi_entity_value` NOCH `..._data` liefern es (leer/`undefined`, + * vermutlich in diesem WASM-Build nicht kompiliert); einziger funktio- + * nierender Weg: `dwg_dynapi_entity_field_offset(tio, "vertind")` (Byte- + * Offset im Struct) + `dwg_ptr_to_int16_t_array(tio + offset, 4)`. + * Punkte werden mit der zum Owner-Block gehörenden INSERT-Transform (s. + * {@link buildInsertTransformsByBlockName}) in Welt-/Tile-lokale Koordinaten + * gebracht — Punkte liegen block-lokal nahe (0,0,0), ohne diese Transform + * bekäme man keine brauchbaren (LV95-nahen) Koordinaten. + */ +export function extractPfaceMeshesByLayer( + libredwg: LibreDwgApi, + dwgPtr: number, + db: ReturnType, + modelSpaceEntities: DwgEntityLike[], +): Map { + const result = new Map(); + const layerNames = handleToNameMap(db.tables?.LAYER?.entries); + const blockNames = handleToNameMap(db.tables?.BLOCK_RECORD?.entries); + const xformByBlock = buildInsertTransformsByBlockName(modelSpaceEntities); + + const bucketFor = (layer: string): MeshBucket => { + let b = result.get(layer); + if (!b) { + b = { positions: [], indices: [] }; + result.set(layer, b); + } + return b; + }; + + let pfaces: number[]; + try { + pfaces = libredwg.dwg_getall_entity_by_type(dwgPtr, DWG_TYPE_POLYLINE_PFACE); + } catch { + return result; // WASM-Build ohne diese Low-Level-Funktion — kein harter Fehler. + } + + for (const tio of pfaces) { + const numOwned = libredwg.dwg_dynapi_entity_value(tio, "num_owned").data; + const vertexArrPtr = libredwg.dwg_dynapi_entity_value(tio, "vertex").data; + if (typeof numOwned !== "number" || numOwned <= 0 || typeof vertexArrPtr !== "number" || !vertexArrPtr) { + continue; + } + const entityPtr = libredwg.dwg_dynapi_entity_value(tio, "parent").data; + if (typeof entityPtr !== "number" || !entityPtr) continue; + + const layerRef = libredwg.dwg_object_entity_get_layer_object_ref(entityPtr); + const layerName = layerNames.get(BigInt(layerRef.absolute_ref ?? 0)) ?? "0"; + const ownerRef = libredwg.dwg_object_entity_get_ownerhandle_object(entityPtr); + const blockName = blockNames.get(BigInt(ownerRef.absolute_ref ?? 0)); + const xform = (blockName ? xformByBlock.get(blockName) : undefined) ?? IDENTITY; + + const bucket = bucketFor(layerName); + const base = bucket.positions.length / 3; + const faceRecords: number[][] = []; + for (const ref of libredwg.dwg_ptr_to_object_ref_array(vertexArrPtr, numOwned)) { + if (!ref.obj) continue; + const childTio = libredwg.dwg_object_to_entity_tio(ref.obj); + if (!childTio) continue; + const point = libredwg.dwg_dynapi_entity_value(childTio, "point"); + if (point.success && point.data && typeof point.data === "object") { + const p = point.data as { x: number; y: number; z: number }; + const xy = applyXY(xform, p.x, p.y); + bucket.positions.push(xy.x, xy.y, applyZ(xform, p.z)); + continue; + } + // Kein Punkt → Face-Record (vertind, s. Moduldoc Schritt 6). + const off = libredwg.dwg_dynapi_entity_field_offset(childTio, "vertind"); + if (!off) continue; + faceRecords.push(libredwg.dwg_ptr_to_int16_t_array(childTio + off, 4)); + } + for (const vertind of faceRecords) { + // 1-basiert, ggf. negativ (unsichtbare Kante) — wie DXF-Faces (s. + // `faceIndicesOf`/`dxfParser.ts`); 0 = ungenutzter 4. Slot bei Dreiecken. + const ring = vertind + .map((i) => Math.abs(i)) + .filter((i) => i >= 1) + .map((i) => base + (i - 1)); + if (ring.length < 3) continue; + for (let i = 1; i + 1 < ring.length; i++) { + pushTri(bucket.indices, bucket.positions, ring[0], ring[i], ring[i + 1]); + } + } + } + return result; +} + /** * Parst eine DWG-Datei (als ArrayBuffer) in dasselbe Kontext-Geometrie-Format * wie der DXF-Parser. Lädt LibreDWG-WASM lazy. Wirft bei fatalen Fehlern (der @@ -263,6 +477,10 @@ interface Accum { * Reale DWGs stecken Geometrie oft in BLÖCKEN, die nur per INSERT referenziert * werden; wir lesen die Block-Definitionen aus `db.tables.BLOCK_RECORD` und * expandieren jedes INSERT mit Transformation (rekursiv, Tiefen-Limit). + * Zusätzlich (s. {@link extractPfaceMeshesByLayer}) werden POLYLINE_PFACE- + * Polyface-Meshes über die Low-Level-API gelesen und NACH LAYER GRUPPIERT + * zurückgegeben — bei swissBUILDINGS3D v3 „separated" ergeben sich so z. B. + * eigene Meshes je „Roof"/„Wall"/„Floor" statt eines einzigen Blobs. */ export async function parseDwg(data: ArrayBuffer): Promise { const libredwg = await createLibreDwg(); @@ -289,8 +507,7 @@ export async function parseDwg(data: ArrayBuffer): Promise { } const acc: Accum = { - meshTriangles: [], - meshIndices: [], + meshesByLayer: new Map(), contours: [], entityCounts: {}, total: 0, @@ -299,14 +516,36 @@ export async function parseDwg(data: ArrayBuffer): Promise { // Modellraum-Entities mappen (INSERTs expandieren Blöcke rekursiv). mapEntities(entities, IDENTITY, blocks, 0, acc); + // POLYLINE_PFACE-Meshes (von `convert()` nicht abgedeckt) additiv dazu. + for (const [layer, pfaceBucket] of extractPfaceMeshesByLayer( + libredwg, + dwgPtr, + db, + entities, + )) { + if (pfaceBucket.indices.length === 0) continue; + const bucket = meshBucket(acc, layer); + const base = bucket.positions.length / 3; + // KEIN `push(...pfaceBucket.positions)`: bei grossen Kacheln (v3- + // Städtetiles, tausende Gebäude) sprengt der Spread-Operator die + // Argumentzahl-Grenze von `push`/`apply` (RangeError „Maximum call + // stack size exceeded" — an einer echten 2000-Gebäude-Kachel verifiziert). + for (const p of pfaceBucket.positions) bucket.positions.push(p); + for (const i of pfaceBucket.indices) bucket.indices.push(base + i); + } + const meshes: ImportedMesh[] = []; - if (acc.meshIndices.length > 0) { + const multiLayer = acc.meshesByLayer.size > 1; + for (const [layer, bucket] of acc.meshesByLayer) { + if (bucket.indices.length === 0) continue; meshes.push({ id: nextId("imported"), type: "importedMesh", - name: "DWG-Mesh", - positions: acc.meshTriangles, - indices: acc.meshIndices, + name: multiLayer ? `DWG-Mesh (${layer})` : "DWG-Mesh", + categoryCode: GENERIC_IMPORT_CATEGORY.code, + layer: layer === "0" ? undefined : layer, + positions: bucket.positions, + indices: bucket.indices, }); } @@ -316,6 +555,7 @@ export async function parseDwg(data: ArrayBuffer): Promise { id: nextId("contours"), type: "contourSet", name: "DWG-Konturen", + categoryCode: GENERIC_IMPORT_CATEGORY.code, contours: acc.contours, }); } @@ -442,8 +682,9 @@ function mapEntities( * Punkte werden mit der aktiven Transform in den Modellraum gebracht. */ function addFace(acc: Accum, e: DwgEntityLike, xform: Transform2D): void { - const positions = acc.meshTriangles; - const indices = acc.meshIndices; + const bucket = meshBucket(acc, e.layer); + const positions = bucket.positions; + const indices = bucket.indices; const corners = [e.corner1, e.corner2, e.corner3, e.corner4].filter( (c): c is DwgPoint => !!c && Number.isFinite(c.x) && Number.isFinite(c.y), ); @@ -490,8 +731,9 @@ function addPolyfaceMesh( e: DwgEntityLike, xform: Transform2D, ): void { - const positions = acc.meshTriangles; - const indices = acc.meshIndices; + const bucket = meshBucket(acc, e.layer); + const positions = bucket.positions; + const indices = bucket.indices; const all = e.vertices ?? []; const hasFaceIdx = (v: DwgVertexLike): boolean => !!( diff --git a/src/io/dxfParser.ts b/src/io/dxfParser.ts index f9a5172b..39377e88 100644 --- a/src/io/dxfParser.ts +++ b/src/io/dxfParser.ts @@ -28,6 +28,7 @@ import DxfParser from "dxf-parser"; import type { Contour, ContourSet, ImportedMesh, ImportedText, Vec2 } from "../model/types"; +import { GENERIC_IMPORT_CATEGORY } from "../model/contextCategories"; /** * Optionale Import-Diagnose: Histogramm der gelesenen Entity-Typen (Typ → Anzahl) @@ -191,6 +192,7 @@ export function parseDxf(text: string): DxfImportResult { id: nextId("imported"), type: "importedMesh", name: "DXF-Mesh", + categoryCode: GENERIC_IMPORT_CATEGORY.code, positions: meshTriangles, indices: meshIndices, }); @@ -202,6 +204,7 @@ export function parseDxf(text: string): DxfImportResult { id: nextId("contours"), type: "contourSet", name: "DXF-Konturen", + categoryCode: GENERIC_IMPORT_CATEGORY.code, contours, }); } diff --git a/src/io/geoContext.ts b/src/io/geoContext.ts index 318e5c4c..b811beaf 100644 --- a/src/io/geoContext.ts +++ b/src/io/geoContext.ts @@ -9,6 +9,7 @@ import Delaunator from "delaunator"; import type { ContextObject, Contour, ImportedMesh } from "../model/types"; +import { GEO_CATEGORY_DEFS } from "../model/contextCategories"; /** Fachliche Kategorie einer importierten Kontext-Linie. */ export type GeoCategory = @@ -99,6 +100,7 @@ export function featuresToContextObjects( type: "contourSet", name: `${CATEGORY_LABEL[cat]} (${sourceLabel})`, layer: CATEGORY_LAYER[cat], + categoryCode: GEO_CATEGORY_DEFS[cat].code, contours, }); } @@ -141,6 +143,7 @@ export function buildingsToMesh( type: "importedMesh", name: `Gebäude 3D (${sourceLabel})`, layer: CATEGORY_LAYER.building, + categoryCode: GEO_CATEGORY_DEFS.building.code, positions, indices, }; diff --git a/src/io/projectFile.ts b/src/io/projectFile.ts index bbf4fef2..03c2d837 100644 --- a/src/io/projectFile.ts +++ b/src/io/projectFile.ts @@ -23,6 +23,17 @@ export const PROJECT_DIALOG_FILTERS = [ { name: "openbureau-Projekt (alt, JSON)", extensions: ["json"] }, ]; +/** Datei-Endung für VORLAGEN (dasselbe JSON-Format wie `.obp`, aber als Start- + * punkt für ein neues, noch ungespeichertes Projekt gedacht — "Neu aus + * Vorlage" öffnet sie, hängt sich aber NICHT an ihren Pfad (kein Lock, kein + * Überschreiben der Vorlage beim nächsten Speichern). */ +export const PROJECT_TEMPLATE_EXT = "obpt"; + +/** Dialog-Filter für den nativen Vorlage-Öffnen-Dialog. */ +export const PROJECT_TEMPLATE_DIALOG_FILTERS = [ + { name: "openbureau-Vorlage", extensions: [PROJECT_TEMPLATE_EXT] }, +]; + /** Erkennt Tauri wie an anderen Stellen (saveFile.ts, nativeSync.ts). */ export function isTauriRuntime(): boolean { return typeof window !== "undefined" && "__TAURI_INTERNALS__" in window; @@ -55,6 +66,29 @@ export async function openProjectFileNative(): Promise return { path: selected, content }; } +/** + * Öffnet eine VORLAGEN-Datei (`.obpt`) über den nativen Öffnen-Dialog. Nur + * unter Tauri sinnvoll — liefert `null` im Browser, dort greift der + * ``-Fluss (analog `openProjectFileNative`). + * Anders als beim Projekt-Öffnen wird der zurückgegebene Pfad NICHT als + * "aktuell offene Datei" gemerkt — die Vorlage bleibt unverändert. + * + * @returns `null` bei Abbruch/ohne Tauri, sonst Pfad + Textinhalt. + */ +export async function openProjectTemplateNative(): Promise { + if (!isTauriRuntime()) return null; + const { open } = await import("@tauri-apps/plugin-dialog"); + const selected = await open({ + multiple: false, + directory: false, + filters: PROJECT_TEMPLATE_DIALOG_FILTERS, + }); + if (!selected || Array.isArray(selected)) return null; + const { readTextFile } = await import("@tauri-apps/plugin-fs"); + const content = await readTextFile(selected); + return { path: selected, content }; +} + /** * Öffnet eine Projektdatei über einen BEKANNTEN Pfad (kein Dialog) — für den * Startbildschirm/„Zuletzt geöffnet" (state/recentProjects.ts): der Pfad kommt diff --git a/src/io/stacApi.ts b/src/io/stacApi.ts index 9934471f..8a27a71b 100644 --- a/src/io/stacApi.ts +++ b/src/io/stacApi.ts @@ -84,6 +84,55 @@ function estimateUncompressedSize(entry: JSZip.JSZipObject): number | null { return typeof data?.uncompressedSize === "number" ? data.uncompressedSize : null; } +/** Wählt den passenden ZIP-Eintrag: eine der `innerExt`-Endungen, optional + * bevorzugt nach `preferNameIncludes` (Teilstring, klein geschrieben) — + * swissBUILDINGS3D-v3-Kacheln bündeln z. B. „…_separated_….dwg" UND + * „…_solid_….dwg" im selben Zip; nur `separated` lässt sich mit LibreDWG + * lesen (`solid` liefert 0 Entities, vermutlich ACIS-Volumenkörper statt + * Polyface-Mesh). Ohne Treffer auf den Präferenz-Teilstring fällt es auf den + * ersten `innerExt`-Treffer zurück (unverändertes Verhalten). */ +function pickZipEntry( + zip: JSZip, + innerExt: string[], + preferNameIncludes?: string, +): JSZip.JSZipObject | null { + const candidates = Object.values(zip.files).filter( + (f) => !f.dir && innerExt.some((ext) => f.name.toLowerCase().endsWith(ext)), + ); + if (candidates.length === 0) return null; + if (preferNameIncludes) { + const preferred = candidates.find((f) => + f.name.toLowerCase().includes(preferNameIncludes), + ); + if (preferred) return preferred; + } + return candidates[0]; +} + +/** Lädt ein Asset als `Response`, sofern es unter {@link MAX_ASSET_BYTES} + * bleibt (STAC-`size` UND — falls vorhanden — `Content-Length`-Header + * VOR dem Body-Download geprüft, s. Doc bei den Aufrufern). `null` bei + * Netzwerkfehler oder Grössenüberschreitung; wirft nie. */ +async function fetchAssetWithinLimit(asset: StacAsset): Promise { + if (asset.size != null && asset.size > MAX_ASSET_BYTES) return null; + const res = await fetch(viaProxy(asset.href)); + if (!res.ok) return null; + // STAC-Metadaten (`file:size`) fehlen manchmal (leeres `file:size`-Feld, + // z. B. bei swissBUILDINGS3D v3) — dann greift die Prüfung oben NICHT, und + // ohne diesen zweiten, `Content-Length`-basierten Check würde eine riesige + // Kachel (in Städten teils >150 MB, im Extremfall >800 MB) komplett + // heruntergeladen, bevor der spätere `byteLength`-Check sie verwirft — + // unnötiger Bandbreiten-/Zeitverbrauch für ein Ergebnis, das ohnehin + // verworfen wird. `Content-Length` selbst kann fehlen (chunked transfer) — + // dann bleibt es beim (späteren) Grössen-Check nach dem Download. + const contentLength = res.headers.get("content-length"); + if (contentLength != null) { + const len = Number.parseInt(contentLength, 10); + if (Number.isFinite(len) && len > MAX_ASSET_BYTES) return null; + } + return res; +} + /** Lädt ein Asset als Text; entpackt automatisch, wenn es ein `.zip` ist * (liefert den Inhalt der ERSTEN enthaltenen Datei mit einer der `innerExt`- * Endungen). `null` bei Fehler, fehlendem Inhalt im ZIP, oder wenn das Asset @@ -95,17 +144,14 @@ export async function downloadAssetText( asset: StacAsset, innerExt: string[], ): Promise { - if (asset.size != null && asset.size > MAX_ASSET_BYTES) return null; try { - const res = await fetch(viaProxy(asset.href)); - if (!res.ok) return null; + const res = await fetchAssetWithinLimit(asset); + if (!res) return null; if (asset.href.toLowerCase().endsWith(".zip")) { const buf = await res.arrayBuffer(); if (buf.byteLength > MAX_ASSET_BYTES) return null; const zip = await JSZip.loadAsync(buf); - const entry = Object.values(zip.files).find( - (f) => !f.dir && innerExt.some((ext) => f.name.toLowerCase().endsWith(ext)), - ); + const entry = pickZipEntry(zip, innerExt); if (!entry) return null; // Proaktiv prüfen: DXF/Text komprimiert stark, ein Zip unter dem Limit // kann trotzdem eine Text-Datei enthalten, die die max. JS-String-Länge @@ -121,3 +167,36 @@ export async function downloadAssetText( return null; } } + +/** Wie {@link downloadAssetText}, aber liefert den rohen Binärinhalt (für + * DWG-Assets, die als `ArrayBuffer` an `parseDwg`/LibreDWG-WASM gehen — + * ein binäres Format als Text zu lesen würde die Daten korrumpieren). + * `preferNameIncludes` wählt bei mehreren Zip-Treffern gezielt einen aus + * (s. {@link pickZipEntry}). */ +export async function downloadAssetBinary( + asset: StacAsset, + innerExt: string[], + preferNameIncludes?: string, +): Promise { + try { + const res = await fetchAssetWithinLimit(asset); + if (!res) return null; + if (asset.href.toLowerCase().endsWith(".zip")) { + const buf = await res.arrayBuffer(); + if (buf.byteLength > MAX_ASSET_BYTES) return null; + const zip = await JSZip.loadAsync(buf); + const entry = pickZipEntry(zip, innerExt, preferNameIncludes); + if (!entry) return null; + const uncompressed = estimateUncompressedSize(entry); + if (uncompressed != null && uncompressed > MAX_ASSET_BYTES) return null; + const arrBuf = await entry.async("arraybuffer"); + if (arrBuf.byteLength > MAX_ASSET_BYTES) return null; + return arrBuf; + } + const arrBuf = await res.arrayBuffer(); + if (arrBuf.byteLength > MAX_ASSET_BYTES) return null; + return arrBuf; + } catch { + return null; + } +} diff --git a/src/io/swissBuildings3d.test.ts b/src/io/swissBuildings3d.test.ts index 7d18afac..80943fad 100644 --- a/src/io/swissBuildings3d.test.ts +++ b/src/io/swissBuildings3d.test.ts @@ -10,6 +10,7 @@ import { clipMeshToBbox, splitMeshComponents, stripOverhangSoffits, + concatMeshes, BUILDING_LAYER, } from "./swissBuildings3d"; import type { ImportedMesh } from "../model/types"; @@ -219,3 +220,42 @@ describe("stripOverhangSoffits", () => { expect(stripOverhangSoffits(empty)).toBe(empty); }); }); + +describe("concatMeshes", () => { + const tri = (id: string, ox: number): ImportedMesh => ({ + id, + type: "importedMesh", + name: id, + layer: id, + positions: [ox, 0, 0, ox + 1, 0, 0, ox, 1, 0], + indices: [0, 1, 2], + }); + + it("führt Positions/Indizes mehrerer Meshes versetzt zusammen", () => { + const merged = concatMeshes([tri("a", 0), tri("b", 10)]); + expect(merged?.positions).toEqual([0, 0, 0, 1, 0, 0, 0, 1, 0, 10, 0, 0, 11, 0, 0, 10, 1, 0]); + // zweites Dreieck referenziert um 3 (erste Mesh-Vertexzahl) versetzte Indizes. + expect(merged?.indices).toEqual([0, 1, 2, 3, 4, 5]); + }); + + it("leere Teile (kein Dreieck) werden übersprungen, kein Beitrag zu Positions/Indizes", () => { + const emptyPart: ImportedMesh = { id: "e", type: "importedMesh", name: "e", positions: [1, 2, 3], indices: [] }; + const merged = concatMeshes([emptyPart, tri("a", 0)]); + expect(merged?.positions).toEqual([0, 0, 0, 1, 0, 0, 0, 1, 0]); + }); + + it("genau EIN nicht-leerer Teil -> dieselbe Referenz (kein unnötiges Kopieren)", () => { + const only = tri("a", 0); + expect(concatMeshes([only])).toBe(only); + }); + + it("ausschliesslich leere Teile -> null", () => { + const empty: ImportedMesh = { id: "e", type: "importedMesh", name: "e", positions: [], indices: [] }; + expect(concatMeshes([empty, empty])).toBeNull(); + }); + + it("übernimmt Metadaten (z. B. `layer`) vom ERSTEN nicht-leeren Teil", () => { + const merged = concatMeshes([tri("a", 0), tri("b", 10)]); + expect(merged?.layer).toBe("a"); + }); +}); diff --git a/src/io/swissBuildings3d.ts b/src/io/swissBuildings3d.ts index 08977410..35a2aa26 100644 --- a/src/io/swissBuildings3d.ts +++ b/src/io/swissBuildings3d.ts @@ -2,25 +2,42 @@ // Dachformen) statt der pauschal auf DEFAULT_BUILDING_HEIGHT extrudierten // VEC25-Footprints (s. `swissTopo.ts::fetchBuildings`). Zwei Datensatz- // Generationen, beide über dieselbe offene STAC-API (`stacApi.ts`): -// • v2 ("ch.swisstopo.swissbuildings3d_2") — stabil, 1-km-Tiles, ~50 MB. -// • v3 ("ch.swisstopo.swissbuildings3d_3_0") — Beta, Solid/Separated- -// Varianten, in Städten teils >150 MB/Tile (nicht 1-km-strukturiert) → -// wir fallen bei leeren/zu grossen v3-Treffern automatisch auf v2 zurück. +// • v2 ("ch.swisstopo.swissbuildings3d_2") — stabil, 1-km-Tiles, ~50 MB, +// liefert `.dxf`/`.dxf.zip` → `parseDxf`. +// • v3 ("ch.swisstopo.swissbuildings3d_3_0") — Beta, liefert NUR noch +// `.dwg.zip`/`.gdb.zip` (kein `.dxf` mehr), in Städten teils >150 MB/Tile +// (nicht 1-km-strukturiert) → wir fallen bei leeren/zu grossen v3-Treffern +// automatisch auf v2 zurück. Das Zip bündelt ZWEI DWG-Varianten +// („…_separated_….dwg" + „…_solid_….dwg"); NUR „separated" ist mit +// LibreDWG lesbar (`downloadAssetBinary(..., "separated")` wählt sie +// gezielt aus) — „solid" liefert 0 Entities (vermutlich ACIS-Volumenkörper +// statt Polyface-Mesh, an echten Kacheln verifiziert). Die Geometrie +// selbst ist ein ganz normales AutoCAD-Polyface-Mesh (DWG-Typ 29), NUR +// über die Low-Level-API lesbar (s. `dwgParser.ts:: +// extractPfaceMeshesByLayer`) und NACH DXF-LAYER GRUPPIERT geliefert: +// „Roof"/„Wall"/„Floor" je Gebäudefläche. // Referenz-Implementierung (Rhino-Vorgänger-Plugin, 1:1 als Blaupause genutzt): // git.kgva.ch/karim/DOSSIER, Datei rhino/swisstopo.py. // // Assets liegen als DXF/DWG/OBJ/IFC vor (teils `.zip`) — wir wählen bevorzugt // DXF: `parseDxf` (dxfParser.ts) liest 3DFACE/MESH/Polyface-Entities bereits -// verlustfrei zu `ImportedMesh` (positions/indices, echtes Z) — kein neuer -// Parser nötig. +// verlustfrei zu `ImportedMesh` (positions/indices, echtes Z); fehlt DXF (v3), +// liest `parseDwg` (dwgParser.ts, LibreDWG-WASM, lazy geladen) dieselbe +// Geometrie aus dem DWG. „Roof"-Layer-Meshes bekommen die Dächer-Kategorie +// ({@link IMPORTED_ROOF_CATEGORY}), alle übrigen (Wand/Boden/ungruppiert) die +// normale Gebäude-Kategorie — VOR dem Zuschnitt zusammengeführt, damit +// Wand+Boden EINES Gebäudes weiterhin ein einziges, löschbares Objekt bleiben +// (nur das Dach wird als eigenes Objekt/Ebene abgespalten, s. Nutzer-Wunsch +// „Dach als eigene, ausblendbare Sub-Ebene"). // // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). Einheiten: Meter. import { bboxAround, lv95BboxToWgs84, makeOrigin } from "./lv95"; import type { GeoOrigin, LV95 } from "./lv95"; -import { stacQuery, pickAsset, downloadAssetText } from "./stacApi"; +import { stacQuery, pickAsset, downloadAssetText, downloadAssetBinary } from "./stacApi"; import { parseDxf } from "./dxfParser"; import type { ImportedMesh } from "../model/types"; +import { GEO_CATEGORY_DEFS, IMPORTED_ROOF_CATEGORY } from "../model/contextCategories"; const COLLECTION_V2 = "ch.swisstopo.swissbuildings3d_2"; const COLLECTION_V3 = "ch.swisstopo.swissbuildings3d_3_0"; @@ -177,7 +194,15 @@ export function splitMeshComponents(mesh: ImportedMesh, weldMm = 1): ImportedMes } g.push(a, b, c); } - if (groups.size <= 1) return [{ ...mesh, layer: mesh.layer ?? BUILDING_LAYER }]; + if (groups.size <= 1) { + return [ + { + ...mesh, + layer: mesh.layer ?? BUILDING_LAYER, + categoryCode: mesh.categoryCode ?? GEO_CATEGORY_DEFS.building.code, + }, + ]; + } // 4) Je Komponente ein eigenes Mesh (Positions kompaktiert, Indizes neu gemappt). const out: ImportedMesh[] = []; @@ -200,6 +225,7 @@ export function splitMeshComponents(mesh: ImportedMesh, weldMm = 1): ImportedMes id: `${mesh.id}-b${n}`, name: `${mesh.name} #${n + 1}`, layer: mesh.layer ?? BUILDING_LAYER, + categoryCode: mesh.categoryCode ?? GEO_CATEGORY_DEFS.building.code, positions, indices, }); @@ -208,6 +234,31 @@ export function splitMeshComponents(mesh: ImportedMesh, weldMm = 1): ImportedMes return out; } +/** + * Führt mehrere Meshes zu einem zusammen (Positions/Indizes je Teil versetzt + * angehängt) — leere Teile (kein Dreieck) werden übersprungen. `null` bei + * ausschliesslich leeren Teilen, das EINE übrige Mesh unverändert bei genau + * einem nicht-leeren Teil (kein unnötiges Kopieren). Metadaten (`layer` etc.) + * kommen vom ersten nicht-leeren Teil — wird vom Aufrufer ohnehin überschrieben + * (`categoryCode`), s. `fetchBuildings3d`. Rein, exportiert für Unit-Tests. + */ +export function concatMeshes(parts: ImportedMesh[]): ImportedMesh | null { + const withGeom = parts.filter((p) => p.indices.length >= 3); + if (withGeom.length === 0) return null; + if (withGeom.length === 1) return withGeom[0]; + const positions: number[] = []; + const indices: number[] = []; + for (const p of withGeom) { + const base = positions.length / 3; + // KEIN `push(...p.positions)`: bei grossen Kacheln sprengt der Spread- + // Operator die Argumentzahl-Grenze von `push` (RangeError, s. dwgParser.ts + // an derselben Stelle — an einer echten 2000-Gebäude-v3-Kachel verifiziert). + for (const v of p.positions) positions.push(v); + for (const i of p.indices) indices.push(base + i); + } + return { ...withGeom[0], positions, indices }; +} + /** Ab welcher Höhe (Meter) über der Grundmauer ein Dreieck NICHT mehr als * Boden-/Sockel-Deckel gilt (siehe {@link stripOverhangSoffits}). */ const BASE_CAP_TOL = 0.05; @@ -344,21 +395,79 @@ export async function fetchBuildings3d( skipped++; continue; } - const text = await downloadAssetText(asset, [".dxf"]); - if (!text) { + // v3 liefert kein `.dxf` mehr (nur `.dwg.zip`/`.gdb.zip`, s. Moduldoc) — + // Asset-Endung entscheidet, welcher Parser läuft. + const isDwg = /\.dwg(\.zip)?$/i.test(asset.href); + let rawMeshes: ImportedMesh[]; + try { + if (isDwg) { + // Zip bündelt „separated" + „solid"-DWG; nur „separated" ist lesbar + // (s. Moduldoc) — gezielt auswählen statt der Zip-internen + // Reihenfolge zu vertrauen. + const buf = await downloadAssetBinary(asset, [".dwg"], "separated"); + if (!buf) { + skipped++; + continue; + } + const { parseDwg } = await import("./dwgParser"); + rawMeshes = (await parseDwg(buf)).meshes; + } else { + const text = await downloadAssetText(asset, [".dxf"]); + if (!text) { + skipped++; + continue; + } + rawMeshes = parseDxf(text).meshes; + } + } catch (err) { + // `parseDwg`/`parseDxf` werfen bei fatalen Parse-Fehlern BEWUSST (s. + // deren Moduldoc) — richtig für einen einzelnen Nutzer-Import, aber + // hier iterieren wir über MEHRERE STAC-Kacheln: eine einzelne kaputte/ + // von LibreDWG-WASM nicht unterstützte Kachel darf nicht den gesamten + // Mehr-Kachel-Import abbrechen. An einer echten v3-Kachel reproduziert: + // „RuntimeError: function signature mismatch" tief in LibreDWG-WASM + // (`dwg_dynapi_header_value`) — vermutlich eine Format-Eigenheit, die + // dieser WASM-Build nicht abdeckt, kein Fehler in unserem Code. + console.warn(`[swissBuildings3d] Kachel ${item.id} übersprungen (Parse-Fehler):`, err); skipped++; continue; } - const parsed = parseDxf(text); - for (const m of parsed.meshes) { - const clipped = clipMeshToBbox(shiftMeshToOrigin(m, origin, item.id), clipBoxLocal); + // „Roof"-Layer-Meshes (v3 „separated") getrennt von allen übrigen + // (Wand/Boden/ungruppiert, inkl. dem einzelnen v2-Mesh ohne Layer) — + // je Gruppe VOR dem Zuschnitt zusammengeführt, damit Wand+Boden EINES + // Gebäudes ein Objekt bleiben und nur das Dach separat abgespalten wird + // (s. Moduldoc). + const roofRaw: ImportedMesh[] = []; + const bodyRaw: ImportedMesh[] = []; + for (const m of rawMeshes) { + ((m.layer ?? "").toLowerCase() === "roof" ? roofRaw : bodyRaw).push(m); + } + for (const [group, isRoof] of [ + [bodyRaw, false], + [roofRaw, true], + ] as const) { + const merged = concatMeshes(group); + if (!merged) continue; + const clipped = clipMeshToBbox(shiftMeshToOrigin(merged, origin, item.id), clipBoxLocal); if (clipped.indices.length < 3) continue; // In EINZELNE Gebäude aufteilen (eine Kachel = ein Mesh mit allen // Häusern) — so ist jedes Haus getrennt anwähl-/löschbar. Je Gebäude // die Dachüberstand-Untersichten (Soffiten) entfernen (Gipsmodell-Look, // s. stripOverhangSoffits-Moduldoc). for (const b of splitMeshComponents(clipped)) { - meshes.push(stripOverhangSoffits(b)); + meshes.push({ + ...stripOverhangSoffits(b), + categoryCode: isRoof ? IMPORTED_ROOF_CATEGORY.code : GEO_CATEGORY_DEFS.building.code, + // `.layer` (kosmetischer SitePanel-Gruppierungs-String, s. + // SitePanel.tsx::layerOf/groupByLayer) explizit setzen — sonst + // trägt er den rohen DXF-Layernamen aus dwgParser.ts ("Wall"/ + // "Floor"/"Roof") weiter, den `splitMeshComponents`s Fallback + // `mesh.layer ?? BUILDING_LAYER` NICHT ersetzt (nur bei leerem + // `.layer`, nicht bei einem bereits vorhandenen Wert). Ohne diesen + // Fix zerfällt die SitePanel-Gruppierung eines v3-Imports in + // „Wall"/„Floor"/„Roof" statt „Gebäude"/„Dächer". + layer: isRoof ? IMPORTED_ROOF_CATEGORY.name : BUILDING_LAYER, + }); } } } diff --git a/src/menus/contextMenu.tsx b/src/menus/contextMenu.tsx index 97dd859c..ad135710 100644 --- a/src/menus/contextMenu.tsx +++ b/src/menus/contextMenu.tsx @@ -60,6 +60,9 @@ export interface MenuActions { patchCategory: (code: string, patch: Partial) => void; duplicateLevel: (id: string) => void; deleteLevel: (id: string) => void; + /** Sortiert eine Zeichnungsebene in der Überlagerungs-Reihenfolge um (z. B. + * eine Ansicht als Kalkierpapier-Unterlage nach hinten legen). */ + reorderLevel: (id: string, op: "front" | "back" | "forward" | "backward") => void; clearSelection: () => void; fit: () => void; fitSelection: () => void; @@ -178,6 +181,31 @@ function levelMenuItems(id: string, a: MenuActions): ContextMenuItem[] { onClick: () => a.duplicateLevel(id), }, { divider: true }, + // Überlagerungs-Reihenfolge (wie beim 2D-z-Anordnen): wirkt, sobald mehrere + // Ebenen gleichzeitig sichtbar sind (Geschoss-/Zeichnungs-Überlagerung, + // Schnitt-/Ansichts-Referenzüberlagerung) — Nutzer-Wunsch "Ansichten in den + // Hintergrund legen können". + { + label: t("ctx.arrange.front"), + icon: , + onClick: () => a.reorderLevel(id, "front"), + }, + { + label: t("ctx.arrange.forward"), + icon: , + onClick: () => a.reorderLevel(id, "forward"), + }, + { + label: t("ctx.arrange.backward"), + icon: , + onClick: () => a.reorderLevel(id, "backward"), + }, + { + label: t("ctx.arrange.back"), + icon: , + onClick: () => a.reorderLevel(id, "back"), + }, + { divider: true }, { label: t("ctx.delete"), icon: , diff --git a/src/model/contextCategories.test.ts b/src/model/contextCategories.test.ts new file mode 100644 index 00000000..f1422a5c --- /dev/null +++ b/src/model/contextCategories.test.ts @@ -0,0 +1,110 @@ +/** + * `ensureContextCategories` — ergänzt fehlende Kontext-Kategorien in + * `project.layers`, ohne vorhandene (auch vom Nutzer umbenannte) Codes + * anzutasten. Grundlage der Ebenen-Zuordnung importierter Kontext-Objekte + * (Gebäude/Terrain/Konturen/Luftbild), s. Kopfkommentar in + * `contextCategories.ts`. Seit 2026-08-31 landen die meisten dieser + * Kategorien als KINDER von "05 Kontext" statt als Top-Level-Geschwister — + * ausser "31 Dächer" (bleibt Top-Level, teilt sich den Code mit modellierten + * `Roof`-Objekten). + */ +import { describe, it, expect } from "vitest"; +import { + ensureContextCategories, + GEO_CATEGORY_DEFS, + IMAGE_CATEGORY, + TERRAIN_CATEGORY, + IMPORTED_ROOF_CATEGORY, + CONTEXT_PARENT_CATEGORY, +} from "./contextCategories"; +import type { LayerCategory } from "./types"; + +const layer = (code: string, name = code): LayerCategory => ({ + code, + name, + color: "#000000", + lw: 0.13, + visible: true, + locked: false, +}); + +describe("ensureContextCategories", () => { + it("legt '05 Kontext' neu an und hängt eine fehlende (nested) Kategorie als Kind ein", () => { + const out = ensureContextCategories([], [TERRAIN_CATEGORY.code]); + expect(out.length).toBe(1); + expect(out[0]).toMatchObject({ + code: CONTEXT_PARENT_CATEGORY.code, + name: CONTEXT_PARENT_CATEGORY.name, + }); + expect(out[0].children).toMatchObject([ + { code: TERRAIN_CATEGORY.code, name: TERRAIN_CATEGORY.name, visible: true, locked: false }, + ]); + }); + + it("lässt eine bereits vorhandene (auch umbenannte) Kategorie unverändert", () => { + const existing = [layer(TERRAIN_CATEGORY.code, "Mein Gelände")]; + const out = ensureContextCategories(existing, [TERRAIN_CATEGORY.code]); + expect(out).toEqual(existing); + expect(out[0].name).toBe("Mein Gelände"); // NICHT auf den Default zurückgesetzt + }); + + it("ist ein No-op (dieselbe Referenz), wenn nichts fehlt", () => { + const existing = [layer(GEO_CATEGORY_DEFS.building.code)]; + const out = ensureContextCategories(existing, [GEO_CATEGORY_DEFS.building.code]); + expect(out).toBe(existing); + }); + + it("findet vorhandene Codes auch in verschachtelten Unterkategorien", () => { + const existing: LayerCategory[] = [ + { ...layer("20", "Wände"), children: [layer(GEO_CATEGORY_DEFS.road.code, "Strasse")] }, + ]; + const out = ensureContextCategories(existing, [GEO_CATEGORY_DEFS.road.code]); + expect(out).toBe(existing); // "11" existiert bereits als Kind -> kein Duplikat oben + }); + + it("hängt mehrere fehlende nested Codes gebündelt unter EIN '05 Kontext' (kein Duplikat), in einem Schritt", () => { + const out = ensureContextCategories([], [ + TERRAIN_CATEGORY.code, + IMAGE_CATEGORY.code, + GEO_CATEGORY_DEFS.building.code, + ]); + expect(out.map((l) => l.code)).toEqual([CONTEXT_PARENT_CATEGORY.code]); + const childCodes = (out[0].children ?? []).map((c) => c.code).sort(); + expect(childCodes).toEqual( + [TERRAIN_CATEGORY.code, IMAGE_CATEGORY.code, GEO_CATEGORY_DEFS.building.code].sort(), + ); + }); + + it("ergänzt fehlende Kinder in ein bereits vorhandenes '05 Kontext' (kein zweites '05')", () => { + const existing: LayerCategory[] = [ + { ...layer(CONTEXT_PARENT_CATEGORY.code, "Kontext"), children: [layer(IMAGE_CATEGORY.code, "Luftbild")] }, + ]; + const out = ensureContextCategories(existing, [IMAGE_CATEGORY.code, TERRAIN_CATEGORY.code]); + expect(out.map((l) => l.code)).toEqual([CONTEXT_PARENT_CATEGORY.code]); // kein zweiter Top-Level-Eintrag + const childCodes = (out[0].children ?? []).map((c) => c.code).sort(); + expect(childCodes).toEqual([IMAGE_CATEGORY.code, TERRAIN_CATEGORY.code].sort()); + // vorhandenes Kind (Luftbild, ggf. umbenannt) bleibt unangetastet. + expect(out[0].children?.find((c) => c.code === IMAGE_CATEGORY.code)?.name).toBe("Luftbild"); + }); + + it("'31 Dächer' bleibt TOP-LEVEL (nicht unter '05 Kontext' verschachtelt)", () => { + const out = ensureContextCategories([], [IMPORTED_ROOF_CATEGORY.code]); + expect(out).toMatchObject([ + { code: IMPORTED_ROOF_CATEGORY.code, name: IMPORTED_ROOF_CATEGORY.name }, + ]); + expect(out[0].children).toBeUndefined(); + }); + + it("mischt nested + Top-Level-Ausnahme korrekt in einem Aufruf", () => { + const out = ensureContextCategories([], [TERRAIN_CATEGORY.code, IMPORTED_ROOF_CATEGORY.code]); + const topCodes = out.map((l) => l.code).sort(); + expect(topCodes).toEqual([CONTEXT_PARENT_CATEGORY.code, IMPORTED_ROOF_CATEGORY.code].sort()); + const kontext = out.find((l) => l.code === CONTEXT_PARENT_CATEGORY.code); + expect(kontext?.children).toMatchObject([{ code: TERRAIN_CATEGORY.code }]); + }); + + it("ignoriert unbekannte Codes (kein Eintrag in den bekannten Definitionen) statt zu crashen", () => { + const out = ensureContextCategories([], ["zz-unknown"]); + expect(out).toEqual([]); + }); +}); diff --git a/src/model/contextCategories.ts b/src/model/contextCategories.ts new file mode 100644 index 00000000..17c39a60 --- /dev/null +++ b/src/model/contextCategories.ts @@ -0,0 +1,175 @@ +// Kategorie-Codes der Kontext-Schicht (`project.context`, s. `ContextObject` +// in `types.ts`): importierte Gebäude/Terrain/Konturen/Luftbilder bekommen +// hier eine `categoryCode`-Zuordnung, damit sie wie jedes andere Bauteil über +// das Ebenen-Panel (Sichtbarkeit/Grau/Sperren) steuerbar sind — bislang +// wurden sie beim 2D-Plan IMMER gezeichnet, unabhängig von der Ebenen- +// Sichtbarkeit (Nutzer-Report: „sollten wie Gebäude/Dächer ausblendbar sein"). +// +// Wiederverwendet, wo möglich, bereits im Sample-Projekt gesäte Codes ("11" +// Strasse, "12" Gebäude) — neue Codes liegen in bislang ungenutzten Lücken +// (02-04, 15-18) der DOSSIER-Nummerierung, damit nichts kollidiert. +// +// GRUPPIERUNG (2026-08-31, Nutzer-Wunsch): alle Kontext-Import-Kategorien +// hängen als KINDER unter einer gemeinsamen Elternebene „05 Kontext" (das +// Ebenen-Panel unterstützt Verschachtelung bereits, s. „20 Wände" mit +// Kindern „21 Türen/Fenster" etc. in `sampleProject.ts`) — statt als lose, +// gleichrangige Top-Level-Einträge. AUSNAHME: „31 Dächer" +// ({@link IMPORTED_ROOF_CATEGORY}) bleibt bewusst TOP-LEVEL, weil es sich mit +// der Dächer-Kategorie modellierter `Roof`-Objekte deckt (ein Ausblenden soll +// beide Quellen gemeinsam treffen) — sie unter „Kontext" zu verschachteln +// würde diese Kopplung optisch zerreissen. +// +// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). + +import type { GeoCategory } from "../io/geoContext"; +import type { LayerCategory } from "./types"; + +/** Eine Kategorie-Definition (Code + Default-Name/Farbe/Strichstärke). */ +export interface ContextCategoryDef { + code: string; + name: string; + color: string; + lw: number; +} + +/** + * Gemeinsame Elternebene aller Kontext-Import-Kategorien (Gelände/Luftbild/ + * Situation/Gebäude/Strasse/Wald/Parkplätze/Bahn/Gewässer/Grünflächen) — + * reine Gruppierung im Ebenen-Panel, trägt selbst keine Geometrie + * (`categoryCode` einzelner Kontext-Objekte zeigt immer auf ein KIND, nie auf + * „05" direkt). Code „05" liegt in der bislang ungenutzten Lücke zwischen + * „01 Vermessung" und „10 Situation" (s. `sampleProject.ts`). + */ +export const CONTEXT_PARENT_CATEGORY: ContextCategoryDef = { + code: "05", + name: "Kontext", + color: "#707078", + lw: 0.13, +}; + +/** Gelände-TIN (swissALTI3D/generiertes Terrain). */ +export const TERRAIN_CATEGORY: ContextCategoryDef = { + code: "02", + name: "Gelände", + color: "#8a9478", + lw: 0.13, +}; + +/** Georeferenziertes Luftbild (SWISSIMAGE/eingefügtes Bild). */ +export const IMAGE_CATEGORY: ContextCategoryDef = { + code: "03", + name: "Luftbild", + color: "#707078", + lw: 0.13, +}; + +/** Generischer DXF/DWG-Mesh-/Konturen-Import ohne spezifischere Zuordnung. */ +export const GENERIC_IMPORT_CATEGORY: ContextCategoryDef = { + code: "10", + name: "Situation", + color: "#909090", + lw: 0.18, +}; + +/** + * Dach-Flächen importierter swissBUILDINGS3D-v3-„separated"-Gebäude (eigener + * DXF-Layer „Roof" je Fläche, s. `swissBuildings3d.ts::splitPfaceMeshByLayer`). + * Teilt sich Code „31" bewusst mit der Dächer-Kategorie modellierter `Roof`- + * Objekte (s. `sampleProject.ts`) — ein Ein-/Ausblenden über „Dächer" soll + * BEIDE Quellen gemeinsam betreffen, nicht zwei separate, verwirrende Einträge + * im Ebenen-Panel erzeugen. + */ +export const IMPORTED_ROOF_CATEGORY: ContextCategoryDef = { + code: "31", + name: "Dächer", + color: "#7a4a3a", + lw: 0.35, +}; + +/** + * Kategorie je {@link GeoCategory} (Standort-Import, swisstopo & OSM) — deckt + * sowohl `featuresToContextObjects` (OSM/flache swissBUILDINGS-Footprints) + * als auch die echten swissBUILDINGS3D-Meshes ab (`building`). + */ +export const GEO_CATEGORY_DEFS: Record = { + building: { code: "12", name: "Gebäude", color: "#888888", lw: 0.25 }, + road: { code: "11", name: "Strasse", color: "#a89070", lw: 0.18 }, + forest: { code: "04", name: "Wald", color: "#3a7a3a", lw: 0.13 }, + parking: { code: "15", name: "Parkplätze", color: "#a0a0a0", lw: 0.13 }, + railway: { code: "16", name: "Bahn", color: "#606060", lw: 0.18 }, + water: { code: "17", name: "Gewässer", color: "#5a90b0", lw: 0.13 }, + green: { code: "18", name: "Grünflächen", color: "#70b070", lw: 0.13 }, +}; + +/** Kategorien, die als KINDER von {@link CONTEXT_PARENT_CATEGORY} gruppiert + * werden (alles ausser der Top-Level-Ausnahme „31 Dächer"). */ +const NESTED_CONTEXT_CATEGORIES: ContextCategoryDef[] = [ + TERRAIN_CATEGORY, + IMAGE_CATEGORY, + GENERIC_IMPORT_CATEGORY, + ...Object.values(GEO_CATEGORY_DEFS), +]; + +const toLayerCategory = (c: ContextCategoryDef): LayerCategory => ({ + code: c.code, + name: c.name, + color: c.color, + lw: c.lw, + visible: true, + locked: false, +}); + +/** + * Ergänzt `layers` um jede fehlende Kontext-Kategorie aus `codes` — bereits + * vorhandene Codes (auch vom Nutzer umbenannte, egal auf welcher Baumtiefe) + * bleiben unverändert, nur wirklich fehlende werden mit ihrem Default-Namen/ + * -Farbe ergänzt. Fehlende {@link NESTED_CONTEXT_CATEGORIES} landen als + * KINDER von {@link CONTEXT_PARENT_CATEGORY} (legt „05 Kontext" bei Bedarf + * selbst an); die Top-Level-Ausnahme „31 Dächer" bleibt Top-Level (s. + * {@link IMPORTED_ROOF_CATEGORY}-Moduldoc). Reiner No-op, wenn nichts fehlt + * (liefert dieselbe Referenz zurück, spart eine unnötige `project`-Neuanlage). + */ +export function ensureContextCategories( + layers: LayerCategory[], + codes: Iterable, +): LayerCategory[] { + const existing = new Set(collectCodes(layers)); + const missing = new Set(); + for (const code of codes) { + if (!existing.has(code)) missing.add(code); + } + if (missing.size === 0) return layers; + + const missingNested = NESTED_CONTEXT_CATEGORIES.filter((c) => missing.has(c.code)).map( + toLayerCategory, + ); + const missingTopLevel = missing.has(IMPORTED_ROOF_CATEGORY.code) + ? [toLayerCategory(IMPORTED_ROOF_CATEGORY)] + : []; + + let out = layers; + if (missingNested.length > 0) { + const parentIdx = out.findIndex((l) => l.code === CONTEXT_PARENT_CATEGORY.code); + if (parentIdx >= 0) { + out = out.map((l, i) => + i === parentIdx ? { ...l, children: [...(l.children ?? []), ...missingNested] } : l, + ); + } else { + out = [...out, { ...toLayerCategory(CONTEXT_PARENT_CATEGORY), children: missingNested }]; + } + } + if (missingTopLevel.length > 0) { + out = [...out, ...missingTopLevel]; + } + return out; +} + +/** Alle Codes eines Kategorie-Baums (rekursiv über `children`). */ +function collectCodes(layers: LayerCategory[]): string[] { + const out: string[] = []; + for (const l of layers) { + out.push(l.code); + if (l.children) out.push(...collectCodes(l.children)); + } + return out; +} diff --git a/src/model/geoRebase.ts b/src/model/geoRebase.ts index e25d5963..f0e71312 100644 --- a/src/model/geoRebase.ts +++ b/src/model/geoRebase.ts @@ -97,6 +97,7 @@ export function translateProject(project: Project, dx: number, dy: number): Proj const g = d.geom; switch (g.shape) { case "line": + case "xline": return { ...d, geom: { ...g, a: shift(g.a, dx, dy), b: shift(g.b, dx, dy) } }; case "polyline": return { ...d, geom: { ...g, pts: shiftAll(g.pts, dx, dy) } }; @@ -117,6 +118,16 @@ export function translateProject(project: Project, dx: number, dy: number): Proj case "kote": return { ...d, geom: { ...g, at: shift(g.at, dx, dy) } }; case "text": + return { + ...d, + geom: { + ...g, + at: shift(g.at, dx, dy), + ...(g.leaderTarget ? { leaderTarget: shift(g.leaderTarget, dx, dy) } : {}), + ...(g.pathPts ? { pathPts: shiftAll(g.pathPts, dx, dy) } : {}), + }, + }; + case "block": return { ...d, geom: { ...g, at: shift(g.at, dx, dy) } }; case "image": return { ...d, geom: { ...g, min: shift(g.min, dx, dy), max: shift(g.max, dx, dy) } }; diff --git a/src/model/joins.test.ts b/src/model/joins.test.ts index ddcf28b1..57b4e6cf 100644 --- a/src/model/joins.test.ts +++ b/src/model/joins.test.ts @@ -186,6 +186,66 @@ describe("computeJoins — Mittelspannen-T-Stoß (Ende trifft Wandseite)", () => }); }); +describe("computeJoins — „+\"-Kreuzung (zwei kollineare Enden kreuzen eine durchlaufende Wand)", () => { + it("schneidet BEIDE kollinearen Hälften gegen die jeweils zugewandte (gegenüberliegende) Fläche der durchlaufenden Wand", () => { + // Vertikale Durchgangswand V (6,2)→(6,11), T=0.3 → halbe Dicke 0.15. Zwei + // kollineare horizontale Hälften HL (0,6)→(6,6) und HR (6,6)→(12,6) treffen + // sich exakt AUF DER ACHSE von V (x=6) — eine reale „+"-Kreuzung, wie sie + // beim Zeichnen einer durchlaufenden Trennwand entsteht, die von einer + // weiteren durchlaufenden Wand gekreuzt wird (Regressionstest für den per + // Massstabsprobe gefundenen Bug: vorher blieb V für Fall 1 unsichtbar, weil + // sie an diesem Punkt keinen eigenen Endpunkt hat, und Fall 2 prüfte nur + // echte EINZEL-Enden — HL/HR bekamen dadurch gar keinen Schnitt). + const proj = threeWallProject( + wall("V", { x: 6, y: 2 }, { x: 6, y: 11 }), + wall("HL", { x: 0, y: 6 }, { x: 6, y: 6 }), + wall("HR", { x: 6, y: 6 }, { x: 12, y: 6 }), + 0.3, + ); + const joins = computeJoins(proj, proj.walls); + + // Die Durchgangswand V bleibt an ihren (freien) Enden unangetastet. + expect(joins.get("V")!.startCut).toBeNull(); + expect(joins.get("V")!.endCut).toBeNull(); + + // HL läuft nach −x aus → Schnitt an der LINKEN Fläche von V (x=5.85). + const cutL = joins.get("HL")!.endCut; + expect(cutL).not.toBeNull(); + expect(distToLine(cutL!, { x: 5.85, y: 2 })).toBeCloseTo(0, 6); + expect(distToLine(cutL!, { x: 5.85, y: 11 })).toBeCloseTo(0, 6); + + // HR läuft nach +x aus → Schnitt an der RECHTEN Fläche von V (x=6.15) — + // die GEGENÜBERLIEGENDE Fläche, nicht dieselbe wie HL (der eigentliche Bug: + // beide Enden teilen sich denselben Kreuzungspunkt, `perp` allein kann sie + // nicht unterscheiden — erst die eigene Auslaufrichtung tut das). + const cutR = joins.get("HR")!.startCut; + expect(cutR).not.toBeNull(); + expect(distToLine(cutR!, { x: 6.15, y: 2 })).toBeCloseTo(0, 6); + expect(distToLine(cutR!, { x: 6.15, y: 11 })).toBeCloseTo(0, 6); + expect(distToLine(cutL!, { x: 6.15, y: 6 })).not.toBeCloseTo(0, 3); + }); + + it("lässt einen echten Stern-Knoten (4 Wandenden treffen sich, keine läuft durch) weiterhin rechtwinklig", () => { + // Vier Wand-STUMMEL enden alle exakt bei (5,5), keiner läuft darüber + // hinaus weiter — kein Durchgang erkennbar, bewusst dokumentierte + // Restlücke (s. Kommentar in computeJoins). + const proj: Project = twoWallProject( + wall("A", { x: 0, y: 5 }, { x: 5, y: 5 }), + wall("B", { x: 5, y: 5 }, { x: 10, y: 5 }), + 0.3, + ); + proj.walls.push( + wall("C", { x: 5, y: 5 }, { x: 5, y: 0 }), + wall("D", { x: 5, y: 5 }, { x: 5, y: 10 }), + ); + const joins = computeJoins(proj, proj.walls); + for (const id of ["A", "B", "C", "D"]) { + const c = joins.get(id)!; + expect(c.startCut ?? c.endCut).toBeNull(); + } + }); +}); + describe("resolveJoinPriority — Ordnungslogik zweier Bauteile am Stoss", () => { const brick: Component = { id: "brick", name: "Backstein", color: "#8c5544", hatchId: "none", joinPriority: 50 }; const brick2: Component = { id: "brick", name: "Backstein (Kopie)", color: "#000", hatchId: "none", joinPriority: 50 }; diff --git a/src/model/joins.ts b/src/model/joins.ts index 35d131ba..921ea58b 100644 --- a/src/model/joins.ts +++ b/src/model/joins.ts @@ -113,9 +113,15 @@ interface WallEnd { /** * Berechnet für jede Wand die Gehrungs-/Anschluss-Schnittlinien. * Behandelt werden: L-Ecken (genau zwei Wandenden treffen sich), T-Knoten - * (drei Wandenden treffen sich, zwei davon kollinear) und Mittelspannen- - * T-Stöße (ein freies Wandende trifft auf die Seite einer anderen Wand). - * X-Stöße (vier und mehr Enden) bleiben vorerst rechtwinklig. + * (drei Wandenden treffen sich, zwei davon kollinear), Mittelspannen-T-Stöße + * (ein freies Wandende trifft auf die Seite einer anderen Wand) UND „+"- + * Kreuzungen (zwei kollineare Wandenden treffen sich exakt auf der Achse einer + * dritten, durchlaufenden Wand — z. B. wenn eine durchgehende Trennwand von + * einer weiteren durchgehenden Wand gekreuzt wird). Nur echte Stern-Knoten + * (vier oder mehr Wand-STUMMEL enden alle exakt am selben Punkt, OHNE dass + * eine von ihnen als Durchgang erkennbar ist) bleiben rechtwinklig — dafür + * fehlt eine eindeutige Rangfolge, welches Ende „durch" und welches „Abzweig" + * wäre. * * `walls` ist die bereits gefilterte Wandmenge (z. B. ein Geschoss); die * Gehrung wird nur innerhalb dieser Menge gebildet. @@ -163,16 +169,35 @@ export function computeJoins( continue; } - // X-Stöße u. ä. (>3 Enden): vorerst rechtwinklig lassen (Folge-Arbeit). + // Echte Stern-Knoten (≥4 WANDENDEN treffen sich exakt hier, KEINS läuft + // als Durchgangswand weiter) bleiben vorerst rechtwinklig (Folge-Arbeit) — + // dafür gibt es (noch) keine eindeutige Rangfolge, welches Ende „durch" + // und welches „Abzweig" ist. Der weit häufigere Fall — eine durchlaufende + // Wand wird von zwei (oder mehr) an ihrem Knoten endenden Wänden gekreuzt, + // eine „+"/„X"-Kreuzung — greift unten in Fall 2, weil dort JEDES noch + // ungeschnittene Ende zusätzlich gegen die Mittelspanne aller anderen + // Wände geprüft wird (nicht nur echte Einzel-Enden wie bisher). } - // Fall 2: Mittelspannen-T-Stoß. Ein freies Wandende (kein anderes Wandende - // teilt sich seinen Knoten) kann trotzdem auf die Seite einer anderen Wand - // treffen (nicht an deren Endpunkten). In dem Fall bekommt das freie Ende - // einen Schnitt entlang der zugewandten Fläche dieser Wand. + // Fall 2: Mittelspannen-T-Stoß, verallgemeinert. Jedes Wandende, das nach + // Fall 1 noch UNGESCHNITTEN ist — das schliesst nicht nur echte Einzel-Enden + // ein, sondern auch die beiden kollinearen Hälften eines 2er-/3er-Knotens + // (die bewusst ungeschnitten bleiben, s. o.) —, wird zusätzlich geprüft, ob + // es auf die Mittelspanne (nicht das Ende) einer WEITEREN, an diesem Knoten + // gar nicht beteiligten Wand trifft. Das deckt genau die „+"-Kreuzung ab: + // zwei kollineare Wandhälften enden an einem Punkt, DURCH den eine dritte, + // durchlaufende Wand hindurchläuft (sonst für Fall 1 unsichtbar, weil sie + // dort keinen eigenen Endpunkt hat) — beide Hälften bekommen unabhängig + // voneinander (mit jeweils eigenem Vorzeichen/zugewandter Fläche) einen + // Schnitt gegen die durchlaufende Wand, die selbst unangetastet bleibt. + // Bereits geschnittene Enden (L-Ecke, T-Abzweig) werden NICHT erneut + // angefasst — additiv, bit-identisch zum bisherigen Verhalten überall sonst. for (const [, ends] of junctions) { - if (ends.length !== 1) continue; - applyMidSpanTee(project, byId, walls, ends[0], result); + for (const end of ends) { + const cuts = result.get(end.wallId)!; + if (end.end === "start" ? cuts.startCut : cuts.endCut) continue; + applyMidSpanTee(project, byId, walls, end, result); + } } return result; @@ -534,7 +559,20 @@ function applyMidSpanTee( const uW = dirOf(w); const nW = leftNormal(uW); const offW = wallReferenceOffset(w, tw); - const sign = best.perp >= 0 ? 1 : -1; + // Zugewandte Seite: primär aus der AUSLAUFRICHTUNG des freien Endes in + // seinen eigenen Körper (wie `dBranch`/`sign` in applyTJunction) — nicht aus + // der lateralen Position `perp`. Bei einer „+"-Kreuzung (zwei kollineare + // Enden treffen exakt auf der ACHSE der durchlaufenden Wand, `perp≈0`) ist + // `perp` für beide Enden identisch und liefert für BEIDE dieselbe (falsche) + // Seite; die Auslaufrichtung unterscheidet sie dagegen korrekt (linke Hälfte + // läuft nach −u aus, rechte nach +u — je die gegenüberliegende Fläche der + // Durchgangswand). Nur wenn die Auslaufrichtung (nahezu) parallel zur + // Durchgangsachse liegt (dot≈0 — geometrisch entartet für einen T-Stoss), + // bleibt `perp` als Fallback (bisheriges Verhalten). + const dFree = + freeEnd.end === "start" ? dirOf(freeWall) : scale(dirOf(freeWall), -1); + const facing = dot(nW, dFree); + const sign = Math.abs(facing) > 1e-6 ? (facing >= 0 ? 1 : -1) : best.perp >= 0 ? 1 : -1; const facePoint = add(w.start, scale(nW, offW + sign * (tw / 2))); const faceCut: Line = { point: facePoint, dir: uW }; diff --git a/src/model/penSets.test.ts b/src/model/penSets.test.ts new file mode 100644 index 00000000..38649600 --- /dev/null +++ b/src/model/penSets.test.ts @@ -0,0 +1,352 @@ +import { describe, it, expect } from "vitest"; +import { + activePenSet, + resolvePenColor, + resolvePenWeight, + rebakePenColors, + generateStandardPenPalette, + seedStandardPenSet, + PEN_FALLBACK_COLOR, + PEN_FALLBACK_WEIGHT, +} from "./penSets"; +import type { Ceiling, Component, Drawing2D, LayerCategory, PenStyle, Project, Room, Wall } from "./types"; + +function baseProject(overrides: Partial = {}): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [], + layers: [], + walls: [], + doors: [], + drawings2d: [], + ...overrides, + }; +} + +/** Kurzform für einen PenStyle-Eintrag in Tests. */ +const ps = (color: string, weight = 0.5): PenStyle => ({ color, weight }); + +describe("activePenSet/resolvePenColor/resolvePenWeight", () => { + it("liefert undefined ohne Stiftsätze/aktiven Verweis", () => { + const p = baseProject(); + expect(activePenSet(p)).toBeUndefined(); + }); + + it("löst Farbe UND Strichstärke gegen den aktiven Stiftsatz auf", () => { + const p = baseProject({ + penSets: [ + { id: "std", name: "Standard", pens: { "1": ps("#ff0000", 0.35) } }, + { id: "bw", name: "S/W", pens: { "1": ps("#000000", 0.13) } }, + ], + activePenSetId: "bw", + }); + expect(resolvePenColor(p, "1")).toBe("#000000"); + expect(resolvePenWeight(p, "1")).toBe(0.13); + }); + + it("liefert den Fallback, wenn der Stift im aktiven Satz keinen Eintrag hat", () => { + const p = baseProject({ + penSets: [{ id: "std", name: "Standard", pens: {} }], + activePenSetId: "std", + }); + expect(resolvePenColor(p, "1")).toBe(PEN_FALLBACK_COLOR); + expect(resolvePenWeight(p, "1")).toBe(PEN_FALLBACK_WEIGHT); + }); + + it("liefert den Fallback ohne aktiven Stiftsatz", () => { + const p = baseProject({ penSets: [{ id: "std", name: "Standard", pens: { "1": ps("#ff0000") } }] }); + expect(resolvePenColor(p, "1")).toBe(PEN_FALLBACK_COLOR); + }); +}); + +const comp = (overrides: Partial = {}): Component => ({ + id: "c1", + name: "C1", + color: "#111111", + hatchId: "none", + joinPriority: 10, + ...overrides, +}); + +const cat = (overrides: Partial = {}): LayerCategory => ({ + code: "20", + name: "Wände", + color: "#222222", + lw: 0.35, + visible: true, + locked: false, + ...overrides, +}); + +describe("rebakePenColors — Bauteile (nur Farbe, kein Stärke-Feld)", () => { + it("lässt ein Bauteil OHNE Stift-Verweis unangetastet (referenzgleich)", () => { + const c = comp(); + const p = baseProject({ components: [c] }); + const out = rebakePenColors(p); + expect(out.components[0]).toBe(c); + }); + + it("bäckt `color` aus dem aktiven Stiftsatz, wenn `colorPenId` gesetzt ist", () => { + const p = baseProject({ + components: [comp({ colorPenId: "1", color: "#stale" })], + penSets: [{ id: "std", name: "Standard", pens: { "1": ps("#abcdef") } }], + activePenSetId: "std", + }); + const out = rebakePenColors(p); + expect(out.components[0].color).toBe("#abcdef"); + }); + + it("bäckt `foreground`/`background` unabhängig voneinander", () => { + const p = baseProject({ + components: [ + comp({ + color: "#base", + foregroundPenId: "fg", + backgroundPenId: "bg", + }), + ], + penSets: [{ id: "std", name: "Standard", pens: { fg: ps("#f00"), bg: ps("#0f0") } }], + activePenSetId: "std", + }); + const out = rebakePenColors(p); + expect(out.components[0].foreground).toBe("#f00"); + expect(out.components[0].background).toBe("#0f0"); + // color selbst hat keinen Stift-Verweis -> bleibt unverändert. + expect(out.components[0].color).toBe("#base"); + }); + + it("nutzt den Fallback, wenn der referenzierte Stift im aktiven Satz fehlt", () => { + const p = baseProject({ + components: [comp({ colorPenId: "missing" })], + penSets: [{ id: "std", name: "Standard", pens: {} }], + activePenSetId: "std", + }); + const out = rebakePenColors(p); + expect(out.components[0].color).toBe(PEN_FALLBACK_COLOR); + }); +}); + +describe("rebakePenColors — Ebenen (Farbe UND Strichstärke, inkl. verschachtelt)", () => { + it("bäckt `color` UND `lw` einer Top-Level-Kategorie", () => { + const p = baseProject({ + layers: [cat({ colorPenId: "1" })], + penSets: [{ id: "std", name: "Standard", pens: { "1": ps("#123456", 0.7) } }], + activePenSetId: "std", + }); + const out = rebakePenColors(p); + expect(out.layers[0].color).toBe("#123456"); + expect(out.layers[0].lw).toBe(0.7); + }); + + it("bäckt eine verschachtelte Kategorie (children) und lässt Geschwister ohne Stift unverändert", () => { + const child = cat({ code: "21", colorPenId: "2" }); + const untouchedChild = cat({ code: "22", color: "#untouched" }); + const parent = cat({ code: "20", children: [child, untouchedChild] }); + const p = baseProject({ + layers: [parent], + penSets: [{ id: "std", name: "Standard", pens: { "2": ps("#00ff00") } }], + activePenSetId: "std", + }); + const out = rebakePenColors(p); + expect(out.layers[0].children?.[0].color).toBe("#00ff00"); + expect(out.layers[0].children?.[1]).toBe(untouchedChild); // referenzgleich, unangetastet + }); + + it("lässt eine Kategorie OHNE Stift-Verweis referenzgleich", () => { + const c = cat(); + const p = baseProject({ layers: [c] }); + const out = rebakePenColors(p); + expect(out.layers[0]).toBe(c); + }); +}); + +const wall = (overrides: Partial = {}): Wall => ({ + id: "w1", + type: "wall", + floorId: "eg", + categoryCode: "20", + start: { x: 0, y: 0 }, + end: { x: 5, y: 0 }, + wallTypeId: "aw", + height: 2.6, + ...overrides, +}); + +const ceiling = (overrides: Partial = {}): Ceiling => ({ + id: "c1", + type: "ceiling", + floorId: "eg", + categoryCode: "30", + outline: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }], + wallTypeId: "aw", + ...overrides, +}); + +const drawing2d = (overrides: Partial = {}): Drawing2D => ({ + id: "d1", + type: "drawing2d", + levelId: "eg", + categoryCode: "00", + geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } }, + ...overrides, +}); + +const room = (overrides: Partial = {}): Room => ({ + id: "r1", + type: "room", + floorId: "eg", + categoryCode: "60", + siaCategory: "HNF", + name: "Wohnen", + boundary: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }], + color: "#stale", + ...overrides, +}); + +describe("rebakePenColors — Elemente MIT Strichstärke-Feld (Wand/Decke/Drawing2D)", () => { + it("bäckt Farbe UND `strokeWeight` einer Wand", () => { + const p = baseProject({ + walls: [wall({ colorPenId: "1", strokeWeight: 0.05 })], + penSets: [{ id: "std", name: "Standard", pens: { "1": ps("#c0ffee", 0.6) } }], + activePenSetId: "std", + }); + const out = rebakePenColors(p); + expect(out.walls[0].color).toBe("#c0ffee"); + expect(out.walls[0].strokeWeight).toBe(0.6); + }); + + it("lässt eine Wand OHNE Stift-Verweis referenzgleich", () => { + const w = wall(); + const p = baseProject({ walls: [w] }); + const out = rebakePenColors(p); + expect(out.walls[0]).toBe(w); + }); + + it("bäckt Farbe UND `strokeWeight` einer Decke", () => { + const p = baseProject({ + ceilings: [ceiling({ colorPenId: "1" })], + penSets: [{ id: "std", name: "Standard", pens: { "1": ps("#aaaaaa", 0.25) } }], + activePenSetId: "std", + }); + const out = rebakePenColors(p); + expect(out.ceilings![0].color).toBe("#aaaaaa"); + expect(out.ceilings![0].strokeWeight).toBe(0.25); + }); + + it("bäckt Farbe UND `weightMm` eines Drawing2D (eigenes Feld, nicht `strokeWeight`)", () => { + const p = baseProject({ + drawings2d: [drawing2d({ colorPenId: "1" })], + penSets: [{ id: "std", name: "Standard", pens: { "1": ps("#ff00ff", 0.4) } }], + activePenSetId: "std", + }); + const out = rebakePenColors(p); + expect(out.drawings2d[0].color).toBe("#ff00ff"); + expect(out.drawings2d[0].weightMm).toBe(0.4); + }); + + it("bäckt `foreground`/`background` einer Wand UNABHÄNGIG von `colorPenId` und OHNE Strichstärke anzufassen", () => { + const p = baseProject({ + walls: [wall({ foregroundPenId: "2", backgroundPenId: "3", strokeWeight: 0.05 })], + penSets: [ + { + id: "std", + name: "Standard", + pens: { "2": ps("#00ff00", 0.9), "3": ps("#0000ff", 0.9) }, + }, + ], + activePenSetId: "std", + }); + const out = rebakePenColors(p); + expect(out.walls[0].foreground).toBe("#00ff00"); + expect(out.walls[0].background).toBe("#0000ff"); + // Kein `colorPenId` gesetzt ⇒ `color`/`strokeWeight` bleiben unangetastet. + expect(out.walls[0].color).toBeUndefined(); + expect(out.walls[0].strokeWeight).toBe(0.05); + }); + + it("lässt eine Wand MIT `foreground`/`background` OHNE Stift-Verweis referenzgleich", () => { + const w = wall({ foreground: "#fixed", background: "#alsoFixed" }); + const p = baseProject({ walls: [w] }); + const out = rebakePenColors(p); + expect(out.walls[0]).toBe(w); + }); +}); + +describe("rebakePenColors — Elemente OHNE Strichstärke-Feld (Raum), Robustheit", () => { + it("bäckt einen Raum (nur `color`, PFLICHT-Feld, kein Stärke-Feld vorhanden)", () => { + const p = baseProject({ + rooms: [room({ colorPenId: "1" })], + penSets: [{ id: "std", name: "Standard", pens: { "1": ps("#112233") } }], + activePenSetId: "std", + }); + const out = rebakePenColors(p); + expect(out.rooms![0].color).toBe("#112233"); + }); + + it("übersteht ein Projekt ohne optionale Arrays (ceilings/roofs/... fehlen ganz)", () => { + const p = baseProject({ activePenSetId: "std", penSets: [{ id: "std", name: "S", pens: {} }] }); + expect(() => rebakePenColors(p)).not.toThrow(); + expect(rebakePenColors(p).ceilings).toBeUndefined(); + }); +}); + +describe("generateStandardPenPalette", () => { + const { pens, styles } = generateStandardPenPalette(); + + it("liefert genau 255 Stifte mit IDs '1'..'255', je Farbe+Strichstärke", () => { + expect(pens.length).toBe(255); + expect(new Set(pens.map((p) => p.id)).size).toBe(255); + for (let i = 1; i <= 255; i++) { + expect(styles[String(i)].color).toMatch(/^#[0-9a-f]{6}$/); + expect(styles[String(i)].weight).toBe(PEN_FALLBACK_WEIGHT); + } + }); + + it("nutzt für 1-9 die klassischen Grundfarben (Rot/Gelb/.../Grau)", () => { + expect(styles["1"].color).toBe("#ff0000"); + expect(styles["2"].color).toBe("#ffff00"); + expect(styles["3"].color).toBe("#00ff00"); + }); + + it("liefert für 250-255 einen monoton aufhellenden Graukeil", () => { + const greys = [250, 251, 252, 253, 254, 255].map((i) => parseInt(styles[String(i)].color.slice(1, 3), 16)); + for (let i = 1; i < greys.length; i++) expect(greys[i]).toBeGreaterThan(greys[i - 1]); + }); + + it("erzeugt für 10-249 gültige, paarweise unterschiedliche Hex-Farben", () => { + const mid = Array.from({ length: 240 }, (_, i) => styles[String(10 + i)].color); + expect(new Set(mid).size).toBeGreaterThan(200); // Grossteil eindeutig, ein paar Rundungs-Kollisionen sind ok + }); +}); + +describe("seedStandardPenSet", () => { + it("legt `pens` (255) + einen neuen aktiven Stiftsatz mit denselben Stilen an", () => { + const p = baseProject(); + const out = seedStandardPenSet(p); + expect(out.pens?.length).toBe(255); + expect(out.penSets?.length).toBe(1); + expect(out.activePenSetId).toBe(out.penSets![0].id); + expect(out.penSets![0].pens["1"].color).toBe("#ff0000"); + }); + + it("aktiviert den neuen Satz NICHT, wenn bereits ein anderer Satz aktiv war", () => { + const p = baseProject({ + penSets: [{ id: "existing", name: "Alt", pens: {} }], + activePenSetId: "existing", + }); + const out = seedStandardPenSet(p); + expect(out.activePenSetId).toBe("existing"); + expect(out.penSets?.length).toBe(2); + }); + + it("bäckt sofort gekoppelte Bauteil-Farben, wenn der neue Satz aktiv wird", () => { + const p = baseProject({ components: [comp({ colorPenId: "3" })] }); + const out = seedStandardPenSet(p); + expect(out.components[0].color).toBe("#00ff00"); + }); +}); diff --git a/src/model/penSets.ts b/src/model/penSets.ts new file mode 100644 index 00000000..144a3a40 --- /dev/null +++ b/src/model/penSets.ts @@ -0,0 +1,253 @@ +// Stiftsatz-Auflösung (ArchiCAD-Stiftsatz-Muster) — reine Funktionen, keine +// Modell-Mutation. Der Trick, der jeden bestehenden Farb-/Strichstärke-Leser +// (2D-Plan, beide 3D-Renderer, DXF-Export, Vorschau-Swatches) UNVERÄNDERT +// lässt: `Component.color`/`.foreground`/`.background`, `LayerCategory.color`/ +// `.lw` bzw. die Element-Felder (`color`/`strokeWeight`/`weightMm`) bleiben +// IMMER die eine gültige, aufgelöste Farbe/Strichstärke. Ein Stift-Verweis +// (`xxxPenId`) schreibt diese Felder nur bei Gelegenheit (Stiftsatz-Wechsel, +// Stift-Änderung, neue Zuweisung) per `rebakePenColors` aus dem aktiven +// Stiftsatz NEU — kein Leser muss je einen Stift auflösen. +// +// Ein Stift (`PenStyle`) trägt Farbe UND Strichstärke zusammen (wie ein +// echter ArchiCAD-/AutoCAD-Stift) — beide wandern gemeinsam, wenn ein +// Element/eine Ebene auf „Stift" statt „Frei" gestellt wird. +// +// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). + +import type { ColorPen, Component, LayerCategory, PenSet, PenStyle, Project } from "./types"; + +/** Farbe eines Stifts, der im aktiven Stiftsatz (noch) keinen Eintrag hat. */ +export const PEN_FALLBACK_COLOR = "#9aa0a6"; +/** Strichstärke (mm) eines Stifts, der im aktiven Stiftsatz (noch) keinen Eintrag hat. */ +export const PEN_FALLBACK_WEIGHT = 0.18; + +/** HSL (h in Grad 0..360, s/l in 0..1) → "#rrggbb". Reine Konvertierung, keine Bibliothek nötig. */ +export function hslToHex(h: number, s: number, l: number): string { + const c = (1 - Math.abs(2 * l - 1)) * s; + const hp = (((h % 360) + 360) % 360) / 60; + const x = c * (1 - Math.abs((hp % 2) - 1)); + const [r1, g1, b1] = + hp < 1 ? [c, x, 0] : hp < 2 ? [x, c, 0] : hp < 3 ? [0, c, x] : hp < 4 ? [0, x, c] : hp < 5 ? [x, 0, c] : [c, 0, x]; + const m = l - c / 2; + const toHex = (v: number) => Math.round((v + m) * 255).toString(16).padStart(2, "0"); + return `#${toHex(r1)}${toHex(g1)}${toHex(b1)}`; +} + +/** + * Feste Freie-Farbe-Palette für den Palette-Popover (`ui/PenColorField.tsx`): + * 8 Graustufen (Schwarz→Weiss) + 8 Farbtöne × 5 Helligkeitsstufen = 48 + * Swatches. Rein prozedural (HSL), dieselbe Begründung wie + * `generateStandardPenPalette` — kein externes Farbschema. + */ +export const FREE_COLOR_PALETTE: string[] = (() => { + const out: string[] = []; + for (let i = 0; i < 8; i++) { + const v = Math.round((i / 7) * 255); + out.push(`#${v.toString(16).padStart(2, "0").repeat(3)}`); + } + for (let hue = 0; hue < 8; hue++) { + for (let level = 0; level < 5; level++) { + out.push(hslToHex(hue * 45, 0.75, 0.75 - level * 0.14)); + } + } + return out; +})(); + +/** + * Generiert 255 Stifte + einen passenden Stiftsatz nach klassischer CAD- + * Nummerierungs-Konvention (AutoCAD Color Index / ArchiCAD-Stiftsätze): Stifte + * 1–9 die Grundfarben (Rot/Gelb/Grün/Cyan/Blau/Magenta/Schwarz/zwei Grautöne — + * dieselben Werte wie die bestehende `ACI_PALETTE` in `export/exportDxf.ts`, + * damit beide Stellen konsistent bleiben), 10–249 24 Farbtöne × 10 Helligkeits-/ + * Sättigungsstufen (prozedural per HSL erzeugt), 250–255 ein Graustufen-Keil + * (identische Werte wie `ACI_PALETTE`s 250–255). **Keine externe Bibliothek + * oder ein konkretes lizenziertes Farbschema** — reine Mathematik (HSL-Kreis), + * daher lizenzfrei; strukturell an die altbekannte 255-Stift-Konvention aus + * AutoCAD/ArchiCAD angelehnt, nicht Pixel-für-Pixel identisch mit deren + * (proprietärer) Originaltabelle. Strichstärke einheitlich `PEN_FALLBACK_WEIGHT` + * (0.18 mm) — im Stiftsatz-Tab pro Stift frei änderbar. + */ +export function generateStandardPenPalette(): { pens: ColorPen[]; styles: Record } { + const pens: ColorPen[] = []; + const styles: Record = {}; + const add = (id: number, name: string, color: string) => { + pens.push({ id: String(id), name }); + styles[String(id)] = { color, weight: PEN_FALLBACK_WEIGHT }; + }; + + // 1–9: Grundfarben (wie ACI_PALETTE in exportDxf.ts). + add(1, "Rot", "#ff0000"); + add(2, "Gelb", "#ffff00"); + add(3, "Grün", "#00ff00"); + add(4, "Cyan", "#00ffff"); + add(5, "Blau", "#0000ff"); + add(6, "Magenta", "#ff00ff"); + add(7, "Schwarz", "#000000"); + add(8, "Dunkelgrau", "#414141"); + add(9, "Grau", "#808080"); + + // 10–249: 24 Farbtöne (15°-Schritte) × 10 Stufen (5 gesättigt hell→dunkel, + // 5 entsättigt hell→dunkel) — 240 Stifte. + let id = 10; + for (let hue = 0; hue < 24; hue++) { + const h = hue * 15; + for (let step = 0; step < 10; step++) { + const saturated = step < 5; + const level = step % 5; // 0..4 + const l = 0.75 - level * 0.14; // 0.75 → 0.19 + const s = saturated ? 0.85 : 0.4; + add(id, `Stift ${id}`, hslToHex(h, s, l)); + id++; + } + } + + // 250–255: Graustufen-Keil (wie ACI_PALETTE). + const greys: [number, string][] = [ + [250, "#333333"], + [251, "#5b5b5b"], + [252, "#848484"], + [253, "#adadad"], + [254, "#d6d6d6"], + [255, "#ffffff"], + ]; + for (const [gid, color] of greys) add(gid, `Grau ${gid}`, color); + + return { pens, styles }; +} + +/** + * Setzt `Project.pens`/`penSets` auf die generierte 255er-Standardpalette + * (s. {@link generateStandardPenPalette}) — ERSETZT bestehende `pens`/den neu + * angelegten Satz vollständig (kein Merge), gedacht für den Erststart, bevor + * eigene Stifte/Sätze existieren. Der neue Satz wird aktiv, wenn noch KEIN + * Stiftsatz aktiv war (dieselbe Konvention wie `addPenSet`). + */ +export function seedStandardPenSet(project: Project): Project { + const { pens, styles } = generateStandardPenPalette(); + const penSet: PenSet = { id: `penset-${Date.now()}`, name: "Standard (CAD-Palette)", pens: styles }; + return rebakePenColors({ + ...project, + pens, + penSets: [...(project.penSets ?? []), penSet], + activePenSetId: project.activePenSetId ?? penSet.id, + }); +} + +/** Der aktuell aktive Stiftsatz, oder `undefined` (kein Stiftsatz angelegt/aktiviert). */ +export function activePenSet(project: Project) { + return project.penSets?.find((s) => s.id === project.activePenSetId); +} + +/** Der Stil (Farbe+Strichstärke) EINES Stifts im aktiven Stiftsatz, oder `undefined` ohne Eintrag/Satz. */ +export function resolvePenStyle(project: Project, penId: string): PenStyle | undefined { + return activePenSet(project)?.pens[penId]; +} + +/** Löst einen Stift gegen den aktiven Stiftsatz auf; Fallback bei fehlendem Eintrag. */ +export function resolvePenColor(project: Project, penId: string): string { + return resolvePenStyle(project, penId)?.color ?? PEN_FALLBACK_COLOR; +} + +/** Strichstärke (mm) eines Stifts, analog {@link resolvePenColor}. */ +export function resolvePenWeight(project: Project, penId: string): number { + return resolvePenStyle(project, penId)?.weight ?? PEN_FALLBACK_WEIGHT; +} + +/** Bäckt die Stift-Farbe(n) EINES Bauteils neu (reine Funktion, unverändert wenn kein Stift gesetzt). */ +function bakeComponent(project: Project, c: Component): Component { + if (!c.colorPenId && !c.foregroundPenId && !c.backgroundPenId) return c; + return { + ...c, + ...(c.colorPenId ? { color: resolvePenColor(project, c.colorPenId) } : {}), + ...(c.foregroundPenId ? { foreground: resolvePenColor(project, c.foregroundPenId) } : {}), + ...(c.backgroundPenId ? { background: resolvePenColor(project, c.backgroundPenId) } : {}), + }; +} + +/** Bäckt Farbe UND Strichstärke (`.lw`) EINER Ebenen-Kategorie neu (rekursiv über `children`). */ +function bakeCategory(project: Project, cat: LayerCategory): LayerCategory { + const next: LayerCategory = cat.colorPenId + ? { ...cat, color: resolvePenColor(project, cat.colorPenId), lw: resolvePenWeight(project, cat.colorPenId) } + : cat; + if (!cat.children) return next; + const children = cat.children.map((c) => bakeCategory(project, c)); + return children === cat.children ? next : { ...next, children }; +} + +/** + * Bäckt die eigene `color`-Stift-Kopplung EINES Modell-Elements neu (nur + * Farbe — für Elementarten ohne eigenes Strichstärke-Override-Feld: Dach, + * Öffnung, Treppe, Raum). Unverändert (referenzgleich), wenn kein Stift + * gesetzt ist. + */ +function bakeElementColor( + project: Project, + x: T, +): T { + return x.colorPenId ? { ...x, color: resolvePenColor(project, x.colorPenId) } : x; +} + +/** + * Wie {@link bakeElementColor}, zusätzlich (a) die Strichstärke unter + * `weightKey` (Wand/Decke/Stütze: `strokeWeight`; Drawing2D: `weightMm`) — + * nur über `colorPenId` gekoppelt (ein Stift trägt Farbe UND Strichstärke + * zusammen; Vordergrund/Hintergrund sind reine Musterfarben ohne + * Strichstärke-Aspekt) — und (b) die Attribut-Override-Farben `foreground`/ + * `background` DIESER Element-Instanz, unabhängig über `foregroundPenId`/ + * `backgroundPenId` (analog `Component.foregroundPenId`/`backgroundPenId`, + * nur eben am Element statt am Bauteil). Für Elementarten MIT eigenem + * Strichstärke- UND Vordergrund/Hintergrund-Override-Feld (Wand/Decke/ + * Stütze/Drawing2D — exakt dieselben vier wie bei der Strichstärke). + */ +function bakeElementColorAndWeight< + T extends { + colorPenId?: string; + color?: string; + foregroundPenId?: string; + foreground?: string; + backgroundPenId?: string; + background?: string; + }, + K extends string, +>(project: Project, x: T & Partial>, weightKey: K): T { + if (!x.colorPenId && !x.foregroundPenId && !x.backgroundPenId) return x; + return { + ...x, + ...(x.colorPenId + ? { color: resolvePenColor(project, x.colorPenId), [weightKey]: resolvePenWeight(project, x.colorPenId) } + : {}), + ...(x.foregroundPenId ? { foreground: resolvePenColor(project, x.foregroundPenId) } : {}), + ...(x.backgroundPenId ? { background: resolvePenColor(project, x.backgroundPenId) } : {}), + }; +} + +/** + * Schreibt für JEDES Bauteil/JEDE Ebenen-Kategorie/JEDES Modell-Element mit + * gesetztem Stift die Farbe (+ ggf. Strichstärke) des AKTIVEN Stiftsatzes in + * `color`/`foreground`/`background`/`lw`/`strokeWeight`/`weightMm` — reine + * Funktion, liefert ein neues `Project` (unveränderte Teile bleiben + * referenzgleich). Aufzurufen nach: Stiftsatz-Wechsel, Änderung EINES Stifts + * im aktiven Satz, oder Neuzuweisung eines Stifts an ein Bauteil/eine Ebene + * (dort reicht meist ein direkter Patch, s. `resolvePenColor`/ + * `resolvePenWeight` — diese Funktion ist für die FLÄCHIGEN Fälle, die viele + * Objekte auf einmal betreffen). + * + * Bewusst NICHT abgedeckt: Layout-Annotationen (`Layout.annotations[]`, + * verschachtelt in `Project.layouts`) und `Tür`/`ExtrudedSolid`/Kontext- + * Objekte — kein `colorPenId`-Feld dort (Scope-Entscheid, s. PENDENZEN.md). + */ +export function rebakePenColors(project: Project): Project { + return { + ...project, + components: project.components.map((c) => bakeComponent(project, c)), + layers: project.layers.map((cat) => bakeCategory(project, cat)), + walls: project.walls.map((w) => bakeElementColorAndWeight(project, w, "strokeWeight")), + drawings2d: project.drawings2d.map((d) => bakeElementColorAndWeight(project, d, "weightMm")), + ceilings: project.ceilings?.map((c) => bakeElementColorAndWeight(project, c, "strokeWeight")), + columns: project.columns?.map((c) => bakeElementColorAndWeight(project, c, "strokeWeight")), + roofs: project.roofs?.map((r) => bakeElementColor(project, r)), + openings: project.openings?.map((o) => bakeElementColor(project, o)), + stairs: project.stairs?.map((s) => bakeElementColor(project, s)), + rooms: project.rooms?.map((r) => bakeElementColor(project, r)), + }; +} diff --git a/src/model/sampleProject.ts b/src/model/sampleProject.ts index 06105511..ebac3ab5 100644 --- a/src/model/sampleProject.ts +++ b/src/model/sampleProject.ts @@ -372,11 +372,24 @@ export const sampleProject: Project = { layers: [ { code: "00", name: "Raster", color: "#484850", lw: 0.13, visible: true, locked: false }, { code: "01", name: "Vermessung", color: "#707078", lw: 0.18, visible: true, locked: false }, - { code: "10", name: "Situation", color: "#909090", lw: 0.18, visible: true, locked: false }, - { code: "11", name: "Strasse", color: "#a89070", lw: 0.18, visible: true, locked: false }, - { code: "12", name: "Gebäude", color: "#888888", lw: 0.25, visible: true, locked: false }, - { code: "13", name: "Bäume", color: "#50a050", lw: 0.13, visible: true, locked: false }, - { code: "14", name: "Höhenlinien", color: "#909050", lw: 0.18, visible: true, locked: false }, + // "05 Kontext" bündelt Bestand/Umgebung (manuell gezeichnet ODER importiert, + // s. `contextCategories.ts::CONTEXT_PARENT_CATEGORY`) als Kinder statt als + // gleichrangige Top-Level-Einträge (Nutzer-Wunsch 2026-08-31). + { + code: "05", + name: "Kontext", + color: "#707078", + lw: 0.13, + visible: true, + locked: false, + children: [ + { code: "10", name: "Situation", color: "#909090", lw: 0.18, visible: true, locked: false }, + { code: "11", name: "Strasse", color: "#a89070", lw: 0.18, visible: true, locked: false }, + { code: "12", name: "Gebäude", color: "#888888", lw: 0.25, visible: true, locked: false }, + { code: "13", name: "Bäume", color: "#50a050", lw: 0.13, visible: true, locked: false }, + { code: "14", name: "Höhenlinien", color: "#909050", lw: 0.18, visible: true, locked: false }, + ], + }, { code: "20", name: "Wände", diff --git a/src/model/terrain.ts b/src/model/terrain.ts index b83fcfe5..a1082226 100644 --- a/src/model/terrain.ts +++ b/src/model/terrain.ts @@ -10,6 +10,7 @@ import Delaunator from "delaunator"; import type { Contour, TerrainMesh } from "./types"; +import { TERRAIN_CATEGORY } from "./contextCategories"; let terrainSeq = 0; @@ -55,7 +56,7 @@ export function generateTerrainFromContours(contours: Contour[]): TerrainMesh { // Zu wenige Punkte für ein Dreieck → triviales leeres Mesh. if (xs.length < 3) { - return { id, type: "terrainMesh", name, positions: [], indices: [] }; + return { id, type: "terrainMesh", name, categoryCode: TERRAIN_CATEGORY.code, positions: [], indices: [] }; } // 2. Delaunay über die (x,y)-Projektion. Delaunator erwartet ein flaches @@ -71,7 +72,7 @@ export function generateTerrainFromContours(contours: Contour[]): TerrainMesh { try { triangles = new Delaunator(coords2d).triangles; } catch { - return { id, type: "terrainMesh", name, positions: [], indices: [] }; + return { id, type: "terrainMesh", name, categoryCode: TERRAIN_CATEGORY.code, positions: [], indices: [] }; } // 3. positions (x,y,z) aufbauen; Z aus zs je Vertex. @@ -99,7 +100,15 @@ export function generateTerrainFromContours(contours: Contour[]): TerrainMesh { indices.push(a, b, c); } - return { id, type: "terrainMesh", name, layer: TERRAIN_LAYER, positions, indices }; + return { + id, + type: "terrainMesh", + name, + layer: TERRAIN_LAYER, + categoryCode: TERRAIN_CATEGORY.code, + positions, + indices, + }; } /** @@ -154,7 +163,15 @@ export function terrainMeshFromGrid(grid: TerrainGrid): TerrainMesh { } if (positions.length < 9 || indices.length < 3) { - return { id, type: "terrainMesh", name, positions: [], indices: [] }; + return { id, type: "terrainMesh", name, categoryCode: TERRAIN_CATEGORY.code, positions: [], indices: [] }; } - return { id, type: "terrainMesh", name, layer: TERRAIN_LAYER, positions, indices }; + return { + id, + type: "terrainMesh", + name, + layer: TERRAIN_LAYER, + categoryCode: TERRAIN_CATEGORY.code, + positions, + indices, + }; } diff --git a/src/model/types.ts b/src/model/types.ts index 83743f77..3dc006ed 100644 --- a/src/model/types.ts +++ b/src/model/types.ts @@ -30,6 +30,46 @@ import type { DetailLevel, View3d, ViewType } from "../ui/TopBar"; // Geometrie eingebacken (siehe docs/design/resources-graphics.md). /** Ein wiederverwendbarer Linienstil (Line Manager). */ +/** + * Ein Stift (ArchiCAD-Stiftsatz-Muster): ein reiner NAME/PLATZHALTER, der + * projektweit über alle {@link PenSet}s hinweg dieselbe Identität `id` behält. + * Ein Stift trägt selbst KEINE Farbe — welche Farbe er zeigt, bestimmt der + * jeweils AKTIVE Stiftsatz (`Project.activePenSetId`). Ein Bauteil/eine Ebene, + * die statt einer freien Farbe auf einen Stift zeigt (`xxxPenId`), übernimmt + * dadurch automatisch jede Farbänderung des Stifts bzw. jeden Stiftsatz- + * Wechsel — ohne selbst angefasst zu werden. + */ +export interface ColorPen { + id: string; + name: string; +} + +/** + * Ein Stiftsatz — ordnet JEDEM Stift (`ColorPen.id`) eine konkrete Farbe zu. + * Mehrere Stiftsätze können nebeneinander existieren (z. B. „Standard", + * „Plot S/W", „Präsentation"); nur einer ist je Projekt AKTIV + * (`Project.activePenSetId`). Fehlt ein Stift im `colors`-Objekt (z. B. neu + * angelegt, aber in diesem Satz noch nicht befüllt), gilt `PEN_FALLBACK_COLOR` + * (s. `model/penSets.ts`). + */ +/** + * Farbe + Strichstärke EINES Stifts in EINEM Stiftsatz — wie ein echter + * ArchiCAD-/AutoCAD-Stift wandern beide zusammen, wenn ein Element/eine Ebene + * auf diesen Stift gestellt wird (s. `Component.colorPenId`-Doku). + */ +export interface PenStyle { + color: string; + /** Strichstärke in Millimetern. */ + weight: number; +} + +export interface PenSet { + id: string; + name: string; + /** Stift-ID (`ColorPen.id`) → Farbe+Strichstärke. */ + pens: Record; +} + export interface LineStyle { id: string; name: string; @@ -89,7 +129,14 @@ export type HatchPattern = | "solid" | "insulation" | "diagonal" - | "crosshatch"; + | "crosshatch" + /** + * Frei gezeichnetes Wiederhol-Motiv (Parameter in {@link HatchStyle.motif}, + * gleiche Form wie `LineStyle.motif` — der Editor `MotifEditor.tsx` ist + * bereits generisch für beide gebaut). Ohne gesetztes `motif` degradiert die + * Fläche zu geraden Parallel-Musterlinien (wie „diagonal"). + */ + | "custom"; /** Eine wiederverwendbare Schraffur (Hatch Manager). */ export interface HatchStyle { @@ -160,6 +207,16 @@ export interface HatchStyle { lengthMin?: number; /** Maximale Strichlänge in mm (Papier). Fehlt es, greift die `scale`-abhängige Default-Länge. */ lengthMax?: number; + /** + * Frei gezeichnetes Wiederhol-Motiv (nur `pattern==="custom"`) — gleiche Form + * wie `LineStyle.motif`: eine offene Polylinie in Papier-mm, `x` läuft + * 0..`length` (Wiederhollänge ENTLANG der Musterlinie), `y` = Versatz quer zur + * Musterlinie. Wird alle `length` Papier-mm entlang jeder Musterlinie + * gekachelt UND (wie bei diagonal/crosshatch) im Abstand von `scale`- + * abhängigen 8 px quer versetzt wiederholt. Fehlt es, zeichnet „custom" wie + * „diagonal" (gerade Linien) — kein Absturz bei frisch angelegten Hatches. + */ + motif?: { points: Vec2[]; length: number }; } /** @@ -214,6 +271,22 @@ export interface Component { * `color`. Migrationsabsicht: `background` ⇐ `color`. */ background?: string; + /** + * Stift-Kopplung (ArchiCAD-Stiftsatz-Muster, s. {@link ColorPen}/{@link + * PenSet}): ist eines dieser Felder gesetzt, wird `color`/`foreground`/ + * `background` NICHT frei editiert, sondern bei jedem Stiftsatz-Wechsel + * bzw. jeder Stift-Farbänderung automatisch aus dem aktiven Stiftsatz NEU + * GESCHRIEBEN (`rebakePenColors`, `model/penSets.ts`) — die drei Felder + * bleiben dadurch für ALLE bestehenden Leser (2D-Plan, beide 3D-Renderer, + * Export) unverändert die eine gültige, aufgelöste Farbe; nur die Herkunft + * ist jetzt ein Stift statt eine freie Wahl. Ein gesetzter `xxxPenId` gilt + * genauso als „eigen" (explizit) wie eine frei gewählte Farbe — beides sind + * Werte AM Bauteil, kein Verweis auf eine Ebene (anders als `foregroundSource` + * an Wand/Decke/etc.). + */ + colorPenId?: string; + foregroundPenId?: string; + backgroundPenId?: string; /** Schnitt-Schraffur → Hatch Manager. Gilt, wo das Bauteil echt geschnitten ist. */ hatchId: string; /** @@ -291,6 +364,21 @@ export interface RoofType { layers: Layer[]; } +/** + * Wiederverwendbares 2D-Symbol (Möbelblock, Sanitär-/Normsymbol, Nordpfeil + * u. Ä.) — s. `Project.blockDefs` + `Drawing2DGeom["block"]`. `geom2d` ist + * LOKALE Geometrie (Ursprung = Einfügepunkt der Instanz, Winkel 0 = wie + * definiert); jede Instanz transformiert sie beim Rendern per `at`/`rotation`. + * Bewusst KEIN verschachtelter `"block"`-Shape in `geom2d` (keine Blöcke in + * Blöcken, v1) — nicht technisch erzwungen, nur Konvention der Autoren-Seite + * (`commands/cmds/defblock.ts`). + */ +export interface BlockDef { + id: string; + name: string; + geom2d: Drawing2DGeom[]; +} + // ── Bauteil-Typen: Tür / Fenster / Treppe ────────────────────────────────── // Wiederverwendbare Stile (Presets) für Türen, Fenster und Treppen — analog // `WallType`/`CeilingType` (Bibliothek im Projekt, referenziert per `typeId`). @@ -817,6 +905,14 @@ export interface LayerCategory { name: string; /** Darstellungsfarbe (hex). */ color: string; + /** + * Stift-Kopplung (s. `Component.colorPenId`): ist sie gesetzt, wird `color` + * bei jedem Stiftsatz-Wechsel automatisch aus dem aktiven Stiftsatz neu + * geschrieben. Zeichnet ein Objekt „nach Ebene", übernimmt es dadurch den + * Stift dieser Ebene — bleibt aber selbst bei einer FREIEN Farbe, keinem + * eigenen Stift-Verweis (nur `color` wandert mit). + */ + colorPenId?: string; /** Linienstärke in Millimetern. */ lw: number; visible: boolean; @@ -890,6 +986,8 @@ export interface Wall { * nicht die Schicht-Füllfarben/Schraffuren. */ color?: string; + /** Stift-Kopplung von `color` (s. `Component.colorPenId`-Doku). */ + colorPenId?: string; /** * Attribut-Override der Muster-/Schraffurfarbe (Vordergrund) DIESER Wand- * Instanz. `undefined` = „Nach System" (erben → Component.foreground → @@ -901,6 +999,10 @@ export interface Wall { * `undefined` = „Nach System" (erben → Component.background → Component.color). */ background?: string; + /** Stift-Kopplung von `foreground` (s. `Component.foregroundPenId`-Doku). */ + foregroundPenId?: string; + /** Stift-Kopplung von `background`, analog {@link Wall.foregroundPenId}. */ + backgroundPenId?: string; /** * Attribut-Override der Strichstärke (mm Papier) DIESER Wand-Instanz (Umriss/ * Schichtfugen). `undefined` = „Nach System" (erben → `strokeWeightSource`). @@ -1028,6 +1130,8 @@ export interface Ceiling { * Kategorie-Farbe. */ color?: string; + /** Stift-Kopplung von `color` (s. `Component.colorPenId`-Doku). */ + colorPenId?: string; /** * Attribut-Override der Muster-/Schraffurfarbe (Vordergrund) DIESER Decken- * Instanz. `undefined` = „Nach System" (erben → Component.foreground → @@ -1039,6 +1143,10 @@ export interface Ceiling { * `undefined` = „Nach System" (erben → Component.background → Component.color). */ background?: string; + /** Stift-Kopplung von `foreground` (s. `Component.foregroundPenId`-Doku). */ + foregroundPenId?: string; + /** Stift-Kopplung von `background`, analog {@link Wall.foregroundPenId}. */ + backgroundPenId?: string; /** * Attribut-Override der Strichstärke (mm Papier) DIESER Decken-Instanz. * `undefined` = „Nach System" (erben → `strokeWeightSource`). @@ -1144,6 +1252,8 @@ export interface Roof { roofTypeId?: string; /** Optionale Übersteuerung der Strich-/Umrissfarbe; sonst Kategorie-Farbe. */ color?: string; + /** Stift-Kopplung von `color` (s. `Component.colorPenId`-Doku). */ + colorPenId?: string; } /** Schwenkrichtung der Tür relativ zur Wandachse. */ @@ -1234,6 +1344,8 @@ export interface Opening { * Kategorie-Farbe. */ color?: string; + /** Stift-Kopplung von `color` (s. `Component.colorPenId`-Doku). */ + colorPenId?: string; /** * Nur Fenster, Grundriss: Übersteuerung von Farbe/Strichstärke der * GESCHNITTENEN Blendrahmen-Querschnittsblöcke an den Laibungs-Enden @@ -1372,6 +1484,8 @@ export interface Stair { * Kategorie-Farbe. */ color?: string; + /** Stift-Kopplung von `color` (s. `Component.colorPenId`-Doku). */ + colorPenId?: string; /** * Darstellung des Auf-/Abpfeils an der Lauflinie: "line" (offener * Winkelpfeil, Default = heutiges Verhalten) oder "filled" (gefülltes @@ -1409,6 +1523,8 @@ export interface Room { boundary: Vec2[]; /** Strich-/Füllfarbe des Raums (hex). */ color: string; + /** Stift-Kopplung von `color` (s. `Component.colorPenId`-Doku). */ + colorPenId?: string; /** * Anker des Raum-Stempels (Meter). Wird bei der Erstellung EINMAL auf den * Zentroid gesetzt und danach nie automatisch neu berechnet — der Stempel ist @@ -1498,7 +1614,34 @@ export interface Door { /** Geometrie-Form eines 2D-Zeichenelements. */ export type Drawing2DGeom = | { shape: "line"; a: Vec2; b: Vec2 } - | { shape: "polyline"; pts: Vec2[]; closed: boolean } + /** + * Konstruktionslinie (Hilfslinie): unendliche Ausrichtungslinie durch `a` + * und `b`, nur zwei gesetzte Punkte gespeichert — beim Rendern/Picken WEIT + * über beide hinaus verlängert (s. `XLINE_EXTEND_M`), damit sie optisch/ + * funktional unendlich wirkt, ohne echte Unendlichkeits-Sonderfälle in der + * SVG-/PDF-/DXF-Pipeline zu brauchen. Bewusst NICHT offset-/trim-/ + * extend-/join-fähig (reine Ausrichtungshilfe, kein reales Bauteil). + */ + | { shape: "xline"; a: Vec2; b: Vec2 } + | { + shape: "polyline"; + pts: Vec2[]; + closed: boolean; + /** + * Optionale Bogen-Segmente (DXF-„Bulge"-Konvention): `bulge[i]` krümmt + * das Segment `pts[i] → pts[i+1]` (bei `closed` zusätzlich `bulge[pts. + * length-1]` für das Schliess-Segment `pts[letzter] → pts[0]`) zu einem + * Kreisbogen statt einer Geraden. `bulge[i] = tan(Δ/4)` (Δ = Öffnungs- + * winkel des Bogens); Vorzeichen bestimmt die Seite (positiv = links von + * a→b, s. `geometry/bulge.ts::bulgeArcPoints`). Fehlt der Eintrag oder + * ist er 0/nahe 0 (`< 1e-9`), bleibt das Segment gerade — rein additiv, + * jede bestehende Polylinie ohne `bulge` verhält sich exakt wie bisher. + * Nur DIESES Feld unterscheidet eine „echte" Bogen-Polylinie von der + * bisherigen rein geradlinigen; Rendering/Fläche/Export tessellieren den + * Bogen (kein eigenes SVG-Arc-Primitiv, analog Ellipse/Spline/Bezier). + */ + bulge?: number[]; + } | { shape: "rect"; min: Vec2; max: Vec2 } | { shape: "circle"; center: Vec2; r: number } | { shape: "arc"; center: Vec2; r: number; a0: number; a1: number } @@ -1586,7 +1729,34 @@ export type Drawing2DGeom = * `text`). `width` bricht wie gehabt wortweise um. */ doc?: RichTextDoc; + /** + * Legenden-/Vorführungspfeil (Leader): optionale Zielposition, auf die + * eine dünne Linie + Pfeilspitze vom Text aus zeigt (z. B. Beschriftung + * eines entfernten Details). Kein eigener Shape — erbt dadurch die + * komplette Inline-Text-Editor-Infrastruktur (analog `width` bei der + * Textspalte). Gesetzt vom `leader`-Befehl, am normalen `text`-Werkzeug + * unverändert `undefined`. + */ + leaderTarget?: Vec2; + /** + * Text-entlang-Pfad: mind. 2 Stützpunkte, entlang derer der Text (nur + * `text`, KEIN `doc`/Rich-Formatting — v1 bewusst einstilig) über ein + * echtes SVG `` fliesst. Ist gesetzt, bestimmt der Pfad die + * Position/Neigung jedes Zeichens; `at`/`angle` werden dann ignoriert + * (bleiben nur als Fallback für Alt-Konsumenten, die `pathPts` nicht + * kennen — s. `drawing2d.ts`). Griffe sind dann die Pfadpunkte selbst + * (wie bei `polyline`), nicht der einzelne Anker. + */ + pathPts?: Vec2[]; } + /** + * Platzierte Instanz eines wiederverwendbaren 2D-Symbols (`Project. + * blockDefs`, s. dort). `rotation` in Radiant. Trägt selbst KEINE Geometrie + * — die kommt beim Rendern/Picken/Snapping aus `blockDefId` + dieser + * Transformation. Verweist die Instanz auf eine gelöschte/unbekannte + * `blockDefId`, rendert sie schlicht nichts (kein Crash, s. `drawing2d.ts`). + */ + | { shape: "block"; blockDefId: string; at: Vec2; rotation: number } | { shape: "image"; /** Obere-linke Ecke der Bild-Box (Modell-Meter). */ @@ -1625,8 +1795,14 @@ export interface Drawing2D { * hat es Vorrang vor `fillColor` (der Poché-Hintergrund der geschlossenen Form). */ background?: string; + /** Stift-Kopplung von `foreground` (s. `Component.foregroundPenId`-Doku). */ + foregroundPenId?: string; + /** Stift-Kopplung von `background`, analog {@link Wall.foregroundPenId}. */ + backgroundPenId?: string; /** Optionale explizite Strichfarbe; sonst Kategorie-Farbe. */ color?: string; + /** Stift-Kopplung von `color` (s. `Component.colorPenId`-Doku). */ + colorPenId?: string; /** * Optionale Vollton-Füllfarbe für geschlossene Formen (getrennt von der * Strichfarbe `color`). Fehlt sie, ist die Fläche transparent (nur Schraffur @@ -1777,6 +1953,8 @@ export interface Column { * Kategorie-Farbe. */ color?: string; + /** Stift-Kopplung von `color` (s. `Component.colorPenId`-Doku). */ + colorPenId?: string; /** * Attribut-Override der Muster-/Schraffurfarbe (Vordergrund) DIESER Stütze. * `undefined` = „Nach System" (erben → Component.foreground), analog `Wall. @@ -1789,6 +1967,10 @@ export interface Column { * nach Schraffur-Muster), analog `Wall.background`. */ background?: string; + /** Stift-Kopplung von `foreground` (s. `Component.foregroundPenId`-Doku). */ + foregroundPenId?: string; + /** Stift-Kopplung von `background`, analog {@link Wall.foregroundPenId}. */ + backgroundPenId?: string; /** * Attribut-Override der Strichstärke (mm Papier) DIESER Stütze. `undefined` * = „Nach System" (erben → `strokeWeightSource`), analog `Wall.strokeWeight`. @@ -1827,6 +2009,13 @@ export interface ImportedMesh { name: string; /** Ursprünglicher DXF-Layer-Name (für spätere Kategorisierung). */ layer?: string; + /** + * Grafik-Kategorie-Code (s. {@link LayerCategory}, `model/contextCategories.ts`) + * — steuert Sichtbarkeit/Grau/Sperren wie bei jedem anderen Bauteil (Ebenen- + * Panel). Fehlt er (ältere Importe vor dieser Erweiterung), bleibt das Objekt + * IMMER sichtbar (Rückwärtskompatibilität), s. `generatePlan/context.ts`. + */ + categoryCode?: string; positions: number[]; indices: number[]; } @@ -1882,6 +2071,8 @@ export interface ContourSet { name: string; /** Ursprünglicher DXF-Layer-Name (für spätere Kategorisierung). */ layer?: string; + /** Grafik-Kategorie-Code, s. {@link ImportedMesh.categoryCode}. */ + categoryCode?: string; contours: Contour[]; } @@ -1896,6 +2087,8 @@ export interface TerrainMesh { name: string; /** Ebenen-/Gruppierungsname (SitePanel), z. B. „Terrain". Optional. */ layer?: string; + /** Grafik-Kategorie-Code, s. {@link ImportedMesh.categoryCode}. */ + categoryCode?: string; positions: number[]; indices: number[]; /** @@ -1920,6 +2113,8 @@ export interface ContextImage { name: string; /** Ebenen-/Gruppierungsname (SitePanel), z. B. „Luftbild". Optional. */ layer?: string; + /** Grafik-Kategorie-Code, s. {@link ImportedMesh.categoryCode}. */ + categoryCode?: string; /** Bildquelle als Data-URL (PNG/JPEG). */ src: string; /** Modell-Meter Bounding-Box (das Bild füllt [min..max] planar von oben). */ @@ -1933,6 +2128,22 @@ export interface ContextImage { * der 2D-Hintergrund-Darstellung. Default false. */ drape?: boolean; + /** + * Bildkorrektur (2D-Grundriss, CSS-`filter`-Semantik) — alle Werte optional, + * fehlend = neutral (kein visueller Unterschied zu keinem Filter). `grayscale` + * ist eine STETIGE 0..1-Blendung (nicht der binäre `mono`-Druckmodus von + * `generatePlan()`, der Luftbilder ganz ausblendet — unabhängige Konzepte). + */ + filters?: { + /** 0 = Graustufen, 1 = Original, >1 = übersättigt. Default 1. */ + saturation?: number; + /** 0 = schwarz, 1 = Original, >1 = heller. Default 1. */ + brightness?: number; + /** 0 = flaches Grau, 1 = Original, >1 = kontrastreicher. Default 1. */ + contrast?: number; + /** 0 = kein Effekt, 1 = vollständig Graustufen. Default 0. */ + grayscale?: number; + }; } /** Ein Kontext-Objekt: importiertes Mesh, Konturen-Satz, TIN oder Rasterbild. */ @@ -2275,6 +2486,14 @@ export interface Project { * Dächer ohne `roofTypeId` lösen über die einschichtige `Roof.thickness` auf. */ roofTypes?: RoofType[]; + /** + * Wiederverwendbare 2D-Symbol-Bibliothek (Möbelblöcke, Sanitär-/Norm- + * symbole u. Ä.) — analog `wallTypes`: einmal definieren, beliebig oft als + * `{shape:"block"}`-Instanz platzieren. V1 bewusst NUR 2D (kein 3D-Körper, + * keine verschachtelten Blöcke). Optional, damit bestehende Projekte ohne + * `blockDefs` gültig bleiben. + */ + blockDefs?: BlockDef[]; /** * Türtypen-Bibliothek (Türstile), analog `wallTypes`. Optional, damit * bestehende Projekte/Tests ohne `doorTypes` gültig bleiben; Türen ohne @@ -2289,6 +2508,22 @@ export interface Project { * Treppentypen-Bibliothek (Treppenstile). Optional (siehe `doorTypes`). */ stairTypes?: StairType[]; + /** + * Stift-Bibliothek (ArchiCAD-Stiftsatz-Muster, s. {@link ColorPen}): + * projektweite Liste der Stift-IDs/-Namen. Optional, damit bestehende + * Projekte/Tests ohne Stifte gültig bleiben. + */ + pens?: ColorPen[]; + /** + * Stiftsätze (s. {@link PenSet}) — je einer eine vollständige Stift→Farbe- + * Zuordnung. Optional (siehe `pens`). + */ + penSets?: PenSet[]; + /** + * ID des aktuell AKTIVEN Stiftsatzes (`penSets`). Fehlt sie (kein Stiftsatz + * angelegt/aktiviert), lösen Stift-Verweise auf `PEN_FALLBACK_COLOR` auf. + */ + activePenSetId?: string; /** Oberste Schnitte: Geschosse + Schnitte/Ansichten. */ drawingLevels: DrawingLevel[]; /** Grafik-Kategorie-Baum (geschossübergreifend). */ diff --git a/src/native/appMenu.ts b/src/native/appMenu.ts index a0288e2c..3a191d6d 100644 --- a/src/native/appMenu.ts +++ b/src/native/appMenu.ts @@ -20,6 +20,9 @@ import type { View3d, ViewType } from "../ui/TopBar"; /** Alle Aktionen, die die native Menüleiste auslösen kann. */ export interface NativeAppMenuHandlers { + onNewProject: () => void; + onNewProjectFromSample: () => void; + onNewProjectFromTemplate: () => void; onOpenProject: () => void; onSaveProject: () => void; onImport: () => void; @@ -130,6 +133,25 @@ export function useNativeAppMenu( const fileMenu = await Submenu.new({ text: t("menu.native.file"), items: [ + await MenuItem.new({ + text: t("menu.native.new"), + accelerator: "CmdOrCtrl+N", + action: () => handlersRef.current.onNewProject(), + }), + await Submenu.new({ + text: t("menu.native.newFromTemplate"), + items: [ + await MenuItem.new({ + text: t("menu.native.newFromSample"), + action: () => handlersRef.current.onNewProjectFromSample(), + }), + await MenuItem.new({ + text: t("menu.native.newFromTemplateFile"), + action: () => handlersRef.current.onNewProjectFromTemplate(), + }), + ], + }), + await PredefinedMenuItem.new({ item: "Separator" }), await MenuItem.new({ text: t("menu.native.open"), accelerator: "CmdOrCtrl+O", diff --git a/src/panels/AttributesPanel.tsx b/src/panels/AttributesPanel.tsx index 61d3aee4..f5a0e9a5 100644 --- a/src/panels/AttributesPanel.tsx +++ b/src/panels/AttributesPanel.tsx @@ -22,6 +22,7 @@ // Label→Wert-Grid. Bezeichner englisch, UI-Text/Kommentare deutsch (CONVENTIONS.md). // Alle sichtbaren Texte über t(...). +import { Fragment } from "react"; import type { ReactNode } from "react"; import { t } from "../i18n"; import { formatM, wallTypeLabel } from "../model/types"; @@ -29,7 +30,8 @@ import { PEN_WEIGHTS } from "../model/types"; import type { AttributeSource } from "../model/types"; import { usePanelHost } from "./host"; import { Dropdown } from "../ui/Dropdown"; -import { ColorHexField } from "../ui/ColorHexField"; +import { PenColorField } from "../ui/PenColorField"; +import { activePenSet, resolvePenWeight } from "../model/penSets"; // Element-spezifische Attribut-Abschnitte (Wand/Decke/Öffnung/Treppe/Raum) — // aus ObjectInfoPanel hierher verschoben (Ribbon Phase 3: ObjectInfo trägt nur // noch Bezugspunkt + Masse). @@ -175,18 +177,6 @@ export function AttributesPanel() { /> ); - // Farb-Swatch — IMMER sichtbar (Nutzer-Wunsch: den aktuell EFFEKTIVEN Wert - // (welche Farbe auch immer Ebene/Bauteil/Override gerade liefert) jederzeit - // sehen, nicht nur bei „eigener Wert"). Ändert man ihn direkt, wird - // automatisch „eigener Wert": der Setter schreibt den Override, wodurch - // `uiSourceOf` beim nächsten Render „custom" ableitet (kein separater - // Umschalt-Schritt nötig). - const colorValue = ( - value: string | undefined, - onSet: (color: string) => void, - editable: boolean, - ) => ; - // Eine Attribut-Zeile: Label + IMMER sichtbares Eingabe-Element (zeigt den // effektiven Wert) + Quellen-Dropdown. const sourceRow = ( @@ -271,17 +261,34 @@ export function AttributesPanel() { {/* ── Stift/Strich ──────────────────────────────────────────── */}
{t("attr.stroke")}
- {/* Farbe — gilt für Wand UND Drawing2D (Kontrakt setzt beide). */} + {/* Farbe — gilt für Wand, Decke, Öffnung, Treppe, Raum UND Drawing2D + (Kontrakt setzt sie alle). Ein Stift trägt Farbe UND Strichstärke + zusammen (s. model/penSets.ts) — daher `showWeight`, wenn diese + Elementart überhaupt ein eigenes Strichstärke-Feld hat + (`weightEditable`, nicht bei reinen Annotationen ohne Bauteil- + Bezug relevant, aber harmlos, falls doch angeklickt). */} {t("attr.color")} - + {/* Strichstärke (mm): Wand/Decke/Drawing2D mit Nach-Ebene/Nach-Bauteil/ eigener-Wert-Quelle; eine Layout-Annotation kennt diese Vererbung nicht (kein Bauteil/keine Ebene) — dort ein schlichtes Zahlenfeld ohne Quellen-Dropdown, wenn die Art überhaupt eine Strichstärke - trägt (Linie/Rechteck, nicht Text/Bild). */} + trägt (Linie/Rechteck, nicht Text/Bild). Ist die Farbe oben an + einen Stift gekoppelt (`sel.colorPenId`), ist dieses Feld + GESPERRT und zeigt die Strichstärke DES STIFTS (ein Stift trägt + beides zusammen, s. model/penSets.ts) statt des sonst aufgelösten + `weightMm`. */} {isAnnotation ? ( weightEditable && ( <> @@ -306,7 +313,7 @@ export function AttributesPanel() { ) : ( sourceRow( "attr.weight", - weightEditable, + weightEditable && !sel.colorPenId, weightUi, onWeightSourceChange, <> @@ -316,9 +323,9 @@ export function AttributesPanel() { type="number" step={0.01} min={0} - disabled={!weightEditable} + disabled={!weightEditable || !!sel.colorPenId} list="attr-pen-weights" - value={sel.weightMm} + value={sel.colorPenId ? resolvePenWeight(project, sel.colorPenId) : sel.weightMm} onChange={(e) => { const v = Number(e.target.value); if (Number.isFinite(v)) host.onSetSelectionWeight(v); @@ -358,6 +365,44 @@ export function AttributesPanel() { )} + {/* Bildkorrektur (Sättigung/Helligkeit/Kontrast/Graustufen) — NUR + Kontext-Objekt-Luftbilder (`ContextImage.filters`); Drawing2D-/ + Layout-Bilder haben (noch) keine Korrektur. Neutral-Defaults + (1/1/1/0), damit ein fehlendes `filters`-Objekt als "kein Effekt" + angezeigt wird statt als 0/0/0/0. */} + {sel.kind === "contextObject" && sel.isImage && ( + <> + {( + [ + ["saturation", "attr.saturation", 1, 0, 2] as const, + ["brightness", "attr.brightness", 1, 0, 2] as const, + ["contrast", "attr.contrast", 1, 0, 2] as const, + ["grayscale", "attr.grayscale", 0, 0, 1] as const, + ] + ).map(([key, labelKey, neutral, min, max]) => ( + + {t(labelKey)} + + { + const v = Number(e.target.value); + if (Number.isFinite(v)) + host.onSetSelectionImageFilters({ [key]: Math.max(min, Math.min(max, v)) }); + }} + /> + + + ))} + + )} + {/* Linienstil — nur Drawing2D trägt ihn (Wand/Decke/Annotation etc. read-only), Rest wie gehabt. */} {!isAnnotation && ( @@ -392,12 +437,26 @@ export function AttributesPanel() { <>
{t("attr.fill")}
+ {/* Swatch — IMMER sichtbar (zeigt den effektiven Wert, welche + Ebene/Bauteil/Override auch immer gerade liefert), aber nur bei + „eigener Wert" editierbar (`disabled`). Trägt wie die Strich- + farbe oben eine eigene Stift-Kopplung (`foregroundPenId`/ + `backgroundPenId`) — Frei/Stift + Popover-Palette identisch zur + Stift-Zeile, nur pro Element statt pro Bauteil gekoppelt. */} {sourceRow( "attr.foreground", pocheEditable, fgUi, onForegroundSourceChange, - colorValue(sel.effectiveForeground, host.onSetSelectionForeground, pocheEditable), + , )} {sourceRow( @@ -405,7 +464,15 @@ export function AttributesPanel() { pocheEditable, bgUi, onBackgroundSourceChange, - colorValue(sel.effectiveBackground, host.onSetSelectionBackground, pocheEditable), + , )} {sourceRow( diff --git a/src/panels/ToolsPanel.tsx b/src/panels/ToolsPanel.tsx index d4e8dd2e..9f439d06 100644 --- a/src/panels/ToolsPanel.tsx +++ b/src/panels/ToolsPanel.tsx @@ -108,6 +108,14 @@ export function ToolIcon({ id }: { id: ToolId }) { ); + case "xline": + // Volle Diagonale (randberührend) im Strich-Punkt-Muster — deutet die + // „unendliche" Konstruktionslinie an. + return ( + + + + ); case "polyline": // Dreisegmentiger Zickzack. return ( @@ -145,6 +153,23 @@ export function ToolIcon({ id }: { id: ToolId }) { ); + case "polygon": + // Regelmässiges Sechseck als generisches Vieleck-Symbol. + return ( + + + + ); + case "block": + // Gestricheltes Symbol-Rechteck (gruppierter Inhalt) + Einfügepunkt + // (gefüllter Punkt am Ursprung). + return ( + + + + + + ); case "spline": // Glatte S-Kurve durch drei Wegpunkte. return ( @@ -196,6 +221,24 @@ export function ToolIcon({ id }: { id: ToolId }) { ); + case "leader": + // Pfeil zu einem Zielpunkt + kurze Textzeile (Legenden-/Vorführungspfeil). + return ( + + + + + + + ); + case "textpath": + // „A" auf einer gebogenen Grundlinie — deutet Text-entlang-Pfad an. + return ( + + + + + ); case "textbox": // Spalten-Rahmen mit drei Textzeilen (Absatztext). return ( @@ -226,22 +269,27 @@ export function ToolIcon({ id }: { id: ToolId }) { // Bauteile · Bearbeiten-Aktionen). const TOOLS_2D: ToolId[] = [ "line", + "xline", "polyline", "rect", "circle", "arc", "ellipse", + "polygon", + "block", "spline", "bezier", "dimension", "kote", "text", + "leader", + "textpath", "textbox", "image", ]; const TOOLS_3D: ToolId[] = ["wall", "ceiling", "window", "door", "stair", "room"]; const COMMANDS_3D = ["column", "ceilingopening", "roof", "extrude", "sectionline", "viewline"]; -const COMMANDS_EDIT = ["move", "copy", "array", "rotate", "mirror", "offset", "multiline", "trim", "extend", "fillet", "chamfer", "join", "measure"]; +const COMMANDS_EDIT = ["move", "copy", "array", "rotate", "mirror", "offset", "multiline", "trim", "extend", "fillet", "chamfer", "join", "defblock", "measure"]; type ToolsView = "list" | "icons"; const VIEW_STORAGE_KEY = "dossier.toolsPanel.view"; diff --git a/src/panels/ViewSnapshotsPanel.tsx b/src/panels/ViewSnapshotsPanel.tsx index 7c4b6d76..e2913929 100644 --- a/src/panels/ViewSnapshotsPanel.tsx +++ b/src/panels/ViewSnapshotsPanel.tsx @@ -29,6 +29,7 @@ import { buildViewSnapshotTree, type ViewSnapshotFolderNode, } from "../state/viewSnapshotFolders"; +import { matchingComboName } from "../state/viewSnapshots"; import { t } from "../i18n"; // ── Baum-Icons (inline-SVG im Panel-Stil: 14px, stroke currentColor 1.4) ────── @@ -131,36 +132,6 @@ function RenameInput({ ); } -/** Deep-Equal zweier `Record`-Maps (gleiche Keys UND Werte). */ -function boolMapEqual( - a: Record, - b: Record, -): boolean { - const ka = Object.keys(a); - if (ka.length !== Object.keys(b).length) return false; - for (const k of ka) { - if (a[k] !== b[k]) return false; - } - return true; -} - -/** - * Sucht unter den gespeicherten Kombinationen (`names` + `load`) diejenige, - * deren Map EXAKT `target` entspricht — liefert den Namen oder `null`. Grundlage - * der Footer-Anzeige „welche Ebenen-/Zeichnungskombi war aktiv". - */ -function matchingComboName( - names: string[], - load: (name: string) => Record | null, - target: Record, -): string | null { - for (const name of names) { - const map = load(name); - if (map && boolMapEqual(map, target)) return name; - } - return null; -} - /** Welche Zeilenart gerade inline umbenannt wird (Commit unterscheidet sich). */ type RenameKind = "folder" | "snapshot"; interface Renaming { diff --git a/src/panels/host.ts b/src/panels/host.ts index 01af8b2d..597d909a 100644 --- a/src/panels/host.ts +++ b/src/panels/host.ts @@ -19,6 +19,7 @@ import type { CeilingType, RoofType, Component, + ContextImage, ContextObject, DrawingLevel, HatchStyle, @@ -175,6 +176,14 @@ export interface PanelHostValue { measurement: MeasurementReadout | null; /** Setzt die (Strich-)Farbe der aktuellen Selektion (Wand oder Drawing2D). */ onSetSelectionColor: (color: string) => void; + /** + * Koppelt/entkoppelt die Farbe oben an einen Stift (ArchiCAD-Stiftsatz- + * Muster, `model/penSets.ts`) — `undefined` = „Frei" (zurück zur normalen + * Farbwahl, letzter Wert bleibt stehen). Wirkt auf jede Selektionsart mit + * eigenem `colorPenId`-Feld (Wand/Decke/Dach/Öffnung/Treppe/Raum/Stütze/ + * Drawing2D); No-op bei den übrigen Arten. + */ + onSetSelectionColorPen: (penId: string | undefined) => void; /** * Setzt den Strichstärke-Override (mm, „eigener Wert") — Wand/Decke * (`strokeWeight`) oder Drawing2D (`weightMm`). Die Quelle (Ebene/Bauteil) @@ -199,9 +208,17 @@ export interface PanelHostValue { onSetSelectionFillColor: (color: string | null) => void; /** * Setzt die Deckkraft (0..1) — wirkt NUR auf Bild-Elemente (Drawing2D - * `{shape:"image"}` oder Layout-Annotation `kind:"image"`), sonst No-op. + * `{shape:"image"}`, Layout-Annotation `kind:"image"` oder Kontext-Objekt + * `type:"image"`), sonst No-op. */ onSetSelectionOpacity: (opacity: number) => void; + /** + * Setzt eine oder mehrere Bildkorrektur-Werte (Sättigung/Helligkeit/ + * Kontrast/Graustufen) — wirkt NUR auf Kontext-Objekt-Bilder (`ContextImage`, + * `sel.kind === "contextObject"` mit `isImage`), sonst No-op. Merged mit den + * bestehenden Werten (Teil-Update, wie bei `onSetSelectionOpacity`). + */ + onSetSelectionImageFilters: (filters: Partial>) => void; /** * Setzt/entfernt den Vordergrund-Override (Muster-/Schraffurfarbe, „eigener * Wert") der Selektion — Wand, Decke oder geschlossene Drawing2D. `null` = @@ -215,6 +232,14 @@ export interface PanelHostValue { * System" (siehe {@link onSetSelectionBackgroundSource}). */ onSetSelectionBackground: (color: string | null) => void; + /** + * Koppelt/entkoppelt den Vordergrund-Override oben an einen Stift, analog + * {@link onSetSelectionColorPen} — wirkt auf Wand, Decke oder geschlossene + * Drawing2D (dieselben Arten wie {@link onSetSelectionForeground}). + */ + onSetSelectionForegroundPen: (penId: string | undefined) => void; + /** Koppelt/entkoppelt den Hintergrund-Override, analog {@link onSetSelectionForegroundPen}. */ + onSetSelectionBackgroundPen: (penId: string | undefined) => void; /** * Setzt die Quelle des Vordergrunds, wenn KEIN „eigener Wert" gilt: "layer" = * Nach Ebene, "object" = Nach Bauteil. Löscht dabei IMMER den expliziten @@ -498,9 +523,17 @@ export interface PanelHostValue { /** * Erfasst den aktuellen Darstellungszustand als neuen, benannten Ausschnitt. * `folderId` legt ihn direkt im angegebenen Ordner ab (sonst Wurzelebene) — - * additiv, Alt-Aufrufe ohne Ordner-Argument bleiben gültig. + * additiv, Alt-Aufrufe ohne Ordner-Argument bleiben gültig. Liefert die neue + * Ausschnitt-Id (leer bei leerem/ungetrimmtem Namen). */ - onCaptureViewSnapshot: (name: string, folderId?: string) => void; + onCaptureViewSnapshot: (name: string, folderId?: string) => string; + /** + * Wie `onCaptureViewSnapshot`, aber mit automatisch bestimmtem Namen (aktive + * Zeichnungskombination falls exakt passend, sonst das aktive Blatt) — für + * die Ausschnitt-Tab-Leiste ("+"-Knopf, s. DrawingTabs.tsx). Wählt den neuen + * Ausschnitt sofort an. + */ + onCaptureViewSnapshotAuto: () => string; /** Stellt alle Felder eines Ausschnitts wieder her (Geschoss/Sichtbarkeit/Overrides/Ansicht). */ onApplyViewSnapshot: (id: string) => void; /** Benennt einen Ausschnitt um. */ diff --git a/src/plan/PlanView.cssImageFilter.test.ts b/src/plan/PlanView.cssImageFilter.test.ts new file mode 100644 index 00000000..d8a36dd7 --- /dev/null +++ b/src/plan/PlanView.cssImageFilter.test.ts @@ -0,0 +1,37 @@ +// `cssImageFilter` baut die CSS-`filter`-Kette für ein Hintergrund-Luftbild +// aus `ContextImage.filters` (Sättigung/Helligkeit/Kontrast/Graustufen, s. +// PENDENZEN.md „Bildschraffur: Bild-Filter"). Reiner Helfer, kein React nötig. + +import { describe, it, expect } from "vitest"; +import { cssImageFilter } from "./PlanView"; + +describe("cssImageFilter", () => { + it("liefert undefined bei fehlenden filters (kein style-Attribut nötig)", () => { + expect(cssImageFilter(undefined)).toBeUndefined(); + }); + + it("liefert undefined bei ausschliesslich neutralen Werten (1/1/1/0)", () => { + expect(cssImageFilter({ saturation: 1, brightness: 1, contrast: 1, grayscale: 0 })).toBeUndefined(); + }); + + it("liefert undefined bei leerem filters-Objekt (alle Defaults greifen)", () => { + expect(cssImageFilter({})).toBeUndefined(); + }); + + it("baut nur die tatsächlich abweichenden Filter-Funktionen", () => { + expect(cssImageFilter({ saturation: 0.5 })).toBe("saturate(0.5)"); + expect(cssImageFilter({ brightness: 1.3 })).toBe("brightness(1.3)"); + expect(cssImageFilter({ contrast: 1.2 })).toBe("contrast(1.2)"); + expect(cssImageFilter({ grayscale: 0.8 })).toBe("grayscale(0.8)"); + }); + + it("kombiniert mehrere abweichende Werte in EINEM filter-String", () => { + expect(cssImageFilter({ saturation: 0, grayscale: 1 })).toBe("saturate(0) grayscale(1)"); + }); + + it("volle Kombination aller vier Werte, in fester Reihenfolge", () => { + expect( + cssImageFilter({ saturation: 0.5, brightness: 1.2, contrast: 1.1, grayscale: 0.3 }), + ).toBe("saturate(0.5) brightness(1.2) contrast(1.1) grayscale(0.3)"); + }); +}); diff --git a/src/plan/PlanView.tsx b/src/plan/PlanView.tsx index 739c87c7..1cba2d0e 100644 --- a/src/plan/PlanView.tsx +++ b/src/plan/PlanView.tsx @@ -14,7 +14,7 @@ import { useState, } from "react"; import type { CSSProperties } from "react"; -import type { HatchRender, Plan, Primitive } from "./generatePlan"; +import type { HatchRender, Plan, PlanImage, Primitive } from "./generatePlan"; import type { EdgeGrip, Vec2 } from "../model/types"; import type { ToolHandlers, ToolId, ToolMods } from "../tools/types"; import type { RichTextDoc } from "../text/richText"; @@ -47,6 +47,7 @@ import { buildDrawingRuns, DrawingRunShape, PrimitiveShape, + greyColor, } from "./planView/primitives"; import { DraftOverlay } from "./planView/overlays"; import { PlanRulers } from "./planView/PlanRulers"; @@ -511,6 +512,28 @@ export interface GripHandlers { onEdgeCancel(edge: EdgeGrip, anchor: Vec2): void; } +/** + * Baut die CSS-`filter`-Kette für ein Hintergrund-Luftbild aus + * `ContextImage.filters` (Sättigung/Helligkeit/Kontrast/Graustufen). `null` + * bei fehlenden/neutralen Werten (kein `style`-Attribut nötig — vermeidet + * unnötige Re-Renders/DOM-Diffs für das Gros der Bilder ohne Korrektur). + * Reihenfolge (saturate→brightness→contrast→grayscale) ist beliebig, da jeder + * Filter unabhängig auf den vorherigen Zustand wirkt. + */ +export function cssImageFilter(filters: PlanImage["filters"]): string | undefined { + if (!filters) return undefined; + const { saturation = 1, brightness = 1, contrast = 1, grayscale = 0 } = filters; + if (saturation === 1 && brightness === 1 && contrast === 1 && grayscale === 0) { + return undefined; + } + const parts: string[] = []; + if (saturation !== 1) parts.push(`saturate(${saturation})`); + if (brightness !== 1) parts.push(`brightness(${brightness})`); + if (contrast !== 1) parts.push(`contrast(${contrast})`); + if (grayscale !== 0) parts.push(`grayscale(${grayscale})`); + return parts.join(" "); +} + export const PlanView = forwardRef( function PlanView( { @@ -2328,12 +2351,17 @@ export const PlanView = forwardRef( const drawingRuns = useMemo(() => buildDrawingRuns(plan.primitives), [plan]); // Pro Polygon mit Linien-/Kreuz-Schraffur ein eigenes sammeln. - // Vollfüllung ("solid") und "none" brauchen kein Muster. + // Vollfüllung ("solid") und "none" brauchen kein Muster. Gedimmte Polygone + // (greyed) bekommen HIER separat dieselbe Grau-Umfärbung wie `greyedCopy` in + // primitives.tsx — die -Definition ist eine eigene, vom Primitiv + // losgelöste Ressource (nur über `url(#hatch-i)` referenziert) und würde + // sonst weiterhin in der ORIGINAL-Bauteilfarbe erscheinen. const hatched = useMemo(() => { const list: HatchedPoly[] = []; plan.primitives.forEach((p, i) => { if (p.kind === "polygon" && polyUsesPattern(p.hatch)) { - list.push({ patternId: `hatch-${i}`, hatch: p.hatch }); + const hatch = p.greyed ? { ...p.hatch, color: greyColor(p.hatch.color) ?? p.hatch.color } : p.hatch; + list.push({ patternId: `hatch-${i}`, hatch }); } }); return list; @@ -2490,6 +2518,7 @@ export const PlanView = forwardRef( const w = (img.max.x - img.min.x) * PX_PER_M; const h = (img.max.y - img.min.y) * PX_PER_M; if (w <= 0 || h <= 0) return null; + const filter = cssImageFilter(img.filters); return ( ( width={w} height={h} opacity={img.opacity} + style={filter ? { filter } : undefined} preserveAspectRatio="none" pointerEvents="none" /> @@ -2704,7 +2734,7 @@ export const PlanView = forwardRef( const c2 = toScreen({ x: groupBBox.maxX, y: groupBBox.minY }); const c3 = toScreen({ x: groupBBox.maxX, y: groupBBox.maxY }); const c4 = toScreen({ x: groupBBox.minX, y: groupBBox.maxY }); - const size = 5 / (meetScale(view, svgRef.current) ?? 1); + const size = 4 / (meetScale(view, svgRef.current) ?? 1); const corners = [c1, c2, c3, c4]; return ( <> @@ -2714,13 +2744,12 @@ export const PlanView = forwardRef( pointerEvents="none" /> {corners.map((s, i) => ( - ))} @@ -2761,19 +2790,20 @@ export const PlanView = forwardRef( /> ))} {/* Editier-Griffe des selektierten Elements (Wand-Enden / 2D-Vertices): - ziehbare Quadrate. Bildschirmkonstante Größe über die meet-Skala. */} + ziehbare Kreise. Bildschirmkonstante Größe über die meet-Skala. + Radius bewusst kleiner als der Treffer-Radius (GRIP_HIT_PX) — die + Klickfläche bleibt grosszügig, nur die sichtbare Form schrumpft. */} {gripsActive && grips!.map((g, i) => { const s = toScreen(g); - const size = 6 / (meetScale(view, svgRef.current) ?? 1); + const size = 4.5 / (meetScale(view, svgRef.current) ?? 1); return ( - ); @@ -2784,7 +2814,7 @@ export const PlanView = forwardRef( {roomStamp && (() => { const s = toScreen(roomStamp.anchor); - const size = 5 / (meetScale(view, svgRef.current) ?? 1); + const size = 4 / (meetScale(view, svgRef.current) ?? 1); const pts = [ `${s.x},${s.y - size}`, `${s.x + size},${s.y}`, diff --git a/src/plan/generatePlan.context.test.ts b/src/plan/generatePlan.context.test.ts index b591fc2d..beb5d883 100644 --- a/src/plan/generatePlan.context.test.ts +++ b/src/plan/generatePlan.context.test.ts @@ -189,6 +189,42 @@ describe("generatePlan — Luftbild (ContextImage)", () => { expect(plan.primitives.some((pr) => (pr as { kind?: string }).kind === "image")).toBe(false); }); + it("reicht `filters` (Sättigung/Helligkeit/Kontrast/Graustufen) unverändert durch", () => { + const p = projectWith([ + { + id: "IMG1", + type: "image", + name: "Luftbild", + src: "data:image/jpeg;base64,AAAA", + min: { x: 0, y: 0 }, + max: { x: 10, y: 10 }, + filters: { saturation: 0.4, brightness: 1.1, contrast: 1.2, grayscale: 0.6 }, + }, + ]); + const plan = generatePlan(p, "eg", visible); + expect(plan.backgroundImages![0].filters).toEqual({ + saturation: 0.4, + brightness: 1.1, + contrast: 1.2, + grayscale: 0.6, + }); + }); + + it("`filters` fehlt bei einem Bild ohne Korrektur (kein leeres Objekt erfunden)", () => { + const p = projectWith([ + { + id: "IMG1", + type: "image", + name: "Luftbild", + src: "data:image/jpeg;base64,AAAA", + min: { x: 0, y: 0 }, + max: { x: 10, y: 10 }, + }, + ]); + const plan = generatePlan(p, "eg", visible); + expect(plan.backgroundImages![0].filters).toBeUndefined(); + }); + it("im Mono-Modus wird das Luftbild ausgeblendet (reiner S/W-Plan)", () => { const p = projectWith([ { @@ -204,3 +240,45 @@ describe("generatePlan — Luftbild (ContextImage)", () => { expect(plan.backgroundImages).toHaveLength(0); }); }); + +describe("generatePlan — Kontext-Objekte: Ebenen-Sichtbarkeit (categoryCode)", () => { + // Ein Kontext-Objekt MIT `categoryCode` respektiert dieselbe visibleCodes- + // Allowlist wie jedes andere Bauteil (Wand/Dach/…) — Nutzer-Report: "sollten + // wie Gebäude/Dächer ausblendbar sein". Objekte OHNE categoryCode (ältere + // Importe) bleiben unabhängig davon immer sichtbar (Rückwärtskompatibilität). + const buildingMesh = (id: string, categoryCode?: string) => ({ + id, + type: "importedMesh" as const, + name: "Haus", + categoryCode, + positions: [0, 0, 0, 2, 0, 0, 2, 3, 0, 0, 3, 0], + indices: [0, 1, 2, 0, 2, 3], + }); + + it("visibleCodes ohne den categoryCode des Objekts blendet es aus", () => { + const p = projectWith([buildingMesh("B1", "12")]); + const visibleWithoutBuildings = new Set(["20"]); // nur Wände sichtbar + const lines = generatePlan(p, "eg", visibleWithoutBuildings).primitives.filter( + (pr) => pr.kind === "line" && (pr as { cls?: string }).cls === "context-line", + ); + expect(lines.length).toBe(0); + }); + + it("visibleCodes MIT dem categoryCode des Objekts zeigt es normal", () => { + const p = projectWith([buildingMesh("B1", "12")]); + const visibleWithBuildings = new Set(["12"]); + const lines = generatePlan(p, "eg", visibleWithBuildings).primitives.filter( + (pr) => pr.kind === "line" && (pr as { cls?: string }).cls === "context-line", + ); + expect(lines.length).toBeGreaterThan(0); + }); + + it("ein Objekt OHNE categoryCode bleibt immer sichtbar (Altbestand)", () => { + const p = projectWith([buildingMesh("B1", undefined)]); + const visibleEmpty = new Set(); // schliesst alles Benannte aus + const lines = generatePlan(p, "eg", visibleEmpty).primitives.filter( + (pr) => pr.kind === "line" && (pr as { cls?: string }).cls === "context-line", + ); + expect(lines.length).toBeGreaterThan(0); + }); +}); diff --git a/src/plan/generatePlan.sectionLine.test.ts b/src/plan/generatePlan.sectionLine.test.ts index 833c4875..669c0404 100644 --- a/src/plan/generatePlan.sectionLine.test.ts +++ b/src/plan/generatePlan.sectionLine.test.ts @@ -3,13 +3,19 @@ * Schnitt-/Ansichtsebene MIT `linePoints` erzeugt eine Strichpunkt-Linie * (cls "section-line"), Endmarken + ein unsichtbares Pick-Band (Polygon mit * `sectionLineId`). Ebenen OHNE Linie erzeugen nichts. + * + * Sichtbarkeit läuft über die feste Kategorie "90" (Referenzen) — NICHT über + * das eigene `visible`-Flag der Schnitt-/Ansichtsebene (Nutzer-Feedback: "das + * sollten Elemente sein, die sich auf einer Ebene befinden und nur damit + * ein-/ausgeblendet werden"). Das Flag ist daher für dieses Symbol wirkungslos. */ import { describe, it, expect } from "vitest"; import { generatePlan } from "./generatePlan"; +import type { CategoryDisplayResolver } from "./generatePlan"; import type { DrawingLevel, Project } from "../model/types"; -const visible = new Set(["20", "35"]); +const visible = new Set(["20", "35", "90"]); function baseProject(levels: DrawingLevel[]): Project { return { @@ -79,7 +85,7 @@ describe("generatePlan — Schnittführungs-Symbol", () => { expect(prims.some((pr) => pr.kind === "line" && pr.cls === "section-line")).toBe(false); }); - it("zeichnet NICHTS für eine unsichtbare Schnittebene (visible=false)", () => { + it("zeichnet TROTZDEM, auch wenn die Schnittebene selbst visible=false trägt (nur Kategorie '90' zählt)", () => { const p = baseProject([ floor, { @@ -93,8 +99,46 @@ describe("generatePlan — Schnittführungs-Symbol", () => { }, ]); const prims = generatePlan(p, "eg", visible).primitives; - expect(prims.some((pr) => pr.kind === "polygon" && pr.sectionLineId === "s-hidden")).toBe(false); - expect(prims.some((pr) => pr.kind === "line" && pr.cls === "section-line")).toBe(false); + expect(prims.some((pr) => pr.kind === "polygon" && pr.sectionLineId === "s-hidden")).toBe(true); + }); + + it("zeichnet NICHTS, wenn Kategorie '90' NICHT sichtbar ist (visibleCodes ohne '90')", () => { + const p = baseProject([ + floor, + { + id: "s-cat", + name: "Schnitt D", + kind: "section", + visible: true, + locked: false, + linePoints: [{ x: 0, y: 2 }, { x: 6, y: 2 }], + directionSign: 1, + }, + ]); + const prims = generatePlan(p, "eg", new Set(["20", "35"])).primitives; + expect(prims.some((pr) => pr.kind === "polygon" && pr.sectionLineId === "s-cat")).toBe(false); + }); + + it("dimmt (greyed), wenn categoryDisplay('90') greyed liefert", () => { + const p = baseProject([ + floor, + { + id: "s-grey", + name: "Schnitt E", + kind: "section", + visible: true, + locked: false, + linePoints: [{ x: 0, y: 2 }, { x: 6, y: 2 }], + directionSign: 1, + }, + ]); + const categoryDisplay: CategoryDisplayResolver = (code) => + code === "90" ? { render: true, greyed: true, locked: false } : { render: true, greyed: false, locked: false }; + const prims = generatePlan(p, "eg", visible, categoryDisplay).primitives; + const line = prims.find((pr) => pr.kind === "line" && pr.cls === "section-line") as + | { greyed?: boolean } + | undefined; + expect(line?.greyed).toBe(true); }); it("behandelt Ansichtsebenen (elevation) gleich", () => { diff --git a/src/plan/generatePlan.ts b/src/plan/generatePlan.ts index 8c4ff51a..43c381da 100644 --- a/src/plan/generatePlan.ts +++ b/src/plan/generatePlan.ts @@ -18,6 +18,7 @@ import type { Ceiling, Component, + ContextImage, ContextObject, Drawing2D, LayerCategory, @@ -46,7 +47,7 @@ import { } from "../model/types"; import { roofGeometry } from "../geometry/roof"; import { effectiveOverrides, hasOverrides } from "../overrides/engine"; -import { stairVerticalExtent } from "../model/wall"; +import { stairVerticalExtent, wallVerticalExtent } from "../model/wall"; import { stairGeometry } from "../geometry/stair"; import { wallCorners } from "../model/geometry"; import { computeJoins } from "../model/joins"; @@ -180,6 +181,8 @@ export interface PlanImage { min: Vec2; max: Vec2; opacity: number; + /** Bildkorrektur, s. `ContextImage.filters` — durchgereicht, unverändert. */ + filters?: ContextImage["filters"]; } export interface Plan { @@ -205,6 +208,11 @@ export function generatePlan( detail: DetailLevel = "mittel", showReferenceLines = false, mono = false, + // Schalter für die projektglobalen Zutaten (Kontext-Konturen, Schnittlinien, + // Luftbilder): beim Überlagern mehrerer Geschosse (siehe + // `generateVisibleLevelsPlan`) dürfen diese NICHT je Geschoss dupliziert + // werden — nur der aktive Aufruf liefert sie. + includeGlobal = true, ): Plan { const primitives: Primitive[] = []; // Aktives Geschoss (für die Grundriss-Schnitthöhe der Treppen). @@ -375,10 +383,16 @@ export function generatePlan( const gaps = wallGaps(wall, doors, openings); const cuts = joins.get(wall.id) ?? { startCut: null, endCut: null }; // Schnitt vs. Ansicht nach Schnitthöhe (BIM-Standard): erreicht die Wand die - // Grundriss-Schnittebene nicht (Höhe < Schnitthöhe des Geschosses, z. B. eine - // Brüstung/ein Podestrand), wird sie nur als Ansichts-Umriss gezeichnet — - // keine Schnitt-Poché. Normale Wände (Höhe ≥ Schnitthöhe) sind unberührt. - const wallViewOnly = wall.height < (floor?.cutHeight ?? 1.0); + // Grundriss-Schnittebene nicht (z. B. eine Brüstung/ein Podestrand), wird sie + // nur als Ansichts-Umriss gezeichnet — keine Schnitt-Poché. Normale Wände + // (Schnittebene liegt in ihrer vertikalen Ausdehnung) sind unberührt. Über + // `wallVerticalExtent` aufgelöst (nicht nur `wall.height`), damit ein + // `bottom`/`top`-Override (VerticalAnchor) korrekt einfliesst — sonst würde + // z. B. eine hochgesetzte Wand (angehobenes UK, Höhe allein sieht „hoch genug" + // aus) fälschlich als Schnitt-Poché statt als Ansichts-Umriss gezeichnet. + const { zBottom: wallZBottom, zTop: wallZTop } = wallVerticalExtent(project, wall); + const cutPlaneZ = (floor?.baseElevation ?? 0) + (floor?.cutHeight ?? 1.0); + const wallViewOnly = wallZTop < cutPlaneZ || wallZBottom > cutPlaneZ; addWallPoche( primitives, project, wall, gaps, cuts, wallGreyed, detail, wallLwMm, wallCategory, wallViewOnly, ); @@ -465,12 +479,16 @@ export function generatePlan( // Kontext-Konturen (Höhenlinien) als dezente Linien zeichnen — UNTER der // Wand-Poché wäre ideal, aber da sie eine eigene gedämpfte Farbe tragen, ist - // die Reihenfolge unkritisch; wir hängen sie als Referenz an. - addContextContours(primitives, project); + // die Reihenfolge unkritisch; wir hängen sie als Referenz an. Projektglobal + // (nicht je Geschoss) → nur beim aktiven Aufruf einer Mehrfach-Überlagerung. + if (includeGlobal) { + addContextContours(primitives, project, visibleCodes, categoryDisplay); - // Schnittführungs-Symbole (klassische Schnittlinien) aller Schnitt-/Ansichts- - // ebenen mit gesetzter Linie — projektglobale Referenzgeometrie über dem Plan. - addSectionLines(primitives, project); + // Schnittführungs-Symbole (klassische Schnittlinien) aller Schnitt-/ + // Ansichtsebenen mit gesetzter Linie — ebenfalls projektglobal. Sichtbarkeit + // läuft über die Kategorie "90" (Referenzen), wie jedes andere Bauteil. + addSectionLines(primitives, project, visibleCodes, categoryDisplay); + } // Schwarz-Weiss (mono): nachträglich alle Farben auf reine Tinte zwingen. // Element-/Kategorie-/Hatch-Farben werden ignoriert, Füllungen werden weiss, @@ -479,11 +497,19 @@ export function generatePlan( // Georeferenzierte Luftbilder als Hintergrund-Ebenen (nur interaktive Ansicht, // nicht Teil der Vektor-Primitive) — im Mono-Modus ausgeblendet (reiner S/W-Plan). - const backgroundImages: PlanImage[] = mono + // Projektglobal (nicht je Geschoss), s. `includeGlobal` oben. + const backgroundImages: PlanImage[] = !includeGlobal || mono ? [] : (project.context ?? []) .filter((o): o is Extract => o.type === "image") - .map((o) => ({ id: o.id, src: o.src, min: o.min, max: o.max, opacity: o.opacity ?? 1 })); + .map((o) => ({ + id: o.id, + src: o.src, + min: o.min, + max: o.max, + opacity: o.opacity ?? 1, + filters: o.filters, + })); return { primitives, @@ -492,6 +518,75 @@ export function generatePlan( }; } +/** + * Wie `generatePlan`, überlagert aber ZUSÄTZLICH alle sichtbaren Geschoss- + * oder Zeichnungs-Ebenen DERSELBEN Art wie `activeLevelId` in EINEM Plan — + * das Vectorworks-Bild „andere Ebenen als Referenz einblenden": die aktive + * Ebene farbig/bearbeitbar, die übrigen je Darstellungsmodus gedimmt + * (`levelDisplay`, derselbe Resolver wie für Geschosse im Panel/3D). Schnitt-/ + * Ansichts-Ebenen bleiben Einzel-Pane (andere Projektionsachse — ein + * Überlagern mehrerer Schnitte ergäbe kein sinnvolles Bild). + */ +export function generateVisibleLevelsPlan( + project: Project, + activeLevelId: string, + visibleCodes: Set, + categoryDisplay: CategoryDisplayResolver = SHOW_ALL, + detail: DetailLevel = "mittel", + showReferenceLines = false, + mono = false, + levelDisplay: CategoryDisplayResolver = SHOW_ALL, +): Plan { + const active = project.drawingLevels.find((l) => l.id === activeLevelId); + const siblings = + active && (active.kind === "floor" || active.kind === "drawing") + ? project.drawingLevels.filter((l) => l.kind === active.kind && l.id !== activeLevelId) + : []; + + const primitives: Primitive[] = []; + const bounds = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }; + const extend = (b: Plan["bounds"]) => { + bounds.minX = Math.min(bounds.minX, b.minX); + bounds.minY = Math.min(bounds.minY, b.minY); + bounds.maxX = Math.max(bounds.maxX, b.maxX); + bounds.maxY = Math.max(bounds.maxY, b.maxY); + }; + + // Andere sichtbare Ebenen ZUERST (unten als Referenz), die aktive zuletzt + // (obenauf) — wie `buildBuilding` in meshBuilders.ts für die 3D-Szene. + for (const l of siblings) { + const d = levelDisplay(l.id); + if (!d.render) continue; + const p = generatePlan( + project, + l.id, + visibleCodes, + categoryDisplay, + detail, + showReferenceLines, + mono, + false, // includeGlobal: Schnittlinien/Kontext/Luftbilder nur einmal (aktiv) + ); + primitives.push(...(d.greyed ? p.primitives.map((pr) => ({ ...pr, greyed: true })) : p.primitives)); + extend(p.bounds); + } + + const activePlan = generatePlan( + project, + activeLevelId, + visibleCodes, + categoryDisplay, + detail, + showReferenceLines, + mono, + true, + ); + primitives.push(...activePlan.primitives); + extend(activePlan.bounds); + + return { primitives, bounds, backgroundImages: activePlan.backgroundImages }; +} + // ── Schnitt/Ansicht (abgeleitete Projektion aus render3d::section) ────────────── // Die Rohdaten (Cut-Polygone + sichtbare/verdeckte projizierte Kanten) liefert // der WASM-Extraktor (plan/toSection.ts → section.rs). Hier werden sie 1:1 in @@ -536,12 +631,20 @@ const SECTION_HATCH: HatchRender = { * Baut aus einem {@link SectionOutput} (render3d::section, (u, v)-Meter) den * Plan eines Schnitts/einer Ansicht. `u` wird zur Plan-X, `v` (absolute Höhe) * zur Plan-Y — die PlanView zeigt Y nach oben, also erscheint der Schnitt - * aufrecht. Rein darstellend; kennt das Projekt nicht. + * aufrecht. Rein darstellend; kennt das Projekt NICHT direkt — `visibleCodes`/ + * `categoryDisplay` (optional) filtern/dimmen jedes Cut-Band trotzdem über + * `cp.categoryCode` (von `toSection.ts::attachCutStyles` aufgelöst), damit das + * Ebenen-Panel auch im Schnitt/in der Ansicht wirkt, wie im Grundriss. Ein + * Band ohne `categoryCode` (unauflösbares Bauteil) bleibt immer sichtbar. */ export function generateSectionPlan( output: SectionOutput, mono = false, - opts: { hiddenLines?: boolean } = {}, + opts: { + hiddenLines?: boolean; + visibleCodes?: Set; + categoryDisplay?: CategoryDisplayResolver; + } = {}, ): Plan { const primitives: Primitive[] = []; let minX = Infinity, @@ -554,6 +657,7 @@ export function generateSectionPlan( if (x > maxX) maxX = x; if (y > maxY) maxY = y; }; + const catDisplay = opts.categoryDisplay ?? SHOW_ALL; // Cut-Polygone: gefüllte Poché-Fläche + Schnitt-Schraffur + kräftige // Umrisslinie — wie eine geschnittene Wand im Grundriss. `toSection.ts` @@ -565,6 +669,12 @@ export function generateSectionPlan( // monochrom, auch im Fallback-Fall). for (const cp of output.cutPolygons) { if (cp.pts.length < 3) continue; + // Ebenen-Panel-Sichtbarkeit: nur wenn das Quell-Bauteil aufgelöst werden + // konnte (categoryCode gesetzt) — sonst (Fallback) immer zeichnen. + if (cp.categoryCode !== undefined) { + if (opts.visibleCodes && !opts.visibleCodes.has(cp.categoryCode)) continue; + if (!catDisplay(cp.categoryCode).render) continue; + } const pts: Vec2[] = cp.pts.map(([u, v]) => { acc(u, v); return { x: u, y: v }; @@ -594,6 +704,7 @@ export function generateSectionPlan( wallId: kind === "wall" ? sourceId : undefined, ceilingId: kind === "slab" ? sourceId : undefined, roofId: kind === "roof" ? sourceId : undefined, + greyed: cp.categoryCode !== undefined && catDisplay(cp.categoryCode).greyed, }); } diff --git a/src/plan/generatePlan.viewwall.test.ts b/src/plan/generatePlan.viewwall.test.ts index cbd7e514..a58862d5 100644 --- a/src/plan/generatePlan.viewwall.test.ts +++ b/src/plan/generatePlan.viewwall.test.ts @@ -79,6 +79,39 @@ describe("generatePlan — Schnitt vs. Ansicht nach Schnitthöhe", () => { ); expect(low.some((pr) => pr.fill !== "none")).toBe(true); }); + + // Regression: `wall.bottom`/`wall.top` (VerticalAnchor-Override) muss die + // Schnitt-vs-Ansicht-Entscheidung über die ECHTE vertikale Ausdehnung + // (`wallVerticalExtent`) treffen, nicht nur über `wall.height` — sonst + // rutscht eine hochgesetzte Wand fälschlich in die falsche Kategorie. + it("behandelt eine hochgesetzte Wand (bottom-Override ÜBER der Schnittebene) als Ansicht, obwohl ihre Höhe allein 'hoch genug' aussieht", () => { + const p = project(); + // HI (2.6 m hoch) auf ein UK von 1.5 m angehoben → Spanne [1.5, 4.1], + // Schnittebene bei 1.0 m liegt UNTER der Wand → reine Ansicht erwartet. + p.walls[0].bottom = { mode: "custom", z: 1.5 }; + const plan = generatePlan(p, "eg", visible, undefined, "mittel"); + const hi = plan.primitives.filter( + (pr): pr is Extract => + pr.kind === "polygon" && pr.wallId === "HI", + ); + expect(hi.length).toBeGreaterThan(0); + expect(hi.every((pr) => pr.fill === "none")).toBe(true); + }); + + it("behandelt eine hochgesetzte Wand als geschnitten, wenn die Schnittebene weiterhin in ihrer Spanne liegt", () => { + const p = project(); + // HI von [1.5, 4.1] angehoben, Schnittebene mit angehoben auf 2.0 m → liegt + // weiterhin INNERHALB der Wand-Spanne → Poché erwartet. + p.walls[0].bottom = { mode: "custom", z: 1.5 }; + p.drawingLevels[0].cutHeight = 2.0; + const plan = generatePlan(p, "eg", visible, undefined, "mittel"); + const hi = plan.primitives.filter( + (pr): pr is Extract => + pr.kind === "polygon" && pr.wallId === "HI", + ); + expect(hi.length).toBeGreaterThan(0); + expect(hi.some((pr) => pr.fill !== "none")).toBe(true); + }); }); // ── Decke über der Schnittebene → gestrichelte Überkopf-Umrisslinie ────────── diff --git a/src/plan/generatePlan/context.ts b/src/plan/generatePlan/context.ts index 29f6e34a..9dc1c2de 100644 --- a/src/plan/generatePlan/context.ts +++ b/src/plan/generatePlan/context.ts @@ -4,7 +4,7 @@ // nicht das volle Drahtgitter. import type { Project } from "../../model/types"; -import { NO_HATCH, type Primitive } from "./shared"; +import { NO_HATCH, SHOW_ALL, type CategoryDisplayResolver, type Primitive } from "./shared"; /** Dezente Plan-Farbe der Kontext-Konturen (gedämpftes Grau). */ const CONTEXT_LINE_COLOR = "#9aa3ad"; @@ -27,10 +27,28 @@ const FOOTPRINT_Z_TOL = 0.6; * • TerrainMesh → nur der 2D-Umriss (Bounding-Box), da ein volles TIN-Gitter * im Plan unbrauchbar dicht wäre. * Rein additiv — Wand-/Drawing-Darstellung bleibt unberührt. + * + * SICHTBARKEIT: jedes Objekt trägt (seit der Ebenen-Zuordnung der Kontext- + * Schicht) optional eine `categoryCode` (s. `model/contextCategories.ts`) — + * genau wie jedes andere Bauteil wird sie gegen `visibleCodes`/ + * `categoryDisplay` geprüft (Muster 1:1 aus `sections.ts::addSectionLines`). + * Objekte OHNE `categoryCode` (ältere Importe vor dieser Erweiterung) bleiben + * bewusst IMMER sichtbar (Rückwärtskompatibilität) statt stillschweigend zu + * verschwinden. */ -export function addContextContours(out: Primitive[], project: Project): void { +export function addContextContours( + out: Primitive[], + project: Project, + visibleCodes?: Set, + categoryDisplay: CategoryDisplayResolver = SHOW_ALL, +): void { const context = project.context ?? []; for (const obj of context) { + const code = obj.categoryCode; + if (code !== undefined) { + const d = categoryDisplay(code); + if ((visibleCodes && !visibleCodes.has(code)) || !d.render) continue; + } if (obj.type === "contourSet") { for (const c of obj.contours) { const pts = c.pts; diff --git a/src/plan/generatePlan/drawing2d.test.ts b/src/plan/generatePlan/drawing2d.test.ts index 6dc53a52..34d4831e 100644 --- a/src/plan/generatePlan/drawing2d.test.ts +++ b/src/plan/generatePlan/drawing2d.test.ts @@ -231,3 +231,195 @@ describe("addDrawing2D — kote (SIA 400 B.5.4)", () => { if (text?.kind === "drawingText") expect(text.text).toBe("±0.00"); }); }); + +describe("addDrawing2D — xline (Konstruktionslinie)", () => { + it("verlängert weit über a/b hinaus, in beide Richtungen entlang a→b", () => { + const d: Drawing2D = { + id: "x1", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "xline", a: { x: 0, y: 0 }, b: { x: 4, y: 0 } }, + }; + const out: Primitive[] = []; + addDrawing2D(out, project(), d, false, lwByCode, colorByCode, catByCode); + expect(out.length).toBe(1); + const l = out[0]; + if (l.kind === "line") { + expect(l.a.x).toBeLessThan(-500); + expect(l.b.x).toBeGreaterThan(500); + expect(l.a.y).toBeCloseTo(0, 6); + expect(l.b.y).toBeCloseTo(0, 6); + expect(l.dash).not.toBeNull(); + expect(l.drawingId).toBe("x1"); + } else { + throw new Error("expected a line primitive"); + } + }); + + it("entartet (a===b) erzeugt kein Primitiv", () => { + const d: Drawing2D = { + id: "x2", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "xline", a: { x: 2, y: 2 }, b: { x: 2, y: 2 } }, + }; + const out: Primitive[] = []; + addDrawing2D(out, project(), d, false, lwByCode, colorByCode, catByCode); + expect(out.length).toBe(0); + }); +}); + +describe("addDrawing2D — polyline mit bulge (Bogen-Segmente)", () => { + it("ohne bulge: unverändertes Verhalten (gerade Segmente, ein Primitiv je Segment)", () => { + const d: Drawing2D = { + id: "pl1", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }], closed: false }, + }; + const out: Primitive[] = []; + addDrawing2D(out, project(), d, false, lwByCode, colorByCode, catByCode); + const lines = out.filter((p) => p.kind === "line"); + expect(lines.length).toBe(2); + }); + + it("mit bulge an einem Segment: tessellierter Bogen statt einer Geraden", () => { + const d: Drawing2D = { + id: "pl2", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { + shape: "polyline", + pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 4, y: 0 }], + closed: false, + bulge: [1, 0], + }, + }; + const out: Primitive[] = []; + addDrawing2D(out, project(), d, false, lwByCode, colorByCode, catByCode); + const lines = out.filter((p) => p.kind === "line"); + // Segment 0 (Halbkreis, bulge=1) tessellierter Bogen → mehrere Teilstücke; + // Segment 1 bleibt eine einzelne Gerade → insgesamt > 2 (statt 2 wie oben). + expect(lines.length).toBeGreaterThan(2); + // Erster und letzter Punkt der gesamten Kette bleiben exakt die echten Endpunkte. + if (lines[0].kind === "line") { + expect(lines[0].a).toEqual({ x: 0, y: 0 }); + } + if (lines[lines.length - 1].kind === "line") { + expect(lines[lines.length - 1].b).toEqual({ x: 4, y: 0 }); + } + }); + + it("geschlossene Bogen-Polylinie füllt eine korrekte (tessellierte) Fläche", () => { + const d: Drawing2D = { + id: "pl3", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { + shape: "polyline", + pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }], + closed: true, + bulge: [0, 0, 0.5, 0], + }, + }; + const out: Primitive[] = []; + addDrawing2D(out, project(), d, false, lwByCode, colorByCode, catByCode); + const poly = out.find((p) => p.kind === "polygon"); + expect(poly).toBeDefined(); + if (poly?.kind === "polygon") { + // Mehr Punkte als die 4 Ecken, weil eine Seite tessellierter Bogen ist. + expect(poly.pts.length).toBeGreaterThan(4); + } + }); +}); + +describe("addDrawing2D — text mit pathPts (Text-entlang-Pfad)", () => { + it("gibt ein drawingTextPath-Primitiv statt drawingText aus, wenn pathPts ≥2 gesetzt ist", () => { + const d: Drawing2D = { + id: "tp1", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { + shape: "text", + at: { x: 0, y: 0 }, + text: "Bachlauf", + height: 0.3, + angle: 0, + pathPts: [{ x: 0, y: 0 }, { x: 2, y: 1 }, { x: 4, y: 0 }], + }, + }; + const out: Primitive[] = []; + addDrawing2D(out, project(), d, false, lwByCode, colorByCode, catByCode); + expect(out.length).toBe(1); + const p = out[0]; + expect(p.kind).toBe("drawingTextPath"); + if (p.kind === "drawingTextPath") { + expect(p.text).toBe("Bachlauf"); + expect(p.pathPts.length).toBe(3); + expect(p.drawingId).toBe("tp1"); + } + }); + + it("ohne pathPts (normaler Text) bleibt es beim bestehenden drawingText-Primitiv", () => { + const d: Drawing2D = { + id: "t1", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "text", at: { x: 0, y: 0 }, text: "Normal", height: 0.3, angle: 0 }, + }; + const out: Primitive[] = []; + addDrawing2D(out, project(), d, false, lwByCode, colorByCode, catByCode); + expect(out.length).toBe(1); + expect(out[0].kind).toBe("drawingText"); + }); +}); + +describe("addDrawing2D — block (Symbol-Instanz)", () => { + it("expandiert die BlockDef-Geometrie rotiert+verschoben um at/rotation", () => { + const proj = project(); + proj.blockDefs = [ + { id: "blk1", name: "Stuhl", geom2d: [{ shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } }] }, + ]; + const d: Drawing2D = { + id: "i1", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "block", blockDefId: "blk1", at: { x: 5, y: 5 }, rotation: Math.PI / 2 }, + }; + const out: Primitive[] = []; + addDrawing2D(out, proj, d, false, lwByCode, colorByCode, catByCode); + expect(out.length).toBe(1); + const l = out[0]; + if (l.kind === "line") { + // Lokal (0,0)→(1,0), um 90° gedreht → (0,0)→(0,1), verschoben um (5,5). + expect(l.a.x).toBeCloseTo(5, 6); + expect(l.a.y).toBeCloseTo(5, 6); + expect(l.b.x).toBeCloseTo(5, 6); + expect(l.b.y).toBeCloseTo(6, 6); + expect(l.drawingId).toBe("i1"); + } else { + throw new Error("expected a line primitive"); + } + }); + + it("unbekannte blockDefId rendert nichts (kein Crash)", () => { + const d: Drawing2D = { + id: "i2", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "block", blockDefId: "ghost", at: { x: 0, y: 0 }, rotation: 0 }, + }; + const out: Primitive[] = []; + addDrawing2D(out, project(), d, false, lwByCode, colorByCode, catByCode); + expect(out.length).toBe(0); + }); +}); diff --git a/src/plan/generatePlan/drawing2d.ts b/src/plan/generatePlan/drawing2d.ts index 0b6722b6..675bb31e 100644 --- a/src/plan/generatePlan/drawing2d.ts +++ b/src/plan/generatePlan/drawing2d.ts @@ -14,6 +14,8 @@ import { type Primitive, } from "./shared"; import { ellipsePts, sampleBezierChain, sampleCatmullRom } from "../../tools/curves"; +import { mvGeom } from "../../tools/transform"; +import { bulgeArcPoints } from "../../geometry/bulge"; // ── Bemassung (SIA 400 B.5.3) ──────────────────────────────────────────────── // Modell-Meter-Konstanten für rein grafische (nicht reale) Bemassungs-Details @@ -113,6 +115,48 @@ function formatKoteLabel(value: number): string { return (value > 0 ? "+" : "") + value.toFixed(2); } +// ── Konstruktionslinie (Hilfslinie) ───────────────────────────────────────── +const XLINE_EXTEND_M = 1000; // Verlängerung über a/b hinaus je Richtung +const XLINE_WEIGHT_MM = 0.13; // dünnste übliche Linienstärke (nie dicker als das Objekt) +const XLINE_DASH: number[] = [0.3, 0.1, 0.03, 0.1]; // Strich-Punkt (CAD-Mittellinien-Konvention) + +// ── Leader (Vorführungspfeil) ──────────────────────────────────────────────── +const LEADER_ARROW_LEN_M = 0.12; +const LEADER_ARROW_HALF_W_M = 0.045; + +/** Dünne Linie `from`→`to` + gefüllte Pfeilspitze bei `to` (Ziel des Leaders). */ +function addLeaderLine( + out: Primitive[], + from: Vec2, + to: Vec2, + weightMm: number, + color: string, + greyed: boolean, + drawingId: string, +): void { + const dx = to.x - from.x, dy = to.y - from.y; + const len = Math.hypot(dx, dy); + if (len < 1e-6) return; + const ux = dx / len, uy = dy / len; + const nx = -uy, ny = ux; + const base: Vec2 = { x: to.x - ux * LEADER_ARROW_LEN_M, y: to.y - uy * LEADER_ARROW_LEN_M }; + out.push({ kind: "line", a: from, b: base, cls: "draw2d", weightMm, dash: null, color, greyed, drawingId }); + out.push({ + kind: "polygon", + pts: [ + to, + { x: base.x + nx * LEADER_ARROW_HALF_W_M, y: base.y + ny * LEADER_ARROW_HALF_W_M }, + { x: base.x - nx * LEADER_ARROW_HALF_W_M, y: base.y - ny * LEADER_ARROW_HALF_W_M }, + ], + fill: color, + stroke: color, + strokeWidthMm: weightMm, + hatch: NO_HATCH, + greyed, + drawingId, + }); +} + export function addDrawing2D( out: Primitive[], project: Project, @@ -184,11 +228,44 @@ export function addDrawing2D( case "line": seg(g.a, g.b); break; + case "xline": { + // Konstruktionslinie: weit über a/b hinaus verlängert (wirkt unendlich), + // immer im Strich-Punkt-Muster gezeichnet (überstimmt den LineStyle- + // Strich — Erkennbarkeit als Hilfslinie hat Vorrang vor Objektstil). + const dx = g.b.x - g.a.x, dy = g.b.y - g.a.y; + const len = Math.hypot(dx, dy); + if (len < 1e-6) break; + const ux = dx / len, uy = dy / len; + out.push({ + kind: "line", + a: { x: g.a.x - ux * XLINE_EXTEND_M, y: g.a.y - uy * XLINE_EXTEND_M }, + b: { x: g.b.x + ux * XLINE_EXTEND_M, y: g.b.y + uy * XLINE_EXTEND_M }, + cls: "draw2d", + weightMm: Math.min(weightMm, XLINE_WEIGHT_MM), + dash: XLINE_DASH, + color, + greyed, + drawingId: d.id, + }); + break; + } case "polyline": { - // Geschlossene Polylinie: zuerst die gefüllte Fläche (Vollton/Schraffur). - if (g.closed && g.pts.length > 2) fillPoly(g.pts); - for (let i = 0; i < g.pts.length - 1; i++) seg(g.pts[i], g.pts[i + 1]); - if (g.closed && g.pts.length > 2) seg(g.pts[g.pts.length - 1], g.pts[0]); + // Bogen-Segmente (`bulge`, DXF-Konvention) zu Geradenstücken tessellieren + // — ohne `bulge` liefert `bulgeArcPoints` exakt `[a,b]`, das Ergebnis ist + // dann bitgleich zum alten reinen Geradenzug (kein Sonderpfad nötig). + const ring: Vec2[] = [g.pts[0]]; + for (let i = 0; i < g.pts.length - 1; i++) { + const sub = bulgeArcPoints(g.pts[i], g.pts[i + 1], g.bulge?.[i]); + for (let k = 1; k < sub.length; k++) ring.push(sub[k]); + } + if (g.closed && g.pts.length > 2) { + const sub = bulgeArcPoints(g.pts[g.pts.length - 1], g.pts[0], g.bulge?.[g.pts.length - 1]); + for (let k = 1; k < sub.length; k++) ring.push(sub[k]); + // Letzter Punkt dupliziert ring[0] (Schliess-Segment endet dort) — für + // die Füllfläche nicht nötig, das SVG-`` schliesst implizit. + fillPoly(ring.slice(0, -1)); + } + for (let i = 0; i < ring.length - 1; i++) seg(ring[i], ring[i + 1]); break; } case "rect": { @@ -296,6 +373,20 @@ export function addDrawing2D( break; } case "text": + if (g.pathPts && g.pathPts.length >= 2) { + // Text-entlang-Pfad: eigener Primitive-Typ (echtes SVG textPath), + // Rich-Doc/marks/Leader bewusst ignoriert (v1 nur schlichter String). + out.push({ + kind: "drawingTextPath", + pathPts: g.pathPts, + text: g.text, + heightM: g.height, + color: g.marks?.color ?? color, + greyed, + drawingId: d.id, + }); + break; + } out.push({ kind: "drawingText", at: g.at, @@ -310,7 +401,29 @@ export function addDrawing2D( greyed, drawingId: d.id, }); + if (g.leaderTarget) { + addLeaderLine(out, g.at, g.leaderTarget, weightMm, color, greyed, d.id); + } break; + case "block": { + // Block-Instanz trägt selbst keine Geometrie: Definition nachschlagen, + // jede Teilgeometrie per `mvGeom` (Rotation um den Ursprung + Verschiebung + // um `at`) transformieren und REKURSIV über denselben Renderpfad ausgeben + // — eine synthetische Drawing2D-Hülle mit derselben Ebene/Kategorie/ + // Farb-Overrides wie die Instanz selbst (Sub-Elemente tragen in v1 keinen + // eigenen Stil). Unbekannte/gelöschte `blockDefId` ⇒ nichts rendern. + const def = project.blockDefs?.find((b) => b.id === g.blockDefId); + if (!def) break; + const c = Math.cos(g.rotation), s = Math.sin(g.rotation); + const xf = (p: Vec2): Vec2 => ({ + x: g.at.x + p.x * c - p.y * s, + y: g.at.y + p.x * s + p.y * c, + }); + for (const sub of def.geom2d) { + addDrawing2D(out, project, { ...d, geom: mvGeom(sub, xf) }, greyed, lwByCode, colorByCode, catByCode); + } + break; + } case "image": out.push({ kind: "drawingImage", diff --git a/src/plan/generatePlan/sections.ts b/src/plan/generatePlan/sections.ts index 0c213251..633e5b87 100644 --- a/src/plan/generatePlan/sections.ts +++ b/src/plan/generatePlan/sections.ts @@ -6,7 +6,17 @@ import { leftNormal, normalize, sub } from "../../model/geometry"; import type { Project } from "../../model/types"; -import { NO_HATCH, type Primitive } from "./shared"; +import { NO_HATCH, SHOW_ALL, type CategoryDisplayResolver, type Primitive } from "./shared"; + +/** + * Kategorie-Code der Schnittführungs-Symbole — feste Zuordnung zu "90" + * (Referenzen), derselben Kategorie wie Kontext-Konturen/Höhenlinien: + * Schnittlinien sind Dokumentations-/Referenzelemente, keine Bauteile, und + * bekommen deshalb kein eigenes Sichtbarkeits-Flag mehr am DrawingLevel — + * sie sind ein Element AUF einer Ebene und werden NUR darüber (Ebenen-Panel, + * visibleCodes/categoryDisplay) ein-/ausgeblendet, wie jedes andere Bauteil. + */ +const SECTION_LINE_CATEGORY = "90"; /** Tinte der Schnittführungs-Linie/Marken (kräftiges Grau). */ const SECTION_LINE_INK = "#1f242c"; @@ -40,14 +50,25 @@ function sectionLabelTag(name: string): string { * auf der Blickseite (`directionSign`) und das Schnitt-Label (Kurz-Tag) daneben. * Zusätzlich ein unsichtbares Pick-Band (Polygon mit `sectionLineId`), damit die * Linie im Grundriss anklickbar ist (analog dem Dach-Traufe-Pick-Polygon). + * + * Sichtbarkeit/Dimmen läuft über die Kategorie "90" (Referenzen) — genau wie + * bei Wänden/Decken/Räumen, NICHT über das eigene Sichtbarkeits-Flag der + * Schnitt-/Ansichtsebene (Nutzer-Feedback: "diese sollten Elemente sein, die + * sich auf einer Ebene befinden und nur damit ein-/ausgeblendet werden"). + * `visibleCodes`/`categoryDisplay` fehlen sie (Export-/Print-Pfad ohne + * Ebenen-Filter) → immer sichtbar, wie bisher. */ -export function addSectionLines(out: Primitive[], project: Project): void { +export function addSectionLines( + out: Primitive[], + project: Project, + visibleCodes?: Set, + categoryDisplay: CategoryDisplayResolver = SHOW_ALL, +): void { + const d = categoryDisplay(SECTION_LINE_CATEGORY); + if ((visibleCodes && !visibleCodes.has(SECTION_LINE_CATEGORY)) || !d.render) return; + const greyed = d.greyed; for (const level of project.drawingLevels) { if (level.kind !== "section" && level.kind !== "elevation") continue; - // Schnittebene ist ein-/ausblendbar wie andere Ebenen: eine unsichtbare - // Schnitt-/Ansichtsebene zeigt ihre Linie im Grundriss nicht (Nutzer-Vision - // „eigene Ebene Schnittebenen"). `visible` fehlt = sichtbar (Alt-Projekte). - if (level.visible === false) continue; const line = level.linePoints; if (!line) continue; const [p0, p1] = line; @@ -68,6 +89,7 @@ export function addSectionLines(out: Primitive[], project: Project): void { weightMm: SECTION_LINE_MM, dash: SECTION_LINE_DASH, color: SECTION_LINE_INK, + greyed, }); // Endmarken (Querstrich + Richtungspfeil + Label) an beiden Enden. @@ -83,6 +105,7 @@ export function addSectionLines(out: Primitive[], project: Project): void { cls: "section-line", weightMm: SECTION_LINE_MARK_MM, color: SECTION_LINE_INK, + greyed, }); // Richtungspfeil: vom Querstrich-Ende auf der Blickseite entlang bn. const base = { x: end.x + bn.x * half, y: end.y + bn.y * half }; @@ -92,7 +115,7 @@ export function addSectionLines(out: Primitive[], project: Project): void { y: tip.y - bn.y * SECTION_MARK_LEN * 0.4, }; const w = SECTION_MARK_LEN * 0.25; - out.push({ kind: "line", a: base, b: tip, cls: "section-line", weightMm: SECTION_LINE_MARK_MM, color: SECTION_LINE_INK }); + out.push({ kind: "line", a: base, b: tip, cls: "section-line", weightMm: SECTION_LINE_MARK_MM, color: SECTION_LINE_INK, greyed }); out.push({ kind: "line", a: tip, @@ -100,6 +123,7 @@ export function addSectionLines(out: Primitive[], project: Project): void { cls: "section-line", weightMm: SECTION_LINE_MARK_MM, color: SECTION_LINE_INK, + greyed, }); out.push({ kind: "line", @@ -108,6 +132,7 @@ export function addSectionLines(out: Primitive[], project: Project): void { cls: "section-line", weightMm: SECTION_LINE_MARK_MM, color: SECTION_LINE_INK, + greyed, }); // Label (Kurz-Tag) etwas hinter dem Pfeil, horizontal. const labelAt = { @@ -121,6 +146,7 @@ export function addSectionLines(out: Primitive[], project: Project): void { heightM: SECTION_LABEL_H, angle: 0, color: SECTION_LINE_INK, + greyed, }); } diff --git a/src/plan/generatePlan/shared.resolve.test.ts b/src/plan/generatePlan/shared.resolve.test.ts index 1ed6ad3e..26106f81 100644 --- a/src/plan/generatePlan/shared.resolve.test.ts +++ b/src/plan/generatePlan/shared.resolve.test.ts @@ -16,8 +16,9 @@ import { resolveBackground, resolveHatchId, resolveStrokeWeight, + resolveHatch, } from "./shared"; -import type { Component, LayerCategory } from "../../model/types"; +import type { Component, HatchStyle, LayerCategory, Project } from "../../model/types"; const comp: Component = { id: "c1", @@ -79,6 +80,37 @@ describe("resolveStrokeWeight — Default bleibt 'Nach Bauteil'", () => { }); }); +describe("resolveHatch — reicht `motif` (custom-Muster) unverändert durch", () => { + const motif: NonNullable = { + points: [{ x: 0, y: 0 }, { x: 2, y: 1 }, { x: 4, y: 0 }], + length: 4, + }; + const hatchStyle: HatchStyle = { + id: "h-custom", + name: "Eigenes Motiv", + pattern: "custom", + scale: 1, + angle: 0, + color: "#000", + motif, + }; + const project = { + hatches: [hatchStyle], + lineStyles: [], + } as unknown as Project; + + it("HatchRender.motif entspricht dem HatchStyle.motif", () => { + const render = resolveHatch(project, "h-custom"); + expect(render.motif).toEqual(motif); + }); + + it("ein Hatch OHNE motif liefert HatchRender.motif === undefined (kein erfundener Default)", () => { + const diagonal: HatchStyle = { id: "h-diag", name: "Diagonal", pattern: "diagonal", scale: 1, angle: 0, color: "#000" }; + const p2 = { hatches: [diagonal], lineStyles: [] } as unknown as Project; + expect(resolveHatch(p2, "h-diag").motif).toBeUndefined(); + }); +}); + describe("Drawing2D-Panel-Vorschau (selectionInfo.ts) — mappt fehlende Source explizit auf 'layer'", () => { it("simuliert das Aufrufer-Mapping `d.foregroundSource ?? \"layer\"`: liefert die Kategorie-Farbe für ein Drawing2D ohne Bauteil", () => { const noComponent: Component = { id: "", name: "", color: "#000", hatchId: "", joinPriority: 0 }; diff --git a/src/plan/generatePlan/shared.ts b/src/plan/generatePlan/shared.ts index 35df5887..a58e6241 100644 --- a/src/plan/generatePlan/shared.ts +++ b/src/plan/generatePlan/shared.ts @@ -12,6 +12,7 @@ import type { AttributeSource, Component, HatchPattern, + HatchStyle, LayerCategory, Project, Vec2, @@ -124,6 +125,8 @@ export interface HatchRender { density?: number; lengthMin?: number; lengthMax?: number; + /** Frei gezeichnetes Wiederhol-Motiv (nur `pattern==="custom"`); 1:1 aus dem HatchStyle durchgereicht. */ + motif?: HatchStyle["motif"]; } /** @@ -323,6 +326,20 @@ export type Primitive = drawingId?: string; greyed?: boolean; } + | { + // Text-entlang-Pfad (aus Drawing2D `{shape:"text", pathPts}` mit ≥2 + // Stützpunkten) — echtes SVG ``, nur schlichter String (kein + // Rich-Doc/mehrere Formate in v1). Eigener Primitive-Typ statt einer + // Variante von `drawingText`, damit der bestehende Rich-Text-Renderpfad + // unangetastet bleibt. + kind: "drawingTextPath"; + pathPts: Vec2[]; + text: string; + heightM: number; + color: string; + drawingId?: string; + greyed?: boolean; + } | { // Eingebettetes Rasterbild (aus Drawing2D `{shape:"image"}`, Foto/Logo/ // gerasterte PDF-Seite) — achsparalleles Rechteck, Data-URL als Quelle. @@ -411,6 +428,7 @@ export function resolveHatch( density: h.density, lengthMin: h.lengthMin, lengthMax: h.lengthMax, + motif: h.motif, }; } diff --git a/src/plan/generateSectionPlan.category.test.ts b/src/plan/generateSectionPlan.category.test.ts new file mode 100644 index 00000000..e8868d1a --- /dev/null +++ b/src/plan/generateSectionPlan.category.test.ts @@ -0,0 +1,95 @@ +// Ebenen-Panel-Sichtbarkeit im Schnitt/in der Ansicht: generateSectionPlan +// filtert/dimmt jedes Cut-Band über `cp.categoryCode` (visibleCodes/ +// categoryDisplay) — genau wie jedes andere Bauteil im Grundriss. Vorher +// wirkte das Ebenen-Panel im Schnitt/in der Ansicht gar nicht (Nutzer-Report). + +import { describe, it, expect } from "vitest"; +import { generateSectionPlan } from "./generatePlan"; +import type { CategoryDisplayResolver } from "./generatePlan"; +import type { SectionCutPolygon, SectionOutput } from "./toSection"; + +function cut(kind: "wall" | "slab" | "roof", categoryCode: string | undefined): SectionCutPolygon { + return { + component: { kind, index: 0 }, + color: [0.5, 0.5, 0.5], + pts: [ + [0, 0], + [1, 0], + [1, 2], + [0, 2], + ], + sourceId: "X1", + categoryCode, + }; +} + +const SHOW_ALL: CategoryDisplayResolver = () => ({ render: true, greyed: false, locked: false }); + +describe("generateSectionPlan — Kategorie-Sichtbarkeit (Ebenen-Panel)", () => { + it("lässt ein Band mit kategorie-verstecktem categoryCode weg (visibleCodes ohne den Code)", () => { + const output: SectionOutput = { + cutPolygons: [cut("wall", "20")], + visibleEdges: [], + hiddenEdges: [], + }; + const polys = generateSectionPlan(output, false, { + visibleCodes: new Set(["30"]), // "20" fehlt + categoryDisplay: SHOW_ALL, + }).primitives.filter((p) => p.kind === "polygon"); + expect(polys.length).toBe(0); + }); + + it("lässt ein Band weg, wenn categoryDisplay(code).render=false liefert", () => { + const output: SectionOutput = { + cutPolygons: [cut("wall", "20")], + visibleEdges: [], + hiddenEdges: [], + }; + const hideCat: CategoryDisplayResolver = () => ({ render: false, greyed: false, locked: false }); + const polys = generateSectionPlan(output, false, { + visibleCodes: new Set(["20"]), + categoryDisplay: hideCat, + }).primitives.filter((p) => p.kind === "polygon"); + expect(polys.length).toBe(0); + }); + + it("dimmt (greyed) ein sichtbares Band, wenn categoryDisplay greyed=true liefert", () => { + const output: SectionOutput = { + cutPolygons: [cut("wall", "20")], + visibleEdges: [], + hiddenEdges: [], + }; + const greyCat: CategoryDisplayResolver = () => ({ render: true, greyed: true, locked: false }); + const polys = generateSectionPlan(output, false, { + visibleCodes: new Set(["20"]), + categoryDisplay: greyCat, + }).primitives.filter( + (p): p is Extract => p.kind === "polygon", + ); + expect(polys[0]?.greyed).toBe(true); + }); + + it("zeichnet ein Band OHNE categoryCode immer (unauflösbares Bauteil, Fallback)", () => { + const output: SectionOutput = { + cutPolygons: [cut("wall", undefined)], + visibleEdges: [], + hiddenEdges: [], + }; + const hideAll: CategoryDisplayResolver = () => ({ render: false, greyed: false, locked: false }); + const polys = generateSectionPlan(output, false, { + visibleCodes: new Set([]), + categoryDisplay: hideAll, + }).primitives.filter((p) => p.kind === "polygon"); + expect(polys.length).toBe(1); + }); + + it("ohne opts (Export-/Print-Pfad) bleibt jedes Band sichtbar wie bisher", () => { + const output: SectionOutput = { + cutPolygons: [cut("wall", "20")], + visibleEdges: [], + hiddenEdges: [], + }; + const polys = generateSectionPlan(output).primitives.filter((p) => p.kind === "polygon"); + expect(polys.length).toBe(1); + }); +}); diff --git a/src/plan/generateVisibleLevelsPlan.test.ts b/src/plan/generateVisibleLevelsPlan.test.ts new file mode 100644 index 00000000..bdf9a7c0 --- /dev/null +++ b/src/plan/generateVisibleLevelsPlan.test.ts @@ -0,0 +1,163 @@ +/** + * `generateVisibleLevelsPlan` — Überlagerung mehrerer sichtbarer Geschoss-/ + * Zeichnungs-Ebenen in EINEM Plan (Nutzer-Wunsch: "mehrere Geschosse + * gleichzeitig einschaltbar", "wie bei den Ebenen" — aktive Ebene farbig, + * andere je Darstellungsmodus gedimmt/gesperrt/versteckt). + */ + +import { describe, it, expect } from "vitest"; +import { generateVisibleLevelsPlan } from "./generatePlan"; +import type { CategoryDisplayResolver } from "./generatePlan"; +import type { DrawingLevel, Project, Wall } from "../model/types"; + +const visible = new Set(["20", "90"]); +const SHOW_ALL: CategoryDisplayResolver = () => ({ render: true, greyed: false, locked: false }); + +function wallOf(id: string, floorId: string, x: number): Wall { + return { + id, + type: "wall", + floorId, + categoryCode: "20", + start: { x, y: 0 }, + end: { x: x + 4, y: 0 }, + wallTypeId: "aw", + height: 2.6, + } as unknown as Wall; +} + +function baseProject(levels: DrawingLevel[], walls: Wall[]): Project { + return { + id: "t", + name: "T", + lineStyles: [{ id: "thin", name: "d", weight: 0.13, color: "#111", dash: null }], + hatches: [{ id: "none", name: "Ohne", pattern: "none", scale: 1, angle: 0, color: "#111" }], + components: [{ id: "a", name: "A", color: "#d8d2c7", hatchId: "none", joinPriority: 10 }], + wallTypes: [{ id: "aw", name: "AW", layers: [{ componentId: "a", thickness: 0.2 }] }], + drawingLevels: levels, + layers: [{ code: "20", name: "Wände", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls, + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + } as unknown as Project; +} + +function floor(id: string, name: string): DrawingLevel { + return { + id, + name, + kind: "floor", + visible: true, + locked: false, + floorHeight: 2.6, + cutHeight: 1.0, + baseElevation: 0, + }; +} + +describe("generateVisibleLevelsPlan", () => { + it("überlagert eine zweite sichtbare Ebene zusätzlich zur aktiven", () => { + const p = baseProject( + [floor("eg", "EG"), floor("og", "OG")], + [wallOf("w-eg", "eg", 0), wallOf("w-og", "og", 10)], + ); + const levelDisplay: CategoryDisplayResolver = (id) => ({ + render: true, + greyed: id !== "eg", + locked: false, + }); + const plan = generateVisibleLevelsPlan(p, "eg", visible, SHOW_ALL, "mittel", false, false, levelDisplay); + const wallIds = plan.primitives.map((pr) => (pr as { wallId?: string }).wallId).filter(Boolean); + expect(wallIds).toContain("w-eg"); + expect(wallIds).toContain("w-og"); + }); + + it("gedimmte (nicht-aktive) Ebene: ihre Primitive tragen greyed=true", () => { + const p = baseProject( + [floor("eg", "EG"), floor("og", "OG")], + [wallOf("w-eg", "eg", 0), wallOf("w-og", "og", 10)], + ); + const levelDisplay: CategoryDisplayResolver = (id) => ({ + render: true, + greyed: id !== "eg", + locked: false, + }); + const plan = generateVisibleLevelsPlan(p, "eg", visible, SHOW_ALL, "mittel", false, false, levelDisplay); + const ogPoche = plan.primitives.find( + (pr) => (pr as { wallId?: string }).wallId === "w-og" && pr.kind === "polygon", + ) as { greyed?: boolean } | undefined; + const egPoche = plan.primitives.find( + (pr) => (pr as { wallId?: string }).wallId === "w-eg" && pr.kind === "polygon", + ) as { greyed?: boolean } | undefined; + expect(ogPoche?.greyed).toBe(true); + expect(egPoche?.greyed).toBeFalsy(); + }); + + it("Modus 'active' (render=false für andere): zeigt NUR die aktive Ebene", () => { + const p = baseProject( + [floor("eg", "EG"), floor("og", "OG")], + [wallOf("w-eg", "eg", 0), wallOf("w-og", "og", 10)], + ); + const levelDisplay: CategoryDisplayResolver = (id) => ({ + render: id === "eg", + greyed: false, + locked: false, + }); + const plan = generateVisibleLevelsPlan(p, "eg", visible, SHOW_ALL, "mittel", false, false, levelDisplay); + const wallIds = plan.primitives.map((pr) => (pr as { wallId?: string }).wallId).filter(Boolean); + expect(wallIds).toContain("w-eg"); + expect(wallIds).not.toContain("w-og"); + }); + + it("dedupliziert projektglobale Zutaten (Schnittlinien) — nur einmal, nicht je Ebene", () => { + const p = baseProject( + [ + floor("eg", "EG"), + floor("og", "OG"), + { + id: "s-a", + name: "Schnitt A", + kind: "section", + visible: true, + locked: false, + linePoints: [{ x: 0, y: 2 }, { x: 6, y: 2 }], + directionSign: 1, + }, + ], + [wallOf("w-eg", "eg", 0), wallOf("w-og", "og", 10)], + ); + const plan = generateVisibleLevelsPlan(p, "eg", visible, SHOW_ALL, "mittel", false, false, SHOW_ALL); + const bands = plan.primitives.filter( + (pr) => pr.kind === "polygon" && (pr as { sectionLineId?: string }).sectionLineId === "s-a", + ); + expect(bands.length).toBe(1); + }); + + it("Schnitt/Ansicht-Ebenen bleiben Einzel-Pane (kein Stapeln über kind-Grenze)", () => { + const p = baseProject( + [ + floor("eg", "EG"), + { + id: "s-a", + name: "Schnitt A", + kind: "section", + visible: true, + locked: false, + linePoints: [{ x: 0, y: 2 }, { x: 6, y: 2 }], + directionSign: 1, + }, + ], + [wallOf("w-eg", "eg", 0)], + ); + // Aktive Ebene ist der Schnitt selbst — Geschoss "eg" darf NICHT als + // Referenz-Wand-Poché mit hineingemischt werden (andere Projektionsachse). + const plan = generateVisibleLevelsPlan(p, "s-a", visible, SHOW_ALL, "mittel", false, false, SHOW_ALL); + const wallIds = plan.primitives.map((pr) => (pr as { wallId?: string }).wallId).filter(Boolean); + expect(wallIds).not.toContain("w-eg"); + }); +}); diff --git a/src/plan/glPlan/glPlanCompile.ts b/src/plan/glPlan/glPlanCompile.ts index 472517d6..f8d603ce 100644 --- a/src/plan/glPlan/glPlanCompile.ts +++ b/src/plan/glPlan/glPlanCompile.ts @@ -142,6 +142,16 @@ function dim(color: Rgba, greyed: boolean | undefined): Rgba { return greyed ? [GREY_RGB, GREY_RGB, GREY_RGB, color[3]] : color; } +/** + * Wie `dim`, aber für FLÄCHEN-Füllung: gedimmte Flächen bleiben WEISS statt + * grau eingefärbt — nur der Umriss (weiterhin `dim`) macht das Element als + * gedimmt erkennbar (Nutzer-Wunsch: "im Hintergrund nicht als graue Fläche + * gefüllt, sondern weiss mit nur den Linien sichtbar"). + */ +function dimFill(color: Rgba, greyed: boolean | undefined): Rgba { + return greyed ? [1, 1, 1, color[3]] : color; +} + /** * Tessellliert Plan-Primitive zu GPU-Geometrie (MVP: gefüllte Polygone + * bildschirmkonstante Striche). Text/Bögen bleiben im SVG-Overlay. @@ -399,7 +409,7 @@ export function compilePrimitivesToGpu( track(pt.x, pt.y); } for (const t of tris) fillIdx.push(base + t); - addFillBatch(tris.length, dim(fill, prim.greyed)); + addFillBatch(tris.length, dimFill(fill, prim.greyed)); } } // Schraffur (nach der Füllung, vor/passend zum Umriss — wie der SVG stapelt): diff --git a/src/plan/glPlan/glPlanHatch.test.ts b/src/plan/glPlan/glPlanHatch.test.ts index 6828a90d..75892f52 100644 --- a/src/plan/glPlan/glPlanHatch.test.ts +++ b/src/plan/glPlan/glPlanHatch.test.ts @@ -327,6 +327,39 @@ describe('buildHatchRuns', () => { const runs = buildHatchRuns(sq, hatch({ pattern: 'diagonal', scale: 0 })); expect(runs.length).toBeGreaterThan(0); }); + + it('custom OHNE gesetztes Motiv fällt auf gerade 2-Punkt-Läufe zurück (wie diagonal)', () => { + const runs = buildHatchRuns(sq, hatch({ pattern: 'custom' })); + expect(runs.length).toBeGreaterThan(0); + for (const r of runs) expect(r.length).toBe(2); + }); + + it('custom MIT Motiv tesseliert jede Musterlinie zu einer Motiv-Polylinie (>2 Punkte)', () => { + const motif = { + points: [ + { x: 0, y: 0 }, + { x: 1, y: 1.5 }, + { x: 2, y: 0 }, + { x: 3, y: -1.5 }, + { x: 4, y: 0 }, + ], + length: 4, + }; + const withMotif = buildHatchRuns(sq, hatch({ pattern: 'custom', motif })); + const withoutMotif = buildHatchRuns(sq, hatch({ pattern: 'diagonal' })); + expect(withMotif.length).toBe(withoutMotif.length); // gleiche Anzahl Musterlinien + // Mindestens ein Lauf ist eine echte, tesselierte Polylinie (nicht nur 2 Punkte). + expect(withMotif.some((r) => r.length > 2)).toBe(true); + // Alle Punkte endlich (kein NaN/Infinity) — der Quer-Versatz des Motivs + // kann die Läufe leicht über die Original-Musterlinie hinaus versetzen + // (wie bei "insulation" oben, das ebenfalls nur x prüft, nicht y). + for (const r of withMotif) { + for (const p of r) { + expect(Number.isFinite(p.x)).toBe(true); + expect(Number.isFinite(p.y)).toBe(true); + } + } + }); }); describe('applyDashRuns', () => { diff --git a/src/plan/glPlan/glPlanHatch.ts b/src/plan/glPlan/glPlanHatch.ts index c9183058..085ae860 100644 --- a/src/plan/glPlan/glPlanHatch.ts +++ b/src/plan/glPlan/glPlanHatch.ts @@ -403,7 +403,16 @@ export function buildHatchRuns(poly: Vec2[], hatch: HatchRender): HatchRun[] { const dir1 = rotate({ x: 0, y: -1 }, rot); const a1 = Math.atan2(dir1.y, dir1.x); // Gerade Musterlinien → 2-Punkt-Läufe (visuell identisch zu Butt-Cap-Segmenten). - const runs: HatchRun[] = hatchLineFamily(poly, a1, spacingM, 0).map((s) => [s.a, s.b]); + // „custom" mit gesetztem Motiv: jede Musterlinie wird per `motifPoints` entlang + // ihrer eigenen Länge tesselliert (Papier-mm → Modell-Meter über dieselbe + // Kopplung wie bei Linien-Motiven, DASH_MM_TO_M, zusätzlich mit `scale` + // verknüpft — konsistent zur Zeilenabstand-Formel oben). Ohne Motiv (frisch + // angelegter Hatch) fällt „custom" auf gerade Linien zurück (kein Absturz). + const runs: HatchRun[] = hatchLineFamily(poly, a1, spacingM, 0).map((s) => + pattern === 'custom' && hatch.motif + ? motifPoints(s.a, s.b, hatch.motif, scale * DASH_MM_TO_M) + : [s.a, s.b], + ); if (pattern === 'crosshatch') { // Zweite Schar: die SVG-Kachel trägt zusätzlich eine horizontale Linie diff --git a/src/plan/planView/overlays.tsx b/src/plan/planView/overlays.tsx index cf1e3531..5abfb602 100644 --- a/src/plan/planView/overlays.tsx +++ b/src/plan/planView/overlays.tsx @@ -60,13 +60,12 @@ export function DraftOverlay({ {draft.vertices.map((v, i) => { const s = toScreen(v); return ( - ); diff --git a/src/plan/planView/primitives.tsx b/src/plan/planView/primitives.tsx index 11490773..c273196b 100644 --- a/src/plan/planView/primitives.tsx +++ b/src/plan/planView/primitives.tsx @@ -4,6 +4,7 @@ // Zugriff auf PlanView-internen State. import type { HatchRender, Primitive } from "../generatePlan"; +import { NO_HATCH } from "../generatePlan/shared"; import { docToLines, wrapDocToLines, type SvgLine } from "../../text/renderHtml"; import type { Vec2 } from "../../model/types"; import { quantizePen } from "../../export/sceneToPrintSvg"; @@ -19,7 +20,8 @@ export function needsPattern(pattern: HatchRender["pattern"]): boolean { return ( pattern === "insulation" || pattern === "diagonal" || - pattern === "crosshatch" + pattern === "crosshatch" || + pattern === "custom" ); } @@ -121,7 +123,46 @@ export function HatchPattern({ ); } - // Diagonal + Crosshatch: dünne Linien, Winkel via patternTransform. + if ( + hatch.pattern === "custom" && + hatch.motif && + hatch.motif.points.length >= 2 && + hatch.motif.length > 1e-6 + ) { + // Frei gezeichnetes Motiv: EINE Wiederhollänge (Papier-mm → viewBox über + // `hatch.scale`) per `motifPoints` entlang eines vertikalen Referenz- + // segments (0,0)→(0,period) tesselliert und als in die Kachel + // gelegt — dieselbe „Musterlinie läuft entlang der Kachel-y-Achse"- + // Konvention wie diagonal/crosshatch (Zeilenabstand `rowSpacing` = Kachel- + // breite, wie deren `tile`; das Motiv selbst bestimmt die Kachelhöhe). + const rowSpacing = 8 * hatch.scale; + const period = hatch.motif.length * hatch.scale; + const pts = motifPoints({ x: 0, y: 0 }, { x: 0, y: period }, hatch.motif, hatch.scale); + const d = pts.map((p, i) => `${i === 0 ? "M" : "L"}${p.x} ${p.y}`).join(" "); + return ( + + + + ); + } + + // Diagonal + Crosshatch (+ "custom" ohne gesetztes Motiv, s. o. — degradiert + // bewusst zu geraden Linien statt abzustürzen): dünne Linien, Winkel via + // patternTransform. // Kachel 8×8 × Maßstab; crosshatch fügt eine zweite, senkrechte Schar hinzu. const tile = 8 * hatch.scale; return ( @@ -289,13 +330,27 @@ export function greyColor(c: string | undefined): string | undefined { return !c || c === "none" || c === "transparent" ? c : GREYED_COLOR; } -/** Flache Kopie eines Primitivs mit allen Farbfeldern auf `GREYED_COLOR` umgefärbt. */ +/** + * Flache Kopie eines Primitivs, gedimmt für den Hintergrund: die Flächen- + * Grundfüllung bleibt WEISS (Nutzer-Wunsch: "im Hintergrund nicht als graue + * Fläche gefüllt"), aber echte Schraffur-LINIEN (Kreuz/Parallel/Dämmung/Kies) + * bleiben sichtbar — nur grau eingefärbt statt in ihrer Bauteilfarbe (Nutzer- + * Präzisierung: "Schraffuren selber sollten sichtbar sein, also die Linien + * davon"). Nur eine reine VOLLFÜLLUNG ("solid", hat keine eigenen Linien) und + * Bild-Schraffuren (keine sinnvolle Grau-Variante) weichen auf `NO_HATCH` — + * sonst bliebe die Fläche grau bzw. in voller Bild-Farbe gefüllt. + */ export function greyedCopy(p: T): T { const q: any = { ...p }; - if ("fill" in q) q.fill = greyColor(q.fill); + if ("fill" in q && q.fill && q.fill !== "none") q.fill = "#ffffff"; if ("stroke" in q) q.stroke = greyColor(q.stroke); if ("color" in q) q.color = greyColor(q.color); - if ("hatch" in q && q.hatch) q.hatch = { ...q.hatch, color: greyColor(q.hatch.color) }; + if ("hatch" in q && q.hatch) { + const noLines = q.hatch.pattern === "solid" || q.hatch.kind === "image"; + q.hatch = noLines + ? { ...NO_HATCH, color: greyColor(q.hatch.color) } + : { ...q.hatch, color: greyColor(q.hatch.color) }; + } return q; } @@ -818,6 +873,29 @@ export function renderPrimitive( ); } + case "drawingTextPath": { + // Text-entlang-Pfad: unsichtbarer `` (nur Geometrie-Träger) + + // `` — der Browser übernimmt die Zeichen-Positionierung + // entlang der Kurve, keine eigene Glyphen-Transform-Mathematik nötig. + if (p.pathPts.length < 2 || !p.text) return null; + const screenPts = p.pathPts.map(toScreen); + const d = `M ${screenPts.map((s) => `${s.x} ${s.y}`).join(" L ")}`; + const fontSize = p.heightM * PX_PER_M; + const pathId = `textpath-${p.drawingId ?? index}`; + return ( + <> + + + {p.text} + + + ); + } case "drawingCircle": { // Echtes `` — rund bei jedem Zoom (kein Vieleck). Füllung optional. const c = toScreen(p.center); diff --git a/src/plan/toElevation.test.ts b/src/plan/toElevation.test.ts index aaeb376f..010a56eb 100644 --- a/src/plan/toElevation.test.ts +++ b/src/plan/toElevation.test.ts @@ -10,6 +10,7 @@ import { describe, it, expect } from "vitest"; import type { Project, Wall } from "../model/types"; import type { RModel3d, RSlab, RWall } from "./toWalls3d"; import type { SectionPlaneSpec } from "./toSection"; +import type { CategoryDisplayResolver } from "./generatePlan"; import { buildShadows, collectElevationFaces, @@ -91,6 +92,7 @@ describe("toElevation — Painter-Reihenfolge", () => { ], slabs: [], meshes: [], + roofLayers: [], }; const faces = collectElevationFaces(model, frame); const near = faces.find((f) => f.wallId === "NEAR")!; @@ -119,7 +121,7 @@ describe("toElevation — Schlagschatten", () => { const frame = elevationFrame(PLANE_SOUTH); // Wandfläche (Fassade) hinter dem Überstand. const wallFaces = collectElevationFaces( - { walls: [wall()], slabs: [], meshes: [] }, + { walls: [wall()], slabs: [], meshes: [], roofLayers: [] }, frame, ); // Überstand-Slab, der VOR der Wand (näher, z < −0.1) liegt und sie u-seitig @@ -137,7 +139,7 @@ describe("toElevation — Schlagschatten", () => { ceilingId: "R", }; const slabFaces = collectElevationFaces( - { walls: [], slabs: [slab], meshes: [] }, + { walls: [], slabs: [slab], meshes: [], roofLayers: [] }, frame, ); const shadows = buildShadows(wallFaces, slabFaces); @@ -147,7 +149,7 @@ describe("toElevation — Schlagschatten", () => { it("buildShadows: kein Überlapp → keine Schatten", () => { const frame = elevationFrame(PLANE_SOUTH); const wallFaces = collectElevationFaces( - { walls: [wall({ start: [0, 0], end: [4, 0] })], slabs: [], meshes: [] }, + { walls: [wall({ start: [0, 0], end: [4, 0] })], slabs: [], meshes: [], roofLayers: [] }, frame, ); // Slab weit seitlich versetzt (u außerhalb der Wand). @@ -164,7 +166,7 @@ describe("toElevation — Schlagschatten", () => { ceilingId: "R", }; const slabFaces = collectElevationFaces( - { walls: [], slabs: [slab], meshes: [] }, + { walls: [], slabs: [slab], meshes: [], roofLayers: [] }, frame, ); expect(buildShadows(wallFaces, slabFaces).length).toBe(0); @@ -193,6 +195,71 @@ describe("toElevation — Fallback", () => { }); }); +describe("toElevation — Ebenen-Panel-Sichtbarkeit (Nutzer-Report: 'Kategorien sollten auch in der Ansicht wirken')", () => { + it("eine kategorie-ausgeblendete Wand verschwindet vollständig aus der Ansicht", () => { + const project = elevationProject({ overhang: false }); + const level = project.drawingLevels[1]; + const hideAll: CategoryDisplayResolver = () => ({ render: false, greyed: false, locked: false }); + const plan = generateElevationPlan(project, level, { + visibleCodes: new Set(["20"]), + categoryDisplay: hideAll, + })!; + const wallPolys = plan.primitives.filter((p) => p.kind === "polygon" && p.wallId != null); + expect(wallPolys.length).toBe(0); + }); + + it("bleibt sichtbar, wenn die Kategorie erlaubt ist", () => { + const project = elevationProject({ overhang: false }); + const level = project.drawingLevels[1]; + const showAll: CategoryDisplayResolver = () => ({ render: true, greyed: false, locked: false }); + const plan = generateElevationPlan(project, level, { + visibleCodes: new Set(["20"]), + categoryDisplay: showAll, + })!; + const wallPolys = plan.primitives.filter((p) => p.kind === "polygon" && p.wallId != null); + expect(wallPolys.length).toBeGreaterThan(0); + }); + + it("eine ausgeblendete NÄHERE Wand verdeckt die fernere nicht mehr (fällt auch als Occluder weg)", () => { + const project = elevationProject({ overhang: false }); + const level = project.drawingLevels[1]; + // NEAR (categoryCode "20") ausblenden — FAR bleibt sichtbar UND wird nicht + // mehr von NEAR verdeckt (anders als eine normale Verdeckung). + const hideCat: CategoryDisplayResolver = () => ({ render: false, greyed: false, locked: false }); + const plan = generateElevationPlan(project, level, { + visibleCodes: new Set([]), + categoryDisplay: hideCat, + })!; + const near = plan.primitives.find((p) => p.kind === "polygon" && p.wallId === "NEAR"); + const far = plan.primitives.find((p) => p.kind === "polygon" && p.wallId === "FAR"); + expect(near).toBeUndefined(); + expect(far).toBeUndefined(); // beide tragen categoryCode "20", beide ausgeblendet + }); + + it("ohne visibleCodes/categoryDisplay (Export-/Print-Pfad) bleibt alles sichtbar wie bisher", () => { + const project = elevationProject({ overhang: false }); + const level = project.drawingLevels[1]; + const plan = generateElevationPlan(project, level)!; + const wallPolys = plan.primitives.filter((p) => p.kind === "polygon" && p.wallId != null); + expect(wallPolys.length).toBeGreaterThan(0); + }); + + it("markiert eine sichtbare, aber gedimmte Kategorie als greyed (nicht ausgeblendet)", () => { + const project = elevationProject({ overhang: false }); + const level = project.drawingLevels[1]; + const greyCat: CategoryDisplayResolver = () => ({ render: true, greyed: true, locked: false }); + const plan = generateElevationPlan(project, level, { + visibleCodes: new Set(["20"]), + categoryDisplay: greyCat, + })!; + const wallPolys = plan.primitives.filter( + (p): p is Extract => p.kind === "polygon" && p.wallId != null, + ); + expect(wallPolys.length).toBeGreaterThan(0); + for (const p of wallPolys) expect(p.greyed).toBe(true); + }); +}); + // ── Minimalprojekt-Factory ────────────────────────────────────────────────── // Zwei parallele Wände (nah/fern) + optional eine auskragende Dach-Decke. function elevationProject(opts: { overhang: boolean }): Project { @@ -549,3 +616,72 @@ describe("Dächer in der Ansicht (roofWorldFacesAll)", () => { expect(maxV).toBeCloseTo(ridge, 5); }); }); + +describe("toElevation — Tür-Teilverglasung (glazingRatio)", () => { + const GLASS_FILL_COLOR = "#9fc2d9"; + const DOOR_LEAF_FILL_COLOR = "#ede6d9"; + + function doorProject(dt: { + leafStyle: "glatt" | "kassette" | "glas"; + glazingRatio?: number; + }): Project { + const base = elevationProject({ overhang: false }); + const doorType = { + id: "dt", + name: "Tür", + kind: "dreh" as const, + leafCount: 1 as const, + leafStyle: dt.leafStyle, + glazingRatio: dt.glazingRatio, + frameThickness: 0.05, + }; + const opening = { + id: "op", + type: "opening" as const, + hostWallId: "NEAR", + categoryCode: "21", + kind: "door" as const, + typeId: "dt", + position: 1.5, + width: 1, + height: 2.1, + sillHeight: 0, + }; + return { + ...base, + doorTypes: [doorType], + openings: [opening], + } as unknown as Project; + } + + function fillsOf(project: Project): string[] { + const plan = generateElevationPlan(project, project.drawingLevels[1])!; + return plan.primitives + .filter((p) => p.kind === "polygon") + .map((p) => (p as { fill: string }).fill); + } + + it("glattes Blatt (kein Glas): nur die Blattfarbe, keine Glasfläche", () => { + const fills = fillsOf(doorProject({ leafStyle: "glatt" })); + expect(fills).toContain(DOOR_LEAF_FILL_COLOR); + expect(fills).not.toContain(GLASS_FILL_COLOR); + }); + + it("Glasblatt, glazingRatio=1 (voll verglast): nur Glasfarbe, keine Blattfläche", () => { + const fills = fillsOf(doorProject({ leafStyle: "glas", glazingRatio: 1 })); + expect(fills).toContain(GLASS_FILL_COLOR); + expect(fills).not.toContain(DOOR_LEAF_FILL_COLOR); + }); + + it("Glasblatt, glazingRatio=0.5 (teilverglast): BEIDE Farben + Trennlinie", () => { + const project = doorProject({ leafStyle: "glas", glazingRatio: 0.5 }); + const fills = fillsOf(project); + expect(fills).toContain(GLASS_FILL_COLOR); + expect(fills).toContain(DOOR_LEAF_FILL_COLOR); + const plan = generateElevationPlan(project, project.drawingLevels[1])!; + const divisionLines = plan.primitives.filter( + (p) => p.kind === "line" && (p as { cls?: string }).cls === "elevation-division", + ); + expect(divisionLines.length).toBeGreaterThan(0); + }); +}); diff --git a/src/plan/toElevation.ts b/src/plan/toElevation.ts index 074fac24..05df5809 100644 --- a/src/plan/toElevation.ts +++ b/src/plan/toElevation.ts @@ -34,6 +34,7 @@ import type { DrawingLevel, Project, Vec2, Wall } from "../model/types"; import { getComponent, + getDoorType, getWallType, getWindowType, openingsOfWall, @@ -48,7 +49,7 @@ import { projectToModel3d } from "./toWalls3d"; import type { RModel3d, RRgb, RSlab, RVec2, RWall } from "./toWalls3d"; import { sectionPlaneFromLevel } from "./toSection"; import type { SectionPlaneSpec } from "./toSection"; -import type { HatchRender, Plan, Primitive } from "./generatePlan"; +import type { CategoryDisplayResolver, HatchRender, Plan, Primitive } from "./generatePlan"; /** Welt-3D-Punkt (x, Höhe/y, z) — Y-up, identisch zur render3d-Weltkonvention. */ export type V3 = [number, number, number]; @@ -604,6 +605,14 @@ interface ProjectedOpening { depth: number; /** Glasfelder (je Flügel/Feld) innerhalb des Blendrahmens. */ glass: Array>; + /** + * Blinde (undurchsichtige) Türblatt-Felder — Gegenstück zu `glass` bei Türen: + * ein Glasblatt (`DoorType.leafStyle==="glas"`) mit `glazingRatio<1` teilt + * sich in einen Glas-Anteil (oben, → `glass`) und einen blinden Blattanteil + * (unten, → `doorLeaf`); ein nicht-verglastes Blatt landet komplett hier. + * Fenster füllen dieses Feld nie. + */ + doorLeaf: Array>; /** Teilungslinien (Pfosten/Kämpfer) über den Rahmen. */ divisions: Array<[[number, number], [number, number]]>; /** Flügelrahmen-Rechtecke (Kontur je öffenbarem/festem Flügel). */ @@ -663,7 +672,7 @@ function projectOpeningRect( if (depth <= EPS) continue; // pts-Reihenfolge: [unten-von, unten-bis, oben-bis, oben-von] — Basis für // die (fa, fz)-Interpolation der Flügel-/Glasfelder in collectOpenings. - return { pts, depth, glass: [], divisions: [], sashRects: [], sill: [], symbol: [], isDoor: false }; + return { pts, depth, glass: [], doorLeaf: [], divisions: [], sashRects: [], sill: [], symbol: [], isDoor: false }; } return null; } @@ -718,9 +727,25 @@ function collectOpenings(project: Project, frame: ElevationFrame): ProjectedOpen const w = iv.to - iv.from; const h = v.zTop - v.zBottom; if (op.kind === "door") { - // Türen im Projekt-`openings`-Array: Blatt-Fläche (kein Glasraster). + // Türen im Projekt-`openings`-Array: Blatt-Fläche, bei Glasblatt mit + // Teilverglasung (`glazingRatio`, Kämpferhöhe von OBEN gemessen wie + // beim Fenster-Oberlicht) — Glasanteil oben (`glass`), blinder Rest + // unten (`doorLeaf`), Trennlinie dazwischen ab Kämpfer. pr.isDoor = true; - pr.glass.push(rect(pr.pts, 0.04, 0.96, 0, 0.97)); + const dt = getDoorType(project, op); + if (dt?.leafStyle === "glas") { + const ratio = Math.max(0.05, Math.min(1, dt.glazingRatio ?? 1)); + if (ratio >= 1 - EPS) { + pr.glass.push(rect(pr.pts, 0.04, 0.96, 0, 0.97)); + } else { + const splitZ = 0.97 * (1 - ratio); + pr.glass.push(rect(pr.pts, 0.04, 0.96, splitZ, 0.97)); + pr.doorLeaf.push(rect(pr.pts, 0.04, 0.96, 0, splitZ)); + pr.divisions.push([quadAt(pr.pts, 0.04, splitZ), quadAt(pr.pts, 0.96, splitZ)]); + } + } else { + pr.doorLeaf.push(rect(pr.pts, 0.04, 0.96, 0, 0.97)); + } out.push(pr); continue; } @@ -874,7 +899,7 @@ function collectOpenings(project: Project, frame: ElevationFrame): ProjectedOpen const pr = projectOpeningRect(frame, wall, from, to, zBottom, oTop, thickness); if (pr) { pr.isDoor = true; - pr.glass.push(rect(pr.pts, 0.04, 0.96, 0, 0.97)); + pr.doorLeaf.push(rect(pr.pts, 0.04, 0.96, 0, 0.97)); // Legacy-Tür: kein Typ, kein Glasblatt out.push(pr); } } @@ -1167,6 +1192,16 @@ export interface ElevationOptions { shadows?: boolean; /** Schwarz-Weiss-Modus (neutralisierte Füllungen). */ mono?: boolean; + /** + * Ebenen-Panel-Sichtbarkeit (wie im Grundriss/Schnitt): eine Fläche, deren + * Quell-Bauteil (Wand/Decke/Dach, über `wallId`/`ceilingId`/`roofId`) einer + * NICHT sichtbaren Kategorie angehört, wird VOLLSTÄNDIG entfernt — vor der + * Verdeckungsberechnung, damit sie auch nichts mehr verdeckt (wie eine + * ausgeblendete Wand im Grundriss). Fehlt eine der beiden Optionen, bleibt + * jede Fläche sichtbar (Export-/Print-Pfad ohne Ebenen-Filter). + */ + visibleCodes?: Set; + categoryDisplay?: CategoryDisplayResolver; } /** @@ -1189,12 +1224,40 @@ export function generateElevationPlan( const model = projectToModel3d(project, { layeredWalls: false }); // Ansichts-u-Achse in Grundriss-Koordinaten (Welt x,z = Modell x,y). extendWallCornersForElevation(project, model.walls, { x: frame.U[0], y: frame.U[2] }); - const faces = collectElevationFaces(model, frame); + let faces = collectElevationFaces(model, frame); // Dächer analytisch (roofGeometry) — nicht Teil von RModel3d walls/slabs. for (const rf of roofWorldFacesAll(project)) { const pf = projectFace(frame, rf); if (pf) faces.push(pf); } + // Grafik-Kategorie einer projizierten Fläche (Quell-Wand/-Decke/-Dach) — für + // Ebenen-Panel-Sichtbarkeit UND -Dimmen (s. u.). + const categoryCodeOfFace = (f: ProjectedFace): string | undefined => { + if (f.wallId) return project.walls.find((w) => w.id === f.wallId)?.categoryCode; + if (f.ceilingId) return (project.ceilings ?? []).find((c) => c.id === f.ceilingId)?.categoryCode; + if (f.roofId) return (project.roofs ?? []).find((r) => r.id === f.roofId)?.categoryCode; + return undefined; + }; + // Ebenen-Panel-Sichtbarkeit: kategorie-ausgeblendete Flächen VOR der + // Verdeckungsberechnung entfernen (s. ElevationOptions.visibleCodes) — wie + // im Grundriss verdeckt eine ausgeblendete Wand dann auch nichts mehr. + if (opts.visibleCodes && opts.categoryDisplay) { + const { visibleCodes, categoryDisplay } = opts; + faces = faces.filter((f) => { + const code = categoryCodeOfFace(f); + if (code === undefined) return true; + return visibleCodes.has(code) && categoryDisplay(code).render; + }); + } + // Ebenen-Panel-Dimmen ("Andere grau"): je Fläche, ob ihre Kategorie gedimmt + // ist — wirkt NUR auf die Flächen-Füllung selbst (Silhouetten-/Kanten-Linien + // fassen ggf. MEHRERE Flächen gleicher Tiefe zu EINEM Umriss zusammen, s. + // `frontalGroups` unten, und tragen deshalb keine eindeutige Kategorie). + const isFaceGreyed = (f: ProjectedFace): boolean => { + if (!opts.categoryDisplay) return false; + const code = categoryCodeOfFace(f); + return code !== undefined && opts.categoryDisplay(code).greyed; + }; const wallFaces = faces.filter((f) => f.role === "wall"); const slabFaces = faces.filter((f) => f.role === "slab"); const roofFaces = faces.filter((f) => f.role === "roof"); @@ -1333,6 +1396,7 @@ export function generateElevationPlan( stroke: "none", strokeWidthMm: 0, hatch: NO_HATCH, + greyed: isFaceGreyed(f), ...(f.wallId ? { wallId: f.wallId } : {}), ...(f.ceilingId ? { ceilingId: f.ceilingId } : {}), ...(f.roofId ? { roofId: f.roofId } : {}), @@ -1447,7 +1511,22 @@ export function generateElevationPlan( prim: { kind: "polygon", pts: toVec(g), - fill: mono ? GLASS_FILL_MONO : op.isDoor ? DOOR_LEAF_FILL_COLOR : GLASS_FILL_COLOR, + fill: mono ? GLASS_FILL_MONO : GLASS_FILL_COLOR, + stroke: EDGE_INK, + strokeWidthMm: EDGE_MM, + hatch: NO_HATCH, + }, + }); + } + // Blinde Türblatt-Felder (Gegenstück zu `glass`, s. `ProjectedOpening.doorLeaf`). + for (const g of op.doorLeaf) { + items.push({ + depth: d, + seq: seq++, + prim: { + kind: "polygon", + pts: toVec(g), + fill: mono ? "#ffffff" : DOOR_LEAF_FILL_COLOR, stroke: EDGE_INK, strokeWidthMm: EDGE_MM, hatch: NO_HATCH, diff --git a/src/plan/toRenderScene.ts b/src/plan/toRenderScene.ts index ff688c95..ed9ce135 100644 --- a/src/plan/toRenderScene.ts +++ b/src/plan/toRenderScene.ts @@ -170,6 +170,16 @@ function withOpacity(col: RRgba, cls: string | undefined, greyed: boolean | unde return o === 1 ? rgb : [rgb[0], rgb[1], rgb[2], rgb[3] * o]; } +/** + * Wie `withOpacity`, aber für FLÄCHEN-Füllung: gedimmte Flächen bleiben WEISS + * statt grau eingefärbt — nur der Umriss (weiterhin `withOpacity`) macht das + * Element als gedimmt erkennbar (Nutzer-Wunsch: "im Hintergrund nicht als + * graue Fläche gefüllt, sondern weiss mit nur den Linien sichtbar"). + */ +function withFillOpacity(col: RRgba, greyed: boolean | undefined): RRgba { + return greyed ? [1, 1, 1, col[3]] : col; +} + /** Strichfarbe einer line/arc-Primitive: CSS-Klassen-Farbe > Modell-Farbe > Tinte. */ function strokeColorFor(cls: string | undefined, color: string | undefined): RRgba { const css = cls ? CLS_STROKE[cls] : undefined; @@ -389,7 +399,7 @@ export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAUL // Füllung const fillCol = toRgba(p.fill, 1); if (fillCol && pts.length >= 3) { - fills.push({ pts, color: withOpacity(fillCol, undefined, p.greyed), z: zc++ }); + fills.push({ pts, color: withFillOpacity(fillCol, p.greyed), z: zc++ }); } // Schraffur: die aufs Polygon geclippten Musterlinien wie im Browser diff --git a/src/plan/toSection.ts b/src/plan/toSection.ts index e60ef7ca..a7ed29ba 100644 --- a/src/plan/toSection.ts +++ b/src/plan/toSection.ts @@ -87,6 +87,14 @@ export interface SectionCutPolygon { * Fehlt (unauflösbares Bauteil), bleibt das Band ohne Auswahlbezug. */ sourceId?: string; + /** + * Grafik-Kategorie-Code des QUELL-Elements (wie `sourceId`, aus derselben + * Auflösung in `attachCutStyles`) — `generateSectionPlan` filtert/dimmt jedes + * Cut-Band darüber wie jedes andere Bauteil (`visibleCodes`/`categoryDisplay`), + * damit das Ebenen-Panel auch im Schnitt/in der Ansicht wirkt, nicht nur im + * Grundriss. Fehlt (unauflösbares Bauteil), bleibt das Band immer sichtbar. + */ + categoryCode?: string; } /** Ein projiziertes Liniensegment in (u, v)-Metern. */ @@ -306,13 +314,16 @@ function attachCutStyles(output: SectionOutput, project: Project, plane: Section // aufgelöst; keine Boolean-Dominanz (joinPriority undefined) — unverändert // übernehmen. WICHTIG vor dem Slab-Zweig (sonst falscher owner-Lookup). if (ref.kind === "roof") { - cp.sourceId = (project.roofs ?? [])[ref.index]?.id; + const owner = (project.roofs ?? [])[ref.index]; + cp.sourceId = owner?.id; + cp.categoryCode = owner?.categoryCode; bands.push(cp); continue; } if (ref.kind === "wall") { const owner = walls[ref.index]; cp.sourceId = owner?.id; + cp.categoryCode = owner?.categoryCode; // Wand: bei mehrschichtigem Wandtyp wird das EINE geschnittene Rechteck in // stehende Teil-Rechtecke je Schicht quer zur Dicke (u) aufgeteilt — das // vertikale Gegenstück zur Decken-Zerlegung (dort quer zur Höhe v), siehe @@ -342,6 +353,7 @@ function attachCutStyles(output: SectionOutput, project: Project, plane: Section // `addCeilingPoche`). const owner = slabs[ref.index]; cp.sourceId = owner?.id; + cp.categoryCode = owner?.categoryCode; if (owner) { const wt = getCeilingType(project, owner); if (wt.layers.length > 1) { @@ -813,6 +825,7 @@ export function splitSlabLayers( joinPriority: comp.joinPriority, componentId: comp.id, sourceId: cp.sourceId, + categoryCode: cp.categoryCode, }); } return out; @@ -918,6 +931,7 @@ export function splitWallLayers( joinPriority: comp.joinPriority, componentId: comp.id, sourceId: cp.sourceId, + categoryCode: cp.categoryCode, }); } return out; diff --git a/src/plan/toWalls3d.test.ts b/src/plan/toWalls3d.test.ts index f29c91fb..00fdd0f4 100644 --- a/src/plan/toWalls3d.test.ts +++ b/src/plan/toWalls3d.test.ts @@ -1086,13 +1086,15 @@ describe("VW-fein-Öffnungsdetails: Fensterbank, DIN-Symbole, verschachtelte Fl expect(s.positions[i]).toBeLessThanOrEqual(0.9 + 1e-6); } } - // sillBoard-Gating: "keine"/"innen" -> keine Bank; "aussen"/"beide" -> Bank. + // sillBoard-Gating: "keine" -> keine Bank; "aussen" -> Aussenbank (2 Meshes: + // Bank+Tropfkante); "innen" -> Innenbank (1 Mesh, keine Tropfkante, s. eigener + // Test unten); "beide" -> beide zusammen (3 Meshes). const count = (sb: "keine" | "innen" | "aussen" | "beide"): number => projectToModel3d(winProject({ ...baseWin, id: `win-sb-${sb}`, sillBoard: sb })).meshes.filter(isSill).length; expect(count("keine")).toBe(0); - expect(count("innen")).toBe(0); + expect(count("innen")).toBe(1); expect(count("aussen")).toBe(2); - expect(count("beide")).toBe(2); + expect(count("beide")).toBe(3); // DetailLevel: grob -> keine Bank; mittel/fein -> Bank. const byDetail = (detail: "grob" | "mittel" | "fein"): number => projectToModel3d(pDefault, { detail }).meshes.filter(isSill).length; @@ -1101,6 +1103,39 @@ describe("VW-fein-Öffnungsdetails: Fensterbank, DIN-Symbole, verschachtelte Fl expect(byDetail("fein")).toBe(2); }); + it("Innen-Fensterbank (Ablage): eigenes Band auf der GEGENÜBERLIEGENDEN Seite der Aussenbank, ohne Tropfkante", () => { + // "innen" -> genau 1 Band (keine Tropfkante, das ist eine Aussen-Witterungskante). + const innerOnly = projectToModel3d(winProject({ ...baseWin, id: "win-innen", sillBoard: "innen" })).meshes.filter( + isSill, + ); + expect(innerOnly.length).toBe(1); + // "beide" -> 3 Bänder (2 aussen: Bank+Tropfkante, 1 innen: Bank). + const both = projectToModel3d(winProject({ ...baseWin, id: "win-beide", sillBoard: "beide" })).meshes.filter( + isSill, + ); + expect(both.length).toBe(3); + // Die Innenbank liegt auf der GEGENÜBERLIEGENDEN Seite der Wandachse (y-Vorzeichen + // umgekehrt) zur Aussenbank — unabhängig von der konkreten Achsen-Konvention der + // Wand robust geprüft (relativ zueinander statt ein hartes Vorzeichen anzunehmen). + const outerOnly = projectToModel3d(winProject({ ...baseWin, id: "win-aussen", sillBoard: "aussen" })).meshes.filter( + isSill, + ); + const avgY = (meshes: typeof outerOnly): number => { + let sum = 0; + let n = 0; + for (const m of meshes) { + for (let i = 1; i < m.positions.length; i += 3) { + sum += m.positions[i]; + n++; + } + } + return sum / n; + }; + const outerY = avgY(outerOnly); + const innerY = avgY(innerOnly); + expect(Math.sign(outerY)).not.toBe(Math.sign(innerY)); + }); + it("DIN-Öffnungssymbole: nur fein, nur je NICHT-festem Flügel; Dreh=V, Kipp=V, Dreh-Kipp=beide", () => { // Dreh-Kipp (öffenbar): Dreh (2 Diagonalen) + Kipp (2 Diagonalen) = 4 Symbol-Boxen. const pDrehkipp = winProject({ ...baseWin, id: "win-drehkipp", kind: "drehkipp" }); @@ -1259,6 +1294,63 @@ describe("VW-fein-Öffnungsdetails: Fensterbank, DIN-Symbole, verschachtelte Fl expect(projectToModel3d(doorProject("zarge"), { detail: "grob" }).meshes.filter(isFrame).length).toBe(0); expect(projectToModel3d(doorProject("zarge"), { detail: "mittel" }).meshes.filter(isFrame).length).toBe(9); }); + + it("Echtes Schwellenprofil: nur Tür mit `threshold`, eigenes SILL_RGB-Band über die Wanddicke", () => { + // frameKind explizit "blockrahmen" (kein Zargen-Umgriff) — hält den Test + // unabhängig vom Umgriff-Fund oben (dessen Bekleidungs-Riegel sind + // ebenfalls FRAME_RGB und würden die y-Spanne verfälschen). + const doorProject = (threshold?: boolean): Project => ({ + ...sampleProject, + doorTypes: [ + { + id: "door-threshold-test", + name: "Test Schwelle", + kind: "dreh", + leafCount: 1, + leafStyle: "glatt", + frameThickness: 0.05, + frameKind: "blockrahmen", + frameWidth: 0.06, + defaultWidth: 0.9, + defaultHeight: 2.0, + threshold, + }, + ], + openings: [ + { + id: "DTH", + type: "opening", + hostWallId: "W1", + categoryCode: "31", + kind: "door", + typeId: "door-threshold-test", + position: 3.0, + width: 0.9, + height: 2.0, + sillHeight: 0, + }, + ], + doors: [], + context: [], + }); + // Ohne threshold: der Blendrahmen-Riegel (FRAME_RGB) fehlt bereits (hasSill + // folgt derselben Bedingung) UND das neue Schwellenprofil (SILL_RGB) auch. + expect(projectToModel3d(doorProject(false)).meshes.filter(isSill).length).toBe(0); + // Mit threshold: genau EIN zusätzliches SILL_RGB-Band — additiv zum + // (weiterhin FRAME_RGB-farbenen) Blendrahmen-Riegel, nicht dessen Ersatz. + const withThreshold = projectToModel3d(doorProject(true)).meshes.filter(isSill); + expect(withThreshold.length).toBe(1); + // Nur mittel/fein (detailBodies-Gating wie bei der Fensterbank), nicht grob. + expect(projectToModel3d(doorProject(true), { detail: "grob" }).meshes.filter(isSill).length).toBe(0); + expect(projectToModel3d(doorProject(true), { detail: "mittel" }).meshes.filter(isSill).length).toBe(1); + // Das Profil überspannt die GANZE Wanddicke (nicht nur die Rahmentiefe, + // die bei „aw" 0.07 m beträgt) — W1 ist die 0.345-m-Aussenwand. + const sillYs: number[] = []; + for (const m of withThreshold) { + for (let i = 1; i < m.positions.length; i += 3) sillYs.push(m.positions[i]); + } + expect(Math.max(...sillYs) - Math.min(...sillYs)).toBeCloseTo(0.345, 6); + }); }); describe("Per-Schicht-Decken-Dominanz Wand/Decke (3D-Entsprechung der Schnitt-Boolean-Dominanz)", () => { @@ -1838,6 +1930,165 @@ describe("Wand-Joins im 3D (L-/T-Stösse, identisch zum 2D-Grundriss/Schnitt)", }); }); +describe("Wand-Referenzlinie (referenceLine) im Standard-3D — Achsversatz", () => { + // Bug bis 2026-08-30: `resolveWallBands` zentrierte den Schichtstapel immer + // auf die Wandachse, unabhängig von `Wall.referenceLine`/`referenceOffset` — + // obwohl der 2D-Plan UND die Gehrungs-/Anschluss-Cuts an Ecken + // (`model/joins.ts::miterLine`) den Versatz längst berücksichtigten. Eine + // Wand mit `referenceLine:"left"`/`"right"` sass dadurch im Standard-3D + // mittig, obwohl ihre Ecken schon versetzt geschnitten waren. + const withRef = (referenceLine: Wall["referenceLine"]): Project => ({ + ...sampleProject, + walls: sampleProject.walls.map((w) => (w.id === "W1" ? { ...w, referenceLine } : w)), + }); + // Die render-ext-Schicht (0.02 m dick) ist wie im Join-Test oben eindeutig + // über ihre Dicke identifizierbar, unabhängig von Eck-Gehrung (die betrifft + // nur die Achsen-/x-Ausdehnung, nicht den Quer-/y-Versatz). + const outerBandY = (p: Project): number => { + const w1 = projectToWalls3d(p, true).filter((w) => w.wallId === "W1"); + const outer = w1.find((s) => Math.abs(s.thickness - 0.02) < 1e-9)!; + expect(outer.start[1]).toBeCloseTo(outer.end[1], 9); // W1 ist achsparallel zu Welt-x + return outer.start[1]; + }; + + it("'left'/'right' verschieben den Schichtstapel um ±die halbe Wanddicke gegenüber 'center'", () => { + const centerY = outerBandY(withRef(undefined)); + const leftY = outerBandY(withRef("left")); + const rightY = outerBandY(withRef("right")); + // aw-Wandtyp (W1): Gesamtdicke 0.345 m -> halbe Dicke 0.1725 m Versatz. + expect(leftY - centerY).toBeCloseTo(0.1725, 6); + expect(centerY - rightY).toBeCloseTo(0.1725, 6); + }); + + it("freier `referenceOffset` übersteuert die benannte Referenzlinie 1:1", () => { + const centerY = outerBandY(withRef(undefined)); + const p: Project = { + ...sampleProject, + walls: sampleProject.walls.map((w) => (w.id === "W1" ? { ...w, referenceOffset: 0.05 } : w)), + }; + expect(outerBandY(p) - centerY).toBeCloseTo(0.05, 6); + }); +}); + +describe("emitStairs — Trittkanten-Nase (nosing) im WASM-Default-3D", () => { + // Feld existierte im Modell + der ResourceManager-UI, wurde aber vom + // WASM/wgpu-Default-Renderer nie gelesen (nur der Three.js-Fallback-Pfad + // las es) — hier ans Default-3D nachgezogen (s. PENDENZEN.md). + const stairType = ( + structure: "wange" | "massiv", + nosing?: number, + ): NonNullable[number] => ({ + id: "st-nosing-test", + name: "Test Nase", + structure, + closedRisers: false, + treadThickness: 0.04, + nosing, + defaultWidth: 1.0, + }); + const stairProject = (structure: "wange" | "massiv", nosing?: number): Project => ({ + ...sampleProject, + stairTypes: [stairType(structure, nosing)], + stairs: [ + { + id: "STN", + type: "stair", + floorId: "eg", + categoryCode: "40", + shape: "straight", + typeId: "st-nosing-test", + start: { x: 3.7, y: 0.4 }, + dir: { x: 0, y: 1 }, + runLength: 3.2, + width: 1.0, + totalRise: 2.6, + stepCount: 15, + up: true, + }, + ], + }); + // Y-Spanne (Lauf-/Nase-Achse, `dir={0,1}`) des ERSTEN Tritts (hat immer + // einen Nachfolger, damit die Vorderkante eindeutig bestimmt ist). + const firstTreadYExtent = (p: Project): number => { + const { slabs } = projectToModel3d(p); + const ownSlabs = slabs.filter((s) => s.ceilingId === "STN"); + const ys = ownSlabs[0].outline.map(([, y]) => y); + return Math.max(...ys) - Math.min(...ys); + }; + + it("offene Tragart (wange) + nosing: die Tritt-Vorderkante wird um `nosing` verlängert", () => { + const without = firstTreadYExtent(stairProject("wange", 0)); + const withNosingV = firstTreadYExtent(stairProject("wange", 0.05)); + expect(withNosingV).toBeCloseTo(without + 0.05, 3); + }); + + it("massiv ignoriert nosing (Vollblock hat keinen sichtbaren Trittkanten-Vorstand)", () => { + const a = firstTreadYExtent(stairProject("massiv", 0)); + const b = firstTreadYExtent(stairProject("massiv", 0.05)); + expect(b).toBeCloseTo(a, 6); + }); +}); + +describe("emitStairs — geschlossene Setzstufen (closedRisers) im WASM-Default-3D", () => { + // Derselbe Bug-Typ wie bei `nosing` oben: Feld existierte im Modell + der + // ResourceManager-UI, wurde aber vom WASM/wgpu-Default-Renderer nie gelesen. + const stairType = ( + structure: "wange" | "massiv", + closedRisers: boolean, + ): NonNullable[number] => ({ + id: "st-riser-test", + name: "Test Setzstufe", + structure, + closedRisers, + treadThickness: 0.04, + defaultWidth: 1.0, + }); + const stairProject = (structure: "wange" | "massiv", closedRisers: boolean): Project => ({ + ...sampleProject, + stairTypes: [stairType(structure, closedRisers)], + stairs: [ + { + id: "STR", + type: "stair", + floorId: "eg", + categoryCode: "40", + shape: "straight", + typeId: "st-riser-test", + start: { x: 3.7, y: 0.4 }, + dir: { x: 0, y: 1 }, + runLength: 3.2, + width: 1.0, + totalRise: 2.6, + stepCount: 15, + up: true, + }, + ], + }); + const ownSlabs = (p: Project) => projectToModel3d(p).slabs.filter((s) => s.ceilingId === "STR"); + + it("offene Tragart (wange) + closedRisers: eine zusätzliche dünne Setzstufen-Platte je Tritt", () => { + // Ohne: nur die Tritt-Platten (15). Mit: zusätzlich 15 Setzstufen-Platten = 30. + expect(ownSlabs(stairProject("wange", false)).length).toBe(15); + const withRisers = ownSlabs(stairProject("wange", true)); + expect(withRisers.length).toBe(30); + // Jede Setzstufen-Platte überspannt vertikal GENAU eine Steighöhe + // (baseRise..topRise desselben Tritts); Tritt-Platten sind dünn + // (treadThickness=0.04) — beide Sorten unterscheidbar am Span. + const riserHeight = 2.6 / 15; + for (const s of withRisers) { + const span = s.zTop - s.zBottom; + const isRiserSpan = Math.abs(span - riserHeight) < 1e-6; + const isTreadSpan = Math.abs(span - 0.04) < 1e-6; + expect(isRiserSpan || isTreadSpan).toBe(true); + } + }); + + it("massiv ignoriert closedRisers (Vollblock hat schon eine geschlossene Front)", () => { + expect(ownSlabs(stairProject("massiv", false)).length).toBe(15); + expect(ownSlabs(stairProject("massiv", true)).length).toBe(15); + }); +}); + describe("emitStairMeshes (Betontreppe: glatte Laufplatte als Mesh)", () => { it("gerade Betontreppe -> Mesh mit 8 Ecken je Tritt, glatte schräge Untersicht", () => { // Sample-Treppe ST1: Typ "stair-standard" (Tragart "beton"), gerade, @@ -1911,6 +2162,23 @@ describe("emitRoofs (Dachflächen + Giebel als Meshes)", () => { expect(Math.max(...allHeights)).toBeCloseTo(expectedRidgeZ, 6); }); + it("emitRoofCutLayers: eine Eingabe je (Schicht, geneigte Fläche) für den 3D-Live-Schnitt", () => { + // Satteldach: 2 geneigte Flächen (g.planes), einschichtig (thickness-Fallback) + // -> genau 2 RoofLayer-Einträge (kein zusammengefasstes Mesh wie bei emitRoofs). + const project: Project = { ...sampleProject, roofs: [baseRoof] }; + const { roofLayers } = projectToModel3d(project); + expect(roofLayers.length).toBe(2); + for (const layer of roofLayers) { + expect(layer.polygon.length).toBeGreaterThanOrEqual(3); + expect(layer.polygon.every((p) => p.every((v) => Number.isFinite(v)))).toBe(true); + // Normale ist normalisiert (Länge ≈ 1). + const [nx, ny, nz] = layer.normal; + expect(Math.hypot(nx, ny, nz)).toBeCloseTo(1, 5); + expect(layer.thickness).toBeCloseTo(baseRoof.thickness!, 6); + expect(layer.color).toEqual(ROOF_RGB); + } + }); + it("Dach mit Bauteil-Material (roofTypeId) bekommt eine Textur-Ebene (Stil 'Textured')", () => { // Vorher waren Dächer im Textured-Modus IMMER auf das Fallback-Schachbrett // geklemmt (Nutzer-Report: "Dach soll wie Dachziegel aussehen, nicht so diff --git a/src/plan/toWalls3d.ts b/src/plan/toWalls3d.ts index d01cf702..8a1a5994 100644 --- a/src/plan/toWalls3d.ts +++ b/src/plan/toWalls3d.ts @@ -69,7 +69,7 @@ import { emitStairMeshes, emitStairs } from "./toWalls3d/stairs"; import { emitExtrudedSolids, TRUCK_MESH_READY_EVENT } from "./toWalls3d/extrusions"; import { emitDrawingLines } from "./toWalls3d/drawing2d"; import { emitColumns } from "./toWalls3d/columns"; -import { emitRoofs } from "./toWalls3d/roofs"; +import { emitRoofCutLayers, emitRoofs } from "./toWalls3d/roofs"; import { emitLegacyDoorLeaves, emitOpeningFrames, emitOpeningGlass, emitOpeningShading } from "./toWalls3d/openings"; // Re-Export des gemeinsamen Vokabulars — externe Konsumenten (viewport/, @@ -210,6 +210,10 @@ export function projectToModel3d(project: Project, opts: Model3dOptions = {}): R ...emitStairMeshes(project), ...emitRoofs(project), ], + // Dach-Schicht-Eingabe für den 3D-Live-Schnitt (render3d::roof_cut) — s. + // Kopfkommentar bei `RRoofLayer`/`emitRoofCutLayers`: getrennt von `meshes`, + // weil `section.rs` beliebige Dreiecksnetze nicht schneiden kann. + roofLayers: emitRoofCutLayers(project), }; } diff --git a/src/plan/toWalls3d/bands.ts b/src/plan/toWalls3d/bands.ts index 79c781a7..bcb4d48d 100644 --- a/src/plan/toWalls3d/bands.ts +++ b/src/plan/toWalls3d/bands.ts @@ -22,7 +22,7 @@ import { roofLayers, wallTypeThickness, } from "../../model/types"; -import { ceilingVerticalExtent, wallVerticalExtent } from "../../model/wall"; +import { ceilingVerticalExtent, wallReferenceOffset, wallVerticalExtent } from "../../model/wall"; import { pointInOutline } from "../../geometry/ceiling"; import { openingInterval, openingVerticalExtent } from "../../geometry/opening"; import { roofBaseElevation, roofGeometry, roofUndersideAt } from "../../geometry/roof"; @@ -112,11 +112,19 @@ function bandCutMeta(b: WallBand): RCutMeta | undefined { /** * Löst den Schichtstapel EINER Wand auf: je Materiallage ein {@link WallBand} * mit ihrer Dicke, Component-Farbe und dem Mitten-Versatz entlang der Normalen. - * Die Versätze zentrieren den Stapel um die Wandachse; als Gesamtdicke T dient - * die SUMME der tatsächlichen Lagen-Dicken (nicht `wallTypeThickness`, falls es + * Die Versätze zentrieren den Stapel um die Wandachse UND verschieben ihn um + * {@link wallReferenceOffset} (`Wall.referenceLine`/`referenceOffset` — links/ + * Mitte/rechts/frei), damit die Achse bei „außen"/„innen" tatsächlich auf der + * gewählten Wandfläche liegt statt immer mittig — dieselbe Grösse, die der 2D- + * Plan (`generatePlan/walls.ts`) UND die Gehrungs-/Anschluss-Cuts an Ecken + * (`model/joins.ts::miterLine`) bereits verwenden. Bis 2026-08-30 rechnete + * dieser Pfad NICHT damit (Bug: Wände mit `referenceLine !== "center"` sassen + * im Standard-3D mittig, obwohl die Eckenverschneidung schon den Versatz + * annahm → Geraden und Ecken liefen auseinander). Als Gesamtdicke T dient die + * SUMME der tatsächlichen Lagen-Dicken (nicht `wallTypeThickness`, falls es * abweicht) — so schließen die Bänder lückenlos aneinander an. Kein auflösbarer * WallType / keine Lagen ⇒ EIN Vollkörper-Band über die volle Dicke im - * neutralen Grundton (heutiges Fallback-Verhalten). + * neutralen Grundton (heutiges Fallback-Verhalten), ebenfalls Referenz-versetzt. */ function resolveWallBands(project: Project, wall: Wall, layered = true): WallBand[] { try { @@ -125,6 +133,7 @@ function resolveWallBands(project: Project, wall: Wall, layered = true): WallBan // Gesamtdicke = Summe der Lagen (konsistent mit den Offsets); wenn diese // von wallTypeThickness abwiche, gewinnt die Lagen-Summe (keine Lücken). const total = wt.layers.reduce((s, l) => s + l.thickness, 0); + const refOff = wallReferenceOffset(wall, total); // Schnitt-Eingabe (layered=false): EINE Voll-Box über die ganze Dicke statt // je Lage eine Box. So bleibt die Emission 1:1 Wand→Rechteck — passend zu // `wallSegmentOwners`/`splitWallLayers` in toSection.ts, die die Schicht- @@ -136,7 +145,7 @@ function resolveWallBands(project: Project, wall: Wall, layered = true): WallBan { thickness: total, color: dominantLayerColor(wt.layers, project, WALL_RGB), - offset: 0, + offset: refOff, hatch: dominantLayerHatch(wt.layers, project, SECTION_WALL_AXIS_ANGLE_DEG), materialIndex: resolveComponentMaterialLayer(project, dominant.componentId), }, @@ -151,7 +160,7 @@ function resolveWallBands(project: Project, wall: Wall, layered = true): WallBan bands.push({ thickness: l.thickness, color, - offset: -total / 2 + prefix + l.thickness / 2, + offset: refOff - total / 2 + prefix + l.thickness / 2, priority: comp.joinPriority, componentId: comp.id, cutLineColor: lineStyle?.color, @@ -164,10 +173,12 @@ function resolveWallBands(project: Project, wall: Wall, layered = true): WallBan return bands; } // WallType ohne Schichten: EIN Vollkörper über die Typ-Gesamtdicke. - return [{ thickness: wallTypeThickness(wt), color: WALL_RGB, offset: 0 }]; + const total = wallTypeThickness(wt); + return [{ thickness: total, color: WALL_RGB, offset: wallReferenceOffset(wall, total) }]; } catch { // Kein auflösbarer WallType: EIN Vollkörper mit Default-Dicke/Grundton. - return [{ thickness: 0.2, color: WALL_RGB, offset: 0 }]; + const total = 0.2; + return [{ thickness: total, color: WALL_RGB, offset: wallReferenceOffset(wall, total) }]; } } diff --git a/src/plan/toWalls3d/openings.ts b/src/plan/toWalls3d/openings.ts index ea3eef81..2b050b22 100644 --- a/src/plan/toWalls3d/openings.ts +++ b/src/plan/toWalls3d/openings.ts @@ -281,11 +281,29 @@ interface OpeningFrameParams { * (fehlt ⇒ zeichnen, wie in der 2D-Ansicht). Türen: nie. */ drawSill: boolean; + /** + * Innen-Fensterbank zeichnen: nur Fenster mit `sillBoard` === "innen"/"beide". + * Gegenstück zu {@link drawSill} auf der Wand-Innenfläche (kein Überstand/ + * keine Tropfkante — das ist eine reine Innenausbau-Ablage, keine + * Witterungskante). Türen: nie. + */ + drawInteriorSill: boolean; /** * Zargen-Umgriff (Bekleidung VOR beiden Wandflächen) zeichnen: nur Türen mit * `frameKind === "zarge"`. Blockrahmen bleibt bündig (false). */ zargeCladding: boolean; + /** + * Echtes Schwellenprofil (dünne, farblich abgesetzte Leiste über die GANZE + * Wanddicke am Fussboden, analog zur Fensterbank-Leiste) zeichnen: nur + * Türen mit `threshold === true`. Zusätzlich zum bisherigen, strukturellen + * Blendrahmen-Riegel ({@link hasSill}) — der bleibt unverändert (steuert + * weiterhin, wo der Flügel-/Blatt-Bereich beginnt), das Profil kommt als + * eigenständiges, sichtbar unterscheidbares Bauteil obendrauf, nicht als + * dessen Ersatz. Fenster: nie (ihre Schwelle ist die `hasSill`-Sohlbank, + * kein Bodenanschlag). + */ + drawThresholdProfile: boolean; } function resolveOpeningFrame(project: Project, wall: Wall, op: Opening): OpeningFrameParams | null { @@ -319,8 +337,10 @@ function resolveOpeningFrame(project: Project, wall: Wall, op: Opening): Opening sashes: [], halfThickness, drawSill: false, + drawInteriorSill: false, // Zarge umgreift die Wand (Bekleidung auf beiden Flächen); Blockrahmen bleibt bündig. zargeCladding: (dt.frameKind ?? "zarge") === "zarge", + drawThresholdProfile: dt.threshold === true, }; } const wt = getWindowType(project, op); @@ -365,7 +385,10 @@ function resolveOpeningFrame(project: Project, wall: Wall, op: Opening): Opening halfThickness, // Fensterbank zeichnen, ausser explizit "keine"/"innen" (fehlt ⇒ zeichnen). drawSill: wt.sillBoard !== "keine" && wt.sillBoard !== "innen", + // Innen-Fensterbank nur bei explizit "innen"/"beide". + drawInteriorSill: wt.sillBoard === "innen" || wt.sillBoard === "beide", zargeCladding: false, + drawThresholdProfile: false, }; } @@ -420,6 +443,24 @@ function frameMeshesForOpening( push(iv.from + fw, iv.to - fw, vert.zTop - fw, vert.zTop); // Schwelle: Fenster immer, Tür nur mit Bodenanschlag (threshold). if (params.hasSill) push(iv.from + fw, iv.to - fw, vert.zBottom, vert.zBottom + fw); + // Echtes Schwellenprofil (Tür, `threshold`): eine dünne, farblich abgesetzte + // Leiste ÜBER DIE GANZE WANDDICKE am Fussboden (nicht nur die Rahmentiefe + // wie der Blendrahmen-Riegel oben) — analog zur Fensterbank-Leiste + // (SILL_RGB statt FRAME_RGB), zeigt den realen Bodenanschlag (Stein/Metall- + // Streifen) statt eines rahmenfarbenen Riegels. Zusätzlich zum bestehenden + // Riegel, nicht dessen Ersatz (der bleibt für die Flügel-/Blatt-Z-Basis unten). + if (detailBodies && params.drawThresholdProfile) { + const stripH = 0.02; // Schwellen-Dicke + pushC( + iv.from + fw, + iv.to - fw, + vert.zBottom, + vert.zBottom + stripH, + -params.halfThickness, + params.halfThickness, + SILL_RGB, + ); + } // Flügel-/Sash-Bereich zwischen Schwelle und Sturz, ggf. durch den Kämpfer // (Oberlicht-Trennung) oben beschnitten. @@ -560,6 +601,21 @@ function frameMeshesForOpening( pushC(iv.from - ov, iv.to + ov, bankBottom - dripH, bankBottom, outerN + proj - dripW, outerN + proj, SILL_RGB); } + // Innen-Fensterbank (Ablage, VW „fein"/„mittel"): wie die Aussenbank + // gespiegelt auf die Wand-INNENfläche, aber ohne Tropfkante (reine + // Innenausbau-Ablage, keine Witterungskante) — `params.drawInteriorSill` + // (sillBoard "innen"/"beide"). + if (detailBodies && params.drawInteriorSill) { + const ov = 0.03; + const proj = 0.04; + const under = 0.02; + const bankH = 0.04; + const innerN = -params.halfThickness; // Wand-Innenfläche + const bankTop = vert.zBottom; + const bankBottom = bankTop - bankH; + pushC(iv.from - ov, iv.to + ov, bankBottom, bankTop, innerN - proj, innerN + under, SILL_RGB); + } + // Tür-Zarge mit Umgriff (VW): die Zarge umgreift die Wand — eine schmale // Bekleidungs-Platte VOR beiden Wandflächen, als Ring (Pfosten links/rechts + // Sturz) rund um die Öffnung, ~1.3 cm vor die Fläche vorstehend. Nur diff --git a/src/plan/toWalls3d/roofs.ts b/src/plan/toWalls3d/roofs.ts index 2a4aac7e..4685957a 100644 --- a/src/plan/toWalls3d/roofs.ts +++ b/src/plan/toWalls3d/roofs.ts @@ -7,7 +7,16 @@ import type { Project } from "../../model/types"; import { getComponent, roofLayers } from "../../model/types"; import { roofBaseElevation, roofGeometry } from "../../geometry/roof"; import type { Vec3 as RoofVec3 } from "../../geometry/roof"; -import { EPS, hexToRgb, resolveComponentMaterialLayer, type RMesh, type RRgb } from "./shared"; +import { + EPS, + hexToRgb, + resolveComponentMaterialLayer, + resolveCutLineStyle, + type RCutMeta, + type RMesh, + type RRgb, + type RRoofLayer, +} from "./shared"; /** Warmer Terrakotta-Grauton für Dachflächen/-giebel — hebt das Dach klar von Wand/Decke/Kontext ab. */ const ROOF_RGB: RRgb = [0.72, 0.45, 0.36]; @@ -145,3 +154,48 @@ export function emitRoofs(project: Project): RMesh[] { } return out; } + +/** + * Baut die Dach-Schicht-Eingabe für den 3D-Live-Schnitt (`RRoofLayer[]`, + * `render3d::roof_cut::cut_roof_layer`) — GETRENNT von {@link emitRoofs} (dem + * Render-Mesh), weil `section.rs` beliebige Dreiecksnetze nicht schneiden + * kann (nur Wand-Boxen/Decken-Polygone; eine Dachfläche ist kein vertikales + * Prisma, s. `RRoofLayer`-Doc in `shared.ts`). EIN Eintrag je (Dach, Schicht, + * geneigte Fläche) — ein mehrflächiges Dach (Sattel/Walm/Mansarde) hat + * mehrere `g.planes`, jede mit ihrer eigenen Normalen, anders als beim + * gemeinsam tessellierten Render-Mesh also KEIN zusammengefasster Eintrag. + * Punkte/Normalen bleiben in MODELL-Metern (wie `emitRoofs`) — render3d macht + * den Modell->Welt-Wechsel selbst (dieselbe Konvention wie `RMesh`). + */ +export function emitRoofCutLayers(project: Project): RRoofLayer[] { + const out: RRoofLayer[] = []; + for (const roof of project.roofs ?? []) { + const eavesZ = roofBaseElevation(project, roof); + const g = roofGeometry(roof, eavesZ); + const overrideColor = roof.color ? hexToRgb(roof.color, ROOF_RGB) : null; + const layers = roofLayers(project, roof); + layers.reduce((offsetAbove, layer) => { + const t = Math.max(0, layer.thickness); + if (t <= EPS) return offsetAbove; + const color = + overrideColor ?? + (layer.componentId ? hexToRgb(getComponent(project, layer.componentId).color, ROOF_RGB) : ROOF_RGB); + const lineStyle = resolveCutLineStyle(project, layer.jointLineStyleId); + const cut: RCutMeta | undefined = + lineStyle && (lineStyle.color !== undefined || lineStyle.weight !== undefined) + ? { lineColor: lineStyle.color, lineWeight: lineStyle.weight } + : undefined; + for (const plane of g.planes) { + const nrm = planeNormalUp(plane.pts); + const top: RoofVec3[] = plane.pts.map((p) => [ + p[0] - nrm[0] * offsetAbove, + p[1] - nrm[1] * offsetAbove, + p[2] - nrm[2] * offsetAbove, + ]); + out.push({ polygon: top, normal: nrm, thickness: t, color, cut }); + } + return offsetAbove + t; + }, 0); + } + return out; +} diff --git a/src/plan/toWalls3d/shared.ts b/src/plan/toWalls3d/shared.ts index 16b50de5..71e4de96 100644 --- a/src/plan/toWalls3d/shared.ts +++ b/src/plan/toWalls3d/shared.ts @@ -10,6 +10,7 @@ import type { HatchPattern, Layer, Project } from "../../model/types"; import { getCeilingType, getComponent, getWallType, roofLayers } from "../../model/types"; import { resolveHatch } from "../generatePlan"; +import type { Vec3 as RoofVec3 } from "../../geometry/roof"; export type RVec2 = [number, number]; export type RRgb = [number, number, number]; @@ -313,11 +314,39 @@ export interface RMesh { materialIndex?: number; } +/** + * EINE Dachflächen-Schicht für den 3D-Live-Schnitt (`render3d::types:: + * RoofLayerInput`/`roof_cut::cut_roof_layer`) — GETRENNT vom Render-Mesh + * ({@link RMesh}, `kind:"extrusion"`), weil `section.rs` kein beliebiges + * Dreiecksnetz schneiden kann (nur Wand-Boxen/Decken-Polygone, s. dessen + * Moduldoc „jedes Bauteil ist ein vertikales Prisma"). Eine Dachfläche ist + * KEIN vertikales Prisma (geneigtes Polygon, entlang der eigenen Normalen + * statt vertikal extrudiert) — daher dieser eigene, parallele Eingabetyp statt + * Wiederverwendung von `RWall`/`RSlab`. + */ +export interface RRoofLayer { + /** Eckpunkte der OBERSEITE dieser Schicht (näher am First/aussen), Welt-Meter. */ + polygon: RoofVec3[]; + /** Nach aussen/oben zeigende Flächennormale (normalisiert) — identisch zu + * der Normalen, mit der {@link RMesh} für dieselbe Schicht gebaut wird + * (`planeNormalUp`), damit Render-Mesh und Schnitt-Geometrie nicht + * auseinanderlaufen. */ + normal: RoofVec3; + /** Schichtdicke (Meter), Extrusion entlang `-normal`. */ + thickness: number; + color: RRgb; + hatch?: RHatch; + cut?: RCutMeta; +} + /** Modell-Bündel für den nativen 3D-Renderer (Wände + Decken + Kontext-Meshes). */ export interface RModel3d { walls: RWall[]; slabs: RSlab[]; meshes: RMesh[]; + /** Dach-Schichten für den Live-Schnitt (s. {@link RRoofLayer}) — separat von + * `meshes`, da render3d sie über einen eigenen Pfad schneidet. */ + roofLayers: RRoofLayer[]; } /** Warmer, neutraler Wand-Grundton (wie render3d default). */ diff --git a/src/plan/toWalls3d/stairs.ts b/src/plan/toWalls3d/stairs.ts index c0b318d7..7621771f 100644 --- a/src/plan/toWalls3d/stairs.ts +++ b/src/plan/toWalls3d/stairs.ts @@ -16,6 +16,101 @@ const STAIR_RGB: RRgb = hexToRgb("#9aa0a6", SLAB_RGB); /** Laufplattendicke einer Ortbetontreppe (Meter). */ const CONCRETE_WAIST = 0.18; +/** Schwerpunkt eines Tritt-Polygons (Grundriss). */ +function centroidOf(pts: Vec2[]): Vec2 { + let x = 0, y = 0; + for (const p of pts) { x += p.x; y += p.y; } + return { x: x / pts.length, y: y / pts.length }; +} + +/** + * Bestimmt die "vordere" Kante eines Tritt-Vielecks (die Kante in Richtung + * des nächsten Tritts) — für die Nasen-Verlängerung ({@link StairType.nosing}). + * `target` ist der Schwerpunkt eines Nachbartritts; `preferNear` wählt die dem + * Ziel NÄCHSTE Kante (Nachbar = nächster Tritt), sonst die FERNSTE (Nachbar = + * vorheriger Tritt, Vorderkante liegt entgegengesetzt). Liefert die Indizes + * der beiden Eckpunkte der Vorderkante + deren Richtung (Trittschwerpunkt → + * Kantenmitte, normiert). Wortgetreu portiert vom Three.js-Pfad + * (`viewport/viewport3d/meshBuilders.ts::frontEdgeOf`), wo dieselbe Logik + * bereits für `nosing` verwendet wird. + */ +function frontEdgeOf( + pts: Vec2[], + target: Vec2, + preferNear: boolean, +): { a: number; b: number; dir: Vec2 } { + const c = centroidOf(pts); + let best = 0; + let bestDist = preferNear ? Infinity : -Infinity; + for (let e = 0; e < pts.length; e++) { + const p0 = pts[e]; + const p1 = pts[(e + 1) % pts.length]; + const mid = { x: (p0.x + p1.x) / 2, y: (p0.y + p1.y) / 2 }; + const d = Math.hypot(mid.x - target.x, mid.y - target.y); + if (preferNear ? d < bestDist : d > bestDist) { + bestDist = d; + best = e; + } + } + const p0 = pts[best]; + const p1 = pts[(best + 1) % pts.length]; + const mid = { x: (p0.x + p1.x) / 2, y: (p0.y + p1.y) / 2 }; + const dx = mid.x - c.x; + const dy = mid.y - c.y; + const len = Math.hypot(dx, dy) || 1e-9; + return { a: best, b: (best + 1) % pts.length, dir: { x: dx / len, y: dy / len } }; +} + +/** + * Verlängert die Vorderkante eines Tritts um `nosing` Meter (Trittkanten- + * Überstand/Nase, {@link StairType.nosing}) — nur bei OFFENEN Tragarten + * sinnvoll (dünne Tritt-Platte mit sichtbarem Vorstand vor der Setzstufe + * darunter), daher nur aus dem `structure !== "massiv"`-Zweig aufgerufen. + */ +function withNosing(pts: Vec2[], neighbors: Vec2[][], k: number, nosing: number): Vec2[] { + if (nosing <= 1e-6) return pts; + const hasNext = k + 1 < neighbors.length; + const hasPrev = k > 0; + const ref = hasNext ? neighbors[k + 1] : hasPrev ? neighbors[k - 1] : null; + if (!ref) return pts; + const { a, b, dir } = frontEdgeOf(pts, centroidOf(ref), hasNext); + const nosed = pts.slice(); + nosed[a] = { x: pts[a].x + dir.x * nosing, y: pts[a].y + dir.y * nosing }; + nosed[b] = { x: pts[b].x + dir.x * nosing, y: pts[b].y + dir.y * nosing }; + return nosed; +} + +/** + * Grundriss einer geschlossenen Setzstufen-Platte ({@link StairType.closedRisers}): + * eine DÜNNE Fläche an der RÜCKKante des Tritts `k` (= Vorderkante des + * Vorgängers, Gegenkante zur eigenen Vorderkante), leicht in Vorderkanten- + * Richtung aufgeweitet, damit ein extrudierbares Vieleck entsteht (statt einer + * entarteten Linie). `null`, wenn kein Nachbartritt zur Vorderkanten- + * Bestimmung existiert (Einzeltritt). Wortgetreu portiert vom Three.js-Pfad + * (`meshBuilders.ts::addStairMeshes`), inkl. der Verwendung der ROHEN + * (nicht genasten) Trittpunkte — die Nase betrifft nur die Trittplatte selbst. + */ +function closedRiserOutline( + trPts: Vec2[], + neighbors: Vec2[][], + k: number, + treadThickness: number, +): Vec2[] | null { + const hasNext = k + 1 < neighbors.length; + const ref = hasNext ? neighbors[k + 1] : k > 0 ? neighbors[k - 1] : null; + if (!ref) return null; + const front = frontEdgeOf(trPts, centroidOf(ref), hasNext); + const n = trPts.length; + const backA = (front.a + Math.floor(n / 2)) % n; + const backB = (front.b + Math.floor(n / 2)) % n; + const riserA = trPts[backA]; + const riserB = trPts[backB]; + const thin = Math.min(treadThickness, 0.02) || 0.01; + const offA = { x: riserA.x - front.dir.x * thin, y: riserA.y - front.dir.y * thin }; + const offB = { x: riserB.x - front.dir.x * thin, y: riserB.y - front.dir.y * thin }; + return [riserA, riserB, offB, offA]; +} + /** * Emittiert Treppen als RSlabs (extrudierte Grundriss-Polygone) — der WASM/wgpu- * Renderer kennt sonst KEINE Treppen (nur Wände/Decken/Meshes), sodass Treppen im @@ -29,8 +124,16 @@ const CONCRETE_WAIST = 0.18; * OFFENE Untersicht der klassischen Betontreppe. * • "wange"/"aufgesattelt"/"spindel" — nur eine dünne Tritt-Platte der Dicke * `treadThickness` an der Tritt-OK, darunter offen. - * Podest (L/Wendel) als Vollblock bis zur halben Steighöhe. Setzstufen/Nase/ - * Geländer sind Verfeinerungen (Three.js-Pfad) — hier zählt zuerst die SICHTBARKEIT. + * Podest (L/Wendel) als Vollblock bis zur halben Steighöhe. Bei OFFENEN + * Tragarten (nicht "massiv") wird die Vorderkante jedes Tritts zusätzlich um + * `StairType.nosing` (Trittkanten-Überstand) verlängert und — bei + * `StairType.closedRisers` — eine dünne Setzstufen-Platte an der Rückkante + * ergänzt (sonst bleibt die Treppe dort offen) — wortgetreu wie im Three.js- + * Pfad, hier ans WASM/wgpu-Default-3D nachgezogen (beide Felder waren dort + * unwirksam: existierten im Modell + der ResourceManager-UI, aber der + * Standard-Renderer las sie nie, s. PENDENZEN.md). Geländer sind weiterhin + * eine Verfeinerung (Three.js-Pfad, dort selbst noch als TODO markiert) — + * hier zählt zuerst die SICHTBARKEIT. * `ceilingId` trägt hier die Treppen-Id (nur TS-seitiges Tagging; render3d ignoriert * das Feld, und der Pick läuft separat über `pickGeometry`). */ @@ -48,8 +151,13 @@ export function emitStairs(project: Project): RSlab[] { if (structure === "beton" && stair.shape === "straight") continue; const treadThickness = st?.treadThickness ?? 0.04; const riser = geo.riserHeight; - for (const tr of geo.treads) { + const open = structure !== "massiv"; + const nosing = open ? st?.nosing ?? 0 : 0; + const neighborPts = geo.treads.map((t) => t.pts); + for (let k = 0; k < geo.treads.length; k++) { + const tr = geo.treads[k]; if (tr.pts.length < 3) continue; + const pts = withNosing(tr.pts, neighborPts, k, nosing); const top = zBottom + tr.topRise; const bottom = structure === "massiv" @@ -57,14 +165,27 @@ export function emitStairs(project: Project): RSlab[] { : structure === "beton" ? Math.max(zBottom, top - riser - CONCRETE_WAIST) // schräge Laufplatte : top - treadThickness; // offene Tritte (Wange/aufgesattelt/Spindel) - if (top - bottom <= EPS) continue; - out.push({ - outline: tr.pts.map((p) => [p.x, p.y] as RVec2), - zBottom: bottom, - zTop: top, - color: STAIR_RGB, - ceilingId: stair.id, - }); + if (top - bottom > EPS) { + out.push({ + outline: pts.map((p) => [p.x, p.y] as RVec2), + zBottom: bottom, + zTop: top, + color: STAIR_RGB, + ceilingId: stair.id, + }); + } + if (open && st?.closedRisers) { + const riserOutline = closedRiserOutline(tr.pts, neighborPts, k, treadThickness); + if (riserOutline) { + out.push({ + outline: riserOutline.map((p) => [p.x, p.y] as RVec2), + zBottom: zBottom + tr.baseRise, + zTop: zBottom + tr.topRise, + color: STAIR_RGB, + ceilingId: stair.id, + }); + } + } } if (geo.landing && geo.landing.length >= 3) { out.push({ diff --git a/src/state/projectSlice.penSets.test.ts b/src/state/projectSlice.penSets.test.ts new file mode 100644 index 00000000..44d16d81 --- /dev/null +++ b/src/state/projectSlice.penSets.test.ts @@ -0,0 +1,160 @@ +/** + * Stiftsatz-Aktionen im Projekt-Store (ArchiCAD-Stiftsatz-Muster): das Backen + * (`rebakePenColors`) selbst ist bereits in `model/penSets.test.ts` pur + * getestet — hier geht es um die Store-spezifische Verdrahtung (Auto-Aktivieren + * des ersten Stiftsatzes, Lösch-Schutz für den aktiven Satz, Synchron-Halten + * der `pens`-Liste über alle Stiftsätze bei `addPen`/`deletePen`). + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { getState, setState } from "./appStore"; +import { sampleProject } from "../model/sampleProject"; + +// Alle `addX`-Aktionen dieser Codebase generieren IDs über `Date.now()` +// (bestehende, projektweite Konvention) — mehrere Aufrufe in DERSELBEN +// Millisekunde (wie hier, synchron im selben Test) würden sonst kollidieren. +// Ein simpler Zähler statt echtem `Date.now()` macht jeden Aufruf eindeutig, +// ohne die Produktionslogik anzufassen. +let clock = 0; +beforeEach(() => { + clock = 1_000_000; + vi.spyOn(Date, "now").mockImplementation(() => clock++); + setState({ + project: { ...sampleProject, components: sampleProject.components.slice(0, 1), pens: [], penSets: [], activePenSetId: undefined }, + undoStack: [], + redoStack: [], + canUndo: false, + canRedo: false, + }); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("addPenSet — erster Satz wird automatisch aktiv", () => { + it("aktiviert den ersten je angelegten Stiftsatz automatisch", () => { + getState().addPenSet(); + const p = getState().project; + expect(p.penSets?.length).toBe(1); + expect(p.activePenSetId).toBe(p.penSets![0].id); + }); + + it("aktiviert einen ZWEITEN Satz NICHT automatisch", () => { + getState().addPenSet(); + const firstId = getState().project.activePenSetId; + getState().addPenSet(); + expect(getState().project.activePenSetId).toBe(firstId); + expect(getState().project.penSets?.length).toBe(2); + }); + + it("übernimmt die Farben des aktiven Satzes als Startwert für den neuen", () => { + getState().addPenSet(); + getState().addPen(); + const penId = getState().project.pens![0].id; + getState().patchPenSetColor(getState().project.activePenSetId!, penId, "#ff00ff"); + getState().addPenSet(); + const sets = getState().project.penSets!; + expect(sets[1].pens[penId].color).toBe("#ff00ff"); + }); +}); + +describe("addPen — bleibt über alle Stiftsätze deckungsgleich", () => { + it("legt in JEDEM bestehenden Stiftsatz sofort einen Farbeintrag an", () => { + getState().addPenSet(); + getState().addPenSet(); + getState().addPen(); + const penId = getState().project.pens![0].id; + for (const s of getState().project.penSets!) { + expect(s.pens[penId]).toBeDefined(); + } + }); +}); + +describe("setActivePenSet — bäckt gekoppelte Farben sofort neu", () => { + it("aktualisiert ein Bauteil mit `colorPenId`, sobald der aktive Satz wechselt", () => { + getState().addPenSet(); + getState().addPen(); + const penId = getState().project.pens![0].id; + const setA = getState().project.activePenSetId!; + getState().patchPenSetColor(setA, penId, "#111111"); + getState().addPenSet(); + const setB = getState().project.penSets!.find((s) => s.id !== setA)!.id; + getState().patchPenSetColor(setB, penId, "#222222"); + + const compId = getState().project.components[0].id; + getState().patchComponent(compId, { colorPenId: penId, color: "#111111" }); + expect(getState().project.components[0].color).toBe("#111111"); + + getState().setActivePenSet(setB); + expect(getState().project.components[0].color).toBe("#222222"); + }); +}); + +describe("patchPenSetColor — bäckt nur bei Änderung des AKTIVEN Satzes neu", () => { + it("lässt gekoppelte Farben unverändert, wenn ein NICHT-aktiver Satz editiert wird", () => { + getState().addPenSet(); + getState().addPen(); + const penId = getState().project.pens![0].id; + const activeId = getState().project.activePenSetId!; + getState().patchPenSetColor(activeId, penId, "#aaaaaa"); + const compId = getState().project.components[0].id; + getState().patchComponent(compId, { colorPenId: penId, color: "#aaaaaa" }); + + getState().addPenSet(); + const otherId = getState().project.penSets!.find((s) => s.id !== activeId)!.id; + getState().patchPenSetColor(otherId, penId, "#bbbbbb"); + + expect(getState().project.components[0].color).toBe("#aaaaaa"); + }); +}); + +describe("patchPenSetWeight — bäckt `strokeWeight` einer gekoppelten Wand sofort neu", () => { + it("aktualisiert die Strichstärke, wenn der editierte Satz aktiv ist", () => { + getState().addPenSet(); + getState().addPen(); + const penId = getState().project.pens![0].id; + const activeId = getState().project.activePenSetId!; + const wallId = getState().project.walls[0]?.id ?? sampleProject.walls[0].id; + getState().updateWall(wallId, { colorPenId: penId }); + getState().patchPenSetWeight(activeId, penId, 0.77); + expect(getState().project.walls.find((w) => w.id === wallId)?.strokeWeight).toBe(0.77); + }); +}); + +describe("deletePenSet — Lösch-Schutz für den aktiven Satz", () => { + it("verweigert das Löschen des aktiven Stiftsatzes", () => { + getState().addPenSet(); + const id = getState().project.activePenSetId!; + getState().deletePenSet(id); + expect(getState().project.penSets?.some((s) => s.id === id)).toBe(true); + }); + + it("löscht einen NICHT-aktiven Stiftsatz anstandslos", () => { + getState().addPenSet(); + getState().addPenSet(); + const [active, other] = getState().project.penSets!.map((s) => s.id); + expect(getState().project.activePenSetId).toBe(active); + getState().deletePenSet(other); + expect(getState().project.penSets?.length).toBe(1); + }); +}); + +describe("deletePen — entfernt den Stift + löst betroffene Verweise, Farbe bleibt", () => { + it("löscht den Stift aus `pens` und aus jedem Stiftsatz, klärt `colorPenId` am Bauteil, behält die zuletzt gebackene Farbe", () => { + getState().addPenSet(); + getState().addPen(); + const penId = getState().project.pens![0].id; + getState().patchPenSetColor(getState().project.activePenSetId!, penId, "#654321"); + const compId = getState().project.components[0].id; + getState().patchComponent(compId, { colorPenId: penId, color: "#654321" }); + + getState().deletePen(penId); + + expect(getState().project.pens?.length).toBe(0); + expect(getState().project.penSets![0].pens[penId]).toBeUndefined(); + const comp = getState().project.components[0]; + expect(comp.colorPenId).toBeUndefined(); + expect(comp.color).toBe("#654321"); // letzte gebackene Farbe bleibt als freie Farbe + }); +}); diff --git a/src/state/projectSlice.polylineBulge.test.ts b/src/state/projectSlice.polylineBulge.test.ts new file mode 100644 index 00000000..6c66f658 --- /dev/null +++ b/src/state/projectSlice.polylineBulge.test.ts @@ -0,0 +1,63 @@ +/** + * Bulge-Griffe der Polylinie (`drawingVertices`/`moveGripOf` in + * `projectSlice.ts`): Segment-Mitte senkrecht zur Sehne ziehen krümmt genau + * dieses Segment (s. `geometry/bulge.ts`). + */ + +import { describe, it, expect, beforeEach } from "vitest"; +import { getState, setState } from "./appStore"; +import { sampleProject } from "../model/sampleProject"; +import { drawingVertices } from "./projectSlice"; +import type { Drawing2D } from "../model/types"; + +const openPoly: Drawing2D = { + id: "d-poly", + type: "drawing2d", + levelId: "eg", + categoryCode: "00", + geom: { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 4, y: 0 }], closed: false }, +}; + +beforeEach(() => { + setState({ + project: { ...sampleProject, drawings2d: [openPoly] }, + undoStack: [], + redoStack: [], + canUndo: false, + canRedo: false, + }); +}); + +describe("drawingVertices — Polylinie mit Bulge-Griffen", () => { + it("liefert 3 Eckpunkt- + 2 Segment-Bulge-Griffe (offen, ohne bulge → Sehnen-Mitte)", () => { + const v = drawingVertices(openPoly); + expect(v.length).toBe(5); + expect(v.slice(0, 3)).toEqual([{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 4, y: 0 }]); + // Ohne bulge sitzt der Griff auf der Sehnen-Mitte. + expect(v[3]).toEqual({ x: 1, y: 0 }); + expect(v[4]).toEqual({ x: 3, y: 0 }); + }); +}); + +describe("moveGripOf — Bulge-Griff einer Polylinie", () => { + it("Ziehen des Segment-0-Griffs nach oben setzt bulge[0] > 0 (Bogen nach links von a→b)", () => { + getState().moveGripOf("d-poly", null, 3, { x: 1, y: 1 }); // Griff-Index 3 = Segment 0 + const g = getState().project.drawings2d[0].geom; + expect(g.shape).toBe("polyline"); + if (g.shape === "polyline") { + expect(g.bulge?.[0]).toBeGreaterThan(0); + expect(g.bulge?.[0]).toBeCloseTo(1, 6); // Sagitta 1 bei Halb-Sehne 1 → bulge 1 + expect(g.pts).toEqual([{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 4, y: 0 }]); // Eckpunkte unangetastet + } + }); + + it("Ziehen nach unten setzt negativen bulge; Eckpunkt-Griffe bleiben normale Punkt-Griffe", () => { + getState().moveGripOf("d-poly", null, 4, { x: 3, y: -0.5 }); // Griff-Index 4 = Segment 1 + let g = getState().project.drawings2d[0].geom; + if (g.shape === "polyline") expect(g.bulge?.[1]).toBeLessThan(0); + + getState().moveGripOf("d-poly", null, 1, { x: 2, y: 5 }); // Eckpunkt-Griff (Index 1) + g = getState().project.drawings2d[0].geom; + if (g.shape === "polyline") expect(g.pts[1]).toEqual({ x: 2, y: 5 }); + }); +}); diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index 4bde38ce..d0fbdf74 100644 --- a/src/state/projectSlice.ts +++ b/src/state/projectSlice.ts @@ -14,20 +14,30 @@ import { recomputeFloorElevations, } from "../model/types"; import type { + ColorPen, Component, Drawing2D, DrawingLevel, HatchStyle, LayerCategory, LineStyle, + PenSet, Project, Vec2, } from "../model/types"; +import { + activePenSet, + rebakePenColors, + seedStandardPenSet as buildStandardPenSet, + PEN_FALLBACK_COLOR, + PEN_FALLBACK_WEIGHT, +} from "../model/penSets"; import { lineIntersect } from "../model/geometry"; import { commitTransform } from "../tools/transform"; import type { CopyMode, TransformOp, TransformSelection } from "../tools/transform"; import { uniqueId } from "../tools/types"; import { centroid as roomCentroid } from "../geometry/roomArea"; +import { bulgeFromSagittaPoint, bulgePointAt } from "../geometry/bulge"; import { t } from "../i18n"; import type { StoreApi } from "./store"; import { createHistorySlice, pushHistoryPatch } from "./historySlice"; @@ -98,6 +108,25 @@ export interface ProjectSlice { importLineStyles: (styles: Omit[]) => void; importHatches: (hatches: Omit[]) => void; + // ── Stiftsätze (ArchiCAD-Stiftsatz-Muster, s. model/penSets.ts) ─────────── + /** Neuer Stift-Platzhalter (Name, keine Farbe) — landet in JEDEM bestehenden Stiftsatz. */ + addPen: () => void; + renamePen: (id: string, name: string) => void; + /** Entfernt den Stift-Platzhalter + seinen Eintrag in allen Stiftsätzen; löst betroffene `xxxPenId`-Verweise (Farbe bleibt der letzte gebackene Wert). */ + deletePen: (id: string) => void; + /** Neuer Stiftsatz — übernimmt die Farben des aktiven Satzes (falls vorhanden), sonst den Fallback; wird aktiv, wenn es der erste Satz ist. */ + addPenSet: () => void; + renamePenSet: (id: string, name: string) => void; + /** Blockiert (mit Hinweis), wenn `id` der aktive Satz ist — zuerst einen anderen aktivieren. */ + deletePenSet: (id: string) => void; + /** Setzt den aktiven Stiftsatz und bäckt sofort alle Stift-gekoppelten Farben neu. */ + setActivePenSet: (id: string) => void; + /** Ändert die Farbe EINES Stifts in EINEM Stiftsatz; bäckt neu, wenn dieser Satz aktiv ist. */ + patchPenSetColor: (setId: string, penId: string, color: string) => void; + patchPenSetWeight: (setId: string, penId: string, weight: number) => void; + /** Ersetzt `pens`/legt einen neuen Satz mit der 255er-CAD-Standardpalette an (s. `model/penSets.ts`). */ + seedStandardPenSet: () => void; + // ── Editier-Griffe + Body-Move des selektierten Elements ────────────────── moveGripOf: ( drawingId: string | null, @@ -177,6 +206,20 @@ export interface ProjectSlice { ids: string[], op: "front" | "back" | "forward" | "backward", ) => void; + /** + * Sortiert die gewählten Zeichnungsebenen in `drawingLevels` um — dieselbe + * "front"/"back"/"forward"/"backward"-Semantik wie `reorderDrawings`, nur + * für Geschosse/Schnitte/Ansichten/2D-Zeichnungen statt Drawing2D-Elemente. + * Die Array-Reihenfolge bestimmt die Überlagerungs-Reihenfolge bei mehreren + * gleichzeitig sichtbaren Ebenen (s. generatePlan.ts::generateVisibleLevelsPlan, + * viewportContent.tsx::overlaySectionLevels) — Nutzer-Wunsch "Ansichten in + * den Hintergrund legen können". Panel-Liste zeigt die REVERSE Array- + * Reihenfolge (oben = zuletzt im Array = vorne/obenauf), s. DrawingLevelsPanel. + */ + reorderDrawingLevels: ( + ids: string[], + op: "front" | "back" | "forward" | "backward", + ) => void; /** * Skaliert die Geometrie eines Elements auf Zielbreite×-höhe (Meter) um einen * Ankerpunkt (fx/fy ∈ [0,1] relativ zur bbox; 0,0 = oben-links). @@ -770,6 +813,137 @@ export function createProjectSlice( ], })), + // ── Stiftsätze ───────────────────────────────────────────────────────── + addPen: () => + setProject((p) => { + const pen: ColorPen = { id: `pen-${Date.now()}`, name: t("default.penName") }; + return { + ...p, + pens: [...(p.pens ?? []), pen], + // Neuer Stift bekommt in JEDEM bestehenden Stiftsatz sofort einen + // Eintrag (Fallback-Grauton+Stärke) — Stiftsätze bleiben dadurch + // immer deckungsgleich zur `pens`-Liste, keine "fehlt in Satz X"-Lücken. + penSets: p.penSets?.map((s) => ({ + ...s, + pens: { ...s.pens, [pen.id]: { color: PEN_FALLBACK_COLOR, weight: PEN_FALLBACK_WEIGHT } }, + })), + }; + }), + + renamePen: (id, name) => + setProject((p) => ({ + ...p, + pens: p.pens?.map((pen) => (pen.id === id ? { ...pen, name } : pen)), + })), + + deletePen: (id) => + setProject((p) => { + const clearPenRefs = (x: T): T => + x.colorPenId === id || x.foregroundPenId === id || x.backgroundPenId === id + ? { + ...x, + colorPenId: x.colorPenId === id ? undefined : x.colorPenId, + foregroundPenId: x.foregroundPenId === id ? undefined : x.foregroundPenId, + backgroundPenId: x.backgroundPenId === id ? undefined : x.backgroundPenId, + } + : x; + const clearCategoryPenRefs = (cat: LayerCategory): LayerCategory => ({ + ...(cat.colorPenId === id ? { ...cat, colorPenId: undefined } : cat), + ...(cat.children ? { children: cat.children.map(clearCategoryPenRefs) } : {}), + }); + return { + ...p, + pens: p.pens?.filter((pen) => pen.id !== id), + penSets: p.penSets?.map((s) => { + const { [id]: _removed, ...rest } = s.pens; + return { ...s, pens: rest }; + }), + components: p.components.map(clearPenRefs), + layers: p.layers.map(clearCategoryPenRefs), + }; + }), + + addPenSet: () => + setProject((p) => { + const current = activePenSet(p); + const penSet: PenSet = { + id: `penset-${Date.now()}`, + name: t("default.penSetName"), + pens: current + ? { ...current.pens } + : Object.fromEntries( + (p.pens ?? []).map((pen) => [pen.id, { color: PEN_FALLBACK_COLOR, weight: PEN_FALLBACK_WEIGHT }]), + ), + }; + const penSets = [...(p.penSets ?? []), penSet]; + // Erster Stiftsatz überhaupt: automatisch aktivieren (sonst löst jeder + // Stift-Verweis bis zur ersten manuellen Aktivierung auf den Fallback auf). + return { + ...p, + penSets, + activePenSetId: p.activePenSetId ?? penSet.id, + }; + }), + + renamePenSet: (id, name) => + setProject((p) => ({ + ...p, + penSets: p.penSets?.map((s) => (s.id === id ? { ...s, name } : s)), + })), + + deletePenSet: (id) => + setProject((p) => { + if (p.activePenSetId === id) { + const name = p.penSets?.find((s) => s.id === id)?.name ?? id; + get().notify(t("alert.penSetIsActive", { name }), "warning"); + return p; + } + return { ...p, penSets: p.penSets?.filter((s) => s.id !== id) }; + }), + + setActivePenSet: (id) => + setProject((p) => rebakePenColors({ ...p, activePenSetId: id })), + + patchPenSetColor: (setId, penId, color) => + setProject((p) => { + const next = { + ...p, + penSets: p.penSets?.map((s) => + s.id === setId + ? { + ...s, + pens: { + ...s.pens, + [penId]: { ...(s.pens[penId] ?? { color: PEN_FALLBACK_COLOR, weight: PEN_FALLBACK_WEIGHT }), color }, + }, + } + : s, + ), + }; + return setId === p.activePenSetId ? rebakePenColors(next) : next; + }), + + patchPenSetWeight: (setId, penId, weight) => + setProject((p) => { + const next = { + ...p, + penSets: p.penSets?.map((s) => + s.id === setId + ? { + ...s, + pens: { + ...s.pens, + [penId]: { ...(s.pens[penId] ?? { color: PEN_FALLBACK_COLOR, weight: PEN_FALLBACK_WEIGHT }), weight }, + }, + } + : s, + ), + }; + return setId === p.activePenSetId ? rebakePenColors(next) : next; + }), + + seedStandardPenSet: () => setProject((p) => buildStandardPenSet(p)), + // ── Editier-Griffe ───────────────────────────────────────────────────── // Diese Aktionen laufen AD-HOC bei jedem Maus-Move-Schritt eines Drags // (kein Draft/Commit-Muster wie bei den Zeichenwerkzeugen) — daher mit @@ -866,6 +1040,12 @@ export function createProjectSlice( drawings2d: reorderDrawings2D(p.drawings2d, ids, op), })), + reorderDrawingLevels: (ids, op) => + setProject((p) => ({ + ...p, + drawingLevels: reorderDrawingLevelsArr(p.drawingLevels, ids, op), + })), + // ── Größe (Resize um Anker) ──────────────────────────────────────────── resizeElement: (kind, id, w, h, anchor) => setProject((p) => resizeElement(p, kind, id, w, h, anchor)), @@ -1159,6 +1339,42 @@ function reorderDrawings2D( return arr; } +/** + * Wie `reorderDrawings2D`, nur für `DrawingLevel[]` (Zeichnungsebenen statt + * Drawing2D-Elemente) — identische "front"/"back"/"forward"/"backward"-Logik, + * bewusst dupliziert statt genericisiert (zwei kleine, unabhängige Domänen). + */ +function reorderDrawingLevelsArr( + levels: DrawingLevel[], + ids: string[], + op: "front" | "back" | "forward" | "backward", +): DrawingLevel[] { + const selected = new Set(ids.filter((id) => levels.some((l) => l.id === id))); + if (selected.size === 0) return levels; + + if (op === "front" || op === "back") { + const picked = levels.filter((l) => selected.has(l.id)); + const rest = levels.filter((l) => !selected.has(l.id)); + return op === "front" ? [...rest, ...picked] : [...picked, ...rest]; + } + + const arr = levels.slice(); + if (op === "forward") { + for (let i = arr.length - 2; i >= 0; i--) { + if (selected.has(arr[i].id) && !selected.has(arr[i + 1].id)) { + [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]]; + } + } + } else { + for (let i = 1; i < arr.length; i++) { + if (selected.has(arr[i].id) && !selected.has(arr[i - 1].id)) { + [arr[i], arr[i - 1]] = [arr[i - 1], arr[i]]; + } + } + } + return arr; +} + function mapCeiling( project: Project, ceilingId: string, @@ -1363,7 +1579,8 @@ function resizeGeom( anchor: { fx: number; fy: number }, ): import("../model/types").Drawing2DGeom { switch (g.shape) { - case "line": { + case "line": + case "xline": { const { ax, ay, sx, sy } = scaleAround(bbox2([g.a, g.b]), w, h, anchor); const f = (p: Vec2): Vec2 => ({ x: ax + (p.x - ax) * sx, y: ay + (p.y - ay) * sy }); return { ...g, a: f(g.a), b: f(g.b) }; @@ -1435,6 +1652,13 @@ function resizeGeom( const { ax, ay, sx, sy } = scaleAround(box, w, h, anchor); return { ...g, at: { x: ax + (g.at.x - ax) * sx, y: ay + (g.at.y - ay) * sy } }; } + case "block": { + // Wie Text: nur der Einfügepunkt wandert (kein Skalierungsfaktor am + // Symbol selbst in v1). + const box = { minX: g.at.x, minY: g.at.y, maxX: g.at.x, maxY: g.at.y }; + const { ax, ay, sx, sy } = scaleAround(box, w, h, anchor); + return { ...g, at: { x: ax + (g.at.x - ax) * sx, y: ay + (g.at.y - ay) * sy } }; + } case "image": { const box = bbox2([g.min, g.max]); const { ax, ay, sx, sy } = scaleAround(box, w, h, anchor); @@ -1480,8 +1704,22 @@ function ellipseOrCircle( */ export function drawingVertices(d: import("../model/types").Drawing2D): Vec2[] { const g = d.geom; - if (g.shape === "line") return [g.a, g.b]; - if (g.shape === "polyline") return [...g.pts]; + if (g.shape === "line" || g.shape === "xline") return [g.a, g.b]; + // Polylinie: Eckpunkt-Griffe (Index 0..n-1) PLUS ein Bulge-Griff je Segment + // (Index n..; Apex des aktuellen Bogens, oder Sehnen-Mitte bei bulge=0) — + // senkrecht zur Sehne ziehen krümmt genau dieses Segment (s. moveGrip). + if (g.shape === "polyline") { + const n = g.pts.length; + const closeSeg = g.closed && n > 2; + const segCount = Math.max(0, n - 1) + (closeSeg ? 1 : 0); + const bulgeGrips: Vec2[] = []; + for (let i = 0; i < segCount; i++) { + const a = g.pts[i]; + const b = i === n - 1 ? g.pts[0] : g.pts[i + 1]; + bulgeGrips.push(bulgePointAt(a, b, g.bulge?.[i] ?? 0, 0.5)); + } + return [...g.pts, ...bulgeGrips]; + } if (g.shape === "rect" || g.shape === "image") { return [ g.min, @@ -1533,8 +1771,17 @@ export function drawingVertices(d: import("../model/types").Drawing2D): Vec2[] { } // Kote: EIN Griff an der Dreieck-Spitze (zum Verschieben; siehe moveGrip). if (g.shape === "kote") return [g.at]; - // Text: EIN Griff am Ankerpunkt (zum Verschieben; siehe moveGrip). - if (g.shape === "text") return [g.at]; + // Text: Griff 0 am Ankerpunkt; trägt der Text einen Leader, zusätzlich Griff + // 1 an dessen Zielpunkt (Pfeilspitze unabhängig verschiebbar; s. moveGrip). + // Text-entlang-Pfad: die Pfadpunkte SELBST sind die Griffe (wie polyline), + // ersetzt das Anker/Leader-Griffmodell komplett (schliessen sich aus). + if (g.shape === "text") { + if (g.pathPts) return [...g.pathPts]; + return g.leaderTarget ? [g.at, g.leaderTarget] : [g.at]; + } + // Block-Instanz: EIN Griff am Einfügepunkt (Rotation läuft über move/mirror, + // kein eigener Rotations-Griff in v1; s. moveGrip). + if (g.shape === "block") return [g.at]; return []; } @@ -1587,10 +1834,27 @@ function moveGrip( drawings2d: project.drawings2d.map((d) => { if (d.id !== drawingId) return d; const g = d.geom; - if (g.shape === "line") { + if (g.shape === "line" || g.shape === "xline") { return { ...d, geom: index === 0 ? { ...g, a: pt } : { ...g, b: pt } }; } - if (g.shape === "polyline" || g.shape === "bezier" || g.shape === "spline") { + if (g.shape === "polyline") { + const n = g.pts.length; + if (index < n) { + const pts = g.pts.map((p, i) => (i === index ? pt : p)); + return { ...d, geom: { ...g, pts } }; + } + // Bulge-Griff (Index ≥ n): Segment-Mitte senkrecht zur Sehne gezogen + // → neuer Bogen-Faktor für GENAU dieses Segment (s. drawingVertices). + const segIndex = index - n; + const a = g.pts[segIndex]; + const b = segIndex === n - 1 ? g.pts[0] : g.pts[segIndex + 1]; + const bulgeVal = bulgeFromSagittaPoint(a, b, pt); + const bulge = [...(g.bulge ?? [])]; + while (bulge.length <= segIndex) bulge.push(0); + bulge[segIndex] = bulgeVal; + return { ...d, geom: { ...g, bulge } }; + } + if (g.shape === "bezier" || g.shape === "spline") { const pts = g.pts.map((p, i) => (i === index ? pt : p)); return { ...d, geom: { ...g, pts } }; } @@ -1622,10 +1886,21 @@ function moveGrip( const max = { x: Math.max(pt.x, opp.x), y: Math.max(pt.y, opp.y) }; return { ...d, geom: { ...g, min, max } }; } - // Text: der einzige Griff (Index 0) sitzt am Ankerpunkt → verschiebt ihn. - if (g.shape === "text") return { ...d, geom: { ...g, at: pt } }; + // Text: Griff 0 = Ankerpunkt; Griff 1 (nur bei Leader) = Zielpunkt; + // trägt der Text einen Pfad, adressiert der Index einen Pfadpunkt. + if (g.shape === "text") { + if (g.pathPts) { + const pathPts = g.pathPts.map((pp, i) => (i === index ? pt : pp)); + return { ...d, geom: { ...g, pathPts } }; + } + return index === 1 && g.leaderTarget + ? { ...d, geom: { ...g, leaderTarget: pt } } + : { ...d, geom: { ...g, at: pt } }; + } // Kote: der einzige Griff (Index 0) sitzt an der Dreieck-Spitze. if (g.shape === "kote") return { ...d, geom: { ...g, at: pt } }; + // Block-Instanz: der einzige Griff (Index 0) sitzt am Einfügepunkt. + if (g.shape === "block") return { ...d, geom: { ...g, at: pt } }; // Kreis: Griff 0 (Ost) bzw. 1 (Nord) — zieht man die beiden Achsen // unabhängig auseinander, wird der Kreis zur Ellipse (rotation 0); // bleiben rx/ry (fast) gleich, bleibt es ein Kreis (s. `ellipseOrCircle`). diff --git a/src/state/reorderDrawingLevels.test.ts b/src/state/reorderDrawingLevels.test.ts new file mode 100644 index 00000000..548c32b4 --- /dev/null +++ b/src/state/reorderDrawingLevels.test.ts @@ -0,0 +1,78 @@ +/** + * Z-Anordnen von Zeichnungsebenen (`reorderDrawingLevels` in + * `src/state/projectSlice.ts`) — dieselbe „front"/„back"/„forward"/„backward"- + * Semantik wie `reorderDrawings`, nur für `project.drawingLevels` statt + * `drawings2d`. Die Array-Reihenfolge bestimmt die Überlagerungs-Reihenfolge + * bei mehreren gleichzeitig sichtbaren Ebenen (Nutzer-Wunsch: "Ansichten in + * den Hintergrund legen können"). + */ + +import { describe, it, expect, beforeEach } from "vitest"; +import { getState, setState } from "./appStore"; +import { sampleProject } from "../model/sampleProject"; +import type { DrawingLevel } from "../model/types"; + +function floor(id: string): DrawingLevel { + return { + id, + name: id, + kind: "floor", + visible: true, + locked: false, + floorHeight: 2.6, + cutHeight: 1.0, + baseElevation: 0, + }; +} + +beforeEach(() => { + setState({ + project: { + ...sampleProject, + drawingLevels: [floor("A"), floor("B"), floor("C"), floor("D")], + }, + undoStack: [], + redoStack: [], + canUndo: false, + canRedo: false, + }); +}); + +function ids(): string[] { + return getState().project.drawingLevels.map((l) => l.id); +} + +describe("reorderDrawingLevels", () => { + it("front: schiebt die Auswahl ans Ende, Reihenfolge untereinander bleibt", () => { + getState().reorderDrawingLevels(["B", "A"], "front"); + expect(ids()).toEqual(["C", "D", "A", "B"]); + }); + + it("back: schiebt die Auswahl an den Anfang", () => { + getState().reorderDrawingLevels(["C"], "back"); + expect(ids()).toEqual(["C", "A", "B", "D"]); + }); + + it("forward: contiguous block überholt genau einen Nachbarn", () => { + getState().reorderDrawingLevels(["B", "C"], "forward"); + expect(ids()).toEqual(["A", "D", "B", "C"]); + }); + + it("backward: contiguous block überholt genau einen Nachbarn rückwärts", () => { + getState().reorderDrawingLevels(["B", "C"], "backward"); + expect(ids()).toEqual(["B", "C", "A", "D"]); + }); + + it("unbekannte IDs werden ignoriert", () => { + getState().reorderDrawingLevels(["nope"], "front"); + expect(ids()).toEqual(["A", "B", "C", "D"]); + }); + + it("ist ein normaler Undo-Schritt", () => { + getState().reorderDrawingLevels(["A"], "front"); + expect(ids()).toEqual(["B", "C", "D", "A"]); + expect(getState().canUndo).toBe(true); + getState().undo(); + expect(ids()).toEqual(["A", "B", "C", "D"]); + }); +}); diff --git a/src/state/selectionInfo.contextImage.test.ts b/src/state/selectionInfo.contextImage.test.ts new file mode 100644 index 00000000..5e7ea00d --- /dev/null +++ b/src/state/selectionInfo.contextImage.test.ts @@ -0,0 +1,74 @@ +// `deriveSelection` für ein selektiertes Kontext-Objekt-Luftbild +// (`ContextImage`) muss `isImage`/`opacity`/`imageFilters` setzen, damit +// AttributesPanel.tsx seine (mit Drawing2D-Bildern geteilte) Deckkraft-Zeile +// + die neue Bildkorrektur-Sektion anzeigt (s. PENDENZEN.md „Bildschraffur: +// Bild-Filter"). `selectionInfo.ts` hatte bislang KEINE Tests — dieser Fokus- +// Test deckt nur den neuen Pfad ab, keine vollständige Modul-Abdeckung. + +import { describe, it, expect } from "vitest"; +import { deriveSelection } from "./selectionInfo"; +import type { Project } from "../model/types"; + +function projectWith(context: Project["context"]): 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: [], + walls: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context, + } as unknown as Project; +} + +describe("deriveSelection — Kontext-Objekt-Luftbild (ContextImage)", () => { + it("setzt isImage/opacity/imageFilters für ein Luftbild mit Filtern", () => { + const project = projectWith([ + { + id: "IMG1", + type: "image", + name: "Luftbild", + src: "data:image/jpeg;base64,AAAA", + min: { x: 0, y: 0 }, + max: { x: 10, y: 10 }, + opacity: 0.8, + filters: { saturation: 0.5, brightness: 1.1, contrast: 1, grayscale: 0.2 }, + }, + ]); + const sel = deriveSelection(project, [], null, null, null, null, null, null, null, null, "IMG1"); + expect(sel?.kind).toBe("contextObject"); + expect(sel?.isImage).toBe(true); + expect(sel?.opacity).toBe(0.8); + expect(sel?.imageFilters).toEqual({ saturation: 0.5, brightness: 1.1, contrast: 1, grayscale: 0.2 }); + }); + + it("opacity fällt auf 1 zurück, wenn das Bild keine eigene Deckkraft trägt", () => { + const project = projectWith([ + { id: "IMG1", type: "image", name: "Luftbild", src: "x", min: { x: 0, y: 0 }, max: { x: 1, y: 1 } }, + ]); + const sel = deriveSelection(project, [], null, null, null, null, null, null, null, null, "IMG1"); + expect(sel?.opacity).toBe(1); + expect(sel?.imageFilters).toBeUndefined(); + }); + + it("isImage bleibt false/undefined für ein Nicht-Bild-Kontext-Objekt (z. B. importiertes Mesh)", () => { + const project = projectWith([ + { id: "M1", type: "importedMesh", name: "Haus", positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [0, 1, 2] }, + ]); + const sel = deriveSelection(project, [], null, null, null, null, null, null, null, null, "M1"); + expect(sel?.isImage).toBeFalsy(); + expect(sel?.opacity).toBeUndefined(); + expect(sel?.imageFilters).toBeUndefined(); + }); +}); diff --git a/src/state/selectionInfo.ts b/src/state/selectionInfo.ts index fc000e29..93748170 100644 --- a/src/state/selectionInfo.ts +++ b/src/state/selectionInfo.ts @@ -24,6 +24,7 @@ import type { Ceiling, Column, ColumnProfile, + ContextImage, ContextObject, Drawing2D, Drawing2DGeom, @@ -378,6 +379,16 @@ export interface Selection { floorId?: string; /** Effektiv aufgelöste Strich-/Umrandungsfarbe (hex). */ color: string; + /** + * Stift-Kopplung der Farbe oben (ArchiCAD-Stiftsatz-Muster, s. + * `model/penSets.ts`): gesetzt, wenn DIESES Element (nicht Bauteil/Ebene) + * seine eigene Farbe an einen Stift gekoppelt hat. `color` bleibt auch dann + * die aufgelöste (gebackene) Farbe — die Kopplung ist nur fürs Panel-UI + * relevant (Dropdown „Frei"/Stiftname). Gesetzt bei Wand/Decke/Dach/ + * Öffnung/Treppe/Raum/Stütze/Drawing2D; bei den übrigen `kind`s (Tür, + * Extrusion, Kontext-Objekt, Layout-Annotation) `undefined`. + */ + colorPenId?: string; /** Effektiv aufgelöste Strichstärke in Millimetern. */ weightMm: number; /** @@ -396,11 +407,19 @@ export interface Selection { * geschlossener Drawing2D. */ foreground?: string; + /** + * Stift-Kopplung von `foreground`, analog {@link Selection.colorPenId} — + * gesetzt bei Wand, Decke, Stütze und Drawing2D (dieselben `kind`s wie + * `foreground` selbst). + */ + foregroundPenId?: string; /** * Hintergrund-Override (Füllfarbe/Poché) des Elements; `undefined` = „Nach * System". Nachfolger von `fillColor`; hat im Plan Vorrang. */ background?: string; + /** Stift-Kopplung von `background`, analog {@link Selection.foregroundPenId}. */ + backgroundPenId?: string; /** * Quelle des Vordergrunds, wenn `foreground` NICHT gesetzt ist ("layer" = * Nach Ebene, "object"/`undefined` = Nach Bauteil, Default). Gesetzt bei @@ -434,12 +453,19 @@ export interface Selection { /** Ob die Form geschlossen ist (rect/circle/closed polyline) — nur Drawing2D. */ closed?: boolean; /** - * Ob das Element ein Bild ist (Drawing2D `{shape:"image"}` ODER Layout- - * Annotation `kind:"image"`) — steuert die Deckkraft-Zeile im Attribute-Panel. + * Ob das Element ein Bild ist (Drawing2D `{shape:"image"}`, Layout- + * Annotation `kind:"image"` ODER Kontext-Objekt `type:"image"`) — steuert + * die Deckkraft-Zeile im Attribute-Panel. */ isImage?: boolean; /** Deckkraft (0..1) — nur wenn `isImage`. */ opacity?: number; + /** + * Bildkorrektur (Sättigung/Helligkeit/Kontrast/Graustufen) — NUR bei + * Kontext-Objekt-Bildern gesetzt (`ContextImage.filters`, s. dort); Drawing2D- + * und Layout-Bilder haben (noch) keine Korrektur. + */ + imageFilters?: ContextImage["filters"]; /** Achsparallele Bounding-Box in Modell-Metern. */ bbox: SelectionBBox; /** @@ -514,6 +540,7 @@ function geomBBox(g: Drawing2DGeom): SelectionBBox { }; switch (g.shape) { case "line": + case "xline": acc(g.a.x, g.a.y); acc(g.b.x, g.b.y); break; @@ -557,6 +584,7 @@ function geomBBox(g: Drawing2DGeom): SelectionBBox { } case "kote": case "text": + case "block": acc(g.at.x, g.at.y); break; } @@ -665,11 +693,14 @@ function wallSelection(project: Project, wall: Wall): Selection { categoryCode: wall.categoryCode, floorId: wall.floorId, color, + colorPenId: wall.colorPenId, weightMm, fillHatchId: wall.hatchId, fillColor: undefined, foreground: wall.foreground, + foregroundPenId: wall.foregroundPenId, background: wall.background, + backgroundPenId: wall.backgroundPenId, foregroundSource: wall.foregroundSource, backgroundSource: wall.backgroundSource, effectiveForeground, @@ -743,11 +774,14 @@ function ceilingSelection(project: Project, ceiling: Ceiling): Selection { categoryCode: ceiling.categoryCode, floorId: ceiling.floorId, color, + colorPenId: ceiling.colorPenId, weightMm, fillHatchId: ceiling.hatchId, fillColor: undefined, foreground: ceiling.foreground, + foregroundPenId: ceiling.foregroundPenId, background: ceiling.background, + backgroundPenId: ceiling.backgroundPenId, foregroundSource: ceiling.foregroundSource, backgroundSource: ceiling.backgroundSource, effectiveForeground, @@ -796,6 +830,7 @@ function roofSelection(project: Project, roof: Roof): Selection { categoryCode: roof.categoryCode, floorId: roof.floorId, color, + colorPenId: roof.colorPenId, weightMm, closed: true, bbox: { minX: bb.x0, minY: bb.y0, maxX: bb.x1, maxY: bb.y1 }, @@ -859,6 +894,7 @@ function openingSelection(project: Project, o: Opening): Selection { id: o.id, categoryCode: o.categoryCode, color, + colorPenId: o.colorPenId, weightMm, fillHatchId: undefined, fillColor: undefined, @@ -900,6 +936,7 @@ function stairSelection(project: Project, s: Stair): Selection { categoryCode: s.categoryCode, floorId: s.floorId, color, + colorPenId: s.colorPenId, weightMm, fillHatchId: undefined, fillColor: undefined, @@ -941,6 +978,7 @@ function roomSelection(project: Project, r: Room): Selection { categoryCode: r.categoryCode, floorId: r.floorId, color, + colorPenId: r.colorPenId, weightMm, fillHatchId: undefined, fillColor: undefined, @@ -1042,10 +1080,13 @@ function columnSelection(project: Project, col: Column): Selection { categoryCode: col.categoryCode, floorId: col.floorId, color: col.color ?? category?.color ?? COLUMN_COLOR, + colorPenId: col.colorPenId, weightMm, fillHatchId: col.hatchId, foreground: col.foreground, + foregroundPenId: col.foregroundPenId, background: col.background, + backgroundPenId: col.backgroundPenId, foregroundSource: col.foregroundSource, backgroundSource: col.backgroundSource, effectiveForeground, @@ -1095,6 +1136,7 @@ function contextObjectSelection(project: Project, obj: ContextObject): Selection { e: anchor.lv95.e - anchor.model.x, n: anchor.lv95.n - anchor.model.y }, ) : undefined; + const isImage = obj.type === "image"; return { kind: "contextObject", id: obj.id, @@ -1103,6 +1145,12 @@ function contextObjectSelection(project: Project, obj: ContextObject): Selection weightMm: WALL_FALLBACK_MM, bbox: { minX, minY, maxX, maxY }, contextObject: { objType: obj.type, lv95Center }, + // Deckkraft + Bildkorrektur nur bei Luftbildern (`ContextImage`) — steuert + // die (wiederverwendete) Deckkraft-Zeile + die neue Bildkorrektur-Sektion + // im Attribute-Panel, s. `AttributesPanel.tsx`. + isImage, + opacity: isImage ? ((obj as ContextImage).opacity ?? 1) : undefined, + imageFilters: isImage ? (obj as ContextImage).filters : undefined, }; } @@ -1149,11 +1197,14 @@ function drawingSelection(project: Project, d: Drawing2D): Selection { categoryCode: d.categoryCode, floorId: d.levelId, color, + colorPenId: d.colorPenId, weightMm, fillHatchId: closed ? d.hatchId ?? null : null, fillColor: closed ? d.fillColor ?? null : null, foreground: closed ? d.foreground : undefined, + foregroundPenId: closed ? d.foregroundPenId : undefined, background: closed ? d.background : undefined, + backgroundPenId: closed ? d.backgroundPenId : undefined, foregroundSource: closed ? d.foregroundSource : undefined, backgroundSource: closed ? d.backgroundSource : undefined, effectiveForeground, diff --git a/src/state/selectionSlice.ts b/src/state/selectionSlice.ts index 144b1194..94d42dcc 100644 --- a/src/state/selectionSlice.ts +++ b/src/state/selectionSlice.ts @@ -27,9 +27,9 @@ export interface SelectionSlice { selectedRoofIds: string[]; // Gewählte Kontext-Objekte (importierte Gebäude/Terrain) als MENGE von IDs. selectedContextObjectIds: string[]; - // Gewählte Schnitt-/Ansichtslinie (DrawingLevel-Id) — EINZELauswahl (eine Linie - // zur Zeit), getrennt von den übrigen Kanälen. `null` = keine Linie gewählt. - selectedSectionLineId: string | null; + // Gewählte Schnitt-/Ansichtslinien (DrawingLevel-Ids) als MENGE von IDs — + // getrennt von den übrigen Kanälen (Shift-Klick togglet, Cmd/Ctrl+A wählt alle). + selectedSectionLineIds: string[]; // Gewählte Gruppen (Vectorworks-artig) als MENGE von IDs — rein informativ/ // fürs UI (Bounding-Box, Doppelklick-Ziel); die eigentlichen Mitglieder // stehen zusätzlich in den übrigen `selected…Ids`-Kanälen (Verschieben/ @@ -51,7 +51,7 @@ export interface SelectionSlice { setSelectedColumnIds: (ids: string[]) => void; setSelectedRoofIds: (ids: string[]) => void; setSelectedContextObjectIds: (ids: string[]) => void; - setSelectedSectionLineId: (id: string | null) => void; + setSelectedSectionLineIds: (ids: string[]) => void; setSelectedGroupIds: (ids: string[]) => void; setGroupPath: (path: string[]) => void; /** Auswahl (Wände + Decken + Öffnungen + Treppen + Dächer + 2D-Elemente) leeren. */ @@ -73,7 +73,7 @@ export function createSelectionSlice( selectedColumnIds: [], selectedRoofIds: [], selectedContextObjectIds: [], - selectedSectionLineId: null, + selectedSectionLineIds: [], selectedGroupIds: [], groupPath: [], setSelectedWallIds: (ids) => set({ selectedWallIds: ids }), @@ -86,7 +86,7 @@ export function createSelectionSlice( setSelectedColumnIds: (ids) => set({ selectedColumnIds: ids }), setSelectedRoofIds: (ids) => set({ selectedRoofIds: ids }), setSelectedContextObjectIds: (ids) => set({ selectedContextObjectIds: ids }), - setSelectedSectionLineId: (id) => set({ selectedSectionLineId: id }), + setSelectedSectionLineIds: (ids) => set({ selectedSectionLineIds: ids }), setSelectedGroupIds: (ids) => set({ selectedGroupIds: ids }), setGroupPath: (path) => set({ groupPath: path }), clearSelection: () => @@ -101,7 +101,7 @@ export function createSelectionSlice( selectedColumnIds: [], selectedRoofIds: [], selectedContextObjectIds: [], - selectedSectionLineId: null, + selectedSectionLineIds: [], selectedGroupIds: [], // groupPath (Isolation) bleibt bewusst erhalten — Leerraum-Klick INNERHALB // einer betretenen Gruppe soll nur deren Auswahl leeren, nicht aus der diff --git a/src/state/siteSlice.ts b/src/state/siteSlice.ts index 0e3fc095..539fcbe0 100644 --- a/src/state/siteSlice.ts +++ b/src/state/siteSlice.ts @@ -12,6 +12,7 @@ import { generateTerrainFromContours } from "../model/terrain"; import type { ContextObject, Project } from "../model/types"; +import { ensureContextCategories } from "../model/contextCategories"; import type { StoreApi } from "./store"; /** Felder/Actions, die diese Slice in den RootState beisteuert. */ @@ -58,11 +59,27 @@ export function createSiteSlice( get().setProject((p) => ({ ...p, context: update(p.context ?? []) })); }; - return { - addContextObject: (obj) => setContext((ctx) => [...ctx, obj]), + // Wie `setContext`, aber fürs HINZUFÜGEN: ergänzt zusätzlich jede fehlende + // Grafik-Kategorie der neu ankommenden Objekte in `project.layers` (s. + // `ensureContextCategories`), damit sie sofort im Ebenen-Panel erscheinen + // und über dessen Sichtbarkeit/Grau/Sperren steuerbar sind — genau wie + // Wand/Decke/Dach, statt wie bisher immer unconditional gezeichnet zu werden. + const addToContext = (added: ContextObject[]): void => { + if (added.length === 0) return; + const codes = added + .map((o) => o.categoryCode) + .filter((c): c is string => !!c); + get().setProject((p) => ({ + ...p, + context: [...(p.context ?? []), ...added], + layers: ensureContextCategories(p.layers, codes), + })); + }; - addContextObjects: (objs) => - setContext((ctx) => (objs.length ? [...ctx, ...objs] : ctx)), + return { + addContextObject: (obj) => addToContext([obj]), + + addContextObjects: (objs) => addToContext(objs), removeContextObject: (id) => setContext((ctx) => ctx.filter((o) => o.id !== id)), @@ -81,7 +98,7 @@ export function createSiteSlice( if (!set || set.type !== "contourSet") return null; const terrain = generateTerrainFromContours(set.contours); if (terrain.indices.length === 0) return null; // kein sinnvolles TIN - setContext((c) => [...c, terrain]); + addToContext([terrain]); return terrain.id; }, diff --git a/src/state/useImportHandling.ts b/src/state/useImportHandling.ts index 15e51e34..37c4416e 100644 --- a/src/state/useImportHandling.ts +++ b/src/state/useImportHandling.ts @@ -38,7 +38,7 @@ export function useImageImportHandling(opts: { setSelectedColumnIds: (ids: string[]) => void; setSelectedRoofIds: (ids: string[]) => void; setSelectedContextObjectIds: (ids: string[]) => void; - setSelectedSectionLineId: (id: string | null) => void; + setSelectedSectionLineIds: (ids: string[]) => void; }): { insertImageDrawings: (assets: { src: string; naturalWidth: number; naturalHeight: number }[]) => void; onImageOrPdfFileChosen: (file: File) => void; @@ -59,7 +59,7 @@ export function useImageImportHandling(opts: { setSelectedColumnIds, setSelectedRoofIds, setSelectedContextObjectIds, - setSelectedSectionLineId, + setSelectedSectionLineIds, } = opts; const insertImageDrawings = ( @@ -87,7 +87,7 @@ export function useImageImportHandling(opts: { setSelectedColumnIds([]); setSelectedRoofIds([]); setSelectedContextObjectIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); } }; diff --git a/src/state/useKeyboardShortcuts.ts b/src/state/useKeyboardShortcuts.ts index a94421ce..d2b1facc 100644 --- a/src/state/useKeyboardShortcuts.ts +++ b/src/state/useKeyboardShortcuts.ts @@ -22,6 +22,12 @@ import { differenceDrawings, intersectionDrawings, unionDrawings } from "../edit import type { BooleanResult } from "../editors/booleanOps"; import { groupSelection, mergeMembership, ungroup, EMPTY_MEMBERSHIP } from "./groupActions"; import type { GroupMembership } from "./groupActions"; +import { + collectElementClipboard, + isClipboardEmpty, + pasteElementClipboard, +} from "../editors/elementClipboard"; +import type { ElementClipboard, ElementSelectionIds } from "../editors/elementClipboard"; /** Aktive Transformation (Bewegen/Spiegeln/Drehen) — Form aus useDrawingToolState. */ type ActiveTransform = { @@ -262,14 +268,18 @@ export function useSelectAllAndDeleteShortcut(opts: { selectedColumnIds: string[]; selectedRoofIds: string[]; selectedContextObjectIds: string[]; - selectedSectionLineId: string | null; + selectedSectionLineIds: string[]; setSelectedWallIds: (ids: string[]) => void; setSelectedDrawingIds: (ids: string[]) => void; setSelectedCeilingIds: (ids: string[]) => void; + setSelectedOpeningIds: (ids: string[]) => void; setSelectedStairIds: (ids: string[]) => void; setSelectedRoomIds: (ids: string[]) => void; setSelectedExtrudedSolidIds: (ids: string[]) => void; setSelectedColumnIds: (ids: string[]) => void; + setSelectedRoofIds: (ids: string[]) => void; + setSelectedContextObjectIds: (ids: string[]) => void; + setSelectedSectionLineIds: (ids: string[]) => void; hasSelectionToDelete: () => boolean; deleteSelection: () => void; }): void { @@ -281,10 +291,13 @@ export function useSelectAllAndDeleteShortcut(opts: { setSelectedWallIds, setSelectedDrawingIds, setSelectedCeilingIds, + setSelectedOpeningIds, setSelectedStairIds, setSelectedRoomIds, setSelectedExtrudedSolidIds, setSelectedColumnIds, + setSelectedRoofIds, + setSelectedSectionLineIds, hasSelectionToDelete, deleteSelection, } = opts; @@ -292,17 +305,24 @@ export function useSelectAllAndDeleteShortcut(opts: { if (activeTool !== "select") return; const onKey = (e: KeyboardEvent) => { if (isEditableTarget(e)) return; - // Alles auswählen (Wände + Zeichnungen des aktiven Geschosses/der Ebene). + // Alles auswählen (alle Bauteilarten des aktiven Geschosses/der Ebene + + // die Schnittlinien-Symbole, die auf JEDEM Grundriss erscheinen). if ((e.ctrlKey || e.metaKey) && (e.key === "a" || e.key === "A")) { const wallIds = project.walls .filter((w) => w.floorId === activeLevelId) .map((w) => w.id); + const wallIdSet = new Set(wallIds); const drawingIds = project.drawings2d .filter((d) => d.levelId === activeLevelId) .map((d) => d.id); const ceilingIds = (project.ceilings ?? []) .filter((c) => c.floorId === activeLevelId) .map((c) => c.id); + // Öffnungen haben kein eigenes floorId (das Geschoss ergibt sich aus + // der Wirtswand) — über die bereits geschossgefilterten Wand-Ids. + const openingIds = (project.openings ?? []) + .filter((o) => wallIdSet.has(o.hostWallId)) + .map((o) => o.id); const stairIds = (project.stairs ?? []) .filter((s) => s.floorId === activeLevelId) .map((s) => s.id); @@ -315,22 +335,42 @@ export function useSelectAllAndDeleteShortcut(opts: { const columnIds = (project.columns ?? []) .filter((c) => c.floorId === activeLevelId) .map((c) => c.id); + const roofIds = (project.roofs ?? []) + .filter((r) => r.floorId === activeLevelId) + .map((r) => r.id); + // Schnittführungs-Symbole sind projektweit (kein floorId-Bezug — sie + // werden auf JEDEM Grundriss gezeichnet, s. generatePlan/sections.ts:: + // addSectionLines), anders als die übrigen, geschossgefilterten Kanäle. + const sectionLineIds = project.drawingLevels + .filter((l) => (l.kind === "section" || l.kind === "elevation") && l.linePoints) + .map((l) => l.id); + // Kontext-Objekte (importierte Gebäude/Terrain) sind ebenfalls + // projektweit, aber bewusst NICHT Teil von „Alles auswählen" — anders + // als Schnittlinien sind sie Hintergrund-/Referenzgeometrie, kein + // Geschossinhalt; ein versehentliches Löschen wäre riskanter als + // hilfreich. Bleibt daher unverändert (kein Clear, kein Select). if ( wallIds.length || drawingIds.length || ceilingIds.length || + openingIds.length || stairIds.length || roomIds.length || extrudedSolidIds.length || - columnIds.length + columnIds.length || + roofIds.length || + sectionLineIds.length ) { setSelectedWallIds(wallIds); setSelectedDrawingIds(drawingIds); setSelectedCeilingIds(ceilingIds); + setSelectedOpeningIds(openingIds); setSelectedStairIds(stairIds); setSelectedRoomIds(roomIds); setSelectedExtrudedSolidIds(extrudedSolidIds); setSelectedColumnIds(columnIds); + setSelectedRoofIds(roofIds); + setSelectedSectionLineIds(sectionLineIds); e.preventDefault(); } return; @@ -356,14 +396,17 @@ export function useSelectAllAndDeleteShortcut(opts: { opts.selectedColumnIds, opts.selectedRoofIds, opts.selectedContextObjectIds, - opts.selectedSectionLineId, + opts.selectedSectionLineIds, opts.project.walls, opts.project.drawings2d, opts.project.ceilings, + opts.project.openings, opts.project.roofs, opts.project.stairs, + opts.project.rooms, opts.project.extrudedSolids, opts.project.columns, + opts.project.drawingLevels, opts.activeLevelId, ]); } @@ -410,20 +453,33 @@ export function useSplitJoinShortcut( } /** - * Ctrl/Cmd+C / Ctrl/Cmd+V = 2D-Zeichenelemente kopieren/einfügen. Kopieren legt - * die GEWÄHLTEN Drawing2D tief in die Zwischenablage; Einfügen erzeugt Klone mit - * neuen IDs auf dem AKTIVEN Geschoss (Zeichnungsebene) und wählt sie aus — so - * wandert z. B. importiertes Mobiliar von einem Geschoss auf ein anderes. Im - * Textfeld bleibt das native Copy/Paste; ohne 2D-Auswahl kein preventDefault. + * Ctrl/Cmd+C / Ctrl/Cmd+V = Bauteile kopieren/einfügen — über ALLE 9 Auswahl- + * Kanäle hinweg (Wand/Decke/Dach/Öffnung/Treppe/Raum/Extrusion/Stütze + + * 2D-Zeichenelemente), s. `editors/elementClipboard.ts` für die reine Logik + * (inkl. der Öffnung↔Wand-Paarkopplung). Einfügen erzeugt Klone mit neuen IDs + * auf dem AKTIVEN Geschoss (an denselben Modell-Koordinaten) und wählt sie + * aus — so wandert z. B. importiertes Mobiliar von einem Geschoss auf ein + * anderes. Im Textfeld bleibt das native Copy/Paste; ohne Auswahl kein + * preventDefault (Browser-Copy bleibt möglich). */ -export function useDrawingClipboardShortcut( - selectedDrawingIds: string[], - drawingClipboard: Drawing2D[], - setDrawingClipboard: (items: Drawing2D[]) => void, +export function useElementClipboardShortcut( + sel: ElementSelectionIds, + elementClipboard: ElementClipboard | null, + setElementClipboard: (c: ElementClipboard | null) => void, activeLevelId: string, - drawings2d: Drawing2D[], - importDrawings: (drawings: Drawing2D[]) => void, - setSelectedDrawingIds: (ids: string[]) => void, + project: Project, + setProject: (next: Project | ((p: Project) => Project)) => void, + setSelected: { + wallIds: (ids: string[]) => void; + drawingIds: (ids: string[]) => void; + ceilingIds: (ids: string[]) => void; + roofIds: (ids: string[]) => void; + openingIds: (ids: string[]) => void; + stairIds: (ids: string[]) => void; + roomIds: (ids: string[]) => void; + extrudedSolidIds: (ids: string[]) => void; + columnIds: (ids: string[]) => void; + }, ): void { useEffect(() => { const onKey = (e: KeyboardEvent) => { @@ -432,30 +488,35 @@ export function useDrawingClipboardShortcut( if (k !== "c" && k !== "v") return; if (isEditableTarget(e)) return; if (k === "c") { - const ids = new Set(selectedDrawingIds); - if (ids.size === 0) return; // nur bei 2D-Auswahl (sonst Browser-Copy) - const picked = drawings2d.filter((d) => ids.has(d.id)); - if (picked.length === 0) return; + const clip = collectElementClipboard(project, sel); + if (!clip) return; // nichts gewählt → natives Browser-Copy zulassen e.preventDefault(); - setDrawingClipboard(picked.map((d) => structuredClone(d))); + setElementClipboard(clip); return; } // Einfügen: Klone auf dem aktiven Geschoss, neue IDs, danach ausgewählt. - if (drawingClipboard.length === 0) return; + if (!elementClipboard || isClipboardEmpty(elementClipboard)) return; e.preventDefault(); - const stamp = Date.now(); - const pasted: Drawing2D[] = drawingClipboard.map((d, i) => ({ - ...structuredClone(d), - id: `drawing-${stamp}-${i}`, - levelId: activeLevelId, - })); - importDrawings(pasted); - setSelectedDrawingIds(pasted.map((p) => p.id)); + const { project: next, pastedIds } = pasteElementClipboard( + project, + elementClipboard, + activeLevelId, + ); + setProject(next); + setSelected.wallIds(pastedIds.wallIds); + setSelected.drawingIds(pastedIds.drawingIds); + setSelected.ceilingIds(pastedIds.ceilingIds); + setSelected.roofIds(pastedIds.roofIds); + setSelected.openingIds(pastedIds.openingIds); + setSelected.stairIds(pastedIds.stairIds); + setSelected.roomIds(pastedIds.roomIds); + setSelected.extrudedSolidIds(pastedIds.extrudedSolidIds); + setSelected.columnIds(pastedIds.columnIds); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [selectedDrawingIds, drawingClipboard, activeLevelId, drawings2d]); + }, [sel, elementClipboard, activeLevelId, project]); } /** diff --git a/src/state/useMouseSelectionHandlers.ts b/src/state/useMouseSelectionHandlers.ts index a0a59a04..ce1304cd 100644 --- a/src/state/useMouseSelectionHandlers.ts +++ b/src/state/useMouseSelectionHandlers.ts @@ -43,6 +43,10 @@ export function useMouseSelectionHandlers(opts: { activeLevelId: string; visibleCodes: Set; categoryDisplay: CategoryDisplayResolver & DisplayResolver; + /** Darstellungsmodus-Resolver je Zeichnungsebene-ID (wie categoryDisplay, + * nur für Geschoss/Zeichnung) — sperrt Elemente einer nicht-aktiven, + * überlagerten Ebene analog zum Kategorie-Sperren unten. */ + floorDisplay: CategoryDisplayResolver & DisplayResolver; selectionState: Pick< ReturnType, | "selectedWallIds" @@ -66,8 +70,8 @@ export function useMouseSelectionHandlers(opts: { | "setSelectedRoofIds" | "selectedContextObjectIds" | "setSelectedContextObjectIds" - | "selectedSectionLineId" - | "setSelectedSectionLineId" + | "selectedSectionLineIds" + | "setSelectedSectionLineIds" | "selectedGroupIds" | "setSelectedGroupIds" | "groupPath" @@ -77,7 +81,7 @@ export function useMouseSelectionHandlers(opts: { "setMenu" | "setStampEditorRoomId" | "editTextId" | "setEditTextId" | "setEditTextMinHeightM" >; }) { - const { project, setProject, activeLevelId, visibleCodes, categoryDisplay, selectionState, contextMenuState } = opts; + const { project, setProject, activeLevelId, visibleCodes, categoryDisplay, floorDisplay, selectionState, contextMenuState } = opts; const { selectedWallIds, setSelectedWallIds, @@ -100,8 +104,8 @@ export function useMouseSelectionHandlers(opts: { setSelectedRoofIds, selectedContextObjectIds, setSelectedContextObjectIds, - selectedSectionLineId, - setSelectedSectionLineId, + selectedSectionLineIds, + setSelectedSectionLineIds, setSelectedGroupIds, groupPath, } = selectionState; @@ -123,7 +127,7 @@ export function useMouseSelectionHandlers(opts: { setSelectedColumnIds([]); setSelectedRoofIds([]); setSelectedContextObjectIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); setStampEditorRoomId(roomId); }; // Doppelklick auf ein Text-2D-Element: selektieren + Inhalts-Editor öffnen. @@ -140,7 +144,7 @@ export function useMouseSelectionHandlers(opts: { setSelectedColumnIds([]); setSelectedRoofIds([]); setSelectedContextObjectIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); // Bestehendes Element per Doppelklick: keine Rahmen-Mindesthöhe (nur bei // frisch aufgezogener Textspalte relevant, s. textbox.ts focusMinHeightM) // — sonst könnte eine vorige Textspalten-Erstellung hier nachwirken. @@ -206,12 +210,36 @@ export function useMouseSelectionHandlers(opts: { return undefined; }; + // Zeichnungsebene (Geschoss/Zeichnung) des getroffenen Elements — für die + // Sperr-Prüfung bei überlagerten (nicht-aktiven) Ebenen, s. `floorDisplay` + // und `generateVisibleLevelsPlan`. Öffnungen gehören zur Wand (keine eigene + // Ebenen-Referenz) — bewusst ausgelassen, wie schon bei categoryCodeOfSelection. + const floorIdOfSelection = (sel: PlanSelection): string | undefined => { + if (sel.wallId) return project.walls.find((w) => w.id === sel.wallId)?.floorId; + if (sel.ceilingId) return (project.ceilings ?? []).find((c) => c.id === sel.ceilingId)?.floorId; + if (sel.stairId) return (project.stairs ?? []).find((s) => s.id === sel.stairId)?.floorId; + if (sel.roomId) return (project.rooms ?? []).find((r) => r.id === sel.roomId)?.floorId; + if (sel.columnId) return (project.columns ?? []).find((c) => c.id === sel.columnId)?.floorId; + if (sel.roofId) return (project.roofs ?? []).find((r) => r.id === sel.roofId)?.floorId; + if (sel.drawingId) return project.drawings2d.find((d) => d.id === sel.drawingId)?.levelId; + return undefined; + }; + const onPlanSelect = (sel: PlanSelection) => { // Darstellungsmodus „Andere grau & gesperrt": ein gesperrtes Element lässt // sich nicht anwählen (und damit auch nicht verschieben/bearbeiten) — der // Klick wird ignoriert, als läge dort nichts. const hitCode = categoryCodeOfSelection(sel); if (hitCode !== undefined && categoryDisplay(hitCode).locked) return; + // Dasselbe für eine überlagerte, nicht-aktive Zeichnungsebene (mehrere + // Geschosse gleichzeitig sichtbar, Modus „Andere grau & gesperrt"/„Nur + // aktive gesperrt"): das Element bleibt sichtbar, ist aber nicht anwählbar. + const hitFloorId = floorIdOfSelection(sel); + if (hitFloorId !== undefined && hitFloorId !== activeLevelId && floorDisplay(hitFloorId).locked) + return; + // Schnitt-/Ansichtslinie: dieselbe Sperr-Prüfung direkt über ihre eigene + // Zeichnungsebene-ID (sie hat keinen Wirts-Floor wie eine Wand). + if (sel.sectionLineId && floorDisplay(sel.sectionLineId).locked) return; // Gruppen-Isolation (Vectorworks „Gruppe betreten"): ausserhalb der // aktiven Gruppe ist alles gesperrt (gedimmt gerendert, s. PlanView) — // derselbe Ignorier-Kurzschluss wie beim normalen Sperren oben. @@ -221,10 +249,12 @@ export function useMouseSelectionHandlers(opts: { // Rest behalten (Wände und 2D-Zeichnungen unabhängig, gemischte Auswahl // erlaubt). Leerraum-Klick mit Shift lässt die Auswahl unverändert. if (sel.shift) { - // Schnittlinie ist Einzelauswahl — Shift+Klick togglet sie an/aus. if (sel.sectionLineId) { - setSelectedSectionLineId( - selectedSectionLineId === sel.sectionLineId ? null : sel.sectionLineId, + const id = sel.sectionLineId; + setSelectedSectionLineIds( + selectedSectionLineIds.includes(id) + ? selectedSectionLineIds.filter((s) => s !== id) + : [...selectedSectionLineIds, id], ); return; } @@ -323,7 +353,7 @@ export function useMouseSelectionHandlers(opts: { setSelectedRoofIds(expanded.roofIds); setSelectedExtrudedSolidIds([]); setSelectedContextObjectIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); setSelectedGroupIds(groupIds); return; } @@ -345,10 +375,10 @@ export function useMouseSelectionHandlers(opts: { if (keep !== "column") setSelectedColumnIds([]); if (keep !== "roof") setSelectedRoofIds([]); if (keep !== "contextObject") setSelectedContextObjectIds([]); - if (keep !== "sectionLine") setSelectedSectionLineId(null); + if (keep !== "sectionLine") setSelectedSectionLineIds([]); }; if (sel.sectionLineId) { - setSelectedSectionLineId(sel.sectionLineId); + setSelectedSectionLineIds([sel.sectionLineId]); clearOthers("sectionLine"); } else if (sel.openingId) { setSelectedOpeningIds([sel.openingId]); @@ -430,7 +460,7 @@ export function useMouseSelectionHandlers(opts: { setSelectedColumnIds([]); setSelectedRoofIds([]); setSelectedContextObjectIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); }; // Rechts-Klick im Grundriss: Wand-Kontextmenü. Trifft der Klick eine Wand, die // NICHT bereits in der Auswahl ist, wird die Auswahl auf sie gesetzt (damit die @@ -457,7 +487,7 @@ export function useMouseSelectionHandlers(opts: { setSelectedExtrudedSolidIds([]); setSelectedColumnIds([]); setSelectedRoofIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); } }; // Links-Klick im 3D: per Raycast getroffene Treppe wählen (Einzelauswahl). @@ -472,7 +502,7 @@ export function useMouseSelectionHandlers(opts: { setSelectedExtrudedSolidIds([]); setSelectedColumnIds([]); setSelectedRoofIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); } }; // Links-Klick im 3D: per Raycast getroffene Decke wählen (Einzelauswahl). @@ -487,7 +517,7 @@ export function useMouseSelectionHandlers(opts: { setSelectedExtrudedSolidIds([]); setSelectedColumnIds([]); setSelectedRoofIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); } }; // Links-Klick im 3D: per Raycast getroffene Öffnung wählen (Einzelauswahl). @@ -502,7 +532,7 @@ export function useMouseSelectionHandlers(opts: { setSelectedExtrudedSolidIds([]); setSelectedColumnIds([]); setSelectedRoofIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); } }; // Links-KLICK im Nordstern-3D-Viewport (WASM, TS-Raycast): getroffenes Bauteil @@ -523,7 +553,7 @@ export function useMouseSelectionHandlers(opts: { setSelectedColumnIds([]); setSelectedRoofIds([]); setSelectedContextObjectIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); return; } if (hit.kind === "contextObject") { @@ -537,7 +567,7 @@ export function useMouseSelectionHandlers(opts: { setSelectedExtrudedSolidIds([]); setSelectedColumnIds([]); setSelectedRoofIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); return; } // Öffnung (Fenster/Tür) und Treppe sind jetzt auch im WASM-Viewport pickbar @@ -554,7 +584,7 @@ export function useMouseSelectionHandlers(opts: { setSelectedColumnIds([]); setSelectedRoofIds([]); setSelectedContextObjectIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); return; } if (hit.kind === "stair") { @@ -568,7 +598,7 @@ export function useMouseSelectionHandlers(opts: { setSelectedColumnIds([]); setSelectedRoofIds([]); setSelectedContextObjectIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); return; } if (hit.kind === "roof") { @@ -603,7 +633,7 @@ export function useMouseSelectionHandlers(opts: { setSelectedExtrudedSolidIds([]); setSelectedColumnIds([]); setSelectedRoofIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); }; // Rechts-Klick im 3D: Wand-Kontextmenü an der Cursorposition. const onViewportContextMenu = (info: ViewportContextInfo) => { diff --git a/src/state/usePanelHostBase.ts b/src/state/usePanelHostBase.ts index 22b6aa63..2e11af8f 100644 --- a/src/state/usePanelHostBase.ts +++ b/src/state/usePanelHostBase.ts @@ -9,6 +9,7 @@ import { useMemo, type RefObject } from "react"; import type { DrawingLevel, Layout, Project } from "../model/types"; +import { resolvePenColor } from "../model/penSets"; import type { ToolId } from "../tools/types"; import type { ViewType } from "../ui/TopBar"; import type { TransformSelection } from "../tools/transform"; @@ -24,6 +25,7 @@ import { t } from "../i18n"; import { applyOverrideRuleEnabled, captureViewSnapshot, + matchingComboName, readViewSnapshot, type ViewSnapshotState, } from "./viewSnapshots"; @@ -164,7 +166,7 @@ export function usePanelHostBase(opts: { | "setSelectedRoofIds" | "setSelectedContextObjectIds" | "selectedSectionLineId" - | "setSelectedSectionLineId" + | "setSelectedSectionLineIds" | "section3dCutId" >; toolState: Pick< @@ -284,7 +286,7 @@ export function usePanelHostBase(opts: { setSelectedRoofIds, setSelectedContextObjectIds, selectedSectionLineId, - setSelectedSectionLineId, + setSelectedSectionLineIds, section3dCutId, } = selectionState; const { activeTool, activeWallTypeId, setActiveWallTypeId, activeCategoryCode, setActiveCategoryCode, snap, setSnap } = @@ -380,6 +382,23 @@ export function usePanelHostBase(opts: { patchAnnotationInLayout(l, selection.id, { color }), ); }, + // Stift-Kopplung der Farbe oben (s. `Selection.colorPenId`-Doku) — + // dieselben Selektionsarten wie `onSetSelectionColor`, MINUS Layout- + // Annotation (kein `colorPenId`-Feld dort, bewusster Scope-Schnitt s. + // PENDENZEN.md). `penId` gesetzt ⇒ Farbe sofort aus dem aktiven + // Stiftsatz backen; `undefined` ⇒ nur die Kopplung lösen, letzter + // gebackener Wert bleibt als freie Farbe stehen. + onSetSelectionColorPen: (penId) => { + if (!selection) return; + const color = penId ? resolvePenColor(project, penId) : undefined; + const patch = color !== undefined ? { colorPenId: penId, color } : { colorPenId: penId }; + if (selection.kind === "wall") updateWall(selection.id, patch); + else if (selection.kind === "drawing2d") updateDrawing2D(selection.id, patch); + else if (selection.kind === "ceiling") updateCeiling(selection.id, patch); + else if (selection.kind === "opening") updateOpening(selection.id, patch); + else if (selection.kind === "stair") updateStair(selection.id, patch); + else if (selection.kind === "room") updateRoom(selection.id, patch); + }, onSetSelectionWeight: (weightMm) => { // Strichstärke-Override: Wand/Decke (`strokeWeight`) oder Drawing2D/ // Layout-Annotation (`weightMm`, Alt-Feldname bleibt). @@ -415,7 +434,8 @@ export function usePanelHostBase(opts: { }, onSetSelectionOpacity: (opacity) => { // Deckkraft nur bei Bild-Elementen (Drawing2D `{shape:"image"}` im - // Plan, Layout-Annotation `kind:"image"` auf dem Blatt). + // Plan, Layout-Annotation `kind:"image"` auf dem Blatt, Kontext-Objekt + // `type:"image"` = importiertes Luftbild). if (selection?.kind === "drawing2d") setProject((p) => ({ ...p, @@ -429,6 +449,27 @@ export function usePanelHostBase(opts: { patchOpenLayout(activeLayout.id, (l) => patchAnnotationInLayout(l, selection.id, { opacity }), ); + else if (selection?.kind === "contextObject") + setProject((p) => ({ + ...p, + context: (p.context ?? []).map((o) => + o.id === selection.id && o.type === "image" ? { ...o, opacity } : o, + ), + })); + }, + onSetSelectionImageFilters: (filters) => { + // Nur Kontext-Objekt-Bilder tragen `filters` (s. `ContextImage`) — + // gemergt mit den bestehenden Werten (Teil-Update, ein Slider ändert + // nur SEINEN eigenen Wert). + if (selection?.kind !== "contextObject") return; + setProject((p) => ({ + ...p, + context: (p.context ?? []).map((o) => + o.id === selection.id && o.type === "image" + ? { ...o, filters: { ...o.filters, ...filters } } + : o, + ), + })); }, onSetSelectionForeground: (color) => { // Vordergrund-Override: Wand, Decke oder Drawing2D. @@ -448,6 +489,36 @@ export function usePanelHostBase(opts: { ) setElementBackground(selection.kind, selection.id, color); }, + // Stift-Kopplung von Vordergrund/Hintergrund (s. `Selection. + // foregroundPenId`/`backgroundPenId`-Doku) — dieselben Selektionsarten + // wie `onSetSelectionForeground`/`onSetSelectionBackground` (Wand/Decke/ + // Drawing2D; Stütze trägt zwar dasselbe Feld im Modell, hat aber ebenso + // wie bei `onSetSelectionColorPen` noch KEINEN UI-Schreibpfad — s. + // PENDENZEN.md-Scope-Entscheid). `penId` gesetzt ⇒ sofort aus dem aktiven + // Stiftsatz backen; `undefined` ⇒ nur die Kopplung lösen, letzter + // gebackener Wert bleibt als freier Override stehen. + onSetSelectionForegroundPen: (penId) => { + if (!selection) return; + const foreground = penId ? resolvePenColor(project, penId) : undefined; + const patch = + foreground !== undefined + ? { foregroundPenId: penId, foreground } + : { foregroundPenId: penId }; + if (selection.kind === "wall") updateWall(selection.id, patch); + else if (selection.kind === "ceiling") updateCeiling(selection.id, patch); + else if (selection.kind === "drawing2d") updateDrawing2D(selection.id, patch); + }, + onSetSelectionBackgroundPen: (penId) => { + if (!selection) return; + const background = penId ? resolvePenColor(project, penId) : undefined; + const patch = + background !== undefined + ? { backgroundPenId: penId, background } + : { backgroundPenId: penId }; + if (selection.kind === "wall") updateWall(selection.id, patch); + else if (selection.kind === "ceiling") updateCeiling(selection.id, patch); + else if (selection.kind === "drawing2d") updateDrawing2D(selection.id, patch); + }, // ── By-Layer/By-Object-Quellen (Vordergrund/Hintergrund/Strichstärke/ // Schraffur): "layer" erzwingt die Ebene, "object" erbt vom Bauteil — // beide löschen dabei den expliziten Wert (siehe Modell-Kommentar @@ -903,7 +974,7 @@ export function usePanelHostBase(opts: { setSelectedColumnIds([]); setSelectedRoofIds([]); setSelectedContextObjectIds([]); - setSelectedSectionLineId(null); + setSelectedSectionLineIds([]); switch (kind) { case "Wand": setSelectedWallIds([id]); @@ -948,9 +1019,9 @@ export function usePanelHostBase(opts: { // Erfassen: aktuellen Darstellungszustand einsammeln (View-State + // Sichtbarkeits-Snapshots + aktive Overrides) → pure captureViewSnapshot → // an project.viewSnapshots anhängen (im Dokument, nicht localStorage). - onCaptureViewSnapshot: (name: string, folderId?: string) => { + onCaptureViewSnapshot: (name: string, folderId?: string): string => { const trimmed = name.trim(); - if (!trimmed) return; + if (!trimmed) return ""; const st: ViewSnapshotState = { viewType, view3d, @@ -972,6 +1043,40 @@ export function usePanelHostBase(opts: { ...p, viewSnapshots: [...(p.viewSnapshots ?? []), full], })); + return full.id; + }, + + // Wie `onCaptureViewSnapshot`, aber OHNE getippten Namen: die Ausschnitt- + // Tab-Leiste (DrawingTabs.tsx) legt per „+" einen neuen Tab aus dem + // aktuellen Stand an — Name automatisch die aktive Zeichnungskombination + // (falls deren Sichtbarkeits-Map exakt passt) oder sonst das aktive Blatt + // (Nutzer-Wunsch). Wählt den neuen Ausschnitt sofort an (Tab wird aktiv). + onCaptureViewSnapshotAuto: (): string => { + const drawingVisibility = snapshotDrawingVisibility(); + const combo = matchingComboName(listDrawingCombos(), loadDrawingCombo, drawingVisibility); + const levelName = + project.drawingLevels.find((l) => l.id === activeLevelId)?.name ?? activeLevelId; + const name = combo ?? levelName; + const st: ViewSnapshotState = { + viewType, + view3d, + fov, + scaleDenominator, + detail, + activeLevelId, + layerVisibility: snapshotLayerVisibility(), + drawingVisibility, + enabledOverrideRuleIds: (project.overrideRules ?? []) + .filter((r) => r.enabled) + .map((r) => r.id), + }; + const snap = captureViewSnapshot(`vs-${Date.now()}`, name, st); + setProject((p) => ({ + ...p, + viewSnapshots: [...(p.viewSnapshots ?? []), snap], + })); + setSelectedViewSnapshotId(snap.id); + return snap.id; }, // Wiederherstellen: ALLE Felder zurückspielen. Reihenfolge: Geschoss ZUERST diff --git a/src/state/useProjectActions.ts b/src/state/useProjectActions.ts index e2d081ec..e8d28789 100644 --- a/src/state/useProjectActions.ts +++ b/src/state/useProjectActions.ts @@ -98,6 +98,16 @@ export function useProjectActions( const patchLineStyle = useStore((s) => s.patchLineStyle); const addLineStyle = useStore((s) => s.addLineStyle); const deleteLineStyle = useStore((s) => s.deleteLineStyle); + const addPen = useStore((s) => s.addPen); + const renamePen = useStore((s) => s.renamePen); + const deletePen = useStore((s) => s.deletePen); + const addPenSet = useStore((s) => s.addPenSet); + const renamePenSet = useStore((s) => s.renamePenSet); + const deletePenSet = useStore((s) => s.deletePenSet); + const setActivePenSet = useStore((s) => s.setActivePenSet); + const patchPenSetColor = useStore((s) => s.patchPenSetColor); + const patchPenSetWeight = useStore((s) => s.patchPenSetWeight); + const seedStandardPenSet = useStore((s) => s.seedStandardPenSet); // Wandstile: immutable Patch eines Wandtyps (z. B. Schichtfugen-Stile). Kein // eigener Store-Slice nötig — läuft direkt über setProject wie die übrigen // Ressourcen-Mutationen. @@ -373,6 +383,7 @@ export function useProjectActions( const setElementBackground = useStore((s) => s.setElementBackground); const updateDrawing2D = useStore((s) => s.updateDrawing2D); const reorderDrawings = useStore((s) => s.reorderDrawings); + const reorderDrawingLevels = useStore((s) => s.reorderDrawingLevels); const resizeElement = useStore((s) => s.resizeElement); const updateWall = useStore((s) => s.updateWall); const setWallThickness = useStore((s) => s.setWallThickness); @@ -423,6 +434,16 @@ export function useProjectActions( patchLineStyle, addLineStyle, deleteLineStyle, + addPen, + renamePen, + deletePen, + addPenSet, + renamePenSet, + deletePenSet, + setActivePenSet, + patchPenSetColor, + patchPenSetWeight, + seedStandardPenSet, patchWallType, setOverrideRules, patchCeilingType, @@ -462,6 +483,7 @@ export function useProjectActions( setElementBackground, updateDrawing2D, reorderDrawings, + reorderDrawingLevels, resizeElement, updateWall, setWallThickness, diff --git a/src/state/useProjectFileActions.ts b/src/state/useProjectFileActions.ts index 0bbc6081..591afe50 100644 --- a/src/state/useProjectFileActions.ts +++ b/src/state/useProjectFileActions.ts @@ -22,6 +22,7 @@ import { saveProjectFile, openProjectFileNative, openProjectFileAtPath, + openProjectTemplateNative, acquireProjectLock, releaseProjectLock, registerLockAutoRelease, @@ -29,6 +30,7 @@ import { } from "../io/projectFile"; import type { LockInfo } from "../io/projectFile"; import { addRecentProject, removeRecentProject } from "./recentProjects"; +import { emptyProject, sampleProject } from "../model/sampleProject"; import type { ContextObject, Drawing2D, Project, Vec2 } from "../model/types"; import type { PlanViewHandle } from "../plan/PlanView"; @@ -43,7 +45,7 @@ function drawingsBBox( }; for (const d of drawings) { const g = d.geom; - if (g.shape === "line") { acc(g.a.x, g.a.y); acc(g.b.x, g.b.y); } + if (g.shape === "line" || g.shape === "xline") { acc(g.a.x, g.a.y); acc(g.b.x, g.b.y); } else if (g.shape === "polyline") for (const p of g.pts) acc(p.x, p.y); else if (g.shape === "rect") { acc(g.min.x, g.min.y); acc(g.max.x, g.max.y); } else if (g.shape === "circle" || g.shape === "arc") { @@ -58,6 +60,7 @@ function drawingsBBox( for (const p of g.pts) acc(p.x, p.y); } else if (g.shape === "kote") acc(g.at.x, g.at.y); else if (g.shape === "text") acc(g.at.x, g.at.y); + else if (g.shape === "block") acc(g.at.x, g.at.y); } return Number.isFinite(minX) ? { minX, minY, maxX, maxY } : null; } @@ -68,6 +71,7 @@ function translateDrawing(d: Drawing2D, dx: number, dy: number): Drawing2D { const g = d.geom; switch (g.shape) { case "line": return { ...d, geom: { ...g, a: mv(g.a), b: mv(g.b) } }; + case "xline": return { ...d, geom: { ...g, a: mv(g.a), b: mv(g.b) } }; case "polyline": return { ...d, geom: { ...g, pts: g.pts.map(mv) } }; case "rect": return { ...d, geom: { ...g, min: mv(g.min), max: mv(g.max) } }; case "circle": return { ...d, geom: { ...g, center: mv(g.center) } }; @@ -77,7 +81,17 @@ function translateDrawing(d: Drawing2D, dx: number, dy: number): Drawing2D { case "spline": return { ...d, geom: { ...g, pts: g.pts.map(mv) } }; case "dimension": return { ...d, geom: { ...g, pts: g.pts.map(mv) } }; case "kote": return { ...d, geom: { ...g, at: mv(g.at) } }; - case "text": return { ...d, geom: { ...g, at: mv(g.at) } }; + case "text": + return { + ...d, + geom: { + ...g, + at: mv(g.at), + ...(g.leaderTarget ? { leaderTarget: mv(g.leaderTarget) } : {}), + ...(g.pathPts ? { pathPts: g.pathPts.map(mv) } : {}), + }, + }; + case "block": return { ...d, geom: { ...g, at: mv(g.at) } }; default: return d; } } @@ -107,6 +121,9 @@ export function useProjectFileActions( // über den nativen Dialog (openProjectFileNative), der einen echten Pfad für // den Lock liefert (File-API im Browser hat keinen echten Dateipfad). const projectFileInputRef = useRef(null); + // Verstecktes Datei-Input für „Neu aus Vorlage" (Datei wählen) — derselbe + // Browser-Fallback wie `projectFileInputRef`, nur mit `.obpt`-Filter. + const projectTemplateFileInputRef = useRef(null); // Pfad + Lock-Status der aktuell offenen .obp/.json-Datei (nur Tauri; sonst // bleibt beides null/false — Browser-Blob-Pfad hat keinen echten Pfad). const openedProjectPathRef = useRef(null); @@ -206,6 +223,65 @@ export function useProjectFileActions( addRecentProject(path, project.name || "modell"), ); }; + // „Neu" (Datei-Menü): leeres Projekt, wie am Startbildschirm — löst dabei + // einen evtl. gehaltenen Datei-Lock der bisherigen Projektdatei und vergisst + // deren Pfad (das leere Projekt ist noch NICHT gespeichert). + const onNewProject = () => { + releaseCurrentProjectLock(); + setProject(emptyProject); + }; + + // Übernimmt ein neues, noch UNGESPEICHERTES Projekt aus Vorlagen-Inhalt + // (Musterhaus ODER eine gewählte `.obpt`-Datei): grobe Form-Prüfung wie beim + // normalen Öffnen, aber bewusst OHNE Pfad/Lock zu setzen — die Vorlage + // bleibt unangetastet, das nächste „Speichern" fragt nach einem neuen Ort. + const applyTemplateContent = (content: string): boolean => { + try { + const parsed = JSON.parse(content) as Partial; + if (!Array.isArray(parsed.walls) || !Array.isArray(parsed.layers)) { + console.warn("Vorlagen-Datei hat kein gültiges Projekt-Format (walls/layers fehlen)."); + return false; + } + releaseCurrentProjectLock(); + setProject(parsed as Project); + return true; + } catch (err) { + console.error("Vorlage konnte nicht geladen werden:", err); + return false; + } + }; + // „Neu aus Vorlage: Musterhaus" — das eingebaute Demo-Haus (model/sampleProject.ts) + // als Start eines neuen Projekts. `structuredClone`, damit spätere Bearbeitung + // nicht das gemeinsame Modul-Singleton mutiert (es dient auch als Store- + // Startzustand, s. state/projectSlice.ts). + const onNewProjectFromSample = () => { + releaseCurrentProjectLock(); + setProject(structuredClone(sampleProject)); + }; + // „Neu aus Vorlage: Datei wählen…" — native `.obpt`-Dialog unter Tauri, sonst + // das versteckte `` (projectTemplateFileInputRef). + const onNewProjectFromTemplate = () => { + if (isTauriRuntime()) { + void (async () => { + let opened: Awaited>; + try { + opened = await openProjectTemplateNative(); + } catch (err) { + console.error("Vorlage konnte nicht geöffnet werden:", err); + return; + } + if (opened) applyTemplateContent(opened.content); + })(); + } else { + projectTemplateFileInputRef.current?.click(); + } + }; + const onProjectTemplateFileChosen = (file: File) => { + const r = new FileReader(); + r.onload = () => applyTemplateContent(String(r.result ?? "")); + r.readAsText(file); + }; + // Gibt den Lock der zuletzt geöffneten Projektdatei frei (falls wir ihn // halten) und vergisst den Pfad — vor dem Wechsel auf ein anderes Projekt. const releaseCurrentProjectLock = () => { @@ -378,12 +454,17 @@ export function useProjectFileActions( return { projectFileInputRef, + projectTemplateFileInputRef, openedProjectPathRef, projectLockOwnedRef, lockConflict, setLockConflict, openImportForFile, onSaveProject, + onNewProject, + onNewProjectFromSample, + onNewProjectFromTemplate, + onProjectTemplateFileChosen, releaseCurrentProjectLock, applyOpenedProjectFile, openProjectViaNativeDialog, diff --git a/src/state/useSelectionState.ts b/src/state/useSelectionState.ts index 1d4b2d84..bdf38f10 100644 --- a/src/state/useSelectionState.ts +++ b/src/state/useSelectionState.ts @@ -11,7 +11,7 @@ import { useState } from "react"; import { useStore } from "./appStore"; -import type { Drawing2D } from "../model/types"; +import type { ElementClipboard } from "../editors/elementClipboard"; export function useSelectionState() { const selectedWallIds = useStore((s) => s.selectedWallIds); @@ -26,11 +26,12 @@ export function useSelectionState() { selectedDrawingIds.length === 1 ? selectedDrawingIds[0] : null; const setSelectedDrawingId = (id: string | null) => setSelectedDrawingIds(id ? [id] : []); - // Zwischenablage für 2D-Zeichenelemente (Ctrl/Cmd+C/V). Kopiert die GEWÄHLTEN - // Drawing2D tief; Einfügen legt Klone mit neuen IDs auf dem AKTIVEN Geschoss - // (Zeichnungsebene) an — so lässt sich z. B. importiertes Mobiliar über - // Geschosse hinweg wiederverwenden. Kategorie/Stil bleiben erhalten. - const [drawingClipboard, setDrawingClipboard] = useState([]); + // Zwischenablage für ALLE Bauteil-Arten (Ctrl/Cmd+C/V) — Wand/Decke/Dach/ + // Öffnung/Treppe/Raum/Extrusion/Stütze + 2D-Zeichenelemente, s. + // `editors/elementClipboard.ts`. Kopiert die GEWÄHLTEN Elemente tief; + // Einfügen legt Klone mit neuen IDs auf dem AKTIVEN Geschoss an — so lässt + // sich z. B. importiertes Mobiliar über Geschosse hinweg wiederverwenden. + const [elementClipboard, setElementClipboard] = useState(null); // Bequemer Einzel-Selektor (erste gewählte Wand). const selectedWallId = selectedWallIds[0] ?? null; // Decken-Auswahl (MENGE); für die Einzel-Element-Maschinerie der „eine" @@ -43,9 +44,12 @@ export function useSelectionState() { const selectedRoofIds = useStore((s) => s.selectedRoofIds); const setSelectedRoofIds = useStore((s) => s.setSelectedRoofIds); const selectedRoofId = selectedRoofIds.length === 1 ? selectedRoofIds[0] : null; - // Schnitt-/Ansichtslinien-Auswahl (Einzel-DrawingLevel-Id oder null). - const selectedSectionLineId = useStore((s) => s.selectedSectionLineId); - const setSelectedSectionLineId = useStore((s) => s.setSelectedSectionLineId); + // Schnitt-/Ansichtslinien-Auswahl (MENGE); Einzel-Element bei genau einer + // gewählten Linie (Attribut-/Patch-Logik bleibt darauf zugeschnitten). + const selectedSectionLineIds = useStore((s) => s.selectedSectionLineIds); + const setSelectedSectionLineIds = useStore((s) => s.setSelectedSectionLineIds); + const selectedSectionLineId = + selectedSectionLineIds.length === 1 ? selectedSectionLineIds[0] : null; // Welche Schnittlinie treibt den 3D-Live-Schnitt (reiner Ansichts-Zustand, // unabhängig von der Auswahl — der Schnitt bleibt beim Klick woanders aktiv). const [section3dCutId, setSection3dCutId] = useState(null); @@ -88,8 +92,8 @@ export function useSelectionState() { setSelectedDrawingIds, selectedDrawingId, setSelectedDrawingId, - drawingClipboard, - setDrawingClipboard, + elementClipboard, + setElementClipboard, selectedWallId, selectedCeilingIds, setSelectedCeilingIds, @@ -97,8 +101,9 @@ export function useSelectionState() { selectedRoofIds, setSelectedRoofIds, selectedRoofId, + selectedSectionLineIds, + setSelectedSectionLineIds, selectedSectionLineId, - setSelectedSectionLineId, section3dCutId, setSection3dCutId, updateRoof, diff --git a/src/state/viewSnapshots.test.ts b/src/state/viewSnapshots.test.ts index 0feb9706..0121dcd0 100644 --- a/src/state/viewSnapshots.test.ts +++ b/src/state/viewSnapshots.test.ts @@ -10,6 +10,8 @@ import { readViewSnapshot, applyOverrideRuleEnabled, snapshotMatchesLiveState, + boolMapEqual, + matchingComboName, type ViewSnapshotState, } from "./viewSnapshots"; @@ -194,3 +196,34 @@ describe("viewSnapshots — snapshotMatchesLiveState", () => { expect(snapshotMatchesLiveState(sampleState(), live)).toBe(false); }); }); + +describe("viewSnapshots — boolMapEqual", () => { + it("gleiche Keys/Werte → true, unabhängig von der Einfüge-Reihenfolge", () => { + expect(boolMapEqual({ a: true, b: false }, { b: false, a: true })).toBe(true); + }); + it("unterschiedliche Werte → false", () => { + expect(boolMapEqual({ a: true }, { a: false })).toBe(false); + }); + it("unterschiedliche Key-Menge → false", () => { + expect(boolMapEqual({ a: true, b: true }, { a: true })).toBe(false); + }); +}); + +describe("viewSnapshots — matchingComboName (Grundlage der Ausschnitt-Tab-Auto-Benennung)", () => { + const combos: Record> = { + "Nur EG": { eg: true, og: false }, + "Alles": { eg: true, og: true }, + }; + const load = (name: string) => combos[name] ?? null; + const names = () => Object.keys(combos); + + it("findet den Namen der exakt passenden Kombination", () => { + expect(matchingComboName(names(), load, { eg: true, og: false })).toBe("Nur EG"); + }); + it("liefert null, wenn keine Kombination exakt passt", () => { + expect(matchingComboName(names(), load, { eg: false, og: false })).toBeNull(); + }); + it("liefert null bei leerer Kombinationsliste", () => { + expect(matchingComboName([], load, { eg: true })).toBeNull(); + }); +}); diff --git a/src/state/viewSnapshots.ts b/src/state/viewSnapshots.ts index 0f7f34c6..088dd383 100644 --- a/src/state/viewSnapshots.ts +++ b/src/state/viewSnapshots.ts @@ -87,7 +87,7 @@ export function readViewSnapshot(snap: ViewSnapshot): ViewSnapshotState { } /** Deep-Equal zweier `Record`-Maps: gleiche Keys UND Werte. */ -function boolMapEqual( +export function boolMapEqual( a: Record, b: Record, ): boolean { @@ -100,6 +100,25 @@ function boolMapEqual( return true; } +/** + * Sucht unter den gespeicherten Kombinationen (`names` + `load`) diejenige, + * deren Map EXAKT `target` entspricht — liefert den Namen oder `null`. Basis + * der Footer-Anzeige im Ausschnitte-Panel UND der Auto-Benennung neuer + * Ausschnitt-Tabs (Nutzer-Wunsch: Tab heisst wie die aktive Zeichnungs- + * kombination, falls eine exakt passt). + */ +export function matchingComboName( + names: string[], + load: (name: string) => Record | null, + target: Record, +): string | null { + for (const name of names) { + const map = load(name); + if (map && boolMapEqual(map, target)) return name; + } + return null; +} + /** Mengengleichheit zweier Id-Listen (Reihenfolge egal, Duplikate ignoriert). */ function idSetEqual(a: string[], b: string[]): boolean { if (a.length !== b.length) return false; diff --git a/src/styles.css b/src/styles.css index b2ef96a6..44f24d7e 100644 --- a/src/styles.css +++ b/src/styles.css @@ -1907,6 +1907,42 @@ body { .drawing-tab-label { pointer-events: none; } +.drawing-tab { + display: inline-flex; + align-items: center; + gap: 6px; +} +.drawing-tab-close { + display: inline-flex; + align-items: center; + justify-content: center; + width: 14px; + height: 14px; + border-radius: 4px; + font-size: 13px; + line-height: 1; + opacity: 0.55; +} +.drawing-tab-close:hover { + opacity: 1; + background: rgba(0, 0, 0, 0.12); +} +.drawing-tab-add { + border: none; + background: transparent; + color: var(--muted); + font-family: inherit; + font-size: 14px; + font-weight: 600; + padding: 5px 10px; + border-radius: 8px; + cursor: pointer; + line-height: 1; +} +.drawing-tab-add:hover { + background: var(--accent-dim); + color: var(--ink); +} /* Eine Ansicht füllt die Restfläche. */ .pane { @@ -2019,6 +2055,26 @@ body { font-size: 12px; } +/* Fett hervorgehobener Hinweis, wenn die 3D-Sicht auf dem three.js- + Notfall-Fallback läuft statt der wgpu-Standard-Engine (kein WebGPU im + Browser, oder manuell auf WebGL2 gestellt) — three.js ist kein + Paritätsziel mehr, daher muss sichtbar sein, wenn man ihn gerade sieht. */ +.viewport-engine-badge { + position: absolute; + top: 10px; + left: 10px; + z-index: 5; + padding: 4px 9px; + background: #b02a1e; + color: #fff; + font-weight: 700; + font-size: 11px; + letter-spacing: 0.06em; + border-radius: 4px; + pointer-events: none; + box-shadow: 0 1px 4px rgba(0, 0, 0, 0.35); +} + /* ── Grundriss (SVG) ─────────────────────────────────────────────────── */ .plan-legend { position: absolute; @@ -2120,12 +2176,8 @@ body { stroke-dasharray: 6 4; vector-effect: non-scaling-stroke; } -.plan-svg .plan-group-bbox-corner { - fill: var(--accent); - stroke: #fff; - stroke-width: 1.5; - vector-effect: non-scaling-stroke; -} +/* Erbt Form/Farbe komplett von .plan-grip (Element trägt beide Klassen) — + keine eigenen Farbregeln mehr nötig. */ /* Hervorhebung selektierter 2D-Zeichenelemente (Mehrfach/Marquee): Akzentkontur über der Geometrie, keine Füllung. */ @@ -2199,13 +2251,16 @@ body { stroke-dasharray: 5 4; } -/* Editier-Griffe (Grips) des selektierten Elements: gefüllte Akzent-Quadrate - mit hellem Rand. Ziehbar (Treffer in PlanView per Bildschirm-Pixel). */ +/* Editier-Griffe (Grips) des selektierten Elements: papierfarbene Kreise mit + Akzent-Ring + weichem Schatten (statt der alten gefüllten Quadrate) — wirkt + wie ein modernes Vektor-Tool statt AutoCAD-Grip. Ziehbar (Treffer in + PlanView per Bildschirm-Pixel, unabhängig von der gerenderten Form). */ .plan-svg .plan-grip { - fill: var(--accent-light); - stroke: #fff; - stroke-width: 1.5; + fill: var(--sheet); + stroke: var(--accent); + stroke-width: 1.75; vector-effect: non-scaling-stroke; + filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3)); } /* Bezier-Hilfslinien (Anker → Kontrollpunkt-Griff): dünn, gestrichelt, deutlich @@ -2219,12 +2274,16 @@ body { } /* Kanten-/Seiten-Griffe (Edge Grips): dreieckiger Anfasser je Seite, Spitze - nach außen. Gleiche Akzent-/Rand-Farben wie die Eckpunkt-Griffe. */ + nach außen. Gleiche papierfarbene + Akzent-Ring-Sprache wie die Eckpunkt- + Griffe, nur mit runden statt spitzen Ecken (stroke-linejoin überstimmt die + globale Miter-Regel für Plan-Polygone via höherer Selektor-Spezifität). */ .plan-svg .plan-edge-grip { - fill: var(--accent); - stroke: #fff; + fill: var(--sheet); + stroke: var(--accent); stroke-width: 1.5; + stroke-linejoin: round; vector-effect: non-scaling-stroke; + filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3)); } /* ── Freie 2D-Zeichengeometrie (Drawing2D) ─────────────────────────────── @@ -2263,9 +2322,10 @@ body { stroke-width: 1.25; } .plan-svg .tool-vertex { - fill: var(--accent); - stroke: #fff; - stroke-width: 1; + fill: var(--sheet); + stroke: var(--accent); + stroke-width: 1.5; + filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3)); } .plan-svg .snap-glyph { fill: none; @@ -2998,6 +3058,216 @@ body { cursor: pointer; background: transparent; } +/* Farbe an einen Stift gekoppelt (s. model/penSets.ts) — Swatch bleibt + sichtbar (zeigt die gebackene Farbe), der native Picker ist gesperrt: die + Farbe kommt jetzt aus dem aktiven Stiftsatz, nicht mehr aus freier Wahl. */ +.res-color-disabled { + cursor: default; + opacity: 0.85; +} +.res-color-disabled .res-color-swatch::after { + content: ""; + position: absolute; + inset: 0; + background: repeating-linear-gradient( + 45deg, + rgba(255, 255, 255, 0.25) 0 3px, + transparent 3px 6px + ); +} + +/* Farbfeld mit Stift-Umschalter (ComponentsTab, Ebenen-Editor): Swatch + ein + Dropdown „Frei"/Stiftname daneben. */ +.res-pen-color { + display: flex; + align-items: center; + gap: 6px; +} + +/* Eine Stift-Zeile im Stiftsatz-Detail: Name + Farbe + Löschen nebeneinander. */ +.res-pen-row { + display: flex; + align-items: center; + gap: 8px; +} +.res-pen-row .res-input { + flex: 1; +} + +/* Aktiv-Kennzeichnung eines Stiftsatzes in der Master-Liste. */ +.res-pen-active-badge { + margin-left: auto; + font-size: 10px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--accent); + background: var(--accent-dim); + border-radius: 999px; + padding: 2px 8px; +} + +/* ── PenColorField (ui/PenColorField.tsx) — Farbe+Stift, gemeinsam für + ComponentsTab/Ebenen-Editor/Attribut-Panel ────────────────────────────── */ +.pen-color-field { + display: flex; + align-items: center; + gap: 6px; + flex-wrap: wrap; +} +/* Hält Swatch + Nummer-Badge zusammen; das Badge sitzt absolut relativ zu + DIESEM Wrapper (nicht mehr im + ); +} + +export function PenColorField({ + color, + penId, + pens, + activeStyles, + onColorChange, + onPenChange, + showWeight, + disabled, +}: PenColorFieldProps) { + const [open, setOpen] = useState(false); + const [pos, setPos] = useState({ left: 0, top: 0 }); + // Tipp-Puffer fürs Hex-Feld — erlaubt unvollständige Zwischenzustände beim + // Tippen (z. B. "#3f"), ohne dass der kontrollierte Wert sie sofort verwirft. + const [hexDraft, setHexDraft] = useState(color); + // Direkt-Edit des Badges (Nutzer-Wunsch): Klick auf das Nummer-Badge ODER + // den Swatch selbst — nur im Stift-Modus — springt sofort in ein kleines + // Inline-Zahlenfeld, ohne erst das ganze Popover öffnen zu müssen. + const [badgeEditing, setBadgeEditing] = useState(false); + const [badgeDraft, setBadgeDraft] = useState(""); + const btnRef = useRef(null); + const badgeInputRef = useRef(null); + const popRef = useRef(null); + + const openPopover = () => { + const r = btnRef.current?.getBoundingClientRect(); + if (r) setPos({ left: r.left, top: r.bottom + 4 }); + setHexDraft(color); + setOpen(true); + }; + const close = () => setOpen(false); + + // Nach dem Öffnen: an den Viewport-Rand clampen (gleiche Technik wie Dropdown.tsx). + useLayoutEffect(() => { + if (!open) return; + const el = popRef.current; + if (!el) return; + const rect = el.getBoundingClientRect(); + const vw = window.innerWidth; + const vh = window.innerHeight; + setPos((p) => { + let left = p.left; + let top = p.top; + if (left + rect.width > vw - EDGE_PAD) left = vw - rect.width - EDGE_PAD; + if (top + rect.height > vh - EDGE_PAD) { + const r = btnRef.current?.getBoundingClientRect(); + top = r ? r.top - rect.height - 4 : vh - rect.height - EDGE_PAD; + } + if (left < EDGE_PAD) left = EDGE_PAD; + if (top < EDGE_PAD) top = EDGE_PAD; + return { left, top }; + }); + }, [open]); + + // Aussenklick/Scroll/Resize schliesst (gleiche Technik wie Dropdown.tsx). + useEffect(() => { + if (!open) return; + const onPointerDown = (e: PointerEvent) => { + const tgt = e.target as Node; + if (popRef.current?.contains(tgt) || btnRef.current?.contains(tgt)) return; + close(); + }; + const onScrollOrResize = () => close(); + window.addEventListener("pointerdown", onPointerDown, true); + window.addEventListener("scroll", onScrollOrResize, true); + window.addEventListener("resize", onScrollOrResize); + return () => { + window.removeEventListener("pointerdown", onPointerDown, true); + window.removeEventListener("scroll", onScrollOrResize, true); + window.removeEventListener("resize", onScrollOrResize); + }; + }, [open]); + + const weight = penId !== undefined ? activeStyles?.[penId]?.weight : undefined; + const isPen = penId !== undefined; + + const commitHex = (raw: string) => { + setHexDraft(raw); + if (HEX_RE.test(raw)) onColorChange(normalizeHex(raw)); + }; + const pickFree = (hex: string) => { + setHexDraft(hex); + onColorChange(hex); + }; + + const startBadgeEdit = (e: MouseEvent) => { + if (disabled || !isPen) return; + e.stopPropagation(); + if (open) close(); + setBadgeDraft(penId ?? "1"); + setBadgeEditing(true); + }; + const commitBadge = () => { + const digits = badgeDraft.replace(/[^0-9]/g, ""); + onPenChange(digits === "" ? "1" : digits); + setBadgeEditing(false); + }; + + // Nach dem Umschalten in den Edit-Modus: Fokus + Textauswahl, damit sofort + // überschrieben werden kann (wie ein Doppelklick-Rename). + useEffect(() => { + if (!badgeEditing) return; + badgeInputRef.current?.focus(); + badgeInputRef.current?.select(); + }, [badgeEditing]); + + return ( +
+ + + ))} + + {showWeight && isPen && ( + + {t("pen.weightHint", { weight: (weight ?? 0).toFixed(2) })} + + )} + {open && + createPortal( +
+
+ onPenChange(v === "pen" ? (penId ?? "1") : undefined)} + options={[ + { value: "free", label: t("pen.free") }, + { value: "pen", label: t("pen.byPen") }, + ]} + /> + {isPen ? ( + { + const digits = e.target.value.replace(/[^0-9]/g, ""); + onPenChange(digits === "" ? "1" : digits); + }} + /> + ) : ( + commitHex(e.target.value)} + onBlur={() => setHexDraft(color)} + /> + )} +
+ {isPen ? ( +
+ {pens.map((p) => ( + { + onPenChange(p.id); + close(); + }} + /> + ))} + {pens.length === 0 &&
{t("resources.pens.empty")}
} +
+ ) : ( + <> +
+ {FREE_COLOR_PALETTE.map((hex) => ( + { + pickFree(hex); + close(); + }} + /> + ))} +
+ + + )} +
, + document.body, + )} +
+ ); +} diff --git a/src/ui/ResourceManager.tsx b/src/ui/ResourceManager.tsx index c0f15f51..f2abdd2a 100644 --- a/src/ui/ResourceManager.tsx +++ b/src/ui/ResourceManager.tsx @@ -40,6 +40,7 @@ import { WindowStylesTab } from "./resourceManager/WindowStylesTab"; import { StairStylesTab } from "./resourceManager/StairStylesTab"; import { MaterialsTab } from "./resourceManager/MaterialsTab"; import { OverridesTab } from "./resourceManager/OverridesTab"; +import { PenSetsTab } from "./resourceManager/PenSetsTab"; // ── Manager-Schublade ────────────────────────────────────────────────────── @@ -54,12 +55,14 @@ export type TabId = | "windowStyles" | "stairStyles" | "materials" - | "overrides"; + | "overrides" + | "pens"; const TABS: { id: TabId; labelKey: string }[] = [ { id: "components", labelKey: "resources.tab.components" }, { id: "hatches", labelKey: "resources.tab.hatches" }, { id: "lines", labelKey: "resources.tab.lines" }, + { id: "pens", labelKey: "resources.tab.pens" }, { id: "wallStyles", labelKey: "resources.tab.wallStyles" }, { id: "ceilingStyles", labelKey: "resources.tab.ceilingStyles" }, { id: "roofStyles", labelKey: "resources.tab.roofStyles" }, @@ -116,6 +119,22 @@ export interface ResourceManagerHandlers { onAddStairType?: () => void; onPatchStairType?: (id: string, patch: Partial) => void; onDeleteStairType?: (id: string) => void; + /** + * Stiftsätze (ArchiCAD-Stiftsatz-Muster, s. `model/penSets.ts`). Optional, + * damit ältere Einbettungen ohne diese Handler weiter kompilieren; ohne + * Handler bleibt der Tab nur lesend (Aktiv-Anzeige, keine Editier-Buttons). + */ + onAddPen?: () => void; + onRenamePen?: (id: string, name: string) => void; + onDeletePen?: (id: string) => void; + onAddPenSet?: () => void; + onRenamePenSet?: (id: string, name: string) => void; + onDeletePenSet?: (id: string) => void; + onSetActivePenSet?: (id: string) => void; + onPatchPenSetColor?: (setId: string, penId: string, color: string) => void; + onPatchPenSetWeight?: (setId: string, penId: string, weight: number) => void; + /** Ersetzt `pens`/legt einen neuen Satz mit der 255er-CAD-Standardpalette an. */ + onSeedStandardPenSet?: () => void; } // ── Schwebendes Fenster (nicht-modal) ────────────────────────────────────── @@ -371,6 +390,21 @@ export function ResourceManager({ onDeleteStairType={handlers.onDeleteStairType} /> )} + {tab === "pens" && ( + + )} {tab === "materials" && } {tab === "overrides" && ( = 2 && hatch.motif.length > 1e-6) { + // Eigenes Motiv: EINE Wiederhollänge als -Kachel (analog zur + // Bild-Schraffur oben) — motif.x (0..length) läuft entlang der Kachel- + // Höhe (wie die Musterlinie bei diagonal/crosshatch), motif.y (Versatz + // quer) entlang der Kachelbreite. Bewusst eigenständig tesseliert (KEIN + // Import aus glPlanHatch, s. Moduldoc oben) — schematisch/px, wie der + // übrige Swatch, nicht deckungsgleich mit dem Plan-Renderer. + const PX_PER_MM = 2; + const rowSpacing = Math.max(3, 8 / Math.sqrt(scale)); + const period = Math.max(4, hatch.motif.length * scale * PX_PER_MM); + const d = hatch.motif.points + .map((p, i) => { + const x = (p.y * scale * PX_PER_MM).toFixed(1); + const y = (p.x * scale * PX_PER_MM).toFixed(1); + return `${i === 0 ? "M" : "L"} ${x} ${y}`; + }) + .join(" "); + inner = ( + <> + + + + + + + + ); } else { - // "diagonal" (Default): eine parallele Schar. + // "diagonal" (Default, auch "custom" ohne gesetztes Motiv): eine parallele Schar. inner = parallelLines(w, h, angle, spacing, 0.8, "d"); } diff --git a/src/ui/resourceManager/ComponentsTab.tsx b/src/ui/resourceManager/ComponentsTab.tsx index 73f0806b..92ea77c5 100644 --- a/src/ui/resourceManager/ComponentsTab.tsx +++ b/src/ui/resourceManager/ComponentsTab.tsx @@ -19,7 +19,16 @@ import { requestMaterialPreview, cancelMaterialPreview } from "../../materials/s import { Dropdown } from "../Dropdown"; import { HatchSwatch } from "../hatchPreview"; import { t } from "../../i18n"; -import { DeleteButton, FieldRow, ImagePickButton, TextField, ColorField, NumberField, SelectField } from "./fields"; +import { activePenSet, resolvePenColor } from "../../model/penSets"; +import { PenColorField } from "../PenColorField"; +import { + DeleteButton, + FieldRow, + ImagePickButton, + TextField, + NumberField, + SelectField, +} from "./fields"; /** * Material-Zelle der Bauteil-Tabelle: ein Button, der den aktuellen Material- @@ -562,14 +571,19 @@ function ComponentMaterialSphere({ function ComponentDetail({ component, hatches, + project, onPatch, onDelete, }: { component: Component; hatches: Project["hatches"]; + /** Für die Stift-Kopplung (`PenColorField`): `project.pens` + aktiver Stiftsatz. */ + project: Project; onPatch: (patch: Partial) => void; onDelete: () => void; }) { + const pens = project.pens ?? []; + const activeStyles = activePenSet(project)?.pens; const hatchOptions = hatches.map((h) => ({ value: h.id, label: h.name })); // Ansichts-Schraffur ist optional; Leer-Eintrag = keine Schraffur (weiss). const viewHatchOptions = [ @@ -610,15 +624,46 @@ function ComponentDetail({ placeholder={t("resources.col.abbrev.placeholder")} /> + + {/* Grundfarbe = 3D-Diffusfarbe + Fallback für Vorder-/Hintergrund. */} + onPatch({ color, colorPenId: undefined })} + onPenChange={(colorPenId) => + onPatch( + colorPenId + ? { colorPenId, color: resolvePenColor(project, colorPenId) } + : { colorPenId: undefined }, + ) + } + /> + {/* Vordergrund = Farbe der Muster-/Schraffurlinien. Fehlt sie, greift als Anzeige-Fallback `color`; das Setzen definiert `foreground`. */} - onPatch({ foreground })} + onPatch({ foreground, foregroundPenId: undefined })} + onPenChange={(foregroundPenId) => + onPatch( + foregroundPenId + ? { foregroundPenId, foreground: resolvePenColor(project, foregroundPenId) } + : { foregroundPenId: undefined }, + ) + } /> {/* Hintergrund = Füllung (Poché). Fehlt sie, gilt `color` als Fallback. */} - onPatch({ background })} + onPatch({ background, backgroundPenId: undefined })} + onPenChange={(backgroundPenId) => + onPatch( + backgroundPenId + ? { backgroundPenId, background: resolvePenColor(project, backgroundPenId) } + : { backgroundPenId: undefined }, + ) + } /> @@ -730,6 +789,7 @@ export function ComponentsTab({ key={selected.id} component={selected} hatches={project.hatches} + project={project} onPatch={(patch) => onPatchComponent(selected.id, patch)} onDelete={() => { revokeMaterialUrls(selected.material); diff --git a/src/ui/resourceManager/HatchesTab.tsx b/src/ui/resourceManager/HatchesTab.tsx index a223ae29..f297aaee 100644 --- a/src/ui/resourceManager/HatchesTab.tsx +++ b/src/ui/resourceManager/HatchesTab.tsx @@ -6,6 +6,7 @@ import { useState } from "react"; import type { HatchPattern, HatchStyle, LineStyle, Project } from "../../model/types"; import { parsePat } from "../../io/patParser"; import { HatchSwatch } from "../hatchPreview"; +import { MotifEditor } from "../MotifEditor"; import { t } from "../../i18n"; import { DeleteButton, @@ -24,8 +25,25 @@ const PATTERN_OPTIONS: { value: HatchPattern; labelKey: string }[] = [ { value: "insulation", labelKey: "pattern.insulation" }, { value: "diagonal", labelKey: "pattern.diagonal" }, { value: "crosshatch", labelKey: "pattern.crosshatch" }, + { value: "custom", labelKey: "pattern.custom" }, ]; +/** + * Default-Motiv beim Umschalten auf „Custom": dieselbe Dreieckszelle wie beim + * Linien-Custom-Motiv (`LinesTab.tsx`) — konsistenter Startpunkt, der Nutzer + * passt sie im MotifEditor an. + */ +const DEFAULT_MOTIF: NonNullable = { + points: [ + { x: 0, y: 0 }, + { x: 1, y: 1.5 }, + { x: 2, y: 0 }, + { x: 3, y: -1.5 }, + { x: 4, y: 0 }, + ], + length: 4, +}; + /** Detail-Panel EINER Schraffur (rechte Seite des Master-Detail-Layouts). */ function HatchDetail({ hatch, @@ -55,6 +73,15 @@ function HatchDetail({ } }; + /** Wechselt das Muster; beim erstmaligen Umschalten auf „Custom" ein Default-Motiv setzen. */ + const setPattern = (pattern: HatchPattern) => { + if (pattern === "custom" && !hatch.motif) { + onPatch({ pattern, motif: DEFAULT_MOTIF }); + } else { + onPatch({ pattern }); + } + }; + /** Merge-Patch für die Bild-Parameter (behält bestehende Werte). */ const patchImage = (part: Partial>) => { const cur = hatch.image ?? { src: "", scaleX: 1, scaleY: 1, rotation: 0 }; @@ -123,13 +150,22 @@ function HatchDetail({ onPatch({ pattern })} + onChange={setPattern} options={PATTERN_OPTIONS.map((o) => ({ value: o.value, label: t(o.labelKey), }))} /> + {hatch.pattern === "custom" && ( + + onPatch({ motif: { points, length } })} + /> + + )} void; + onDelete: () => void; + onActivate: () => void; + onPatchColor: (penId: string, color: string) => void; + onPatchWeight: (penId: string, weight: number) => void; + onAddPen?: () => void; + onRenamePen?: (id: string, name: string) => void; + onDeletePen?: (id: string) => void; +}) { + return ( +
+
+ onRename(e.target.value)} + /> + +
+ + {isActive ? ( +
{t("resources.pens.isActive")}
+ ) : ( + + )} + +
+ {pens.map((pen) => { + const style = penSet.pens[pen.id] ?? { color: PEN_FALLBACK_COLOR, weight: PEN_FALLBACK_WEIGHT }; + return ( + +
+ onRenamePen?.(pen.id, name)} /> + onPatchColor(pen.id, color)} /> + onPatchWeight(pen.id, weight)} + step={0.01} + min={0} + list="pen-set-weights" + /> + onDeletePen?.(pen.id)} + title={t("resources.delete.pen", { name: pen.name })} + /> +
+
+ ); + })} + {pens.length === 0 &&
{t("resources.pens.empty")}
} +
+
+ +
+
+ ); +} + +export function PenSetsTab({ + project, + onAddPen, + onRenamePen, + onDeletePen, + onAddPenSet, + onRenamePenSet, + onDeletePenSet, + onSetActivePenSet, + onPatchPenSetColor, + onPatchPenSetWeight, + onSeedStandardPenSet, +}: { + project: Project; + onAddPen?: () => void; + onRenamePen?: (id: string, name: string) => void; + onDeletePen?: (id: string) => void; + onAddPenSet?: () => void; + onRenamePenSet?: (id: string, name: string) => void; + onDeletePenSet?: (id: string) => void; + onSetActivePenSet?: (id: string) => void; + onPatchPenSetColor?: (setId: string, penId: string, color: string) => void; + onPatchPenSetWeight?: (setId: string, penId: string, weight: number) => void; + onSeedStandardPenSet?: () => void; +}) { + const [selectedId, setSelectedId] = useState(null); + const pens = project.pens ?? []; + const penSets = project.penSets ?? []; + const selected = penSets.find((s) => s.id === selectedId) ?? penSets[0]; + + return ( +
+ {/* Vorschlagswerte für die Strichstärke (Standard-Stiftbreiten in mm) — analog LinesTab. */} + + {PEN_WEIGHTS.map((w) => ( + +
{t("resources.pens.hint")}
+
+
+ {penSets.map((s) => ( + + ))} + {penSets.length === 0 && ( +
{t("resources.pens.emptySets")}
+ )} +
+ + +
+
+
+ {selected ? ( + onRenamePenSet?.(selected.id, name)} + onDelete={() => onDeletePenSet?.(selected.id)} + onActivate={() => onSetActivePenSet?.(selected.id)} + onPatchColor={(penId, color) => onPatchPenSetColor?.(selected.id, penId, color)} + onPatchWeight={(penId, weight) => onPatchPenSetWeight?.(selected.id, penId, weight)} + onAddPen={onAddPen} + onRenamePen={onRenamePen} + onDeletePen={onDeletePen} + /> + ) : ( +
{t("resources.pens.emptySets")}
+ )} +
+
+
+ ); +} diff --git a/src/ui/resourceManager/fields.tsx b/src/ui/resourceManager/fields.tsx index 01a129e9..61661d93 100644 --- a/src/ui/resourceManager/fields.tsx +++ b/src/ui/resourceManager/fields.tsx @@ -69,26 +69,36 @@ export function NumberField({ * Farb-Swatch mit nativem Color-Picker. Das