Aufgestauter Arbeitsstand: Stiftsätze, Bulge/Bögen, neue 2D-Befehle, Geo/Import-Fixes, Dach-Schnittfugen 3D

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.
This commit is contained in:
karim committed 2026-09-10 15:40:04 +02:00
1 parent 91908b1456
commit ef40091f6d
136 files changed
+11109 -665

No files matched your search

+4
View File
@@ -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
+1 -1
View File
@@ -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={}",
+6 -4
View File
@@ -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, &[]);
+1
View File
@@ -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;
+264
View File
@@ -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<CutPolygon> {
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<CutBandMeta>) -> 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<f32> = 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());
}
}
+99 -11
View File
@@ -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<Prism> = 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));
}
}
+36 -26
View File
@@ -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<CutPolygon> {
let out = cut_section(plane, walls, slabs);
fn cut_cap_polys(
plane: &SectionPlane,
walls: &[WallInput],
slabs: &[SlabInput],
roofs: &[RoofLayerInput],
) -> Vec<CutPolygon> {
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<f32> {
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<f32> {
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<f32> = 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"
+44
View File
@@ -268,6 +268,50 @@ pub struct SlabInput {
pub cut: Option<CutBandMeta>,
}
/// 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<Hatch>,
/// 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<CutBandMeta>,
}
fn default_slab_color() -> Rgb {
[0.86, 0.86, 0.88]
}
+26 -6
View File
@@ -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<MeshInput>,
/// 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<RoofLayerInput>,
}
/// 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<WallInput>,
slabs: Vec<SlabInput>,
/// Gecachte Dach-Schichten (analog `walls`/`slabs`) fuer denselben Zweck —
/// der Live-Schnitt braucht sie bei jedem `set_section_plane`/`set_model`.
roof_layers: Vec<RoofLayerInput>,
/// 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(())
}
+134 -47
View File
@@ -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<Record<ToolId, string>> = {
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 (
<StartScreen
onNewProject={() => {
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). */}
<input
ref={projectTemplateFileInputRef}
type="file"
accept={`.${PROJECT_TEMPLATE_EXT}`}
style={{ display: "none" }}
onChange={(e) => {
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 : (
<AppMenuBar
onNewProject={onNewProject}
onNewProjectFromSample={onNewProjectFromSample}
onNewProjectFromTemplate={onNewProjectFromTemplate}
onOpenProject={onOpenProject}
onSaveProject={onSaveProject}
onImport={() => 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() {
/>
</EditorField>
<EditorField label={t("editor.color")}>
<input
type="color"
value={cat.color}
onChange={(e) =>
patchCategory(cat.code, { color: e.target.value })
<PenColorField
color={cat.colorPenId ? resolvePenColor(project, cat.colorPenId) : cat.color}
penId={cat.colorPenId}
pens={project.pens ?? []}
activeStyles={activePenSet(project)?.pens}
showWeight
onColorChange={(color) => patchCategory(cat.code, { color, colorPenId: undefined })}
onPenChange={(colorPenId) =>
patchCategory(cat.code, {
colorPenId,
...(colorPenId
? { color: resolvePenColor(project, colorPenId), lw: resolvePenWeight(project, colorPenId) }
: {}),
})
}
/>
</EditorField>
@@ -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) })
}
+75 -65
View File
@@ -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 (
<div className="drawing-tabs" role="tablist" aria-label={t("tabs.drawings")}>
{drawings.map((d) => (
{snapshots.map((s) => (
<button
key={d.id}
key={s.id}
type="button"
role="tab"
aria-selected={d.levelId === activeLevelId}
className={`drawing-tab${d.levelId === activeLevelId ? " active" : ""}`}
onClick={() => activate(d)}
title={d.title}
aria-selected={s.id === selectedId}
className={`drawing-tab${s.id === selectedId ? " active" : ""}`}
onClick={() => onApply(s.id)}
title={s.name}
>
<span className="drawing-tab-label">{d.title}</span>
<span className="drawing-tab-label">{s.name}</span>
{snapshots.length > 1 && (
<span
className="drawing-tab-close"
role="button"
aria-label={t("tabs.delete")}
title={t("tabs.delete")}
onClick={(e) => {
e.stopPropagation();
onDelete(s.id);
}}
>
×
</span>
)}
</button>
))}
<button
type="button"
className="drawing-tab-add"
aria-label={t("tabs.add")}
title={t("tabs.add")}
onClick={() => onCaptureAuto()}
>
+
</button>
</div>
);
}
+80
View File
@@ -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);
}
});
});
+87
View File
@@ -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(),
};
+3 -1
View File
@@ -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 }],
+111
View File
@@ -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);
});
});
+90
View File
@@ -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(),
};
+110
View File
@@ -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);
});
});
+75 -13
View File
@@ -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<Vec2[]>((acc, [a, b], i) => {
if (i === 0) acc.push(a);
acc.push(b);
return acc;
}, [])
: next.pts;
return [{ kind: "poly", pts, closed: false }];
}
// ── Zustand ───────────────────────────────────────────────────────────────────
+23
View File
@@ -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)", () => {
+32 -12
View File
@@ -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)),
+72
View File
@@ -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);
});
});
+97
View File
@@ -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(),
};
+58 -26
View File
@@ -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<Vec2[]>((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 {
+120
View File
@@ -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);
});
});
+157
View File
@@ -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<string, number> => {
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 };
},
};
+80
View File
@@ -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();
});
});
+137
View File
@@ -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<string, number>, 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<string, number> => {
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,
};
},
};
+108
View File
@@ -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);
});
});
+71 -22
View File
@@ -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<Vec2[]>((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;
+86
View File
@@ -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);
});
});
+136
View File
@@ -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<string, number>, 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<string, number> => {
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,
};
},
};
+25
View File
@@ -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<string, Command> = {
@@ -56,15 +62,19 @@ export const COMMANDS: Record<string, Command> = {
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<string, Command> = {
sectionline: sectionLineCommand,
viewline: viewLineCommand,
georef: georefCommand,
block: blockCommand,
defblock: defblockCommand,
};
/**
@@ -112,11 +124,20 @@ export const ALIASES: Record<string, string> = {
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<string, string> = {
tx: "text",
txt: "text",
beschriftung: "text",
ld: "leader",
vorführer: "leader",
txp: "textpath",
pfadtext: "textpath",
m: "move",
s: "mirror",
spiegeln: "mirror",
-1
View File
@@ -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 ────────────────────────────────────────────────────────────
+145
View File
@@ -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");
});
});
+236
View File
@@ -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<string, string>();
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 };
+95
View File
@@ -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
});
});
+50 -24
View File
@@ -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;
+74
View File
@@ -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);
});
});
+141
View File
@@ -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);
}
+70
View File
@@ -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)
});
});
+77
View File
@@ -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]);
});
});
+118
View File
@@ -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]);
});
});
+491
View File
@@ -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;
}
+73 -1
View File
@@ -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)",
+73 -1
View File
@@ -126,6 +126,10 @@ export const en: Record<TranslationKey, string> = {
// 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<TranslationKey, string> = {
"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<TranslationKey, string> = {
"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<TranslationKey, string> = {
"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<TranslationKey, string> = {
// 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<TranslationKey, string> = {
"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<TranslationKey, string> = {
"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<TranslationKey, string> = {
"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<TranslationKey, string> = {
"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<TranslationKey, string> = {
"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<TranslationKey, string> = {
"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<TranslationKey, string> = {
"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<TranslationKey, string> = {
"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<TranslationKey, string> = {
"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<TranslationKey, string> = {
"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<TranslationKey, string> = {
// 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<TranslationKey, string> = {
"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)",
+186
View File
@@ -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<number, { x: number; y: number; z: number }> = {
[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);
});
});
+256 -14
View File
@@ -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<string, MeshBucket>;
contours: Contour[];
entityCounts: Record<string, number>;
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<bigint, string> {
const map = new Map<bigint, string>();
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<string, Transform2D> {
const map = new Map<string, Transform2D>();
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<LibreDwgApi["convert"]>,
modelSpaceEntities: DwgEntityLike[],
): Map<string, MeshBucket> {
const result = new Map<string, MeshBucket>();
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<DxfImportResult> {
const libredwg = await createLibreDwg();
@@ -289,8 +507,7 @@ export async function parseDwg(data: ArrayBuffer): Promise<DxfImportResult> {
}
const acc: Accum = {
meshTriangles: [],
meshIndices: [],
meshesByLayer: new Map(),
contours: [],
entityCounts: {},
total: 0,
@@ -299,14 +516,36 @@ export async function parseDwg(data: ArrayBuffer): Promise<DxfImportResult> {
// 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<DxfImportResult> {
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 =>
!!(
+3
View File
@@ -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,
});
}
+3
View File
@@ -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,
};
+34
View File
@@ -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<OpenedProjectFile | null>
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
* `<input type=file accept=".obpt">`-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<OpenedProjectFile | null> {
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
+85 -6
View File
@@ -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<Response | null> {
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<string | null> {
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<ArrayBuffer | null> {
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;
}
}
+40
View File
@@ -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");
});
});
+123 -14
View File
@@ -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,
});
}
}
}
+28
View File
@@ -60,6 +60,9 @@ export interface MenuActions {
patchCategory: (code: string, patch: Partial<LayerCategory>) => 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: <MenuIcon name="flip_to_front" />,
onClick: () => a.reorderLevel(id, "front"),
},
{
label: t("ctx.arrange.forward"),
icon: <MenuIcon name="arrow_upward" />,
onClick: () => a.reorderLevel(id, "forward"),
},
{
label: t("ctx.arrange.backward"),
icon: <MenuIcon name="arrow_downward" />,
onClick: () => a.reorderLevel(id, "backward"),
},
{
label: t("ctx.arrange.back"),
icon: <MenuIcon name="flip_to_back" />,
onClick: () => a.reorderLevel(id, "back"),
},
{ divider: true },
{
label: t("ctx.delete"),
icon: <MenuIcon name="delete" />,
+110
View File
@@ -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([]);
});
});
+175
View File
@@ -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<GeoCategory, ContextCategoryDef> = {
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<string>,
): LayerCategory[] {
const existing = new Set(collectCodes(layers));
const missing = new Set<string>();
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;
}
+11
View File
@@ -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) } };
+60
View File
@@ -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 };
+49 -11
View File
@@ -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 };
+352
View File
@@ -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> = {}): 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> = {}): Component => ({
id: "c1",
name: "C1",
color: "#111111",
hatchId: "none",
joinPriority: 10,
...overrides,
});
const cat = (overrides: Partial<LayerCategory> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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");
});
});
+253
View File
@@ -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<string, PenStyle> } {
const pens: ColorPen[] = [];
const styles: Record<string, PenStyle> = {};
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<T extends { colorPenId?: string; color?: string }>(
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<Record<K, number>>, 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)),
};
}
+18 -5
View File
@@ -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",
+22 -5
View File
@@ -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,
};
}
+237 -2
View File
@@ -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<string, PenStyle>;
}
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 `<textPath>` 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). */
+22
View File
@@ -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",
+88 -21
View File
@@ -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,
) => <ColorHexField value={value ?? "#808080"} onChange={onSet} disabled={!editable} />;
// 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 ──────────────────────────────────────────── */}
<div className="attr-section-label">{t("attr.stroke")}</div>
{/* 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). */}
<span className="attr-key">{t("attr.color")}</span>
<span className="attr-val">
<ColorHexField value={sel.color} onChange={host.onSetSelectionColor} />
<PenColorField
color={sel.color}
penId={sel.colorPenId}
pens={project.pens ?? []}
activeStyles={activePenSet(project)?.pens}
showWeight={weightEditable}
onColorChange={host.onSetSelectionColor}
onPenChange={host.onSetSelectionColorPen}
/>
</span>
{/* 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]) => (
<Fragment key={key}>
<span className="attr-key">{t(labelKey)}</span>
<span className="attr-val">
<input
className="attr-num"
style={{ width: 72 }}
type="number"
step={0.05}
min={min}
max={max}
value={sel.imageFilters?.[key] ?? neutral}
onChange={(e) => {
const v = Number(e.target.value);
if (Number.isFinite(v))
host.onSetSelectionImageFilters({ [key]: Math.max(min, Math.min(max, v)) });
}}
/>
</span>
</Fragment>
))}
</>
)}
{/* Linienstil — nur Drawing2D trägt ihn (Wand/Decke/Annotation etc.
read-only), Rest wie gehabt. */}
{!isAnnotation && (
@@ -392,12 +437,26 @@ export function AttributesPanel() {
<>
<div className="attr-section-label">{t("attr.fill")}</div>
{/* 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),
<PenColorField
color={sel.effectiveForeground ?? "#808080"}
penId={sel.foregroundPenId}
pens={project.pens ?? []}
activeStyles={activePenSet(project)?.pens}
disabled={!pocheEditable}
onColorChange={host.onSetSelectionForeground}
onPenChange={host.onSetSelectionForegroundPen}
/>,
)}
{sourceRow(
@@ -405,7 +464,15 @@ export function AttributesPanel() {
pocheEditable,
bgUi,
onBackgroundSourceChange,
colorValue(sel.effectiveBackground, host.onSetSelectionBackground, pocheEditable),
<PenColorField
color={sel.effectiveBackground ?? "#808080"}
penId={sel.backgroundPenId}
pens={project.pens ?? []}
activeStyles={activePenSet(project)?.pens}
disabled={!pocheEditable}
onColorChange={host.onSetSelectionBackground}
onPenChange={host.onSetSelectionBackgroundPen}
/>,
)}
{sourceRow(
+49 -1
View File
@@ -108,6 +108,14 @@ export function ToolIcon({ id }: { id: ToolId }) {
<line x1="3" y1="13" x2="13" y2="3" />
</svg>
);
case "xline":
// Volle Diagonale (randberührend) im Strich-Punkt-Muster — deutet die
// „unendliche" Konstruktionslinie an.
return (
<svg {...common}>
<line x1="0.5" y1="14.5" x2="15.5" y2="1.5" strokeDasharray="3 1.2 0.6 1.2" />
</svg>
);
case "polyline":
// Dreisegmentiger Zickzack.
return (
@@ -145,6 +153,23 @@ export function ToolIcon({ id }: { id: ToolId }) {
<ellipse cx="8" cy="8" rx="6" ry="4" />
</svg>
);
case "polygon":
// Regelmässiges Sechseck als generisches Vieleck-Symbol.
return (
<svg {...common}>
<polygon points="8,2.5 13,5.5 13,10.5 8,13.5 3,10.5 3,5.5" />
</svg>
);
case "block":
// Gestricheltes Symbol-Rechteck (gruppierter Inhalt) + Einfügepunkt
// (gefüllter Punkt am Ursprung).
return (
<svg {...common}>
<rect x="4.5" y="2.5" width="9" height="9" strokeDasharray="2 1.4" />
<circle cx="2.5" cy="13.5" r="1.1" fill="currentColor" stroke="none" />
<line x1="2.5" y1="13.5" x2="6" y2="10" strokeDasharray="1.5 1.2" />
</svg>
);
case "spline":
// Glatte S-Kurve durch drei Wegpunkte.
return (
@@ -196,6 +221,24 @@ export function ToolIcon({ id }: { id: ToolId }) {
<path d="M 5.5 9.5 L 10.5 9.5" fill="none" />
</svg>
);
case "leader":
// Pfeil zu einem Zielpunkt + kurze Textzeile (Legenden-/Vorführungspfeil).
return (
<svg {...common}>
<line x1="9" y1="9" x2="13.5" y2="4" />
<polygon points="13.5,4 10.7,4.4 13.1,6.8" fill="currentColor" stroke="none" />
<line x1="2.5" y1="9" x2="9" y2="9" />
<line x1="2.5" y1="12" x2="6.5" y2="12" />
</svg>
);
case "textpath":
// „A" auf einer gebogenen Grundlinie — deutet Text-entlang-Pfad an.
return (
<svg {...common}>
<path d="M 2 12 Q 8 2 14 12" fill="none" strokeDasharray="1.5 1.2" />
<path d="M 6 9.8 L 8 4.5 L 10 9.8 M 6.7 8 L 9.3 8" fill="none" />
</svg>
);
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";
+1 -30
View File
@@ -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<string, boolean>`-Maps (gleiche Keys UND Werte). */
function boolMapEqual(
a: Record<string, boolean>,
b: Record<string, boolean>,
): 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<string, boolean> | null,
target: Record<string, boolean>,
): 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 {
+36 -3
View File
@@ -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<NonNullable<ContextImage["filters"]>>) => 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. */
+37
View File
@@ -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)");
});
});
+48 -18
View File
@@ -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<PlanViewHandle, PlanViewProps>(
function PlanView(
{
@@ -2328,12 +2351,17 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
const drawingRuns = useMemo(() => buildDrawingRuns(plan.primitives), [plan]);
// Pro Polygon mit Linien-/Kreuz-Schraffur ein eigenes <pattern> 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 <pattern>-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<PlanViewHandle, PlanViewProps>(
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 (
<image
key={img.id}
@@ -2499,6 +2528,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
width={w}
height={h}
opacity={img.opacity}
style={filter ? { filter } : undefined}
preserveAspectRatio="none"
pointerEvents="none"
/>
@@ -2704,7 +2734,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
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<PlanViewHandle, PlanViewProps>(
pointerEvents="none"
/>
{corners.map((s, i) => (
<rect
<circle
key={`gbb-${i}`}
className="plan-group-bbox-corner"
x={s.x - size}
y={s.y - size}
width={size * 2}
height={size * 2}
className="plan-grip plan-group-bbox-corner"
cx={s.x}
cy={s.y}
r={size}
pointerEvents="none"
/>
))}
@@ -2761,19 +2790,20 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
/>
))}
{/* 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 (
<rect
<circle
key={`grip-${i}`}
className="plan-grip"
x={s.x - size}
y={s.y - size}
width={size * 2}
height={size * 2}
cx={s.x}
cy={s.y}
r={size}
pointerEvents="none"
/>
);
@@ -2784,7 +2814,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
{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}`,
+78
View File
@@ -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<string>(["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<string>(["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<string>(); // 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);
});
});
+48 -4
View File
@@ -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", () => {
+125 -14
View File
@@ -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<ContextObject, { type: "image" }> => 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<string>,
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<string>;
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,
});
}
+33
View File
@@ -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<typeof pr, { kind: "polygon" }> =>
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<typeof pr, { kind: "polygon" }> =>
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 ──────────
+20 -2
View File
@@ -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<string>,
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;
+192
View File
@@ -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);
});
});
+117 -4
View File
@@ -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-`<polygon>` 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",
+33 -7
View File
@@ -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<string>,
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,
});
}
+33 -1
View File
@@ -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<HatchStyle["motif"]> = {
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 };
+18
View File
@@ -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 `<textPath>`, 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,
};
}
@@ -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<typeof p, { kind: "polygon" }> => 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);
});
});
+163
View File
@@ -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");
});
});
+11 -1
View File
@@ -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):
+33
View File
@@ -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', () => {
+10 -1
View File
@@ -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
+4 -5
View File
@@ -60,13 +60,12 @@ export function DraftOverlay({
{draft.vertices.map((v, i) => {
const s = toScreen(v);
return (
<rect
<circle
key={`v${i}`}
className="tool-vertex"
x={s.x - vertSize}
y={s.y - vertSize}
width={vertSize * 2}
height={vertSize * 2}
cx={s.x}
cy={s.y}
r={vertSize}
vectorEffect="non-scaling-stroke"
/>
);
+83 -5
View File
@@ -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 <path> 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 (
<pattern
id={id}
patternUnits="userSpaceOnUse"
width={rowSpacing}
height={period}
patternTransform={`rotate(${hatch.angle})`}
>
<path
d={d}
fill="none"
stroke={hatch.color}
strokeWidth={sw}
strokeDasharray={dashes}
strokeLinecap={dashCap}
vectorEffect={vfx}
/>
</pattern>
);
}
// 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<T extends Primitive>(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(
</text>
);
}
case "drawingTextPath": {
// Text-entlang-Pfad: unsichtbarer `<path>` (nur Geometrie-Träger) +
// `<text><textPath>` — 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 (
<>
<path id={pathId} d={d} fill="none" style={{ pointerEvents: "none" }} />
<text
fontSize={fontSize}
fill={p.color}
opacity={p.greyed ? 0.45 : undefined}
style={{ pointerEvents: "none", userSelect: "none" }}
>
<textPath href={`#${pathId}`}>{p.text}</textPath>
</text>
</>
);
}
case "drawingCircle": {
// Echtes `<circle>` — rund bei jedem Zoom (kein Vieleck). Füllung optional.
const c = toScreen(p.center);
+140 -4
View File
@@ -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<typeof p, { kind: "polygon" }> => 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);
});
});
+86 -7
View File
@@ -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<Array<[number, number]>>;
/**
* 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<Array<[number, number]>>;
/** 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<string>;
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,
+11 -1
View File
@@ -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
+15 -1
View File
@@ -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;
+271 -3
View File
@@ -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<Project["stairTypes"]>[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<Project["stairTypes"]>[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
+5 -1
View File
@@ -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),
};
}
+19 -8
View File
@@ -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) }];
}
}
+56
View File
@@ -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
+55 -1
View File
@@ -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;
}
+29
View File
@@ -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). */
+132 -11
View File
@@ -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({
+160
View File
@@ -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
});
});
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff. Show more