From 73479e4812568819321b5b3f9dd872725be19e34 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 17:15:47 +0000 Subject: [PATCH] =?UTF-8?q?[169]=20Runde=20Formen=20als=20echte=20Kreise?= =?UTF-8?q?=20und=20B=C3=B6gen:=20Bogenerkennung=20(plan/arc=5Ffit.rs)=20i?= =?UTF-8?q?n=20Plan-SVG,=20Druck-SVG/PDF=20(,=20A-Pfade),=20DXF/DW?= =?UTF-8?q?G=20(CIRCLE,=20LWPOLYLINE=20mit=20Bulges,=20fileio=20Satz=2024)?= =?UTF-8?q?,=20Bildschirm=20fein=20nachtesselliert,=20Bogen-Musterphase=20?= =?UTF-8?q?([153]);=20runde=20St=C3=BCtze=2048+-Eck=20und=20glatt=20schatt?= =?UTF-8?q?iert,=20TS-columnFootprint=20entfernt;=20Goldens,=20TODO,=20Dok?= =?UTF-8?q?u?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.md | 13 +- doc/ARCHITEKTUR.md | 4 + src-tauri/core/src/gpu_compile.rs | 27 +- src-tauri/core/src/model3d/columns.rs | 54 +- src-tauri/core/src/plan/README.md | 3 +- src-tauri/core/src/plan/arc_fit.rs | 488 ++++++++++++++++++ src-tauri/core/src/plan/arc_output_tests.rs | 79 +++ src-tauri/core/src/plan/dxf.rs | 59 ++- src-tauri/core/src/plan/mod.rs | 3 + src-tauri/core/src/plan/print_svg.rs | 129 +++-- src-tauri/core/src/plan/scene.rs | 21 +- src-tauri/core/src/plan/svg.rs | 149 +++++- src-tauri/core/src/web/line_pattern.rs | 18 + src-tauri/fileio/src/export.rs | 28 + src-tauri/render2d/src/shaders.rs | 51 +- src/core/index.ts | 4 - src/export/sceneToPrintSvg.dash.test.ts | 28 + src/export/sceneToPrintSvg.ts | 38 +- src/geometry/column.ts | 46 -- .../komplex-ansicht-ansicht-sued.txt | 6 +- .../__golden__/komplex-grundriss-eg-100.txt | 10 +- .../__golden__/komplex-grundriss-eg-50.txt | 10 +- .../__golden__/komplex-grundriss-og-100.txt | 9 +- .../__golden__/komplex-grundriss-og-50.txt | 10 +- .../__golden__/komplex-grundriss-ug-100.txt | 12 +- .../__golden__/komplex-grundriss-ug-50.txt | 12 +- src/plan/__golden__/komplex-model3d.txt | 7 +- .../__golden__/komplex-schnitt-schnitt-a.txt | 8 +- src/plan/column.test.ts | 21 +- 29 files changed, 1154 insertions(+), 193 deletions(-) create mode 100644 src-tauri/core/src/plan/arc_fit.rs create mode 100644 src-tauri/core/src/plan/arc_output_tests.rs delete mode 100644 src/geometry/column.ts diff --git a/TODO.md b/TODO.md index b31bc9c1..4ae91737 100644 --- a/TODO.md +++ b/TODO.md @@ -62,6 +62,14 @@ Wer zu einer ID mehr wissen will (Entscheide, Tests, Bilder), sucht dort nach `* lasen den Schraffur-Winkel um 90° verschieden (Standard 0°↔90° hin und her); jetzt alle über `hatch::build_hatch_runs` (DXF 90° − Winkel), Standard 0°, Laden stellt 90° zurück, Bogenwand-Nasen polar; Test `plan/hatch_dir_tests.rs`. Offen: render3d-Live-Schnitt und Mac nicht angesehen. · S +- ◐ **[169]** Runde Formen als echte Kreise/Bögen. 9.11.: Ausgaben erkennen Bögen in Vielecken/Linienzügen (Kern + `plan/arc_fit.rs`: ≥ 4 Punkte auf einem Kreis ± 10 µm, Schritt ≤ 25°, Pfeilhöhe ≥ 0.5 mm): Plan-SVG/Druck-SVG/PDF + `` bzw. `` mit `A`, DXF/DWG CIRCLE bzw. LWPOLYLINE mit Bulges (fileio Satz 24, auch Linienzüge aus + Einzel-Linien), Bildschirm fein nachtesselliert (Szene ≤ 2°, Metal-Pfad nach Zoom); Schraffur am Bogen beschnitten. + Runde Stütze 48–256-Eck (Pfeilhöhe ≤ 0.5 mm), im 3D glatt. Tests `plan/arc_output_tests.rs`. Offen: Bögen auf + schiefen Wänden in der Ansicht (Ellipsen) bleiben Vielecke; Ringe aus Versatz/Boolean ohne exakte Kreispunkte + (Treppenloch-Rand Musterhaus) bleiben Vielecke; DXF-HATCH-Ränder ohne Bögen; Bogenwände im 3D kantig schattiert; + Bildschirm (WebGPU, Metal) nicht angesehen. · M - ◐ **[145]** Texte beim Zoomen synchron. Falls der Mac noch nachläuft: Raumstempel nativ zeichnen (vtext kann nur einzeilig/linksbündig, eine Schrift, kein Fett). 9.11.: `clampInside` nur noch im Kern (`grip_clamp_inside`, Fassade `clampInside` in `src/core`); die Öffnungs-Vorschau beim Setzen zeigt die geklemmte/gerückte Lage @@ -71,7 +79,8 @@ Wer zu einer ID mehr wissen will (Entscheide, Tests, Bilder), sucht dort nach `* `ungestrichene_kante_ohne_strich`); Nähen in Metal-Chunks nur innerhalb eines Chunks (Kern `plan/line_ends.rs`, `render2d`). · M - ◐ **[150]** Gelände im Grundriss am Gebäude. Raumstempel ausserhalb ihres Raums sind kein Hindernis für Höhenlinien-Beschriftungen; Beschriftungen an Bündeln fehlen statt versetzt zu werden. · S -- ◐ **[153]** Strichmuster in Papier-mm. Bögen/Kreise ohne Phase (beginnen mit Strich), DXF/DWG ohne Phase je Objekt, +- ◐ **[153]** Strichmuster in Papier-mm. Bögen mit Phase seit 9.11. ([169]: Plan-/Druck-SVG, PDF, Bogen-Shader), + Kreise ohne (geschlossen), DXF/DWG ohne Phase je Objekt, Metal-Chunks verketten nur über das Ketten-Flag, React-SVG-Ansicht ohne Phase. · M - ◐ **[155]** Treppensymbol. Raumstempel weichen den neuen Linien nicht aus; Lauflinie über Bruchlinie ausgezogen; Absturzsicherung nur im Grundriss (kein Geländer-Bauteil in 3D/IFC); Ende eines freien Lochrings ohne Gehrung; @@ -315,7 +324,7 @@ Wer zu einer ID mehr wissen will (Entscheide, Tests, Bilder), sucht dort nach `* Auf dem Mac (Tauri/Metal) noch nicht angesehen oder geprüft; bisher nur Linux-Container, CLI-SVG, Chromium oder Unit-Tests: [116] (atomares Speichern), [117] (CSP unter `tauri://`), [118], [122], [123], [126], [110], [101], -[102], [131], [133], [136], [140], [145], [146], [153], [64], [T2], [T4], [34], [108], [65]. Je Punkt ansehen, dann hier und +[102], [131], [133], [136], [140], [145], [146], [153], [64], [T2], [T4], [34], [108], [65], [169]. Je Punkt ansehen, dann hier und im jeweiligen Eintrag streichen. · M (gesamt) --- diff --git a/doc/ARCHITEKTUR.md b/doc/ARCHITEKTUR.md index 070bdc09..4eeda9e2 100644 --- a/doc/ARCHITEKTUR.md +++ b/doc/ARCHITEKTUR.md @@ -272,6 +272,10 @@ Beispiel: Die Plan-Ansicht zeigt das Erdgeschoss im Massstab 1:100. | Layout-Blatt, Blatt-PDF | `planToPrintSvg()` in `src/export/planToPrintSvg.ts`, aufgerufen von `src/ui/LayoutSheet.tsx` und `src/export/layoutPdf.ts` | `plan_print_svg_ops()` → `print_svg_ops()` in `plan/print_svg.rs` | SVG-Knoten in Papier-mm | | DXF, DWG | `src/export/exportDxf.ts` | `plan_dxf_flat()` → `collect()`, `encode()` in `plan/dxf.rs` | `fileio`: `export_dxf()`, `export_dwg()` in `src-tauri/fileio/src/export.rs` | +Runde Formen (Stütze, Bogenwand, Bogen-Umrisse) reisen im Puffer als Vielecke; die Ausgaben erkennen die Bögen +darin (`plan/arc_fit.rs`) und schreiben Kreise, SVG-`A`-Pfade bzw. DXF-Bulges, der Bildschirm tesselliert sie fein +nach ([169]). + Bildschirm, SVG, PDF und DXF lesen also denselben Plan-Puffer. Was in einem Ausgabeweg anders aussieht als in einem anderen, ist fast immer ein Fehler im jeweiligen Leser, nicht in der Plan-Erzeugung. diff --git a/src-tauri/core/src/gpu_compile.rs b/src-tauri/core/src/gpu_compile.rs index 93cbffe1..c28023b3 100644 --- a/src-tauri/core/src/gpu_compile.rs +++ b/src-tauri/core/src/gpu_compile.rs @@ -337,9 +337,21 @@ struct Compiler { /// Wände treffen sich an der Ecke als EIN Zug mit Ecke statt zwei Enden (keine Kerbe). solid: Vec<(Rgba, f64, Vec>)>, solid_of: std::collections::HashMap<[u64; 5], usize>, + /// Bildschirm-px je Meter (Feinheit nachtessellierter Bögen, [169]). + ppm: f64, } impl Compiler { + /// [169] Erkannte Bögen (runde Stütze, Bogenwand) nach Zoom fein nachtesselliert (Pfeilhöhe ≤ 0.5 px, wie + /// [`arc_segments`]); `None` = unverändert. + fn smooth(&self, pts: &[V2], closed: bool) -> Option> { + if pts.len() < 4 { + return None; + } + let ppm = self.ppm; + crate::plan::arc_fit::refine(pts, closed, crate::plan::arc_fit::TOL, &|r, sw| arc_segments(r, sw, ppm, 4.0) as usize) + } + #[inline] fn scr(&mut self, p: V2) -> V2 { let sx = p.x * PX_PER_M; @@ -466,6 +478,8 @@ impl Compiler { if pts_m.len() < 2 { return; } + let fine = self.smooth(pts_m, closed); + let pts_m: &[V2] = fine.as_deref().unwrap_or(pts_m); // Maler-Reihenfolge: vorgemerkte volle Züge vor diesem Strich zeichnen ([146]). self.flush_solid(); let close = closed && pts_m.len() > 2 && (pts_m[0].x != pts_m[pts_m.len() - 1].x || pts_m[0].y != pts_m[pts_m.len() - 1].y); @@ -570,6 +584,8 @@ impl Compiler { /// Zusammenhängender Linienzug (Modell-Meter) mit runden Kappen/Ecken. fn stroke_polyline(&mut self, pts_m: &[V2], closed: bool, color: Rgba, stroke_mm: f64, screen_px: bool) { + let fine = self.smooth(pts_m, closed); + let pts_m: &[V2] = fine.as_deref().unwrap_or(pts_m); let mut s_pts = std::mem::take(&mut self.scratch); s_pts.clear(); for &p in pts_m { @@ -866,6 +882,7 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool, ends: LineEnds) scratch: Vec::new(), seg_dir: Vec::new(), seg_ang: Vec::new(), + ppm: px_per_meter, }; let prims = &plan.prims; let plain_line = |p: &Prim| matches!(p, Prim::Line { zigzag: None, motif: None, .. }); @@ -913,7 +930,11 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool, ends: LineEnds) } match prim { Prim::Placeholder => {} - Prim::Polygon { style, fill, stroke, stroke_width_mm, hatch, pts, no_stroke_edges } => { + Prim::Polygon { style, fill, stroke, stroke_width_mm, hatch, pts: pts_raw, no_stroke_edges } => { + // [169] Fläche und Schraffur-Beschnitt am fein nachtessellierten Ring (Bögen), Umriss-Kanten aus + // dem Original (`no_stroke_edges` zählt dessen Kanten; die Züge werden beim Zeichnen verfeinert). + let fine = c.smooth(pts_raw, true); + let pts: &Vec = fine.as_ref().unwrap_or(pts_raw); if let Some(fc) = plan.color(*fill) { let tris = triangulate(pts); if !tris.is_empty() { @@ -931,8 +952,8 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool, ends: LineEnds) } } if let Some(sc) = plan.color(*stroke) { - if *stroke_width_mm > 0.0 && pts.len() >= 2 { - c.stroke_polygon_outline(pts, dim(sc, style), *stroke_width_mm, no_stroke_edges); + if *stroke_width_mm > 0.0 && pts_raw.len() >= 2 { + c.stroke_polygon_outline(pts_raw, dim(sc, style), *stroke_width_mm, no_stroke_edges); } } } diff --git a/src-tauri/core/src/model3d/columns.rs b/src-tauri/core/src/model3d/columns.rs index ea8e131c..6941d981 100644 --- a/src-tauri/core/src/model3d/columns.rs +++ b/src-tauri/core/src/model3d/columns.rs @@ -4,19 +4,35 @@ use super::*; -const COLUMN_ROUND_SEGMENTS: usize = 32; pub(crate) const COLUMN_RGB: Rgb = [0.7, 0.7, 0.72]; +/// [169] Pfeilhöhe der runden Stütze (Meter): höchstens 0.5 mm, Schritt höchstens 7.5° (wie Bogenwände). +const COLUMN_CHORD_TOL: f64 = 5e-4; +/// Knickwinkel (Grad) der glatten Schattierung runder Stützen: Mantel glatt, Kanten zu Deckel/Boden scharf. +const COLUMN_CREASE_DEG: f64 = 30.0; + +/// [169] Segmentzahl des runden Querschnitts: Pfeilhöhe ≤ [`COLUMN_CHORD_TOL`], Schritt ≤ 7.5°, Vielfaches +/// von 4 (symmetrisch zu den Achsen), mindestens 48 (Radius 0.15 m → 48, 0.5 m → 72), höchstens 256. +pub fn column_round_segments(radius: f64) -> usize { + let r = if radius.is_finite() { radius.max(1e-6) } else { 1e-6 }; + let c = (1.0 - COLUMN_CHORD_TOL / r).clamp(-1.0, 1.0); + let step = (2.0 * crate::jsnum::acos(c)).clamp(1e-3, std::f64::consts::PI / 24.0); + let n = ((2.0 * std::f64::consts::PI / step).ceil() as usize).clamp(48, 256); + n.div_ceil(4) * 4 +} /// Grundriss-Querschnitt einer Stütze (`columnFootprint`). pub fn column_footprint(col: &Column) -> Vec { let (cx, cy) = (col.position.x, col.position.y); match &col.profile { - ColumnProfile::Round { radius } => (0..COLUMN_ROUND_SEGMENTS) + ColumnProfile::Round { radius } => { + let n = column_round_segments(*radius); + (0..n) .map(|i| { - let t = (i as f64 / COLUMN_ROUND_SEGMENTS as f64) * std::f64::consts::PI * 2.0; + let t = (i as f64 / n as f64) * std::f64::consts::PI * 2.0; Vec2 { x: cx + radius * cos(t), y: cy + radius * sin(t) } }) - .collect(), + .collect() + } ColumnProfile::Rect { width, depth } => { let (hw, hd) = (width / 2.0, depth / 2.0); let rot = col.rotation; @@ -137,7 +153,9 @@ pub fn emit_columns(p: &Project) -> Vec { .as_deref() .and_then(|id| p.component(id)) .map_or(COLUMN_RGB, |c| hex_to_rgb(&c.color, COLUMN_RGB)); - out.push(RMesh { crease_angle: None, positions, indices, kind: "extrusion", color, vertex_colors: None, material_index: None }); + // [169] Runde Stütze glatt schattiert (Mantel ohne Facetten), eckige kantig. + let crease_angle = matches!(col.profile, ColumnProfile::Round { .. }).then_some(COLUMN_CREASE_DEG); + out.push(RMesh { crease_angle, positions, indices, kind: "extrusion", color, vertex_colors: None, material_index: None }); } out } @@ -171,3 +189,29 @@ pub fn pick_trees(p: &Project) -> Vec { }) .collect() } + +#[cfg(test)] +mod round_tests { + use super::*; + + /// [169] Runde Stütze feiner (Pfeilhöhe ≤ 0.5 mm, Schritt ≤ 7.5°) und im 3D glatt schattiert. + #[test] + fn runde_stuetze_fein_und_glatt() { + assert_eq!(column_round_segments(0.15), 48); + assert_eq!(column_round_segments(0.5), 72); + assert_eq!(column_round_segments(f64::NAN), 48); + for r in [0.1, 0.15, 0.3, 0.5, 1.0, 3.0] { + let n = column_round_segments(r) as f64; + assert!(r * (1.0 - (std::f64::consts::PI / n).cos()) <= COLUMN_CHORD_TOL + 1e-12, "r = {r}"); + } + let mut p = Project::default(); + for (id, profile) in [("r", ColumnProfile::Round { radius: 0.15 }), ("q", ColumnProfile::Rect { width: 0.3, depth: 0.3 })] { + p.columns.get_or_insert_with(Vec::new).push(Column { id: id.into(), r#type: "column".into(), floor_id: "eg".into(), profile, height: 2.6, ..Default::default() }); + } + let m = emit_columns(&p); + assert_eq!(m.len(), 2); + assert_eq!(m[0].crease_angle, Some(COLUMN_CREASE_DEG)); + assert_eq!(m[1].crease_angle, None); + assert_eq!(column_footprint(&p.columns.as_ref().unwrap()[0]).len(), 48); + } +} diff --git a/src-tauri/core/src/plan/README.md b/src-tauri/core/src/plan/README.md index d2a9b1a0..e513ddd0 100644 --- a/src-tauri/core/src/plan/README.md +++ b/src-tauri/core/src/plan/README.md @@ -79,12 +79,13 @@ Herkunft, kein Wegweiser. | `pick.rs` | räumlicher Index für Auswahl und Picken | | `svg.rs` | Plan-SVG (CLI, Goldens, Vorschau) | | `print_svg.rs` | Druck-SVG in Papier-mm für Layout-Blätter | +| `arc_fit.rs` | Bögen in Vielecken/Linienzügen erkennen ([169]): Kreis/`A`-Pfad (SVG), Bulges (DXF), feine Tessellierung (Bildschirm) | | `dxf.rs` | DXF/DWG-Sammler; die Datei schreibt `src-tauri/fileio/src/export.rs` | | `text.rs` | Texte der Ausgaben (Raumstempel, Einzeltexte) | ## Tests Die meisten Dateien haben `mod tests` am Ende. Eigene Testdateien: `wall_join_tests.rs` (Wandknoten im -Grundriss), im Ordner `section/` die Tests des Schnitts (`tests.rs`, `mesh_tests.rs` für importierte Netze, +Grundriss), `arc_output_tests.rs` (runde Stütze/Bogenwand als Kreis und Bogen in allen Ausgaben), im Ordner `section/` die Tests des Schnitts (`tests.rs`, `mesh_tests.rs` für importierte Netze, `ts_faelle.rs`, `dach_faelle.rs`, `abzug_faelle.rs`, `wand_an_dach.rs`, Messung `bench.rs`), `perf_tests.rs` (Leistung, von Hand: `cargo test --release --lib bench159 -- --ignored --nocapture`, siehe Dateikopf). diff --git a/src-tauri/core/src/plan/arc_fit.rs b/src-tauri/core/src/plan/arc_fit.rs new file mode 100644 index 00000000..e18126f6 --- /dev/null +++ b/src-tauri/core/src/plan/arc_fit.rs @@ -0,0 +1,488 @@ +//! [169] Bögen in Linienzügen erkennen: Die Plan-Erzeugung rechnet mit Vielecken (runde Stütze, Bogenwand, +//! Bogen-Umrisse von Decken/Dächern, Booleans); die Ausgaben (Plan-SVG, Druck-SVG/PDF, DXF/DWG, Bildschirm) +//! sollen echte Kreise und Bögen zeigen. [`fit`] zerlegt einen offenen oder geschlossenen Zug in Strecken +//! und Bögen: mindestens vier aufeinanderfolgende Punkte auf einem Kreis (Abstand ≤ `tol`), gleicher +//! Drehsinn, Winkelschritt je Kante ≤ [`MAX_STEP`] — Rechtecke, Achtecke und schwach geknickte Züge +//! bleiben Strecken. [`refine`] tesselliert erkannte Bögen fein nach (Bildschirm), [`svg_d`] schreibt +//! SVG-Pfade (`A`), [`bulges`] die Bulges einer LWPOLYLINE (DXF). + +use crate::hatch::V2; +use crate::jsnum; +use std::f64::consts::PI; + +/// Grösster Winkelschritt (25°) einer Kante, die noch als Teil eines Bogens gilt. Bogenwände zerlegen +/// mit höchstens 7.5° (`wall_arc::MAX_STEP`), Stützen mit höchstens 7.5°; ein regelmässiges 14-Eck nicht. +pub const MAX_STEP: f64 = 25.0 * PI / 180.0; +/// Standard-Toleranz in Modell-Metern (i_overlay rastert auf ≈ Ausdehnung/2³⁰). +pub const TOL: f64 = 1e-5; +/// Kleinster/grösster Radius eines erkannten Bogens als Vielfaches der Toleranz (bei [`TOL`]: 0.1 mm … 1 km). +const R_MIN_TOL: f64 = 10.0; +const R_MAX_TOL: f64 = 1e8; +/// Kleinste Pfeilhöhe eines erkannten Bogens als Vielfaches der Toleranz (bei [`TOL`]: 0.5 mm): fast gerade, +/// leicht verrauschte Züge (Geländelinie in der Ansicht) bleiben Strecken. +const SAGITTA_TOL: f64 = 50.0; + +/// Ein Stück ab dem Ende des vorigen (bzw. ab `start`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Seg { + Line { b: V2 }, + /// Kreisbogen bis `b` um `c`, Radius `r`, Drehwinkel `sweep` (positiv = gegen den Uhrzeiger, Y nach oben), + /// |sweep| ≤ π (längere Bögen sind geteilt). + Arc { b: V2, c: V2, r: f64, sweep: f64 }, +} + +impl Seg { + pub fn end(&self) -> V2 { + match *self { + Seg::Line { b } | Seg::Arc { b, .. } => b, + } + } +} + +/// Ergebnis von [`fit`]. +#[derive(Clone, Debug, PartialEq)] +pub enum Shape { + /// Ganzer Kreis (geschlossener Zug); `a0` = Winkel des ersten Punkts. + Circle { c: V2, r: f64, a0: f64 }, + /// Zug ab `start`; geschlossen endet das letzte Stück wieder in `start`. + Path { start: V2, segs: Vec, closed: bool }, +} + +fn dist(a: V2, b: V2) -> f64 { + crate::jsmath::hypot2(b.x - a.x, b.y - a.y) +} + +/// Umkreis dreier Punkte; `None` bei (fast) kollinearen. +fn circ(a: V2, b: V2, c: V2, tol: f64) -> Option<(V2, f64)> { + let (bx, by, cx, cy) = (b.x - a.x, b.y - a.y, c.x - a.x, c.y - a.y); + let d = 2.0 * (bx * cy - by * cx); + let s = (bx * bx + by * by).max(cx * cx + cy * cy); + if !(d.abs() > 1e-12 * s) || !d.is_finite() { + return None; + } + let (b2, c2) = (bx * bx + by * by, cx * cx + cy * cy); + let ux = (cy * b2 - by * c2) / d; + let uy = (bx * c2 - cx * b2) / d; + let r = crate::jsmath::hypot2(ux, uy); + (r.is_finite() && (R_MIN_TOL * tol..=R_MAX_TOL * tol).contains(&r)).then_some((V2 { x: a.x + ux, y: a.y + uy }, r)) +} + +/// Vorzeichenbehafteter Winkel von `p` nach `q` um `c`, in (−π, π]. +fn step(c: V2, p: V2, q: V2) -> f64 { + let a = jsnum::atan2(p.y - c.y, p.x - c.x); + let b = jsnum::atan2(q.y - c.y, q.x - c.x); + let mut d = b - a; + while d > PI { + d -= 2.0 * PI; + } + while d <= -PI { + d += 2.0 * PI; + } + d +} + +fn step_ok(s: f64, sign: f64) -> bool { + s.abs() > 1e-9 && s.abs() <= MAX_STEP && s * sign > 0.0 +} + +/// Längster Bogen ab `q[i]`: `(j, Mitte, Radius, Drehwinkel)` mit `j ≥ i + 3`. +fn try_arc(q: &[V2], i: usize, tol: f64) -> Option<(usize, V2, f64, f64)> { + let m = q.len() - 1; + if i + 3 > m { + return None; + } + let (c, r) = circ(q[i], q[i + 1], q[i + 2], tol)?; + let s1 = step(c, q[i], q[i + 1]); + let sign = s1.signum(); + let s2 = step(c, q[i + 1], q[i + 2]); + if !step_ok(s1, sign) || !step_ok(s2, sign) { + return None; + } + let mut sweep = s1 + s2; + let mut j = i + 2; + while j < m { + let p = q[j + 1]; + let s = step(c, q[j], p); + if (dist(c, p) - r).abs() > tol || !step_ok(s, sign) || (sweep + s).abs() >= 2.0 * PI - 1e-6 { + break; + } + sweep += s; + j += 1; + } + if j < i + 3 { + return None; + } + // Genauerer Kreis aus Anfang, Mitte und Ende, falls er alle Punkte hält. + let (mut c, mut r) = (c, r); + if let Some((c2, r2)) = circ(q[i], q[(i + j) / 2], q[j], tol) { + if q[i..=j].iter().all(|p| (dist(c2, *p) - r2).abs() <= tol) { + c = c2; + r = r2; + sweep = (i..j).map(|k| step(c, q[k], q[k + 1])).sum(); + } + } + // Fast gerade (Pfeilhöhe kaum über der Toleranz): Strecken. + if r * (1.0 - jsnum::cos(sweep.abs().min(PI) / 2.0)) <= SAGITTA_TOL * tol { + return None; + } + Some((j, c, r, sweep)) +} + +/// Offener Zug → Stücke (mit mindestens einem Bogen, sonst `None`). +fn fit_open(q: &[V2], tol: f64) -> Option> { + let m = q.len().checked_sub(1)?; + let mut segs = Vec::with_capacity(m); + let mut any = false; + let mut i = 0; + while i < m { + if let Some((j, c, r, sweep)) = try_arc(q, i, tol) { + any = true; + if sweep.abs() > PI { + // In zwei Bögen teilen (SVG/DXF rechnen mit höchstens einem Halbkreis stabil). + let mut acc = 0.0; + let mut k = i; + while k < j - 1 && (acc + step(c, q[k], q[k + 1])).abs() <= sweep.abs() / 2.0 { + acc += step(c, q[k], q[k + 1]); + k += 1; + } + let k = k.max(i + 1); + let s1 = (i..k).map(|t| step(c, q[t], q[t + 1])).sum(); + segs.push(Seg::Arc { b: q[k], c, r, sweep: s1 }); + segs.push(Seg::Arc { b: q[j], c, r, sweep: sweep - s1 }); + } else { + segs.push(Seg::Arc { b: q[j], c, r, sweep }); + } + i = j; + } else { + segs.push(Seg::Line { b: q[i + 1] }); + i += 1; + } + } + any.then_some(segs) +} + +/// Ganzer Kreis? Alle Punkte auf einem Kreis, gleicher Drehsinn, Schritte ≤ [`MAX_STEP`], einmal herum. +fn full_circle(p: &[V2], tol: f64) -> Option<(V2, f64)> { + let n = p.len(); + if n < 8 { + return None; + } + let (c, r) = circ(p[0], p[n / 3], p[2 * n / 3], tol)?; + if p.iter().any(|q| (dist(c, *q) - r).abs() > tol) { + return None; + } + let sign = step(c, p[0], p[1]).signum(); + let mut total = 0.0; + for k in 0..n { + let s = step(c, p[k], p[(k + 1) % n]); + if !step_ok(s, sign) { + return None; + } + total += s; + } + ((total.abs() - 2.0 * PI).abs() < 1e-6).then_some((c, r)) +} + +/// Zerlegt `pts` in Strecken und Bögen; `None`, wenn kein Bogen erkannt wurde (dann bleibt der Zug wie er ist). +/// Geschlossen: `pts` ohne wiederholten Anfangspunkt. +pub fn fit(pts: &[V2], closed: bool, tol: f64) -> Option { + if pts.len() < 4 || !pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()) { + return None; + } + if !closed { + let segs = fit_open(pts, tol)?; + return Some(Shape::Path { start: pts[0], segs, closed: false }); + } + let mut pts = pts.to_vec(); + if pts.len() > 1 && dist(pts[0], pts[pts.len() - 1]) <= 1e-12 { + pts.pop(); + } + let n = pts.len(); + if n < 4 { + return None; + } + if let Some((c, r)) = full_circle(&pts, tol) { + return Some(Shape::Circle { c, r, a0: jsnum::atan2(pts[0].y - c.y, pts[0].x - c.x) }); + } + // Anfang an der schärfsten Ecke (ein Bogen läuft dort nicht durch). + let turn = |k: usize| { + let (a, b, c) = (pts[(k + n - 1) % n], pts[k], pts[(k + 1) % n]); + let (ux, uy, vx, vy) = (b.x - a.x, b.y - a.y, c.x - b.x, c.y - b.y); + jsnum::atan2(ux * vy - uy * vx, ux * vx + uy * vy).abs() + }; + let s = (0..n).fold(0, |best, k| if turn(k) > turn(best) + 1e-12 { k } else { best }); + let q: Vec = (0..=n).map(|k| pts[(s + k) % n]).collect(); + let segs = fit_open(&q, tol)?; + let start = q[0]; + Some(Shape::Path { start, segs, closed: true }) +} + +/// Länge eines Zugs mit Bögen. +pub fn length(s: &Shape) -> f64 { + match s { + Shape::Circle { r, .. } => 2.0 * PI * r, + Shape::Path { start, segs, .. } => { + let mut at = *start; + let mut l = 0.0; + for g in segs { + l += match *g { + Seg::Line { b } => dist(at, b), + Seg::Arc { r, sweep, .. } => r * sweep.abs(), + }; + at = g.end(); + } + l + } + } +} + +/// Segmentzahl für den Bildschirm ohne Zoom-Kenntnis: Schritt ≤ 2° und Pfeilhöhe ≤ 0.05 mm (höchstens 1024). +pub fn fine_segments(r: f64, sweep_abs: f64) -> usize { + let c = (1.0 - 5e-5 / r.max(1e-6)).clamp(-1.0, 1.0); + let step = (2.0 * jsnum::acos(c)).clamp(1e-4, PI / 90.0); + ((sweep_abs / step).ceil() as usize).clamp(1, 1024) +} + +/// Punkte eines Bogens ab `a` (ohne `a`, mit `b` exakt am Ende). +fn arc_points(a: V2, b: V2, c: V2, r: f64, sweep: f64, n: usize, out: &mut Vec) { + let a0 = jsnum::atan2(a.y - c.y, a.x - c.x); + for k in 1..n { + let t = a0 + sweep * k as f64 / n as f64; + out.push(V2 { x: c.x + r * jsnum::cos(t), y: c.y + r * jsnum::sin(t) }); + } + out.push(b); +} + +/// Erkannte Bögen fein nachtesselliert (`segments(r, |sweep|)` je Bogen); `None` = nichts erkannt. +/// Geschlossen ohne wiederholten Anfangspunkt (wie die Eingabe). +pub fn refine(pts: &[V2], closed: bool, tol: f64, segments: &dyn Fn(f64, f64) -> usize) -> Option> { + let shape = fit(pts, closed, tol)?; + let mut out = Vec::new(); + match shape { + Shape::Circle { c, r, a0 } => { + let n = segments(r, 2.0 * PI).max(8); + for k in 0..n { + let t = a0 + 2.0 * PI * k as f64 / n as f64; + out.push(V2 { x: c.x + r * jsnum::cos(t), y: c.y + r * jsnum::sin(t) }); + } + } + Shape::Path { start, segs, closed } => { + out.push(start); + let mut at = start; + for g in &segs { + match *g { + Seg::Line { b } => out.push(b), + Seg::Arc { b, c, r, sweep } => arc_points(at, b, c, r, sweep, segments(r, sweep.abs()).max(1), &mut out), + } + at = g.end(); + } + if closed { + out.pop(); + } + } + } + Some(out) +} + +/// SVG-Pfad (`d`) eines Zugs mit Bögen aus Modellpunkten (Y nach oben). `map` bildet sie auf die Ausgabe ab +/// (Y gespiegelt: ein Bogen gegen den Uhrzeiger im Modell ist im SVG `sweep-flag` 0), `k` = Ausgabe-Einheiten +/// je Meter (Radius), `fmt` formatiert Zahlen. +pub fn svg_d(s: &Shape, map: &dyn Fn(V2) -> V2, k: f64, fmt: &dyn Fn(f64) -> String) -> String { + svg_d_with(s, map, k, fmt, false) +} + +/// Wie [`svg_d`], `y_down` = die Punkte liegen schon im SVG-Raum (Y nach unten, z. B. Papier-mm). +pub fn svg_d_with(s: &Shape, map: &dyn Fn(V2) -> V2, k: f64, fmt: &dyn Fn(f64) -> String, y_down: bool) -> String { + let ccw_flag = if y_down { 1 } else { 0 }; + let mut d = String::new(); + let pt = |d: &mut String, p: V2| { + let q = map(p); + d.push_str(&fmt(q.x)); + d.push(' '); + d.push_str(&fmt(q.y)); + }; + match s { + Shape::Circle { c, r, .. } => { + // Zwei Halbkreise (ein einzelner `A` mit gleichem Anfang und Ende zeichnet nichts). + let a = V2 { x: c.x + r, y: c.y }; + let b = V2 { x: c.x - r, y: c.y }; + let rr = fmt(r * k); + d.push('M'); + d.push(' '); + pt(&mut d, a); + for e in [b, a] { + d.push_str(&format!(" A {rr} {rr} 0 0 {ccw_flag} ")); + pt(&mut d, e); + } + d.push_str(" Z"); + } + Shape::Path { start, segs, closed } => { + d.push_str("M "); + pt(&mut d, *start); + let n = segs.len(); + for (i, g) in segs.iter().enumerate() { + match *g { + Seg::Line { b } => { + if *closed && i + 1 == n { + break; + } + d.push_str(" L "); + pt(&mut d, b); + } + Seg::Arc { b, r, sweep, .. } => { + let rr = fmt(r * k); + let large = if sweep.abs() > PI { 1 } else { 0 }; + let flag = if sweep > 0.0 { ccw_flag } else { 1 - ccw_flag }; + d.push_str(&format!(" A {rr} {rr} 0 {large} {flag} ")); + pt(&mut d, b); + } + } + } + if *closed { + d.push_str(" Z"); + } + } + } + d +} + +/// LWPOLYLINE-Ecken und Bulges (tan(Drehwinkel/4), positiv gegen den Uhrzeiger); geschlossen ohne +/// wiederholten Anfangspunkt (der letzte Bulge gilt der Schlusskante). Kreise → `None` (CIRCLE). +pub fn bulges(s: &Shape) -> Option<(Vec, Vec)> { + let Shape::Path { start, segs, closed } = s else { return None }; + let mut v = vec![*start]; + let mut b = Vec::with_capacity(segs.len() + 1); + for g in segs { + v.push(g.end()); + b.push(match *g { + Seg::Line { .. } => 0.0, + Seg::Arc { sweep, .. } => jsnum::tan(sweep / 4.0), + }); + } + if *closed { + v.pop(); + } else { + b.push(0.0); + } + Some((v, b)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ring(c: V2, r: f64, n: usize) -> Vec { + (0..n).map(|i| { + let t = 2.0 * PI * i as f64 / n as f64; + V2 { x: c.x + r * t.cos(), y: c.y + r * t.sin() } + }).collect() + } + + #[test] + fn stuetze_32_eck_ist_kreis() { + let p = ring(V2 { x: 3.0, y: -2.0 }, 0.15, 32); + match fit(&p, true, TOL) { + Some(Shape::Circle { c, r, .. }) => { + assert!((c.x - 3.0).abs() < 1e-9 && (c.y + 2.0).abs() < 1e-9 && (r - 0.15).abs() < 1e-9); + } + o => panic!("{o:?}"), + } + // Offen (Dreiviertelkreis) Bögen. + let open: Vec = p[..25].to_vec(); + let Some(Shape::Path { segs, .. }) = fit(&open, false, TOL) else { panic!() }; + assert!(segs.iter().all(|s| matches!(s, Seg::Arc { .. })), "{segs:?}"); + assert!((length(&Shape::Path { start: open[0], segs, closed: false }) - 1.5 * PI * 0.15).abs() < 1e-9); + } + + #[test] + fn rechteck_achteck_und_gerade_bleiben_strecken() { + let sq = vec![V2 { x: 0.0, y: 0.0 }, V2 { x: 1.0, y: 0.0 }, V2 { x: 1.0, y: 1.0 }, V2 { x: 0.0, y: 1.0 }]; + assert!(fit(&sq, true, TOL).is_none()); + assert!(fit(&ring(V2 { x: 0.0, y: 0.0 }, 1.0, 8), true, TOL).is_none()); + let line: Vec = (0..6).map(|i| V2 { x: i as f64, y: 0.0 }).collect(); + assert!(fit(&line, false, TOL).is_none()); + // Leicht geknickter Zug (nicht auf einem Kreis). + let z = vec![V2 { x: 0.0, y: 0.0 }, V2 { x: 1.0, y: 0.1 }, V2 { x: 2.0, y: 0.1 }, V2 { x: 3.0, y: 0.25 }, V2 { x: 4.0, y: 0.2 }]; + assert!(fit(&z, false, TOL).is_none()); + // Fast gerade Geländelinie (Ansicht): vier Punkte zufällig auf einem Kreis r ≈ 274 m, Pfeilhöhe 45 µm. + let (c, r) = (V2 { x: 0.0, y: -274.0 }, 274.0f64); + let flat: Vec = [-0.16, -0.05, 0.05, 0.16].iter().map(|x: &f64| V2 { x: c.x + x, y: c.y + (r * r - x * x).sqrt() }).collect(); + assert!(fit(&flat, false, TOL).is_none()); + } + + /// Bogenwand-Band: äusserer Bogen, Stirn, innerer Bogen zurück, Stirn. + fn band() -> Vec { + let (r0, r1, n) = (5.0, 4.7, 12); + let mut p: Vec = (0..=n).map(|i| { + let t = PI / 2.0 * i as f64 / n as f64; + V2 { x: r0 * t.cos(), y: r0 * t.sin() } + }).collect(); + p.extend((0..=n).rev().map(|i| { + let t = PI / 2.0 * i as f64 / n as f64; + V2 { x: r1 * t.cos(), y: r1 * t.sin() } + })); + p + } + + #[test] + fn bogenwand_band_zwei_boegen_zwei_stirnen() { + let Some(s @ Shape::Path { .. }) = fit(&band(), true, TOL) else { panic!() }; + let Shape::Path { segs, closed, .. } = &s else { unreachable!() }; + assert!(*closed); + let arcs: Vec<(f64, f64)> = segs.iter().filter_map(|g| if let Seg::Arc { r, sweep, .. } = g { Some((*r, *sweep)) } else { None }).collect(); + let lines = segs.iter().filter(|g| matches!(g, Seg::Line { .. })).count(); + assert_eq!(lines, 2, "{segs:?}"); + assert_eq!(arcs.len(), 2, "{segs:?}"); + assert!(arcs.iter().any(|(r, s)| (r - 5.0).abs() < 1e-9 && (s - PI / 2.0).abs() < 1e-9)); + assert!(arcs.iter().any(|(r, s)| (r - 4.7).abs() < 1e-9 && (s + PI / 2.0).abs() < 1e-9)); + // SVG: zwei A-Befehle, Drehsinn gespiegelt (Y nach unten). + let d = svg_d(&s, &|p| V2 { x: p.x, y: -p.y }, 1.0, &|v| format!("{}", (v * 1e5).round() / 1e5)); + assert_eq!(d.matches(" A ").count(), 2, "{d}"); + assert!(d.contains("A 5 5 0 0 0 ") && d.contains("A 4.7 4.7 0 0 1 ") && d.ends_with(" Z"), "{d}"); + // DXF-Bulges: tan(±π/8) an den Bogen-Ecken. + let (v, b) = bulges(&s).unwrap(); + assert_eq!(v.len(), 4); + assert_eq!(b.iter().filter(|x| (x.abs() - (PI / 8.0).tan()).abs() < 1e-9).count(), 2, "{b:?}"); + } + + #[test] + fn verfeinern_haelt_ecken_und_kreis() { + let p = band(); + let f = refine(&p, true, TOL, &fine_segments).unwrap(); + assert!(f.len() > 2 * p.len(), "{}", f.len()); + for q in &p { + assert!(f.iter().any(|x| dist(*x, *q) < 1e-12) || { + let r = crate::jsmath::hypot2(q.x, q.y); + (r - 5.0).abs() < 1e-9 || (r - 4.7).abs() < 1e-9 + }); + } + // Alle neuen Punkte auf einem der Kreise oder Ecken des Originals. + assert!(f.iter().all(|x| { + let r = crate::jsmath::hypot2(x.x, x.y); + (r - 5.0).abs() < 1e-9 || (r - 4.7).abs() < 1e-9 + })); + let c = refine(&ring(V2 { x: 0.0, y: 0.0 }, 0.15, 32), true, TOL, &fine_segments).unwrap(); + assert!(c.len() >= 180, "{}", c.len()); + assert!(refine(&[V2 { x: 0.0, y: 0.0 }, V2 { x: 1.0, y: 0.0 }, V2 { x: 1.0, y: 1.0 }], true, TOL, &fine_segments).is_none()); + } + + #[test] + fn langer_bogen_wird_geteilt() { + let p: Vec = (0..=40).map(|i| { + let t = 1.6 * PI * i as f64 / 40.0; + V2 { x: t.cos(), y: t.sin() } + }).collect(); + let Some(Shape::Path { segs, .. }) = fit(&p, false, TOL) else { panic!() }; + assert_eq!(segs.len(), 2); + let tot: f64 = segs.iter().map(|g| if let Seg::Arc { sweep, .. } = g { *sweep } else { 0.0 }).sum(); + assert!((tot - 1.6 * PI).abs() < 1e-9); + assert!(segs.iter().all(|g| matches!(g, Seg::Arc { sweep, .. } if sweep.abs() <= PI + 1e-9))); + } + + #[test] + fn unsinn_ergibt_nichts() { + let nan = vec![V2 { x: f64::NAN, y: 0.0 }; 6]; + assert!(fit(&nan, true, TOL).is_none()); + assert!(fit(&[], false, TOL).is_none()); + } +} diff --git a/src-tauri/core/src/plan/arc_output_tests.rs b/src-tauri/core/src/plan/arc_output_tests.rs new file mode 100644 index 00000000..981db316 --- /dev/null +++ b/src-tauri/core/src/plan/arc_output_tests.rs @@ -0,0 +1,79 @@ +//! [169] Runde Formen als echte Kreise und Bögen in den Ausgaben des Grundrisses: runde Stütze (geschnitten +//! und als Ansichtskante unter der Schnitthöhe) und Bogenwand. Plan-SVG und Druck-SVG schreiben `` +//! bzw. `` mit `A`, DXF CIRCLE bzw. LWPOLYLINE mit Bulges, die render2d-Szene tesselliert fein nach. + +use super::buf::View; +use super::domains::{plan_domains_buf, PlanArgs}; +use super::parts::Part; +use super::wall_join_tests::{add_arc_deg, add_column, base}; +use crate::model::*; + +fn project(column_height: f64) -> Project { + let mut p = base(); + add_arc_deg(&mut p, "bw", (0.0, 0.0), 4.0, 0.0, 90.0); + add_column(&mut p, "C", (8.0, 1.0), ColumnProfile::Round { radius: 0.15 }, Some("concrete")); + p.columns.as_mut().unwrap()[0].height = column_height; + p +} + +fn buf(p: &Project, scale: f64) -> Vec { + let t = serde_json::json!({ "floor": "eg", "show": ["20"], "grey": [], "scale": scale }).to_string(); + plan_domains_buf(p, &PlanArgs::parse(2.0, &t).unwrap()).unwrap() +} + +fn parts(bytes: &[u8]) -> Vec { + let view = View::parse(bytes).unwrap(); + let n = view.len(); + vec![Part::new(view, 0, n).unwrap()] +} + +fn svg(bytes: &[u8], scale: f64) -> String { + let o = super::svg::SvgOptions { scale_denominator: scale, margin_m: 0.5, min_x: -1.0, min_y: -1.0, max_x: 9.0, max_y: 5.0, hatch: true, line_ends: Default::default() }; + super::svg::plan_svg(&mut parts(bytes), &o).unwrap() +} + +#[test] +fn runde_stuetze_als_kreis_in_svg_druck_dxf_und_szene() { + for (h, what) in [(2.6, "geschnitten"), (0.5, "unter der Schnitthöhe")] { + let p = project(h); + let b = buf(&p, 20.0); + // Plan-SVG: Kreis um (8, 1), r = 0.15 (y gespiegelt: top = 5.5 → cy = 4.5). + let s = svg(&b, 20.0); + assert!(s.lines().any(|l| l.starts_with("= 1, "{what}: CIRCLE {:?}", f.model); + assert_eq!(f.model[0], 0, "{what}: keine LINE {:?}", f.model); + // Szene: fein nachtesselliert (≥ 180 Punkte im Umriss der Stütze). + let sc = super::scene::build_scene(&mut parts(&b), &[]).unwrap(); + let near = |q: &crate::hatch::V2| ((q.x - 8.0).powi(2) + (q.y - 1.0).powi(2)).sqrt(); + let max_pts = sc.outlines.iter().chain(&sc.polylines).filter(|s| s.pts.iter().all(|q| (near(q) - 0.15).abs() < 1e-6)).map(|s| s.pts.len()).max().unwrap_or(0); + assert!(max_pts >= 180, "{what}: {max_pts}"); + } +} + +#[test] +fn bogenwand_kanten_als_boegen() { + let p = project(2.6); + let b = buf(&p, 50.0); + let s = svg(&b, 50.0); + // Wandfläche (Pfad mit Bögen, kein Vieleck) und Kanten: Radien 3.9 und 4.1 (Beton 0.2 m um die Achse). + let arcs: Vec<&str> = s.lines().filter(|l| l.starts_with(" = (0..n).map(|k| f.nums[i + 4 + 3 * k + 2]).collect(); + assert!(bulges.iter().any(|b| (b.abs() - (std::f64::consts::PI / 8.0).tan()).abs() < 1e-6), "{bulges:?}"); +} diff --git a/src-tauri/core/src/plan/dxf.rs b/src-tauri/core/src/plan/dxf.rs index 1bb69d96..ee91734f 100644 --- a/src-tauri/core/src/plan/dxf.rs +++ b/src-tauri/core/src/plan/dxf.rs @@ -46,6 +46,8 @@ const REC_SHEET_VP: f64 = 21.0; const REC_SHEET_INSERT: f64 = 22.0; /// [146] Linienenden/-ecken des Projekts `[cap | join << 2]` → `$ENDCAPS`/`$JOINSTYLE`. const REC_LINE_ENDS: f64 = 23.0; +/// [169] LWPOLYLINE mit Bulges: `[Ebene, geschlossen, n, n × (x, y, bulge)]`. +const REC_POLYLINE_BULGE: f64 = 24.0; /// Sammel-Ebenen für Primitive ohne eigene Kategorie. const LAYER_HATCH: &str = "HATCH"; @@ -268,6 +270,25 @@ impl Flat { } } + /// [169] Zug mit erkannten Bögen ([`crate::plan::arc_fit`]): ganzer Kreis als CIRCLE, sonst LWPOLYLINE mit + /// Bulges; ohne Bogen `false` (der Aufrufer schreibt den Zug wie bisher). + fn add_curve(&mut self, b: &mut Buf, layer: &str, pts: &[V2], closed: bool) -> bool { + use crate::plan::arc_fit; + let Some(shape) = arc_fit::fit(pts, closed, arc_fit::TOL) else { return false }; + if let arc_fit::Shape::Circle { c, r, .. } = shape { + self.add_circle(b, layer, c, r); + return true; + } + let Some((v, bulge)) = arc_fit::bulges(&shape) else { return false }; + b.counts[K_POLY] += 1; + let l = self.layer(layer); + self.push(b, &[REC_POLYLINE_BULGE, l, b01(closed), v.len() as f64]); + for (p, g) in v.iter().zip(&bulge) { + self.push(b, &[p.x, p.y, *g]); + } + true + } + fn add_arc(&mut self, b: &mut Buf, layer: &str, c: V2, r: f64, start: f64, end: f64) { b.counts[K_ARC] += 1; let l = self.layer(layer); @@ -962,7 +983,10 @@ impl Ctx<'_> { } } self.flat.set_pen(b, -1.0); - self.flat.add_polyline(b, layer, pts, true); + // [169] Runde Stütze als CIRCLE, Bogenwand-/Bogen-Umrisse als LWPOLYLINE mit Bulges. + if !self.flat.add_curve(b, layer, pts, true) { + self.flat.add_polyline(b, layer, pts, true); + } } Prim::Other => {} } @@ -1283,7 +1307,40 @@ fn emit_entries(cx: &mut Ctx, main: &mut Buf, entries: &[Entry], layer_by_code: let mut done: HashSet<&(u8, String)> = HashSet::new(); // 4) Jedes Primitiv in Entitäten übersetzen. + let plain = |e: &Entry| matches!(&e.prim, Prim::Line { zigzag: None, motif: None, .. }); + let mut skip_to = 0usize; for (i, e) in entries.iter().enumerate() { + if i < skip_to { + continue; + } + // [169] Aneinander anschliessende Einzel-Linien gleicher Ebene und gleichen Musters (Ansichtskante einer + // runden Stütze, Umriss-Linien an Bogenwänden): erkannte Bögen als CIRCLE bzw. LWPOLYLINE mit Bulges. + if keys[i].is_none() && plain(e) { + let l = layer_for(e); + let Prim::Line { a, b: q, dash, .. } = &e.prim else { unreachable!() }; + let mut pts = vec![*a, *q]; + let mut j = i + 1; + while j < entries.len() && keys[j].is_none() && plain(&entries[j]) { + let Prim::Line { a: aj, b: bj, dash: dj, .. } = &entries[j].prim else { break }; + let last = pts[pts.len() - 1]; + if dj != dash || (aj.x - last.x).abs() > 1e-9 || (aj.y - last.y).abs() > 1e-9 || layer_for(&entries[j]) != l { + break; + } + pts.push(*bj); + j += 1; + } + if pts.len() >= 4 { + let closed = (pts[0].x - pts[pts.len() - 1].x).abs() <= 1e-9 && (pts[0].y - pts[pts.len() - 1].y).abs() <= 1e-9; + let ring = if closed { &pts[..pts.len() - 1] } else { &pts[..] }; + let lt = cx.ltype_of(dash); + if crate::plan::arc_fit::fit(ring, closed, crate::plan::arc_fit::TOL).is_some() { + cx.flat.set_pen(main, lt); + cx.flat.add_curve(main, &l, ring, closed); + skip_to = j; + continue; + } + } + } if let Some(key) = &keys[i] { if !done.insert(key) { continue; diff --git a/src-tauri/core/src/plan/mod.rs b/src-tauri/core/src/plan/mod.rs index be004568..7e3591c0 100644 --- a/src-tauri/core/src/plan/mod.rs +++ b/src-tauri/core/src/plan/mod.rs @@ -38,8 +38,11 @@ pub mod stamp_place; pub mod floor_finish; pub mod trees; pub mod mesh_plan; +pub mod arc_fit; pub(crate) mod wall_columns; #[cfg(test)] pub(crate) mod wall_join_tests; #[cfg(test)] mod hatch_dir_tests; +#[cfg(test)] +mod arc_output_tests; diff --git a/src-tauri/core/src/plan/print_svg.rs b/src-tauri/core/src/plan/print_svg.rs index b6b0cd9f..dd407b5b 100644 --- a/src-tauri/core/src/plan/print_svg.rs +++ b/src-tauri/core/src/plan/print_svg.rs @@ -26,6 +26,7 @@ use crate::js_fmt::js_number; use crate::jsnum; use crate::plan::buf::{whole, Rec, View, F_COLOR, F_DASH_NULL, F_OPACITY, T_ARC, T_CIRCLE, T_DRAWING_ARC, T_DRAWING_TEXT, T_IMAGE, T_LINE, T_POLYGON, T_TEXT}; use crate::plan::parts::{greyed_of, Part}; +use crate::plan::arc_fit; use crate::plan::text::{SingleText, StampText}; use crate::text_layout::{place_lines, stamp_block, stamp_line_offsets, wrap_doc_to_lines, Line, LayoutOpts, LineAlign, PT_TO_MM, TEXT_LINE_HEIGHT_MULT}; use std::f64::consts::PI; @@ -72,6 +73,25 @@ struct Out { /// [153] Laufender gestrichelter Zug: aneinander anschliessende Linien gleicher Darstellung /// (Farbe, Stift, Muster in mm, Deckkraft) werden EIN `` mit Musterphase. dash_run: Option<((String, String, Vec, String), Vec)>, + /// [169] Toleranz der Bogenerkennung in Papier-mm. + tol: f64, +} + +/// [169] Geometrie eines Rings/Zugs in Papier-mm: ganzer Kreis als `circle`, Zug mit erkannten Bögen als +/// `path` mit `A`-Befehlen ([`arc_fit`]), sonst `polygon`/`polyline` (`points`). Dritter Wert = Länge. +fn geo_mm(pts: &[V2], closed: bool, tol: f64) -> (&'static str, Vec<(&'static str, String)>, f64) { + if let Some(sh) = arc_fit::fit(pts, closed, tol) { + let len = arc_fit::length(&sh); + if let arc_fit::Shape::Circle { c, r, .. } = sh { + return ("circle", vec![("cx", r3(c.x)), ("cy", r3(c.y)), ("r", r3(r))], len); + } + return ("path", vec![("d", arc_fit::svg_d_with(&sh, &|p| p, 1.0, &r3, true))], len); + } + let mut len: f64 = pts.windows(2).map(|w| crate::jsmath::hypot2(w[1].x - w[0].x, w[1].y - w[0].y)).sum(); + if closed && pts.len() > 1 { + len += crate::jsmath::hypot2(pts[0].x - pts[pts.len() - 1].x, pts[0].y - pts[pts.len() - 1].y); + } + (if closed { "polygon" } else { "polyline" }, vec![("points", pts_attr(pts))], len) } impl Out { @@ -95,9 +115,18 @@ impl Out { /// Schreibt den laufenden gestrichelten Zug ([`super::line_pattern::phase`]: Enden auf einem Strich). fn flush_dash(&mut self) { let Some(((color, pen, dash, o), pts)) = self.dash_run.take() else { return }; - let len: f64 = pts.windows(2).map(|w| crate::jsmath::hypot2(w[1].x - w[0].x, w[1].y - w[0].y)).sum(); let pen_mm: f64 = pen.parse().unwrap_or(0.0); - let mut attrs = if pts.len() == 2 { line_attrs(pts[0], pts[1], &color, pen_mm, Some(&dash)) } else { polyline_attrs(&pts, &color, pen_mm, Some(&dash)) }; + // [169] Bögen im Zug als Pfad mit `A`; Phase über die Länge mit Bögen. + let (gtag, geo, len) = geo_mm(&pts, false, self.tol); + let tag = if pts.len() == 2 { "line" } else { gtag }; + let mut attrs = if pts.len() == 2 { + line_attrs(pts[0], pts[1], &color, pen_mm, Some(&dash)) + } else { + let mut a = geo; + a.extend([("fill", "none".to_string()), ("stroke", color.clone()), ("stroke-width", js_number(pen_mm))]); + push_dash(&mut a, Some(&dash)); + a + }; let ph = super::line_pattern::phase(len, &dash); if ph > 1e-9 { attrs.push(("stroke-dashoffset", r3(ph))); @@ -105,7 +134,6 @@ impl Out { if !o.is_empty() { attrs.push(("opacity", o)); } - let tag = if pts.len() == 2 { "line" } else { "polyline" }; let mut f: Vec<&str> = vec!["E", "0", tag]; for (k, v) in &attrs { f.push(k); @@ -135,15 +163,19 @@ impl Out { for (pts, closed, members) in crate::plan::scene::stitch_runs_members(&runs) { let slot = members.iter().map(|&m| slots[m]).max().unwrap_or(0); let line = pts.len() == 2 && !closed; + // [169] Bögen (runde Stütze, Bogenwand) als Kreis bzw. Pfad mit `A`. + let (gtag, geo, _) = if line { ("line", Vec::new(), 0.0) } else { geo_mm(&pts, closed, self.tol) }; let mut attrs = if line { vec![("x1", r3(pts[0].x)), ("y1", r3(pts[0].y)), ("x2", r3(pts[1].x)), ("y2", r3(pts[1].y)), ("stroke", color.clone()), ("stroke-width", pen.clone())] } else { - vec![("points", pts_attr(&pts)), ("fill", "none".to_string()), ("stroke", color.clone()), ("stroke-width", pen.clone())] + let mut a = geo; + a.extend([("fill", "none".to_string()), ("stroke", color.clone()), ("stroke-width", pen.clone())]); + a }; if !o.is_empty() { attrs.push(("opacity", o.clone())); } - let tag = if line { "line" } else if closed { "polygon" } else { "polyline" }; + let tag = gtag; let mut f: Vec<&str> = vec!["E", "0", tag]; for (k, v) in &attrs { f.push(k); @@ -215,19 +247,23 @@ fn split_alpha(color: &str) -> (String, Option) { (color.to_string(), None) } -fn poly_node(pts: &str, fill: &str, stroke: &str, stroke_mm: f64) -> Vec<(&'static str, String)> { +/// Geometrie-Element eines Rings: Tag und Geometrie-Attribute ([`geo_mm`]). +type Geo = (&'static str, Vec<(&'static str, String)>); + +fn poly_node(geo: &[(&'static str, String)], fill: &str, stroke: &str, stroke_mm: f64) -> Vec<(&'static str, String)> { let (fill, fill_opacity) = split_alpha(fill); let opaque = fill_opacity.is_none(); - let mut a = vec![("points", pts.to_string()), ("fill", fill)]; + let mut a = geo.to_vec(); + a.push(("fill", fill.clone())); if let Some(o) = fill_opacity { a.push(("fill-opacity", o)); } if stroke != "none" && stroke_mm > 0.0 { a.push(("stroke", stroke.to_string())); a.push(("stroke-width", js_number(stroke_mm))); - } else if opaque && super::svg::seam_fill(&a[1].1) { + } else if opaque && super::svg::seam_fill(&fill) { // [157] Dunkle, deckende Fläche: Haarstrich in der Füllfarbe gegen die Fuge zur Nachbarfläche. - a.push(("stroke", a[1].1.clone())); + a.push(("stroke", fill)); a.push(("stroke-width", js_number(super::svg::SEAM_MM))); } else { a.push(("stroke", "none".to_string())); @@ -237,23 +273,25 @@ fn poly_node(pts: &str, fill: &str, stroke: &str, stroke_mm: f64) -> Vec<(&'stat /// Polygon mit Füllung und Strich; mit `nse` (nicht gestrichene Kanten, [146]) die Füllung ohne Strich /// und die sichtbaren Kantenläufe als offene Linienzüge — wie das Plan-SVG (`plan/svg.rs`). -fn poly_stroked(out: &mut Out, attr: &str, pts_mm: &[V2], nse: &[f64], fill: &str, stroke: &str, stroke_mm: f64) { +fn poly_stroked(out: &mut Out, geo: &Geo, pts_mm: &[V2], nse: &[f64], fill: &str, stroke: &str, stroke_mm: f64) { if nse.is_empty() || stroke_mm <= 0.0 || stroke == "none" { - out.el(1, "polygon", &poly_node(attr, fill, stroke, stroke_mm)); + out.el(1, geo.0, &poly_node(&geo.1, fill, stroke, stroke_mm)); return; } - out.el(1, "polygon", &poly_node(attr, fill, "none", 0.0)); - poly_outline(out, pts_mm, nse, stroke, stroke_mm); + out.el(1, geo.0, &poly_node(&geo.1, fill, "none", 0.0)); + poly_outline(out, geo, pts_mm, nse, stroke, stroke_mm); } /// Nur der Umriss (Füllung oder Schraffur liegt schon darunter). -fn poly_outline(out: &mut Out, pts_mm: &[V2], nse: &[f64], stroke: &str, stroke_mm: f64) { +fn poly_outline(out: &mut Out, geo: &Geo, pts_mm: &[V2], nse: &[f64], stroke: &str, stroke_mm: f64) { if nse.is_empty() { - out.el(1, "polygon", &poly_node(&pts_attr(pts_mm), "none", stroke, stroke_mm)); + out.el(1, geo.0, &poly_node(&geo.1, "none", stroke, stroke_mm)); return; } for run in crate::plan::scene::visible_edge_runs(pts_mm, nse) { - out.el(1, "polyline", &polyline_attrs(&run, stroke, stroke_mm, None)); + let (tag, mut a, _) = geo_mm(&run, false, out.tol); + a.extend([("fill", "none".to_string()), ("stroke", stroke.to_string()), ("stroke-width", js_number(stroke_mm))]); + out.el(1, tag, &a); } } @@ -292,6 +330,16 @@ fn push_dash(v: &mut Vec<(&'static str, String)>, dash: Option<&[f64]>) { } } +/// [153]/[169] `stroke-dashoffset` eines gestrichelten Bogens der Papier-Länge `len_mm`. +fn push_phase(v: &mut Vec<(&'static str, String)>, dash: Option<&[f64]>, len_mm: f64) { + if let Some(d) = dash.filter(|d| !d.is_empty()) { + let ph = super::line_pattern::phase(len_mm, d); + if ph > 1e-9 { + v.push(("stroke-dashoffset", r3(ph))); + } + } +} + /// Strichmuster der Schraffurlinien in Papier-mm: dieselben Modell-Längen wie Szene/Chunk-Pfad /// (`hatch::hatch_dash` × `DASH_MM_TO_M`), nur auf das Blatt (`mm_per_m`) abgebildet. pub(super) fn hatch_dash_paper(h: &Hatch, mm_per_m: f64) -> Vec { @@ -341,6 +389,11 @@ fn entry(out: &mut Out, view: &View, i: usize, hatches: &[(i32, Hatch, i32)], m: let opacity = opacity_of(greyed, obj(4)); let pts_mm: Vec = pts.iter().map(|p| m.at(p.x, p.y)).collect(); let attr = pts_attr(&pts_mm); + // [169] Kreis bzw. Ring mit Bögen als ``/``; Schraffur am fein nachtesselierten Ring + // beschnitten (endet am Bogen, nicht an der Sehne). + let (gtag, gattrs, _) = geo_mm(&pts_mm, true, out.tol); + let geo: Geo = (gtag, gattrs); + let pts = if gtag == "polygon" { pts } else { arc_fit::refine(&pts, true, arc_fit::TOL, &arc_fit::fine_segments).unwrap_or(pts) }; let nse: Vec = match rec.nse { Some((o, n)) => view.pool(o, n)?.into_iter().filter(|e| e.is_finite() && *e >= 0.0).collect(), None => Vec::new(), @@ -361,19 +414,19 @@ fn entry(out: &mut Out, view: &View, i: usize, hatches: &[(i32, Hatch, i32)], m: let hatch_color = if color >= 0 { view.string(color as usize)? } else { "undefined".to_string() }; if let Some(img) = image { if fill != "none" { - out.el(1, "polygon", &poly_node(&attr, &fill, "none", 0.0)); + out.el(1, geo.0, &poly_node(&geo.1, &fill, "none", 0.0)); } out.rec(&["I", &attr, &img]); if stroke_mm > 0.0 { - poly_outline(out, &pts_mm, &nse, &stroke, stroke_mm); + poly_outline(out, &geo, &pts_mm, &nse, &stroke, stroke_mm); } } else if h.pattern == Pattern::None { - poly_stroked(out, &attr, &pts_mm, &nse, &fill, &stroke, stroke_mm); + poly_stroked(out, &geo, &pts_mm, &nse, &fill, &stroke, stroke_mm); } else if h.pattern == Pattern::Solid { - poly_stroked(out, &attr, &pts_mm, &nse, &hatch_color, &stroke, stroke_mm); + poly_stroked(out, &geo, &pts_mm, &nse, &hatch_color, &stroke, stroke_mm); } else { if fill != "none" { - out.el(1, "polygon", &poly_node(&attr, &fill, "none", 0.0)); + out.el(1, geo.0, &poly_node(&geo.1, &fill, "none", 0.0)); } let pen = quantize_pen(h.line_weight); let hdash = hatch_dash_paper(&h, k); @@ -400,7 +453,7 @@ fn entry(out: &mut Out, view: &View, i: usize, hatches: &[(i32, Hatch, i32)], m: } } if stroke_mm > 0.0 { - poly_outline(out, &pts_mm, &nse, &stroke, stroke_mm); + poly_outline(out, &geo, &pts_mm, &nse, &stroke, stroke_mm); } } out.rec(&["g"]); @@ -446,7 +499,15 @@ fn entry(out: &mut Out, view: &View, i: usize, hatches: &[(i32, Hatch, i32)], m: let sweep = if cross > 0.0 { 1 } else { 0 }; let d = format!("M {} {} A {} {} 0 0 {} {} {}", r3(from.x), r3(from.y), r3(r), r3(r), sweep, r3(to.x), r3(to.y)); let mut attrs = vec![("d", d), ("fill", "none".to_string()), ("stroke", "#111111".to_string()), ("stroke-width", js_number(quantize_pen(f[2])))]; - push_dash(&mut attrs, dash(&rec)?.as_deref()); + let dd = dash(&rec)?; + push_dash(&mut attrs, dd.as_deref()); + // [153]/[169] Musterphase auch auf Bögen (kürzerer Bogen, wie gezeichnet). + let ang = |p: V2| jsnum::atan2(p.y - c.y, p.x - c.x); + let mut sw = (ang(to) - ang(from)).abs(); + if sw > PI { + sw = 2.0 * PI - sw; + } + push_phase(&mut attrs, dd.as_deref(), r * sw); let o = opacity_of(greyed, obj(3)); if !o.is_empty() { attrs.push(("opacity", o)); @@ -481,7 +542,9 @@ fn entry(out: &mut Out, view: &View, i: usize, hatches: &[(i32, Hatch, i32)], m: let large = if sweep > PI { 1 } else { 0 }; let d = format!("M {} {} A {} {} 0 {} 1 {} {}", r3(from.x), r3(from.y), r3(rr), r3(rr), large, r3(to.x), r3(to.y)); let mut attrs = vec![("d", d), ("fill", "none".to_string()), ("stroke", s(f[0])?), ("stroke-width", js_number(quantize_pen(f[1])))]; - push_dash(&mut attrs, dash(&rec)?.as_deref()); + let dd = dash(&rec)?; + push_dash(&mut attrs, dd.as_deref()); + push_phase(&mut attrs, dd.as_deref(), rr * sweep); let o = opacity_of(greyed, obj(2)); if !o.is_empty() { attrs.push(("opacity", o)); @@ -638,7 +701,7 @@ pub fn print_svg_ops(parts: &mut [Part], o: &PrintOptions) -> Option { let content_w = (max_x - min_x) * k; let content_h = (max_y - min_y) * k; let m = Map { off_x: (o.page_w - content_w) / 2.0, off_y: (o.page_h - content_h) / 2.0, min_x, max_y, k }; - let mut out = Out { recs: Vec::new(), solid: Vec::new(), dash_run: None }; + let mut out = Out { recs: Vec::new(), solid: Vec::new(), dash_run: None, tol: arc_fit::TOL * k }; for part in parts.iter_mut() { let hatches = part.view.hatch_table()?; for i in part.from..part.to { @@ -655,20 +718,20 @@ mod tests { #[test] fn schwarze_flaeche_mit_haarstrich() { // [157] Dunkle deckende Fläche ohne Strich: Haarstrich in der Füllfarbe (keine helle Fuge im PDF). - let a = poly_node("0,0 1,0 1,1", "#0f0f0f", "none", 0.0); + let a = poly_node(&[("points", "0,0 1,0 1,1".to_string())], "#0f0f0f", "none", 0.0); assert!(a.contains(&("stroke", "#0f0f0f".to_string())) && a.contains(&("stroke-width", "0.05".to_string())), "{a:?}"); - let b = poly_node("0,0 1,0 1,1", "#ffffff", "none", 0.0); + let b = poly_node(&[("points", "0,0 1,0 1,1".to_string())], "#ffffff", "none", 0.0); assert!(b.contains(&("stroke", "none".to_string())), "{b:?}"); - let c = poly_node("0,0 1,0 1,1", "#0f0f0f", "#222", 0.35); + let c = poly_node(&[("points", "0,0 1,0 1,1".to_string())], "#0f0f0f", "#222", 0.35); assert!(c.contains(&("stroke", "#222".to_string())), "{c:?}"); } #[test] fn raumfuellung_mit_alpha_als_deckkraft() { - let a = poly_node("0,0 1,0 1,1", "#4a6fa526", "none", 0.0); + let a = poly_node(&[("points", "0,0 1,0 1,1".to_string())], "#4a6fa526", "none", 0.0); assert!(a.contains(&("fill", "#4a6fa5".to_string()))); assert!(a.contains(&("fill-opacity", "0.149".to_string()))); - let b = poly_node("0,0 1,0 1,1", "#ffffff", "none", 0.0); + let b = poly_node(&[("points", "0,0 1,0 1,1".to_string())], "#ffffff", "none", 0.0); assert!(b.iter().all(|e| e.0 != "fill-opacity")); } @@ -694,7 +757,7 @@ mod tests { let js = "{\"kind\":\"drawingText\",\"at\":{\"x\":1,\"y\":2},\"text\":\"aa bb\",\"heightM\":0.5,\"angle\":0.5,\"color\":\"#123\",\"wrapWidth\":2,\"marks\":{\"bold\":true}}"; let t: SingleText = serde_json::from_str(js).unwrap(); let m = Map { off_x: 0.0, off_y: 0.0, min_x: 0.0, max_y: 10.0, k: 10.0 }; - let mut out = Out { recs: Vec::new(), solid: Vec::new(), dash_run: None }; + let mut out = Out { recs: Vec::new(), solid: Vec::new(), dash_run: None, tol: arc_fit::TOL }; text_node(&mut out, &t, m, "0.5".into()); let s = out.finish(); let recs: Vec> = s.split('\u{1e}').map(|r| r.split('\u{1f}').collect()).collect(); @@ -713,7 +776,7 @@ mod tests { let js = r##"{"at":{"x":0,"y":10},"text":"","heightM":0.25,"angle":0,"wrapWidth":2,"doc":{"version":1,"paragraphs":[{"runs":[{"text":"aaaa bbbb","marks":{}}]},{"runs":[{"text":"c","marks":{"sizePt":72}}],"lineHeight":2}]}}"##; let t: SingleText = serde_json::from_str(js).unwrap(); let m = Map { off_x: 0.0, off_y: 0.0, min_x: 0.0, max_y: 10.0, k: 10.0 }; - let mut out = Out { recs: Vec::new(), solid: Vec::new(), dash_run: None }; + let mut out = Out { recs: Vec::new(), solid: Vec::new(), dash_run: None, tol: arc_fit::TOL }; text_node(&mut out, &t, m, String::new()); let s = out.finish(); let recs: Vec> = s.split('\u{1e}').map(|r| r.split('\u{1f}').collect()).collect(); @@ -730,7 +793,7 @@ mod tests { let js = r##"{"at":{"x":2,"y":3},"doc":{"version":1,"paragraphs":[{"runs":[{"text":"Wohnen","marks":{"bold":true}}],"align":"center"}]},"extraLines":[{"text":"17.01 m²","align":"center"}],"basePt":10,"color":"#333"}"##; let t: StampText = serde_json::from_str(js).unwrap(); let m = Map { off_x: 0.0, off_y: 0.0, min_x: 0.0, max_y: 10.0, k: 20.0 }; - let mut out = Out { recs: Vec::new(), solid: Vec::new(), dash_run: None }; + let mut out = Out { recs: Vec::new(), solid: Vec::new(), dash_run: None, tol: arc_fit::TOL }; stamp_node(&mut out, &t, m, "0.3".into()); let s = out.finish(); let recs: Vec> = s.split('\u{1e}').map(|r| r.split('\u{1f}').collect()).collect(); diff --git a/src-tauri/core/src/plan/scene.rs b/src-tauri/core/src/plan/scene.rs index d3ca7b06..3e9152aa 100644 --- a/src-tauri/core/src/plan/scene.rs +++ b/src-tauri/core/src/plan/scene.rs @@ -28,6 +28,13 @@ use crate::plan::parts::{greyed_of, in_ranges, pick_id, Part}; use std::collections::HashMap; use std::f64::consts::PI; +/// [169] Erkannte Bögen (runde Stütze, Bogenwand, Bogen-Umrisse) für den Bildschirm fein nachtesselliert +/// ([`crate::plan::arc_fit::refine`]: Schritt ≤ 2°, Pfeilhöhe ≤ 0.05 mm), sonst der Zug unverändert. +fn smooth(pts: Vec, closed: bool) -> Vec { + use crate::plan::arc_fit; + arc_fit::refine(&pts, closed, arc_fit::TOL, &arc_fit::fine_segments).unwrap_or(pts) +} + pub type Rgba = [f64; 4]; /// Strichmuster eines Szenen-Elements. @@ -407,9 +414,9 @@ impl Builder { if closed { let mut p = pts; p.pop(); - self.s.outlines.push(SStroke { pts: p, color: col, width_mm: src.weight, dash, z, width_screen: false }); + self.s.outlines.push(SStroke { pts: smooth(p, true), color: col, width_mm: src.weight, dash, z, width_screen: false }); } else { - self.s.polylines.push(SStroke { pts, color: col, width_mm: src.weight, dash, z, width_screen: false }); + self.s.polylines.push(SStroke { pts: smooth(pts, false), color: col, width_mm: src.weight, dash, z, width_screen: false }); } } } @@ -476,10 +483,12 @@ pub fn build_scene(parts: &mut [Part], greyed_ranges: &[(usize, usize)]) -> Opti if pts.len() < 2 { continue; } + // [169] Ring mit Bögen fein (Fläche, Schraffur-Beschnitt, Umriss); Kantenläufe aus `pts`. + let fine = if pts.len() >= 4 { smooth(pts.clone(), true) } else { pts.clone() }; if let Some(fc) = color(part, f[0]) { if pts.len() >= 3 { let z = b.z(); - b.s.fills.push(SFill { pts: pts.clone(), color: with_fill_opacity(fc, greyed), z }); + b.s.fills.push(SFill { pts: fine.clone(), color: with_fill_opacity(fc, greyed), z }); } } if f[3] != -1.0 { @@ -490,7 +499,7 @@ pub fn build_scene(parts: &mut [Part], greyed_ranges: &[(usize, usize)]) -> Opti if h.kind != HatchKind::Image && h.kind != HatchKind::Gradient && h.pattern != Pattern::None && h.pattern != Pattern::Solid { let hatch_col = with_opacity(color(part, hc as f64).unwrap_or(INK), None, greyed); let hatch_mm = if h.line_weight > 0.0 { h.line_weight } else { 0.13 }; - let runs = if pts.len() < 3 { Vec::new() } else { hatch::build_hatch_runs(&pts, &h) }; + let runs = if pts.len() < 3 { Vec::new() } else { hatch::build_hatch_runs(&fine, &h) }; let runs = hatch::apply_dash_runs(runs, &hatch::hatch_dash(&h)); let hz = b.z(); for run in runs { @@ -510,7 +519,7 @@ pub fn build_scene(parts: &mut [Part], greyed_ranges: &[(usize, usize)]) -> Opti }; if nse.is_empty() { let z = b.z(); - b.s.outlines.push(SStroke { pts, color: sc, width_mm: w, dash: SDash::Absent, z, width_screen: false }); + b.s.outlines.push(SStroke { pts: fine, color: sc, width_mm: w, dash: SDash::Absent, z, width_screen: false }); } else { let rz = b.z(); for run in visible_edge_runs(&pts, &nse) { @@ -635,7 +644,7 @@ pub fn build_scene(parts: &mut [Part], greyed_ranges: &[(usize, usize)]) -> Opti continue; } let z = members.iter().fold(f64::NEG_INFINITY, |m, &i| jsnum::max(m, g.zs[i])); - let s = SStroke { pts, color: g.color, width_mm: g.width_mm, dash: SDash::Absent, z, width_screen: false }; + let s = SStroke { pts: smooth(pts, closed), color: g.color, width_mm: g.width_mm, dash: SDash::Absent, z, width_screen: false }; if closed { b.s.outlines.push(s); } else { diff --git a/src-tauri/core/src/plan/svg.rs b/src-tauri/core/src/plan/svg.rs index 7ca32a19..9aefd264 100644 --- a/src-tauri/core/src/plan/svg.rs +++ b/src-tauri/core/src/plan/svg.rs @@ -13,6 +13,7 @@ use crate::plan::buf::{whole, F_COLOR, F_DASH_LIST, F_GREYED, F_OPACITY, T_ARC, use crate::plan::line_ends::LineEnds; use crate::plan::parts::Part; use crate::plan::scene::stitch_runs_members; +use crate::plan::arc_fit; use std::collections::HashMap; use serde_json::Value; use std::f64::consts::PI; @@ -119,20 +120,16 @@ impl Stitcher { self.groups[gi].2.push(slot); } - fn finish(self, out: &mut [String], xs: &dyn Fn(f64) -> String, ys: &dyn Fn(f64) -> String) { + fn finish(self, out: &mut [String], xs: &dyn Fn(f64) -> String, ys: &dyn Fn(f64) -> String, top: f64) { for (attrs, runs, slots) in self.groups { for (pts, closed, members) in stitch_runs_members(&runs) { if pts.len() < 2 { continue; } let slot = members.iter().map(|&m| slots[m]).max().unwrap_or(0); - let el = if !closed && pts.len() == 2 { - format!("", xs(pts[0].x), ys(pts[0].y), xs(pts[1].x), ys(pts[1].y)) - } else { - let pl = pts.iter().map(|q| format!("{},{}", xs(q.x), ys(q.y))).collect::>().join(" "); - let tag = if closed { "polygon" } else { "polyline" }; - format!("<{tag} points=\"{pl}\" fill=\"none\"{attrs}/>") - }; + // [169] Bögen (runde Stütze, Bogenwand) als Kreis bzw. Pfad mit `A`. + let (g, _) = shape_el(&pts, closed, xs, ys, top); + let el = if g.starts_with("line ") { format!("<{g}{attrs}/>") } else { format!("<{g} fill=\"none\"{attrs}/>") }; if out[slot].is_empty() { out[slot] = el; } else { @@ -191,6 +188,43 @@ fn op(greyed: bool, opacity: Option) -> String { } } +/// [169] Geometrie eines Rings oder Zugs als Element-Anfang (Tag und Geometrie-Attribute): ganzer Kreis als +/// `circle`, Zug mit erkannten Bögen als `path` mit `A`-Befehlen ([`arc_fit`]), sonst `polygon`/`polyline` +/// bzw. `line`. Zweiter Wert = Länge (für die Musterphase). +fn shape_el(pts: &[V2], closed: bool, xs: &dyn Fn(f64) -> String, ys: &dyn Fn(f64) -> String, top: f64) -> (String, f64) { + if let Some(sh) = arc_fit::fit(pts, closed, arc_fit::TOL) { + let len = arc_fit::length(&sh); + if let arc_fit::Shape::Circle { c, r, .. } = sh { + return (format!("circle cx=\"{}\" cy=\"{}\" r=\"{}\"", xs(c.x), ys(c.y), num(r)), len); + } + let d = arc_fit::svg_d(&sh, &|p| V2 { x: p.x, y: top - p.y }, 1.0, &num); + return (format!("path d=\"{d}\""), len); + } + let mut len: f64 = pts.windows(2).map(|w| crate::jsmath::hypot2(w[1].x - w[0].x, w[1].y - w[0].y)).sum(); + if !closed && pts.len() == 2 { + return (format!("line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\"", xs(pts[0].x), ys(pts[0].y), xs(pts[1].x), ys(pts[1].y)), len); + } + if closed && pts.len() > 1 { + len += crate::jsmath::hypot2(pts[0].x - pts[pts.len() - 1].x, pts[0].y - pts[pts.len() - 1].y); + } + let pl = pts.iter().map(|q| format!("{},{}", xs(q.x), ys(q.y))).collect::>().join(" "); + (format!("{} points=\"{pl}\"", if closed { "polygon" } else { "polyline" }), len) +} + +/// [153]/[169] `stroke-dashoffset` eines gestrichelten Bogens der Modell-Länge `len_m` (Muster in Papier-mm). +fn arc_dash_offset(part: &Part, rec: &crate::plan::buf::Rec, len_m: f64, mm_to_m: f64) -> String { + if rec.flags & F_DASH_LIST == 0 || !(mm_to_m > 0.0) { + return String::new(); + } + let Some(d) = rec.dash.and_then(|(o, n)| part.view.pool(o, n)) else { return String::new() }; + let ph = super::line_pattern::phase(len_m / mm_to_m, &d); + if ph > 1e-9 { + format!(" stroke-dashoffset=\"{}\"", num(ph * mm_to_m)) + } else { + String::new() + } +} + /// Gestrichelter Zug aus aneinander anschliessenden Linien gleicher Darstellung ([153]). struct DashRun { /// Attribute ohne Geometrie (Farbe, Breite, Muster, Deckkraft). @@ -204,16 +238,13 @@ struct DashRun { /// Schreibt einen Zug als ``/`` mit der Musterphase ([`super::line_pattern::phase`]): /// beide Enden möglichst auf einem Strich, Phase über die Ecken. -fn flush_dash_run(run: Option, out: &mut [String], mm_to_m: f64, xs: &dyn Fn(f64) -> String, ys: &dyn Fn(f64) -> String) { +fn flush_dash_run(run: Option, out: &mut [String], mm_to_m: f64, xs: &dyn Fn(f64) -> String, ys: &dyn Fn(f64) -> String, top: f64) { let Some(r) = run else { return }; - let len: f64 = r.pts.windows(2).map(|w| crate::jsmath::hypot2(w[1].x - w[0].x, w[1].y - w[0].y)).sum(); + // [169] Bögen im Zug als `A`; Phase über die Länge mit Bögen. + let (g, len) = shape_el(&r.pts, false, xs, ys, top); let ph = if mm_to_m > 0.0 { super::line_pattern::phase(len / mm_to_m, &r.dash) } else { 0.0 }; let off = if ph > 1e-9 { format!(" stroke-dashoffset=\"{}\"", num(ph * mm_to_m)) } else { String::new() }; - out[r.slot] = if r.pts.len() == 2 { - format!("", xs(r.pts[0].x), ys(r.pts[0].y), xs(r.pts[1].x), ys(r.pts[1].y), r.key) - } else { - format!("", r.pts.iter().map(|q| format!("{},{}", xs(q.x), ys(q.y))).collect::>().join(" "), r.key) - }; + out[r.slot] = if g.starts_with("line ") { format!("<{g}{}{off}/>", r.key) } else { format!("<{g} fill=\"none\"{}{off}/>", r.key) }; } /// SVG-Text des Plans; `None` bei kaputtem Puffer. @@ -238,7 +269,7 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option { let f = rec.f.clone(); let fl = rec.flags; if rec.tag != T_LINE || fl & F_DASH_LIST == 0 { - flush_dash_run(run.take(), &mut out, mm_to_m, &xs, &ys); + flush_dash_run(run.take(), &mut out, mm_to_m, &xs, &ys, top); } let greyed = fl & F_GREYED != 0; let opacity = |k: usize| (fl & F_OPACITY != 0).then_some(f[k]); @@ -261,7 +292,10 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option { if pts.len() < 3 { continue; } - let pl = pts.iter().map(|q| format!("{},{}", xs(q.x), ys(q.y))).collect::>().join(" "); + // [169] Ganzer Kreis bzw. Ring mit Bögen als ``/``; Schraffur am fein + // nachtesselierten Ring beschnitten (endet am Bogen, nicht an der Sehne). + let (geo, _) = shape_el(&pts, true, &xs, &ys, top); + let hatch_pts = if geo.starts_with("polygon") { pts.clone() } else { arc_fit::refine(&pts, true, arc_fit::TOL, &arc_fit::fine_segments).unwrap_or_else(|| pts.clone()) }; let fill = esc(part.str(f[0]).unwrap_or("")); let stroke = esc(part.str(f[1]).unwrap_or("")); // Nicht gestrichene Kanten (Stossfugen, Lücken an Anschlüssen): Fläche ohne Strich, @@ -275,7 +309,7 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option { let seam_attr = || format!(" stroke=\"{fill}\" stroke-width=\"{}\"", num(SEAM_MM * mm_to_m)); if !nse.is_empty() && stroke != "none" && !stroke.is_empty() { let st = if seam { seam_attr() } else { " stroke=\"none\"".to_string() }; - out.push(format!("", op(greyed, opacity(4)))); + out.push(format!("<{geo} fill=\"{fill}\"{st}{}/>", op(greyed, opacity(4)))); // Sichtbare Kantenläufe zum Zusammennähen ([146]), Kanten in Ring-Reihenfolge. let nse_f: Vec = nse.iter().map(|&e| e as f64).collect(); let attrs = format!(" stroke=\"{stroke}\" stroke-width=\"{}\"{}", num(f[2] * mm_to_m), op(greyed, opacity(4))); @@ -284,10 +318,10 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option { stitch.add(attrs.clone(), run, out.len() - 1); } } else if seam && (stroke == "none" || stroke.is_empty() || !(f[2] > 0.0)) { - out.push(format!("", seam_attr(), op(greyed, opacity(4)))); + out.push(format!("<{geo} fill=\"{fill}\"{}{}/>", seam_attr(), op(greyed, opacity(4)))); } else { out.push(format!( - "", + "<{geo} fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"{}\"{}/>", num(f[2] * mm_to_m), op(greyed, opacity(4)) )); @@ -308,11 +342,11 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option { }; let mut runs: Vec> = Vec::new(); if h.random { - runs.extend(hatch::build_random_hatch_runs(&pts, &h, None).into_iter().filter(|r| r.len() >= 2).map(|r| vec![r[0], r[r.len() - 1]])); + runs.extend(hatch::build_random_hatch_runs(&hatch_pts, &h, None).into_iter().filter(|r| r.len() >= 2).map(|r| vec![r[0], r[r.len() - 1]])); } else { // [166] Alle Vektor-Schraffuren aus dem Kern-Generator wie Szene/PDF (Winkel-Lesart // der SVG-Kachel, polare Schraffur der Bogenwand). - runs.extend(hatch::build_hatch_runs(&pts, &h)); + runs.extend(hatch::build_hatch_runs(&hatch_pts, &h)); } for run in runs { match run.len() { @@ -343,13 +377,13 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option { if let Some(r) = run.as_mut().filter(|r| r.key == key && r.pts.last().is_some_and(|p| (p.x - a.x).abs() < 1e-9 && (p.y - a.y).abs() < 1e-9)) { r.pts.push(b); } else { - flush_dash_run(run.take(), &mut out, mm_to_m, &xs, &ys); + flush_dash_run(run.take(), &mut out, mm_to_m, &xs, &ys, top); out.push(String::new()); run = Some(DashRun { key, dash: pat, pts: vec![a, b], slot: out.len() - 1 }); } continue; } - flush_dash_run(run.take(), &mut out, mm_to_m, &xs, &ys); + flush_dash_run(run.take(), &mut out, mm_to_m, &xs, &ys, top); // [146] Volle Linien: mit Kantenläufen gleicher Farbe/Breite zusammennähen (Ecke statt // zweier Enden); Enden und Ecken erben die Projekt-Einstellung vom ``. if f[2] > 0.0 { @@ -375,7 +409,7 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option { while sweep < 0.0 && sweep.is_finite() { sweep += PI * 2.0; } - let dash = dash_attr(part)?; + let dash = dash_attr(part)? + &arc_dash_offset(part, &rec, r * sweep.abs(), mm_to_m); out.push(format!( "", xs(fx), @@ -413,7 +447,7 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option { sweep += PI * 2.0; } let stroke = esc(part.str(f[0]).unwrap_or("")); - let dash = dash_attr(part)?; + let dash = dash_attr(part)? + &arc_dash_offset(part, &rec, r * sweep.abs(), mm_to_m); out.push(format!( "", xs(sx), @@ -454,9 +488,9 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option { _ => {} } } - flush_dash_run(run.take(), &mut out, mm_to_m, &xs, &ys); + flush_dash_run(run.take(), &mut out, mm_to_m, &xs, &ys, top); } - stitch.finish(&mut out, &xs, &ys); + stitch.finish(&mut out, &xs, &ys, top); out.retain(|s| !s.is_empty()); Some(format!( "\n\n\n\n{}\n\n\n", @@ -625,4 +659,63 @@ mod tests { let svg = plan_svg(&mut parts, &opts(LineEnds { cap: 1, join: 2 })).unwrap(); assert!(svg.contains("`, Bogenwand-Band mit offenen Stirnkanten als Pfad mit `A`, + /// gestrichelter Bogen mit Musterphase. + #[test] + fn kreise_und_boegen_statt_vielecke() { + use crate::model::Vec2; + use crate::plan::buf::{View, Writer}; + use crate::plan::prim::Primitive; + let v = |x: f64, y: f64| Vec2 { x, y }; + let poly = |pts: Vec, nse: Option>| Primitive::Polygon { + pts, + fill: "#ffffff".into(), + stroke: "#000000".into(), + stroke_width_mm: 0.35, + hatch: crate::plan::style::no_hatch(), + greyed: None, + opacity: None, + no_stroke_edges: nse, + wall_id: None, + drawing_id: None, + ceiling_id: None, + opening_id: None, + stair_id: None, + room_id: None, + extruded_solid_id: None, + context_object_id: None, + column_id: None, + roof_id: None, + section_line_id: None, + }; + let col: Vec = (0..32).map(|i| { let t = PI * 2.0 * i as f64 / 32.0; v(1.0 + 0.15 * t.cos(), 1.0 + 0.15 * t.sin()) }).collect(); + let n = 12; + let mut band: Vec = (0..=n).map(|i| { let t = PI / 2.0 * i as f64 / n as f64; v(5.0 * t.cos(), 5.0 * t.sin()) }).collect(); + band.extend((0..=n).rev().map(|i| { let t = PI / 2.0 * i as f64 / n as f64; v(4.7 * t.cos(), 4.7 * t.sin()) })); + // Stirnkanten (Index n und 2n+1) nicht gestrichen. + let nse = vec![n as f64, (2 * n + 1) as f64]; + let mut w = Writer::new(false); + let g = w.begin_group(); + w.push(&poly(col, None)); + w.push(&poly(band, Some(nse))); + w.push(&Primitive::Arc { center: v(0.0, 0.0), from: v(2.0, 0.0), to: v(0.0, 2.0), r: 2.0, cls: "door-swing".into(), weight_mm: 0.18, dash: Some(Some(vec![2.0, 1.0])), color: None, opening_id: None, stair_id: None, greyed: None, opacity: None }); + w.end_group(g); + let bytes = w.finish(); + let view = View::parse(&bytes).unwrap(); + let len = view.len(); + let mut parts = vec![Part::new(view, 0, len).unwrap()]; + let o = SvgOptions { scale_denominator: 50.0, margin_m: 0.5, min_x: -1.0, min_y: -1.0, max_x: 6.0, max_y: 6.0, hatch: false, line_ends: LineEnds::default() }; + let svg = plan_svg(&mut parts, &o).unwrap(); + let circle = svg.lines().find(|l| l.starts_with(" = svg.lines().filter(|l| l.starts_with(" f64 { 0.0 } } + +/// [169] SVG-Pfad (`d`) eines Zugs in Papier-mm (`[x0, y0, x1, y1, …]`, Y nach unten) mit erkannten Bögen +/// (`crate::plan::arc_fit`): Kreis bzw. Strecken und `A`-Befehle; leer, wenn kein Bogen erkannt wurde oder +/// die Eingabe Unsinn ist (dann bleibt `polygon`/`polyline`). `tol` = Toleranz in mm. +#[wasm_bindgen] +pub fn plan_arc_path_d(pts_mm: &[f64], closed: bool, tol: f64) -> String { + use crate::hatch::V2; + use crate::plan::arc_fit; + if pts_mm.len() < 8 || pts_mm.len() % 2 != 0 || !(tol > 0.0) || !tol.is_finite() { + return String::new(); + } + let pts: Vec = pts_mm.chunks_exact(2).map(|c| V2 { x: c[0], y: c[1] }).collect(); + let fmt = |v: f64| crate::js_fmt::js_number(crate::jsnum::round(v * 1000.0) / 1000.0); + match arc_fit::fit(&pts, closed, tol) { + Some(sh) => arc_fit::svg_d_with(&sh, &|p| p, 1.0, &fmt, true), + None => String::new(), + } +} diff --git a/src-tauri/fileio/src/export.rs b/src-tauri/fileio/src/export.rs index b3818aa1..6a16ad63 100644 --- a/src-tauri/fileio/src/export.rs +++ b/src-tauri/fileio/src/export.rs @@ -108,6 +108,9 @@ pub const REC_SHEET_INSERT: f64 = 22.0; /// [146] Linienenden/-ecken des Projekts: `[cap | join << 2]` (Kern `plan/line_ends.rs`) → /// Kopfvariablen `$ENDCAPS`/`$JOINSTYLE` (DXF und DWG). pub const REC_LINE_ENDS: f64 = 23.0; +/// [169] LWPOLYLINE mit Bögen: `[Ebene, geschlossen, n, n × (x, y, bulge)]` (Bulge = tan(Winkel/4), positiv +/// gegen den Uhrzeiger; Kern `plan/arc_fit.rs`). +pub const REC_POLYLINE_BULGE: f64 = 24.0; /// DXF-Ausgabeversion (s. Kopf). pub const DXF_VERSION: DxfVersion = DxfVersion::AC1032; @@ -630,6 +633,18 @@ pub fn build_document(flat: &[f64], strings: &str) -> Result= 2 && all_finite(v)).then(|| { + let mut pl = LwPolyline::from_points(v.chunks_exact(3).map(|p| Vector2::new(p[0], p[1])).collect()); + for (vx, p) in pl.vertices.iter_mut().zip(v.chunks_exact(3)) { + vx.bulge = p[2]; + } + pl.is_closed = closed; + EntityType::LwPolyline(pl) + }) } else if tag == REC_ARC { let v = r.take(5)?; (all_finite(v) && v[2] > 0.0) @@ -1078,6 +1093,19 @@ mod tests { assert_eq!(line_end_vars(4.0 + 2.0), (3, 1)); } + /// [169] LWPOLYLINE mit Bulges (Bogenwand-Umriss): Bulges bleiben beim Schreiben und Lesen erhalten. + #[test] + fn polylinie_mit_bulges() { + let b = (std::f64::consts::PI / 8.0).tan(); + let flat = vec![FLAT_VERSION, REC_LAYER, 0.0, -1.0, 25.0, REC_POLYLINE_BULGE, 0.0, 1.0, 4.0, 5.0, 0.0, b, 0.0, 5.0, 0.0, 0.0, 4.7, -b, 4.7, 0.0, 0.0]; + let doc = read_dxf(export_dxf(&flat, "a").unwrap()); + let pl = doc.entities().find_map(|e| if let EntityType::LwPolyline(p) = e { Some(p.clone()) } else { None }).unwrap(); + assert!(pl.is_closed); + let bs: Vec = pl.vertices.iter().map(|v| v.bulge).collect(); + assert!((bs[0] - b).abs() < 1e-9 && bs[1] == 0.0 && (bs[2] + b).abs() < 1e-9 && bs[3] == 0.0, "{bs:?}"); + assert!(export_dxf(&[FLAT_VERSION, REC_LAYER, 0.0, -1.0, 25.0, REC_POLYLINE_BULGE, 0.0, 0.0, 2.0, 0.0, 0.0], "a").is_err()); + } + #[test] fn layer_names_sanitized_and_deduplicated() { assert_eq!(sanitize_layer_name(" 10 Wand: tragend/aussen "), "10_Wand__tragend_aussen"); diff --git a/src-tauri/render2d/src/shaders.rs b/src-tauri/render2d/src/shaders.rs index 8ba0b7d5..b314d708 100644 --- a/src-tauri/render2d/src/shaders.rs +++ b/src-tauri/render2d/src/shaders.rs @@ -145,6 +145,53 @@ const PI : f32 = 3.14159265358979; // Instanz-Geometrie bereits in Bildschirm-Raum vorliegt (to_screen skaliert *90). const PX_PER_M_2D : f32 = 90.0; +// [153]/[169] Sichtbares Strichstueck an einem Bogenende (Spiegel `tessellate::dash_stub`, Muster bis 4). +fn arc_dash_stub(p : f32, len : f32, total : f32, n : i32, c : vec4, at_end : bool) -> f32 { + var cyc = array(c.x, c.y, c.z, c.w); + var m = p - floor(p / total) * total; + if (at_end && m <= 0.0) { m = total; } + var acc = 0.0; + var r = 0.0; + for (var i = 0; i < 4; i = i + 1) { + if (i >= n) { break; } + let d = cyc[i]; + var hit = m >= acc && m < acc + d; + var v = acc + d - m; + if (at_end) { + hit = m > acc && m <= acc + d; + v = m - acc; + } + if (hit) { + if ((i % 2) == 0) { r = min(v, len); } else { r = -v; } + } + acc = acc + d; + } + return r; +} + +// [153]/[169] Musterphase am Bogenanfang: beide Enden moeglichst auf einem Strich (Spiegel +// `tessellate::dash_phase`, wie die gestrichelten Linienzuege `DASH_LINE_WGSL`). +fn arc_dash_phase(len : f32, total : f32, n : i32, c : vec4) -> f32 { + if (!(len > 0.0) || !(total > 1e-6) || n < 2) { return 0.0; } + var cyc = array(c.x, c.y, c.z, c.w); + var best_p = 0.0; + var best = min(arc_dash_stub(0.0, len, total, n, c, false), arc_dash_stub(len, len, total, n, c, true)); + var acc = 0.0; + for (var i = 0; i < 4; i = i + 1) { + if (i >= n) { break; } + let d = cyc[i]; + let q = acc + 0.5 * d - 0.5 * len; + let p = q - floor(q / total) * total; + let s = min(arc_dash_stub(p, len, total, n, c, false), arc_dash_stub(p + len, len, total, n, c, true)); + if (s > best + 1e-4 * total) { + best = s; + best_p = p; + } + acc = acc + d; + } + return best_p; +} + struct VsOut { @builtin(position) pos : vec4, @location(0) frag : vec2, @@ -247,7 +294,9 @@ fn fs_main(in : VsOut) -> @location(0) vec4 { progress = max(progress, 0.0); // Muster mit dem Massstab mitskalieren ([96]): statt das Muster zu strecken, die Lauflaenge stauchen. let ds = select(1.0, g.dash_scale, g.dash_scale > 0.0); - let s_model = progress * r_m / ds; + // [153]/[169] Musterphase des ganzen Bogens (Striche an beiden Enden), wie die Linienzuege. + let ph = arc_dash_phase(abs(sweep) * r_m / ds, dash_total, dash_count, in.dash); + let s_model = progress * r_m / ds + ph; let m = s_model - dash_total * floor(s_model / dash_total); var cyc = array(in.dash.x, in.dash.y, in.dash.z, in.dash.w); diff --git a/src/core/index.ts b/src/core/index.ts index ec66f67f..1740d495 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -13,10 +13,6 @@ export { pointOnCircle, } from "../geometry/bulge"; -export { - columnFootprint, -} from "../geometry/column"; - export { sampleBezierChain, sampleCatmullRom, diff --git a/src/export/sceneToPrintSvg.dash.test.ts b/src/export/sceneToPrintSvg.dash.test.ts index 5f478747..6947909b 100644 --- a/src/export/sceneToPrintSvg.dash.test.ts +++ b/src/export/sceneToPrintSvg.dash.test.ts @@ -57,3 +57,31 @@ describe("Druck-SVG: Strichmuster", () => { expect(seen.every((s) => s[1] === seen[0][1])).toBe(true); }); }); + +// [169] Runde Stütze (in der Szene fein nachtesselliert) als Pfad mit Bögen statt Vieleck; gestrichelter +// Bogen (Türschwenk) mit Musterphase. +describe("Druck-SVG: Kreise und Bögen", () => { + it("Kreis-Fläche und -Umriss als mit A, Bogen mit stroke-dashoffset", () => { + const ring: [number, number][] = Array.from({ length: 180 }, (_, i) => { + const t = (2 * Math.PI * i) / 180; + return [1 + 0.15 * Math.cos(t), 1 + 0.15 * Math.sin(t)]; + }); + const sc = { + fills: [{ pts: ring, color: [0, 0, 0, 1], z: 0 }], + outlines: [{ pts: ring, color: [0, 0, 0, 1], widthMm: 0.35, dash: null, z: 1 }], + polylines: [], + arcs: [{ center: [0, 0], from: [2, 0], to: [0, 2], r: 2, color: [0, 0, 0, 1], widthMm: 0.18, dash: [2, 1] }], + lines: [], + texts: [], + images: [], + bounds: { minX: -1, minY: -1, maxX: 3, maxY: 3 }, + } as unknown as RScene; + const svg = sceneToPrintSvg(sc, { scaleDenominator: 50, pageWidthMm: 100, pageHeightMm: 100 }).svg as unknown as FakeEl; + const paths = svg.children.filter((c) => c.tag === "path"); + expect(svg.children.some((c) => c.tag === "polygon")).toBe(false); + // Fläche und Umriss (je zwei Halbkreise r = 3 mm bei 1:50) und der Bogen. + expect(paths.filter((p) => (p.attrs.get("d") ?? "").includes(" A 3 3 ")).length).toBe(2); + const arc = paths.find((p) => p.attrs.has("stroke-dasharray"))!; + expect(arc.attrs.get("stroke-dashoffset")).toBeDefined(); + }); +}); diff --git a/src/export/sceneToPrintSvg.ts b/src/export/sceneToPrintSvg.ts index e4b93117..ce72ae8c 100644 --- a/src/export/sceneToPrintSvg.ts +++ b/src/export/sceneToPrintSvg.ts @@ -228,11 +228,35 @@ function ptsAttrOf(pts: RPoint[], map: Mapper): string { return pts.map((p) => map(p)).map(([x, y]) => `${round(x)},${round(y)}`).join(" "); } +/** + * [169] Zug mit Boegen (runde Stuetze, Bogenwand; in der Szene fein nachtesselliert) als `` mit + * `A`-Befehlen statt Vieleck: Kern `plan_arc_path_d` (Bogenerkennung `plan/arc_fit.rs`) auf den + * Papier-mm-Punkten. Ohne erkannten Bogen `null` (dann `polygon`/`polyline`). + */ +function arcPathEl(pts: RPoint[], closed: boolean, map: Mapper): SVGElement | null { + if (pts.length < 4) return null; + const flat = new Float64Array(pts.length * 2); + pts.forEach((p, i) => { + const [x, y] = map(p); + flat[2 * i] = x; + flat[2 * i + 1] = y; + }); + const d = core().plan_arc_path_d(flat, closed, ARC_TOL_MM); + if (!d) return null; + const el = document.createElementNS(SVG_NS, "path"); + el.setAttribute("d", d); + return el; +} + +/** Toleranz der Bogenerkennung auf dem Blatt (mm). */ +const ARC_TOL_MM = 1e-4; + /** Gefuelltes Polygon (Wand-Poche, Raeume, Decken, Grundfuellung vor Schraffur). */ function appendFill(svg: SVGSVGElement, f: RFill, map: Mapper): void { if (f.pts.length < 3) return; - const el = document.createElementNS(SVG_NS, "polygon"); - el.setAttribute("points", ptsAttrOf(f.pts, map)); + const arc = arcPathEl(f.pts, true, map); + const el = arc ?? document.createElementNS(SVG_NS, "polygon"); + if (!arc) el.setAttribute("points", ptsAttrOf(f.pts, map)); el.setAttribute("fill", rgbCss(f.color)); setOpacityAttr(el, "fill-opacity", f.color[3]); el.setAttribute("stroke", "none"); @@ -267,8 +291,9 @@ function appendStroke( const effectiveMm = widthScreen ? widthMm * HATCH_DENSITY_MM : widthMm; const strokeMm = quantizePen(effectiveMm); - const el = document.createElementNS(SVG_NS, closed ? "polygon" : "polyline"); - el.setAttribute("points", ptsAttrOf(pts, map)); + const arc = widthScreen ? null : arcPathEl(pts, closed, map); + const el = arc ?? document.createElementNS(SVG_NS, closed ? "polygon" : "polyline"); + if (!arc) el.setAttribute("points", ptsAttrOf(pts, map)); el.setAttribute("fill", "none"); el.setAttribute("stroke", rgbCss(color)); setOpacityAttr(el, "stroke-opacity", color[3]); @@ -343,6 +368,11 @@ function appendArc(svg: SVGSVGElement, a: RArc, map: Mapper, mmPerM: number): vo el.setAttribute("stroke-width", String(quantizePen(a.widthMm))); if (a.dash && a.dash.length) { el.setAttribute("stroke-dasharray", a.dash.map((x) => round(x)).join(" ")); + // [153]/[169] Musterphase auch auf Boegen (kuerzerer Bogen, wie gezeichnet). + let sw = Math.abs(Math.atan2(v2.y, v2.x) - Math.atan2(v1.y, v1.x)); + if (sw > Math.PI) sw = 2 * Math.PI - sw; + const ph = core().line_dash_phase(r * sw, Float64Array.from(a.dash)); + if (ph > 1e-9) el.setAttribute("stroke-dashoffset", String(round(ph))); } svg.appendChild(el); } diff --git a/src/geometry/column.ts b/src/geometry/column.ts deleted file mode 100644 index c73c19d4..00000000 --- a/src/geometry/column.ts +++ /dev/null @@ -1,46 +0,0 @@ -// Stützen-Geometrie: leitet aus einer Stütze (Column) ihren Grundriss-Querschnitt -// (Poché-/Footprint-Polygon) ab. Reine Funktion, keine Modell-Mutation — sowohl -// der 2D-Grundriss (generatePlan) als auch die 3D-Extrusion (toWalls3d) und die -// Auswahl-/Transform-Vorschau (transform.ts) nutzen dieselbe Kontur. -// -// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). - -import type { Column, Vec2 } from "../model/types"; - -/** Tessellierungs-Segmentzahl eines runden Stützenprofils (Grundriss + 3D-Prisma). */ -export const COLUMN_ROUND_SEGMENTS = 32; - -/** - * Grundriss-Querschnitt einer Stütze als geschlossenes Polygon (Modell-Meter, - * CCW), um `position` platziert und (bei Rechteck) um `rotation` gedreht. Ein - * rundes Profil wird als regelmäßiges {@link COLUMN_ROUND_SEGMENTS}-Eck - * tesselliert; der Schlusspunkt wird NICHT dupliziert. - */ -export function columnFootprint(col: Column): Vec2[] { - const { x: cx, y: cy } = col.position; - if (col.profile.kind === "round") { - const r = col.profile.radius; - const pts: Vec2[] = []; - for (let i = 0; i < COLUMN_ROUND_SEGMENTS; i++) { - const t = (i / COLUMN_ROUND_SEGMENTS) * Math.PI * 2; - pts.push({ x: cx + r * Math.cos(t), y: cy + r * Math.sin(t) }); - } - return pts; - } - // Rechteck: lokale Ecken ±w/2 (X) × ±d/2 (Y), um `rotation` gedreht. - const hw = col.profile.width / 2; - const hd = col.profile.depth / 2; - const rot = col.rotation ?? 0; - const cos = Math.cos(rot); - const sin = Math.sin(rot); - const local: Vec2[] = [ - { x: -hw, y: -hd }, - { x: +hw, y: -hd }, - { x: +hw, y: +hd }, - { x: -hw, y: +hd }, - ]; - return local.map((p) => ({ - x: cx + p.x * cos - p.y * sin, - y: cy + p.x * sin + p.y * cos, - })); -} diff --git a/src/plan/__golden__/komplex-ansicht-ansicht-sued.txt b/src/plan/__golden__/komplex-ansicht-ansicht-sued.txt index 65c5fe2c..8c4cac37 100644 --- a/src/plan/__golden__/komplex-ansicht-ansicht-sued.txt +++ b/src/plan/__golden__/komplex-ansicht-ansicht-sued.txt @@ -1,11 +1,11 @@ viewBox -4.2 0 37.045 17.378 -bytes 192404 +bytes 193364 circle 4 g 1 line 556 -polygon 1018 +polygon 1026 polyline 44 rect 1 svg 1 text 4 -hash ee49aae5cc3ed4a4 +hash 32b9045a8708e6ad diff --git a/src/plan/__golden__/komplex-grundriss-eg-100.txt b/src/plan/__golden__/komplex-grundriss-eg-100.txt index 6ceed982..c52679cf 100644 --- a/src/plan/__golden__/komplex-grundriss-eg-100.txt +++ b/src/plan/__golden__/komplex-grundriss-eg-100.txt @@ -1,13 +1,13 @@ viewBox -41.5 0 95 63.6 -bytes 79943 +bytes 69342 circle 16 g 1 line 172 -path 18 -polygon 90 -polyline 124 +path 30 +polygon 81 +polyline 121 rect 1 svg 1 text 116 tspan 24 -hash 9dadf0534a699dd9 +hash b09770784bf89a35 diff --git a/src/plan/__golden__/komplex-grundriss-eg-50.txt b/src/plan/__golden__/komplex-grundriss-eg-50.txt index ee3a01f4..6522a4ec 100644 --- a/src/plan/__golden__/komplex-grundriss-eg-50.txt +++ b/src/plan/__golden__/komplex-grundriss-eg-50.txt @@ -1,13 +1,13 @@ viewBox -41.5 0 95 63.6 -bytes 131023 +bytes 117357 circle 16 g 1 line 419 -path 39 -polygon 252 -polyline 145 +path 59 +polygon 236 +polyline 141 rect 1 svg 1 text 121 tspan 32 -hash ff2665a76f5bbb8d +hash d3d02bf2fbc8b704 diff --git a/src/plan/__golden__/komplex-grundriss-og-100.txt b/src/plan/__golden__/komplex-grundriss-og-100.txt index 15d40c3b..9bd7c263 100644 --- a/src/plan/__golden__/komplex-grundriss-og-100.txt +++ b/src/plan/__golden__/komplex-grundriss-og-100.txt @@ -1,12 +1,13 @@ viewBox -12.8 0 37.6 33.6 -bytes 51729 +bytes 48623 circle 14 g 1 line 142 -polygon 52 -polyline 111 +path 8 +polygon 45 +polyline 110 rect 1 svg 1 text 88 tspan 19 -hash 17f9cbe73785a7bd +hash 6dd15cc4f269c858 diff --git a/src/plan/__golden__/komplex-grundriss-og-50.txt b/src/plan/__golden__/komplex-grundriss-og-50.txt index 2b7eaf46..de9befcf 100644 --- a/src/plan/__golden__/komplex-grundriss-og-50.txt +++ b/src/plan/__golden__/komplex-grundriss-og-50.txt @@ -1,13 +1,13 @@ viewBox -12.65 0 37.3 33.3 -bytes 370588 +bytes 365622 circle 14 g 1 line 3238 -path 21 -polygon 213 -polyline 180 +path 36 +polygon 199 +polyline 179 rect 1 svg 1 text 91 tspan 24 -hash d968a9e0e5adcdd3 +hash a53d7dc3ed58eded diff --git a/src/plan/__golden__/komplex-grundriss-ug-100.txt b/src/plan/__golden__/komplex-grundriss-ug-100.txt index 1bb558d7..7f0fe25c 100644 --- a/src/plan/__golden__/komplex-grundriss-ug-100.txt +++ b/src/plan/__golden__/komplex-grundriss-ug-100.txt @@ -1,13 +1,13 @@ viewBox -12.8 0 37.6 33.6 -bytes 52830 -circle 14 +bytes 42610 +circle 15 g 1 line 121 -path 4 -polygon 44 -polyline 83 +path 14 +polygon 37 +polyline 79 rect 1 svg 1 text 73 tspan 18 -hash d87f0eaf1cd610d4 +hash 9e69d187939143f2 diff --git a/src/plan/__golden__/komplex-grundriss-ug-50.txt b/src/plan/__golden__/komplex-grundriss-ug-50.txt index a3c93297..4bd38391 100644 --- a/src/plan/__golden__/komplex-grundriss-ug-50.txt +++ b/src/plan/__golden__/komplex-grundriss-ug-50.txt @@ -1,13 +1,13 @@ viewBox -12.65 0 37.3 33.3 -bytes 62538 -circle 14 +bytes 50135 +circle 15 g 1 line 117 -path 15 -polygon 89 -polyline 92 +path 29 +polygon 80 +polyline 86 rect 1 svg 1 text 75 tspan 20 -hash 0a0d09cb775a502b +hash 4dbe226dec66455c diff --git a/src/plan/__golden__/komplex-model3d.txt b/src/plan/__golden__/komplex-model3d.txt index f11df97d..ce3426de 100644 --- a/src/plan/__golden__/komplex-model3d.txt +++ b/src/plan/__golden__/komplex-model3d.txt @@ -8,8 +8,8 @@ meshes[].indices [180] meshes[].indices [192] x3 meshes[].indices [348] x6 meshes[].indices [36] x1858 -meshes[].indices [372] meshes[].indices [396] +meshes[].indices [564] meshes[].indices [60] x9 meshes[].indices [72] meshes[].indices [84] x2 @@ -19,12 +19,11 @@ meshes[].positions [1044] x6 meshes[].positions [108] x30 meshes[].positions [120] meshes[].positions [180] x9 -meshes[].positions [192] meshes[].positions [216] meshes[].positions [24] x1826 meshes[].positions [252] x2 meshes[].positions [264] -meshes[].positions [288] x6 +meshes[].positions [288] x7 meshes[].positions [306] x3 meshes[].positions [324] x6 meshes[].positions [4746] @@ -61,4 +60,4 @@ walls[].start [2] x1489 walls[].startCut [4] x1164 walls[].topDrop [2] x103 walls[].topPlane [3] x259 -hash 0401db08722c5c30 +hash f77d51f089e28986 diff --git a/src/plan/__golden__/komplex-schnitt-schnitt-a.txt b/src/plan/__golden__/komplex-schnitt-schnitt-a.txt index 8ccd20ed..a8971967 100644 --- a/src/plan/__golden__/komplex-schnitt-schnitt-a.txt +++ b/src/plan/__golden__/komplex-schnitt-schnitt-a.txt @@ -1,11 +1,11 @@ viewBox 4.457 0 21.343 17.378 -bytes 34158 -circle 3 +bytes 33583 +circle 4 g 1 line 33 -polygon 186 +polygon 185 polyline 16 rect 1 svg 1 text 3 -hash ab512b19fa3bae7c +hash ef5a378a0ea326c1 diff --git a/src/plan/column.test.ts b/src/plan/column.test.ts index f0679981..0954a78f 100644 --- a/src/plan/column.test.ts +++ b/src/plan/column.test.ts @@ -11,7 +11,6 @@ import { describe, it, expect } from "vitest"; import { generatePlan } from "./generatePlan"; import { projectToModel3d } from "./toWalls3d"; -import { columnFootprint } from "../geometry/column"; import type { Column, Project } from "../model/types"; /** Minimalprojekt (zwei Geschosse gestapelt) mit einer konfigurierbaren Stütze. */ @@ -111,7 +110,7 @@ describe("Stütze — 3D (projectToModel3d / emitColumns)", () => { expect(Math.max(...zs)).toBeCloseTo(3, 6); }); - it("erzeugt ein tesselliertes Kreis-Prisma (64 Ecken)", () => { + it("erzeugt ein tesselliertes Kreis-Prisma (96 Ecken)", () => { const round: Column = { ...rectColumn, profile: { kind: "round", radius: 0.15 }, @@ -119,20 +118,8 @@ describe("Stütze — 3D (projectToModel3d / emitColumns)", () => { const model = projectToModel3d(projectWithColumn(round)); const mesh = model.meshes.find((m) => m.kind === "extrusion"); if (!mesh) throw new Error("kein Prisma-Mesh"); - // 32-Eck × (unten + oben) = 64 Vertices. - expect(mesh.positions.length).toBe(64 * 3); - }); -}); - -describe("Stütze — Footprint-Helfer (columnFootprint)", () => { - it("tesselliert ein rundes Profil als 32-Eck um die Position", () => { - const round: Column = { ...rectColumn, profile: { kind: "round", radius: 0.15 } }; - const pts = columnFootprint(round); - expect(pts.length).toBe(32); - // Alle Punkte liegen im Radius 0.15 um (2,3). - for (const p of pts) { - const d = Math.hypot(p.x - 2, p.y - 3); - expect(d).toBeCloseTo(0.15, 6); - } + // [169] 48-Eck (Pfeilhöhe ≤ 0.5 mm, Kern `column_round_segments`) × (unten + oben) = 96 Vertices, glatt. + expect(mesh.positions.length).toBe(96 * 3); + expect(mesh.creaseAngle).toBe(30); }); });