diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 1f1263cd..86366c92 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -64,6 +64,7 @@ pub mod plan_pick; pub mod snap; pub mod plan_svg; pub mod plan_dxf; +pub mod plan_print_svg; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/plan_print_svg.rs b/src-tauri/core/src/plan_print_svg.rs new file mode 100644 index 00000000..d7384bcf --- /dev/null +++ b/src-tauri/core/src/plan_print_svg.rs @@ -0,0 +1,500 @@ +//! Druck-SVG eines Plans für Layout-Viewports und den PDF-Altpfad ([K3d], früher der Primitiv-Teil +//! von `src/export/planToPrintSvg.ts`): liest den zusammengesetzten Plan ([`crate::plan_parts`]) und +//! liefert die SVG-Knoten in Papier-Millimetern als flache Anweisungsliste, die TS 1:1 als DOM-Knoten +//! anlegt (gleiche Elemente, Attribute und Reihenfolge wie die TS-Fassung — die Zahlen formatiert wie +//! `String(Math.round(v * 1000) / 1000)`). Schraffuren als geklippte Vektorlinien, Zickzack/Motiv als +//! Polylinie, Bögen als ``. +//! +//! In TS bleiben: der ``-Rahmen und das weisse Blatt, die Bild-Schraffur-`` (laufende +//! Ids im Dokument) und die Einzeltexte (Text-Layout `wrapDocToLines`). Dafür stehen Anweisungen in +//! der Liste. +//! +//! Format: Datensätze getrennt durch `\x1e`, Felder durch `\x1f`: +//! - `E`, Ebene (0 = ins ``, 1 = in die offene Gruppe), Tag, dann Name/Wert-Paare; +//! - `G`, Deckkraft (leer = keine) — öffnet eine ``; `g` schliesst sie (hängt sie ans ``); +//! - `I`, Punkte-Attribut, Bild-JSON — Bild-Schraffur: `` anlegen und ein Polygon damit füllen; +//! - `T`, Plan-Index, Deckkraft — Einzeltext an dieser Stelle. + +use crate::hatch::{self, Hatch, Motif, Pattern, V2}; +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}; +use crate::plan_parts::{greyed_of, Part}; +use std::f64::consts::PI; + +/// Optionen: Massstab-Nenner, Blatt (mm) und Ausmass des Plans (`Plan.bounds`). +pub struct PrintOptions { + pub scale_denominator: f64, + pub page_w: f64, + pub page_h: f64, + pub bounds: [f64; 4], +} + +/// Standard-Stift-Stufen (mm). +const PEN_STEPS: [f64; 7] = [0.13, 0.18, 0.25, 0.35, 0.5, 0.7, 1.0]; +const MIN_PEN_MM: f64 = 0.13; + +/// Mm-Strichstärke auf die nächste Stift-Stufe (`quantizePen`). +fn quantize_pen(mm: f64) -> f64 { + let w = jsnum::max(MIN_PEN_MM, mm); + for s in PEN_STEPS { + if w <= s + 1e-6 { + return s; + } + } + PEN_STEPS[PEN_STEPS.len() - 1] +} + +/// `String(Math.round(v * 1000) / 1000)`. +fn r3(v: f64) -> String { + js_number(jsnum::round(v * 1000.0) / 1000.0) +} + +/// Strichmuster als Attribut (`dash.map(round).join(" ")`). +fn dash_attr(d: &[f64]) -> String { + d.iter().map(|v| r3(*v)).collect::>().join(" ") +} + +/// Anweisungsliste. +struct Out { + s: String, + first: bool, +} + +impl Out { + fn rec(&mut self, fields: &[&str]) { + if !self.first { + self.s.push('\u{1e}'); + } + self.first = false; + self.s.push_str(&fields.join("\u{1f}")); + } + + fn el(&mut self, depth: u8, tag: &str, attrs: &[(&str, String)]) { + let d = depth.to_string(); + let mut f: Vec<&str> = vec!["E", &d, tag]; + for (k, v) in attrs { + f.push(k); + f.push(v); + } + self.rec(&f); + } +} + +/// Papier-Abbildung (Welt-Meter → mm, Y gespiegelt, zentriert). +#[derive(Clone, Copy)] +struct Map { + off_x: f64, + off_y: f64, + min_x: f64, + max_y: f64, + k: f64, +} + +impl Map { + fn at(&self, x: f64, y: f64) -> V2 { + V2 { x: self.off_x + (x - self.min_x) * self.k, y: self.off_y + (self.max_y - y) * self.k } + } +} + +fn pts_attr(p: &[V2]) -> String { + p.iter().map(|q| format!("{},{}", r3(q.x), r3(q.y))).collect::>().join(" ") +} + +fn poly_node(pts: &str, fill: &str, stroke: &str, stroke_mm: f64) -> Vec<(&'static str, String)> { + let mut a = vec![("points", pts.to_string()), ("fill", fill.to_string())]; + if stroke != "none" && stroke_mm > 0.0 { + a.push(("stroke", stroke.to_string())); + a.push(("stroke-width", js_number(stroke_mm))); + a.push(("stroke-linejoin", "round".to_string())); + } else { + a.push(("stroke", "none".to_string())); + } + a +} + +fn line_attrs(a: V2, b: V2, color: &str, stroke_mm: f64, dash: Option<&[f64]>) -> Vec<(&'static str, String)> { + let mut v = vec![ + ("x1", r3(a.x)), + ("y1", r3(a.y)), + ("x2", r3(b.x)), + ("y2", r3(b.y)), + ("stroke", color.to_string()), + ("stroke-width", js_number(stroke_mm)), + ("stroke-linecap", "round".to_string()), + ]; + if let Some(d) = dash.filter(|d| !d.is_empty()) { + v.push(("stroke-dasharray", dash_attr(d))); + } + v +} + +fn polyline_attrs(pts: &[V2], color: &str, stroke_mm: f64, dash: Option<&[f64]>) -> Vec<(&'static str, String)> { + let mut v = vec![ + ("points", pts_attr(pts)), + ("fill", "none".to_string()), + ("stroke", color.to_string()), + ("stroke-width", js_number(stroke_mm)), + ("stroke-linecap", "round".to_string()), + ("stroke-linejoin", "round".to_string()), + ]; + if let Some(d) = dash.filter(|d| !d.is_empty()) { + v.push(("stroke-dasharray", dash_attr(d))); + } + v +} + +/// Strichmuster + runde Kappe bei Punkten (Bögen, Kreise). +fn push_dash(v: &mut Vec<(&'static str, String)>, dash: Option<&[f64]>) { + if let Some(d) = dash.filter(|d| !d.is_empty()) { + v.push(("stroke-dasharray", dash_attr(d))); + if d.iter().any(|x| *x == 0.0) { + v.push(("stroke-linecap", "round".to_string())); + } + } +} + +/// Parallele Linien im Winkel/Abstand, aufs Polygon geklippt (`fillParallel`). +fn fill_parallel(poly: &[V2], angle: f64, spacing: f64, out: &mut Vec<(V2, V2)>) { + if poly.len() < 3 || spacing <= 0.0 { + return; + } + let dir = V2 { x: jsnum::cos(angle), y: jsnum::sin(angle) }; + let nrm = V2 { x: -dir.y, y: dir.x }; + let mut t_min = f64::INFINITY; + let mut t_max = f64::NEG_INFINITY; + for p in poly { + let t = p.x * nrm.x + p.y * nrm.y; + if t < t_min { + t_min = t; + } + if t > t_max { + t_max = t; + } + } + let mut t = (t_min / spacing).ceil() * spacing; + while t <= t_max { + let mut xs: Vec = Vec::new(); + let n = poly.len(); + let mut j = n - 1; + for i in 0..n { + let a = poly[j]; + let b = poly[i]; + j = i; + let ta = a.x * nrm.x + a.y * nrm.y; + let tb = b.x * nrm.x + b.y * nrm.y; + if ta == tb { + continue; + } + let f = (t - ta) / (tb - ta); + if f < 0.0 || f > 1.0 { + continue; + } + let px = a.x + (b.x - a.x) * f; + let py = a.y + (b.y - a.y) * f; + xs.push(px * dir.x + py * dir.y); + } + if xs.len() >= 2 { + // `xs.sort((u, v) => u - v)`: stabil; NaN zählt als gleich. + xs.sort_by(|u, v| (u - v).partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal)); + let mut k = 0; + while k + 1 < xs.len() { + let (u0, u1) = (xs[k], xs[k + 1]); + k += 2; + if u1 - u0 < 1e-6 { + continue; + } + out.push((V2 { x: nrm.x * t + dir.x * u0, y: nrm.y * t + dir.y * u0 }, V2 { x: nrm.x * t + dir.x * u1, y: nrm.y * t + dir.y * u1 })); + } + } + t += spacing; + } +} + +/// Schraffurlinien in Papier-mm (`hatchLines`). +fn hatch_lines(poly_mm: &[V2], h: &Hatch, mm_per_m: f64) -> Vec<(V2, V2)> { + let unit_mm = (1.0 / 90.0) * mm_per_m; + let tile_mm = (if h.pattern == Pattern::Insulation { 10.0 } else { 8.0 }) * h.scale * unit_mm; + let spacing = jsnum::max(0.5, tile_mm); + let angle = (h.angle * PI) / 180.0; + let mut segs = Vec::new(); + fill_parallel(poly_mm, angle, spacing, &mut segs); + if h.pattern == Pattern::Crosshatch { + fill_parallel(poly_mm, angle + PI / 2.0, spacing, &mut segs); + } + if h.pattern == Pattern::Insulation { + fill_parallel(poly_mm, angle - PI / 4.0, spacing, &mut segs); + } + segs +} + +fn num(o: &serde_json::Value, k: &str) -> f64 { + o.get(k).and_then(|x| x.as_f64()).unwrap_or(f64::NAN) +} + +/// Deckkraft-Attribut (`dim · max(0, objOpacity)`, nur unter 1). +fn opacity_of(greyed: bool, obj: f64) -> String { + let combined = (if greyed { 0.3 } else { 1.0 }) * jsnum::max(0.0, obj); + if combined < 1.0 { + js_number(combined) + } else { + String::new() + } +} + +/// Ein Eintrag als Knoten. +fn entry(out: &mut Out, view: &View, i: usize, gi: usize, hatches: &[(i32, Hatch, i32)], m: Map) -> Option<()> { + let rec: Rec = view.rec(i)?; + let f = &rec.f; + let k = m.k; + let s = |idx: f64| -> Option { + if idx == -1.0 { + Some("undefined".to_string()) + } else { + view.string(whole(idx)?) + } + }; + let dash = |rec: &Rec| -> Option>> { + if rec.flags & F_DASH_NULL != 0 { + return Some(None); + } + match rec.dash { + Some((o, n)) => Some(Some(view.pool(o, n)?)), + None => Some(None), + } + }; + let greyed = greyed_of(&rec, false) == Some(true); + let obj = |at: usize| if rec.flags & F_OPACITY != 0 { f[at] } else { 1.0 }; + match rec.tag { + T_POLYGON => { + let pts: Vec = view.pool(whole(f[5])?, whole(f[6])?.checked_mul(2)?)?.chunks_exact(2).map(|c| V2 { x: c[0], y: c[1] }).collect(); + 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); + let sw = f[2]; + let stroke_mm = if sw > 0.0 { quantize_pen(sw) } else { 0.0 }; + let fill = s(f[0])?; + let stroke = s(f[1])?; + out.rec(&["G", &opacity]); + // Ohne Schraffur-Eintrag wie „none“. + let (json, h, color) = if f[3] >= 0.0 { hatches.get(whole(f[3])?)?.clone() } else { (-1, empty_hatch(), -1) }; + let image: Option = if h.kind == hatch::HatchKind::Image && json >= 0 { + let j: serde_json::Value = serde_json::from_str(&view.string(json as usize)?).ok()?; + j.get("image").filter(|v| v.is_object()).map(|v| v.to_string()) + } else { + None + }; + 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.rec(&["I", &attr, &img]); + if stroke_mm > 0.0 { + out.el(1, "polygon", &poly_node(&attr, "none", &stroke, stroke_mm)); + } + } else if h.pattern == Pattern::None { + out.el(1, "polygon", &poly_node(&attr, &fill, &stroke, stroke_mm)); + } else if h.pattern == Pattern::Solid { + out.el(1, "polygon", &poly_node(&attr, &hatch_color, &stroke, stroke_mm)); + } else { + if fill != "none" { + out.el(1, "polygon", &poly_node(&attr, &fill, "none", 0.0)); + } + let pen = quantize_pen(h.line_weight); + if h.random { + for run in hatch::build_random_hatch_runs(&pts, &h, None) { + if run.len() < 2 { + continue; + } + let (a, b) = (run[0], run[run.len() - 1]); + out.el(1, "line", &line_attrs(m.at(a.x, a.y), m.at(b.x, b.y), &hatch_color, pen, None)); + } + } else { + // Strichmuster der Schraffur (null und [] gleich: keins). + for (a, b) in hatch_lines(&pts_mm, &h, k) { + out.el(1, "line", &line_attrs(a, b, &hatch_color, pen, Some(&h.dash))); + } + } + if stroke_mm > 0.0 { + out.el(1, "polygon", &poly_node(&attr, "none", &stroke, stroke_mm)); + } + } + out.rec(&["g"]); + } + T_LINE => { + let a = m.at(f[4], f[5]); + let b = m.at(f[6], f[7]); + let color = if rec.flags & F_COLOR != 0 { s(f[1])? } else { "#111111".to_string() }; + let pen = quantize_pen(f[2]); + let d = dash(&rec)?; + let mut attrs = if let Some((amp, wav)) = rec.zigzag { + let p = hatch::zigzag_points(a, b, amp, wav).unwrap_or_else(|| vec![a, b]); + polyline_attrs(&p, &color, pen, d.as_deref()) + } else if let Some((length, o, n)) = rec.motif { + let pts: Vec = view.pool(o, n.checked_mul(2)?)?.chunks_exact(2).map(|c| V2 { x: c[0], y: c[1] }).collect(); + let p = hatch::motif_points_opt(a, b, &Motif { points: pts, length }, 1.0).unwrap_or_else(|| vec![a, b]); + polyline_attrs(&p, &color, pen, d.as_deref()) + } else { + line_attrs(a, b, &color, pen, d.as_deref()) + }; + let tag = if rec.zigzag.is_some() || rec.motif.is_some() { "polyline" } else { "line" }; + let o = opacity_of(greyed, obj(3)); + if !o.is_empty() { + attrs.push(("opacity", o)); + } + out.el(0, tag, &attrs); + } + T_ARC => { + let c = m.at(f[4], f[5]); + let from = m.at(f[6], f[7]); + let to = m.at(f[8], f[9]); + let r = f[10] * k; + let cross = (from.x - c.x) * (to.y - c.y) - (from.y - c.y) * (to.x - c.x); + 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 o = opacity_of(greyed, obj(3)); + if !o.is_empty() { + attrs.push(("opacity", o)); + } + out.el(0, "path", &attrs); + } + T_CIRCLE => { + let c = m.at(f[4], f[5]); + let fill = s(f[0])?; + let mut attrs = vec![ + ("cx", r3(c.x)), + ("cy", r3(c.y)), + ("r", r3(f[6] * k)), + ("fill", if !fill.is_empty() && fill != "none" { fill } else { "none".to_string() }), + ("stroke", s(f[1])?), + ("stroke-width", js_number(quantize_pen(f[2]))), + ]; + push_dash(&mut attrs, dash(&rec)?.as_deref()); + let o = opacity_of(greyed, obj(3)); + if !o.is_empty() { + attrs.push(("opacity", o)); + } + out.el(0, "circle", &attrs); + } + T_DRAWING_ARC => { + let tau = PI * 2.0; + let (cx, cy, r, a0, a1) = (f[3], f[4], f[5], f[6], f[7]); + let from = m.at(cx + r * jsnum::cos(a0), cy + r * jsnum::sin(a0)); + let to = m.at(cx + r * jsnum::cos(a1), cy + r * jsnum::sin(a1)); + let rr = r * k; + let sweep = (((a1 - a0) % tau) + tau) % tau; + 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 o = opacity_of(greyed, obj(2)); + if !o.is_empty() { + attrs.push(("opacity", o)); + } + out.el(0, "path", &attrs); + } + T_DRAWING_TEXT | T_IMAGE => { + let j: serde_json::Value = serde_json::from_str(&view.string(whole(f[0])?)?).ok()?; + let jg = j.get("greyed").and_then(|g| g.as_bool()).unwrap_or(false); + if rec.tag == T_DRAWING_TEXT { + let obj = j.get("opacity").and_then(|o| o.as_f64()).unwrap_or(1.0); + out.rec(&["T", &gi.to_string(), &opacity_of(jg, obj)]); + } else { + let (min, max) = (j.get("min")?, j.get("max")?); + let (x0, y0, x1, y1) = (num(min, "x"), num(min, "y"), num(max, "x"), num(max, "y")); + let w = (x1 - x0) * k; + let h = (y1 - y0) * k; + if w <= 0.0 || h <= 0.0 { + return Some(()); + } + let tl = m.at(x0, y1); + let mut attrs = vec![ + ("href", j.get("src").and_then(|v| v.as_str()).unwrap_or("undefined").to_string()), + ("x", r3(tl.x)), + ("y", r3(tl.y)), + ("width", r3(w)), + ("height", r3(h)), + ("preserveAspectRatio", "none".to_string()), + ]; + // Bilder: eigene Deckkraft getrennt (gedimmt × 0.45), sonst nur das Dimmen. + let op = num(&j, "opacity"); + if op < 1.0 { + attrs.push(("opacity", js_number(op * if jg { 0.45 } else { 1.0 }))); + } else { + let o = opacity_of(jg, 1.0); + if !o.is_empty() { + attrs.push(("opacity", o)); + } + } + out.el(0, "image", &attrs); + } + } + _ => {} + } + Some(()) +} + +fn empty_hatch() -> Hatch { + Hatch { + pattern: Pattern::None, + kind: hatch::HatchKind::Vector, + random: false, + scale: 1.0, + angle: 0.0, + line_weight: 0.0, + origin: None, + seed: None, + density: None, + length_min: None, + length_max: None, + dash: Vec::new(), + motif: None, + } +} + +/// Anweisungsliste des Druck-SVG (Format s. Modulkopf); `None` bei kaputtem Puffer. +pub fn print_svg_ops(parts: &mut [Part], o: &PrintOptions) -> Option { + let k = 1000.0 / o.scale_denominator; + let [min_x, min_y, max_x, max_y] = o.bounds; + 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 { s: String::new(), first: true }; + let mut gi = 0usize; + for part in parts.iter_mut() { + let hatches = part.view.hatch_table()?; + for i in part.from..part.to { + entry(&mut out, &part.view, i, gi, &hatches, m)?; + gi += 1; + } + } + Some(out.s) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stift_stufen_und_runden() { + assert_eq!(quantize_pen(0.0), 0.13); + assert_eq!(quantize_pen(0.2), 0.25); + assert_eq!(quantize_pen(3.0), 1.0); + assert_eq!(r3(1.23456), "1.235"); + assert_eq!(r3(-0.0001), "0"); + assert_eq!(dash_attr(&[2.0, 0.5]), "2 0.5"); + } + + #[test] + fn schraffur_parallel_geklippt() { + let sq = [V2 { x: 0.0, y: 0.0 }, V2 { x: 10.0, y: 0.0 }, V2 { x: 10.0, y: 10.0 }, V2 { x: 0.0, y: 10.0 }]; + let mut segs = Vec::new(); + fill_parallel(&sq, 0.0, 2.0, &mut segs); + // Waagrechte Linien bei y = 0, 2, …, 10 über die volle Breite. + assert_eq!(segs.len(), 6); + assert!(segs.iter().all(|(a, b)| (b.x - a.x - 10.0).abs() < 1e-9 || (a.x - b.x - 10.0).abs() < 1e-9)); + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 6d66501e..abb96b4b 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -37,6 +37,7 @@ mod plan_pick; mod snap; mod plan_svg; mod plan_dxf; +mod plan_print_svg; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/plan_print_svg.rs b/src-tauri/core/src/web/plan_print_svg.rs new file mode 100644 index 00000000..80fc9a3a --- /dev/null +++ b/src-tauri/core/src/web/plan_print_svg.rs @@ -0,0 +1,20 @@ +//! Bindung des Druck-SVG (`crate::plan_print_svg`) auf gehaltenen Plan-Puffern (Abschnitte wie +//! `plan_parts`). Ergebnis `"1"` + Anweisungsliste; leer = Puffer fehlt (TS legt neu ab und fragt +//! nochmals) oder kaputte Eingabe — nie Panic. + +use crate::plan_parts::parts_from; +use crate::plan_print_svg::{print_svg_ops, PrintOptions}; +use wasm_bindgen::prelude::wasm_bindgen; + +/// `opts` = `[Massstab-Nenner, Blattbreite mm, Blatthöhe mm, minX, minY, maxX, maxY]`. +#[wasm_bindgen] +pub fn plan_print_svg_ops(segs: &[f64], opts: &[f64]) -> String { + let Ok([n, w, h, min_x, min_y, max_x, max_y]) = <[f64; 7]>::try_from(opts) else { return String::new() }; + let Some(held) = super::plan_buf::held_for_segs(segs) else { return String::new() }; + let Some(mut parts) = parts_from(segs, |nr| held.iter().find(|e| e.0 == nr).map(|e| &*e.1)) else { return String::new() }; + let o = PrintOptions { scale_denominator: n, page_w: w, page_h: h, bounds: [min_x, min_y, max_x, max_y] }; + match print_svg_ops(&mut parts, &o) { + Some(s) => format!("1{s}"), + None => String::new(), + } +} diff --git a/src/export/planToPrintSvg.ts b/src/export/planToPrintSvg.ts index 3e3793ff..140f36db 100644 --- a/src/export/planToPrintSvg.ts +++ b/src/export/planToPrintSvg.ts @@ -19,14 +19,20 @@ // Pattern oft nicht sauber), sondern als echte, auf das Polygon geklippte // Vektorlinien direkt ins SVG. So bleibt das PDF rein vektoriell und scharf. // +// Seit [K3d] (29.10.) rechnet der Kern die Knoten aus den Plan-Puffern +// (`src-tauri/core/src/plan_print_svg.rs`, Anweisungsliste); hier bleiben der +// -Rahmen, die Bild- (laufende Ids) und die Einzeltexte +// (Text-Layout `wrapDocToLines`). Ausgabe unverändert (gleiche Knoten/Attribute). +// // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import type { HatchRender, Plan, Primitive } from "../plan/generatePlan"; import type { Vec2 } from "../model/types"; -import { buildRandomHatchRuns, zigzagPoints, motifPoints } from "../plan/glPlan/glPlanHatch"; -import { dashHasDot } from "../geometry/lineSegments"; import { wrapDocToLines, type SvgLine } from "../text/renderHtml"; import { docFromText } from "../text/richText"; +import { core } from "../engine/coreWasm"; +import { planParts, withPlanParts } from "../plan/planParts"; +import { planPrimAt } from "../plan/planLazy"; /** SVG-Namespace für die programmatisch erzeugten Knoten. */ const SVG_NS = "http://www.w3.org/2000/svg"; @@ -77,41 +83,6 @@ function ensureImagePattern( return id; } -/** ``-Knoten (mm-Koordinaten) — für Zickzack-Linien/-Läufe. */ -function polylineNode( - pts: Vec2[], - color: string, - strokeMm: number, - dash: number[] | null | undefined, -): SVGElement { - const el = document.createElementNS(SVG_NS, "polyline"); - el.setAttribute("points", pts.map((p) => `${round(p.x)},${round(p.y)}`).join(" ")); - el.setAttribute("fill", "none"); - el.setAttribute("stroke", color); - el.setAttribute("stroke-width", String(strokeMm)); - el.setAttribute("stroke-linecap", "round"); - el.setAttribute("stroke-linejoin", "round"); - if (dash && dash.length) el.setAttribute("stroke-dasharray", dash.map((d) => round(d)).join(" ")); - return el; -} - -/** - * Standard-Stift-Stufen (mm). Beliebige Kategorie-Strichstärken werden auf die - * NÄCHSTHÖHERE dieser ISO-nahen Stufen gequantelt, damit der Plan saubere, - * unterscheidbare Linienstärken trägt (dünne Hilfslinien ≠ dicke Umrisse). - */ -const PEN_STEPS = [0.13, 0.18, 0.25, 0.35, 0.5, 0.7, 1.0] as const; - -/** Untergrenze einer sichtbaren Druck-Strichstärke (mm) — vermeidet 0-Linien. */ -const MIN_PEN_MM = 0.13; - -/** Quantelt eine mm-Strichstärke auf die nächste Stift-Stufe (≥ MIN_PEN_MM). */ -function quantizePen(mm: number): number { - const w = Math.max(MIN_PEN_MM, mm); - for (const step of PEN_STEPS) if (w <= step + 1e-6) return step; - return PEN_STEPS[PEN_STEPS.length - 1]; -} - /** Ergebnis des Print-SVG-Aufbaus: das Element + Blattmasse (mm). */ export interface PrintSvg { /** Das fertige, in mm bemaßte -Element (für svg2pdf). */ @@ -200,10 +171,11 @@ export function planToPrintSvg(plan: Plan, opts: PrintSvgOptions): PrintSvg { bg.setAttribute("fill", "#ffffff"); svg.appendChild(bg); - // Jedes Primitiv in mm-Knoten übersetzen. - for (const p of plan.primitives) { - appendPrimitive(svg, p, map, k); - } + // Jedes Primitiv in mm-Knoten übersetzen (Kern, Anweisungsliste s. `plan_print_svg.rs`). + const o = Float64Array.of(n, opts.pageWidthMm, opts.pageHeightMm, b.minX, b.minY, b.maxX, b.maxY); + const ops = withPlanParts(planParts(plan, true), (segs) => core().plan_print_svg_ops(segs, o)); + if (!ops) throw new Error("Druck-SVG: Plan im Kern unlesbar"); + applyOps(svg, ops.slice(1), plan, map, k); return { svg, @@ -213,93 +185,50 @@ export function planToPrintSvg(plan: Plan, opts: PrintSvgOptions): PrintSvg { }; } -/** Schreibt ein einzelnes Primitiv (mit ggf. Schraffur) in das SVG. */ -function appendPrimitive( - svg: SVGSVGElement, - p: Primitive, - map: Mapper, - mmPerM: number, -): void { - // Gedimmt (0.3) und Objekt-Transparenz multiplizieren sich; Bilder tragen - // ihre eigene Deckkraft separat (s. dortiger Zweig). - const objOpacity = p.kind === "drawingImage" ? 1 : (p.opacity ?? 1); - const dim = p.greyed ? 0.3 : 1; - const combined = dim * Math.max(0, objOpacity); - const opacity = combined < 1 ? String(combined) : undefined; - switch (p.kind) { - case "polygon": - appendPolygon(svg, p, map, mmPerM, opacity); - break; - case "line": { - const a = map(p.a); - const b = map(p.b); - // Zickzack-Linie (amplitude/wavelength sind Papier-mm = mm-Zielraum) → - // Polylinie; sonst gerade (ggf. gestrichelte) Linie wie bisher. - // Zickzack/Custom-Motiv sind in Papier-mm definiert = mm-Zielraum (scale 1). - const ln = p.zigzag - ? polylineNode( - zigzagPoints(a, b, p.zigzag.amplitude, p.zigzag.wavelength), - p.color ?? "#111111", - quantizePen(p.weightMm), - p.dash, - ) - : p.motif - ? polylineNode( - motifPoints(a, b, p.motif), - p.color ?? "#111111", - quantizePen(p.weightMm), - p.dash, - ) - : lineNode(a, b, p.color ?? "#111111", quantizePen(p.weightMm), p.dash, mmPerM); - if (opacity) ln.setAttribute("opacity", opacity); - svg.appendChild(ln); - break; - } - case "arc": { - const node = arcNode(p, map, mmPerM); - if (opacity) node.setAttribute("opacity", opacity); - svg.appendChild(node); - break; - } - case "drawingCircle": { - const c = map(p.center); - const el = document.createElementNS(SVG_NS, "circle"); - el.setAttribute("cx", String(round(c.x))); - el.setAttribute("cy", String(round(c.y))); - el.setAttribute("r", String(round(p.r * mmPerM))); - el.setAttribute("fill", p.fill && p.fill !== "none" ? p.fill : "none"); - el.setAttribute("stroke", p.stroke); - el.setAttribute("stroke-width", String(quantizePen(p.weightMm))); - if (p.dash && p.dash.length) { - el.setAttribute("stroke-dasharray", p.dash.map((x) => round(x)).join(" ")); - if (dashHasDot(p.dash)) el.setAttribute("stroke-linecap", "round"); +/** + * Legt die Knoten der Kern-Anweisungsliste an (Format s. `plan_print_svg.rs`): Elemente mit ihren + * Attributen in Reihenfolge, Gruppen, Bild-Schraffuren (`` hier) und Einzeltexte (Layout hier). + */ +function applyOps(svg: SVGSVGElement, ops: string, plan: Plan, map: Mapper, mmPerM: number): void { + if (!ops) return; + let g: SVGElement | null = null; + for (const rec of ops.split("\u001e")) { + const f = rec.split("\u001f"); + switch (f[0]) { + case "E": { + const el = document.createElementNS(SVG_NS, f[2]) as SVGElement; + for (let i = 3; i + 1 < f.length; i += 2) el.setAttribute(f[i], f[i + 1]); + (f[1] === "1" && g ? g : svg).appendChild(el); + break; } - if (opacity) el.setAttribute("opacity", opacity); - svg.appendChild(el); - break; - } - case "drawingArc": { - const node = drawingArcNode(p, map, mmPerM); - if (opacity) node.setAttribute("opacity", opacity); - svg.appendChild(node); - break; - } - case "drawingText": { - const node = drawingTextNode(p, map, mmPerM); - if (node) { - if (opacity) node.setAttribute("opacity", opacity); - svg.appendChild(node); + case "G": + g = document.createElementNS(SVG_NS, "g") as SVGElement; + if (f[1]) g.setAttribute("opacity", f[1]); + break; + case "g": + if (g) svg.appendChild(g); + g = null; + break; + case "I": { + // Bild-Schraffur: gekacheltes über die Fläche. + const patId = ensureImagePattern(svg, JSON.parse(f[2]) as NonNullable); + const el = document.createElementNS(SVG_NS, "polygon"); + el.setAttribute("points", f[1]); + el.setAttribute("fill", `url(#${patId})`); + el.setAttribute("stroke", "none"); + g?.appendChild(el); + break; } - break; - } - case "drawingImage": { - const node = drawingImageNode(p, map, mmPerM); - if (node) { - if (p.opacity < 1) node.setAttribute("opacity", String(p.opacity * (p.greyed ? 0.45 : 1))); - else if (opacity) node.setAttribute("opacity", opacity); - svg.appendChild(node); + case "T": { + const p = planPrimAt(plan, Number(f[1])); + if (p?.kind !== "drawingText") break; + const node = drawingTextNode(p, map, mmPerM); + if (node) { + if (f[2]) node.setAttribute("opacity", f[2]); + svg.appendChild(node); + } + break; } - break; } } } @@ -371,309 +300,7 @@ function drawingTextNode( return el; } -/** Eingebettetes Rasterbild (Data-URL) als achsparalleles ``. */ -function drawingImageNode( - p: Extract, - map: Mapper, - mmPerM: number, -): SVGImageElement | null { - const w = (p.max.x - p.min.x) * mmPerM; - const h = (p.max.y - p.min.y) * mmPerM; - if (w <= 0 || h <= 0) return null; - const topLeft = map({ x: p.min.x, y: p.max.y }); - const el = document.createElementNS(SVG_NS, "image"); - el.setAttribute("href", p.src); - el.setAttribute("x", String(round(topLeft.x))); - el.setAttribute("y", String(round(topLeft.y))); - el.setAttribute("width", String(round(w))); - el.setAttribute("height", String(round(h))); - el.setAttribute("preserveAspectRatio", "none"); - return el; -} - -/** - * Polygon mit Füllung/Umriss/Schraffur. Reihenfolge wie in der PlanView: - * • pattern "none" → reine Füllung (oder „none") + Umriss. - * • pattern "solid" → Vollfüllung in der Hatch-Farbe + Umriss. - * • Linien/Kreuz/Dämmung → Grundfüllung, dann geklippte Schraffurlinien, dann Umriss. - */ -function appendPolygon( - svg: SVGSVGElement, - p: Extract, - map: Mapper, - mmPerM: number, - opacity: string | undefined, -): void { - const ptsMm = p.pts.map(map); - const ptsAttr = ptsMm.map((s) => `${round(s.x)},${round(s.y)}`).join(" "); - const strokeMm = p.strokeWidthMm > 0 ? quantizePen(p.strokeWidthMm) : 0; - - const g = document.createElementNS(SVG_NS, "g"); - if (opacity) g.setAttribute("opacity", opacity); - - const pattern = p.hatch.pattern; - if (p.hatch.kind === "image" && p.hatch.image) { - // Bild-Schraffur: gekacheltes mit (scaleX/scaleY/rotation) - // über die Fläche, unabhängig vom `pattern`-Feld. Grundfüllung darunter, - // Umriss obenauf. - if (p.fill !== "none") g.appendChild(polyNode(ptsAttr, p.fill, "none", 0)); - const patId = ensureImagePattern(svg, p.hatch.image); - g.appendChild(polyNode(ptsAttr, `url(#${patId})`, "none", 0)); - if (strokeMm > 0) g.appendChild(polyNode(ptsAttr, "none", p.stroke, strokeMm)); - } else if (pattern === "none") { - g.appendChild(polyNode(ptsAttr, p.fill, p.stroke, strokeMm)); - } else if (pattern === "solid") { - g.appendChild(polyNode(ptsAttr, p.hatch.color, p.stroke, strokeMm)); - } else { - // Grundfüllung (ohne Umriss), dann die geklippten Schraffurlinien, dann der - // Umriss obenauf (separat, damit er die Schraffur-Enden überdeckt). - if (p.fill !== "none") { - g.appendChild(polyNode(ptsAttr, p.fill, "none", 0)); - } - if (p.hatch.lines === "random") { - // Random-Vektor (Kies/Splitt): deterministische Streu-Striche. Wird im - // MODELL-Raum erzeugt (identischer Seed/Geometrie wie Bildschirm/GL/PDF) - // und dann nach Papier-mm abgebildet. - for (const run of buildRandomHatchRuns(p.pts, p.hatch)) { - if (run.length < 2) continue; - g.appendChild( - lineNode( - map(run[0]), - map(run[run.length - 1]), - p.hatch.color, - quantizePen(p.hatch.lineWeight), - null, - mmPerM, - ), - ); - } - } else { - for (const seg of hatchLines(ptsMm, p.hatch, mmPerM)) { - g.appendChild( - lineNode( - seg.a, - seg.b, - p.hatch.color, - quantizePen(p.hatch.lineWeight), - p.hatch.dash, - mmPerM, - ), - ); - } - } - if (strokeMm > 0) { - g.appendChild(polyNode(ptsAttr, "none", p.stroke, strokeMm)); - } - } - - svg.appendChild(g); -} - -/** Erzeugt einen -Knoten (mm-Koordinaten als Attribut-String). */ -function polyNode( - ptsAttr: string, - fill: string, - stroke: string, - strokeMm: number, -): SVGElement { - const el = document.createElementNS(SVG_NS, "polygon"); - el.setAttribute("points", ptsAttr); - el.setAttribute("fill", fill); - if (stroke !== "none" && strokeMm > 0) { - el.setAttribute("stroke", stroke); - el.setAttribute("stroke-width", String(strokeMm)); - el.setAttribute("stroke-linejoin", "round"); - } else { - el.setAttribute("stroke", "none"); - } - return el; -} - -/** Erzeugt einen -Knoten in mm; Strichmuster (mm Welt → mm Papier). */ -function lineNode( - a: Vec2, - b: Vec2, - color: string, - strokeMm: number, - dash: number[] | null | undefined, - _mmPerM: number, -): SVGElement { - const el = document.createElementNS(SVG_NS, "line"); - el.setAttribute("x1", String(round(a.x))); - el.setAttribute("y1", String(round(a.y))); - el.setAttribute("x2", String(round(b.x))); - el.setAttribute("y2", String(round(b.y))); - el.setAttribute("stroke", color); - el.setAttribute("stroke-width", String(strokeMm)); - el.setAttribute("stroke-linecap", "round"); - if (dash && dash.length) { - // Strichmuster ist in mm Papier definiert (wie weightMm), daher direkt. - el.setAttribute("stroke-dasharray", dash.map((d) => round(d)).join(" ")); - } - return el; -} - -/** - * Erzeugt einen Bogen als (A-Kommando). Der Bogen-Radius ist in Metern → - * Papier-mm. Drehrichtung aus dem Kreuzprodukt im Papier-Raum (Y nach unten). - */ -function arcNode( - p: Extract, - map: Mapper, - mmPerM: number, -): SVGElement { - const c = map(p.center); - const from = map(p.from); - const to = map(p.to); - const r = p.r * mmPerM; - const v1 = { x: from.x - c.x, y: from.y - c.y }; - const v2 = { x: to.x - c.x, y: to.y - c.y }; - const cross = v1.x * v2.y - v1.y * v2.x; - const sweep = cross > 0 ? 1 : 0; - const d = `M ${round(from.x)} ${round(from.y)} A ${round(r)} ${round(r)} 0 0 ${sweep} ${round(to.x)} ${round(to.y)}`; - const el = document.createElementNS(SVG_NS, "path"); - el.setAttribute("d", d); - el.setAttribute("fill", "none"); - el.setAttribute("stroke", "#111111"); - el.setAttribute("stroke-width", String(quantizePen(p.weightMm))); - if (p.dash && p.dash.length) { - el.setAttribute("stroke-dasharray", p.dash.map((x) => round(x)).join(" ")); - // Punktmuster (dash enthält eine 0): runde Kappe → Dots am Bogen. - if (dashHasDot(p.dash)) el.setAttribute("stroke-linecap", "round"); - } - return el; -} - -/** - * `drawingArc` → glatter SVG-Bogen. Konvention wie im Bildschirm-Renderer - * (`planView/primitives.tsx`): die Winkel laufen im MODELL immer gegen den - * Uhrzeigersinn von `a0` nach `a1`; da die Ziel-Y-Achse gespiegelt ist, wird - * daraus am Papier ein Uhrzeigersinn-Bogen (sweep-flag 1). `large-arc` aus - * der normierten Spannweite. - */ -function drawingArcNode( - p: Extract, - map: Mapper, - mmPerM: number, -): SVGElement { - const TAU = Math.PI * 2; - const from = map({ x: p.center.x + p.r * Math.cos(p.a0), y: p.center.y + p.r * Math.sin(p.a0) }); - const to = map({ x: p.center.x + p.r * Math.cos(p.a1), y: p.center.y + p.r * Math.sin(p.a1) }); - const r = p.r * mmPerM; - const sweep = (((p.a1 - p.a0) % TAU) + TAU) % TAU; - const largeArc = sweep > Math.PI ? 1 : 0; - const el = document.createElementNS(SVG_NS, "path"); - el.setAttribute( - "d", - `M ${round(from.x)} ${round(from.y)} A ${round(r)} ${round(r)} 0 ${largeArc} 1 ${round(to.x)} ${round(to.y)}`, - ); - el.setAttribute("fill", "none"); - el.setAttribute("stroke", p.stroke); - el.setAttribute("stroke-width", String(quantizePen(p.weightMm))); - if (p.dash && p.dash.length) { - el.setAttribute("stroke-dasharray", p.dash.map((x) => round(x)).join(" ")); - if (dashHasDot(p.dash)) el.setAttribute("stroke-linecap", "round"); - } - return el; -} - /** Auf 3 Nachkommastellen runden (kompaktes, exaktes SVG). */ function round(v: number): number { return Math.round(v * 1000) / 1000; } - -// ── Schraffur als geklippte Vektorlinien ───────────────────────────────────── - -interface Seg { - a: Vec2; - b: Vec2; -} - -/** - * Erzeugt die Schraffurlinien eines Polygons (in Papier-mm), auf das Polygon - * geklippt. Die Kachelgrösse der Bildschirm-PlanView (8 px bzw. 14 px bei - * „insulation", × Maßstab) wird hier in einen mm-Linienabstand übersetzt, damit - * der Druck der Bildschirm-Dichte nahekommt: - * • diagonal/crosshatch: parallele Linienscharen im Winkel `angle`. - * • crosshatch: zusätzlich die um 90° gedrehte Schar. - * • insulation: vereinfacht als eine dichtere diagonale Schar (echte Wellen- - * linie wäre als Pfad möglich; eine Linienschar liest sich im Druck sauber - * und bleibt rein vektoriell — offener Punkt im Report). - */ -function hatchLines(polyMm: Vec2[], hatch: HatchRender, mmPerM: number): Seg[] { - // Kachel der PlanView: 8 viewBox-Einheiten (= px bei dpi-Bezug) × scale. In der - // PlanView ist 1 viewBox-Einheit = 1/PX_PER_M m = 1/90 m. Auf Papier sind das - // (1/90)·mmPerM mm. So bleibt die Strich-Dichte massstäblich konsistent. - const unitMm = (1 / 90) * mmPerM; - const tileMm = (hatch.pattern === "insulation" ? 10 : 8) * hatch.scale * unitMm; - const spacing = Math.max(0.5, tileMm); // Mindestabstand, sonst zu dicht - - const angle = (hatch.angle * Math.PI) / 180; - const segs: Seg[] = []; - fillParallel(polyMm, angle, spacing, segs); - if (hatch.pattern === "crosshatch") { - fillParallel(polyMm, angle + Math.PI / 2, spacing, segs); - } - if (hatch.pattern === "insulation") { - // Zweite, gegenläufige Schar deutet die Dämmungs-Textur an (dichter Filz). - fillParallel(polyMm, angle - Math.PI / 4, spacing, segs); - } - return segs; -} - -/** - * Füllt das Polygon mit parallelen Linien im gegebenen Winkel/Abstand und klippt - * jede Linie auf das Polygon (Scanline über die Polygon-Schnittpunkte). Robust - * für konvexe wie konkave (einfache) Polygone. - */ -function fillParallel( - poly: Vec2[], - angle: number, - spacing: number, - out: Seg[], -): void { - if (poly.length < 3 || spacing <= 0) return; - // Linienrichtung d und Normale nrm (Projektionsachse). - const dir = { x: Math.cos(angle), y: Math.sin(angle) }; - const nrm = { x: -dir.y, y: dir.x }; - - // Projektion der Polygonpunkte auf die Normale → [tMin, tMax]-Band der Linien. - let tMin = Infinity; - let tMax = -Infinity; - for (const p of poly) { - const t = p.x * nrm.x + p.y * nrm.y; - if (t < tMin) tMin = t; - if (t > tMax) tMax = t; - } - // Linien an t = tMin + i·spacing; für jede die Schnitt-Intervalle ermitteln. - const start = Math.ceil(tMin / spacing) * spacing; - for (let t = start; t <= tMax; t += spacing) { - const xs: number[] = []; // Parameter entlang dir der Schnittpunkte - for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { - const a = poly[j]; - const b = poly[i]; - const ta = a.x * nrm.x + a.y * nrm.y; - const tb = b.x * nrm.x + b.y * nrm.y; - // Schneidet die Kante das Niveau t? - if (ta === tb) continue; - const f = (t - ta) / (tb - ta); - if (f < 0 || f > 1) continue; - const px = a.x + (b.x - a.x) * f; - const py = a.y + (b.y - a.y) * f; - xs.push(px * dir.x + py * dir.y); // Position entlang dir - } - if (xs.length < 2) continue; - xs.sort((u, v) => u - v); - // Paarweise Intervalle = Polygon-Inneres entlang der Linie. - for (let k = 0; k + 1 < xs.length; k += 2) { - const u0 = xs[k]; - const u1 = xs[k + 1]; - if (u1 - u0 < 1e-6) continue; - // Punkt = t·nrm + u·dir. - out.push({ - a: { x: nrm.x * t + dir.x * u0, y: nrm.y * t + dir.y * u0 }, - b: { x: nrm.x * t + dir.x * u1, y: nrm.y * t + dir.y * u1 }, - }); - } - } -} diff --git a/src/plan/planLazy.test.ts b/src/plan/planLazy.test.ts index 2c89745c..f597543b 100644 --- a/src/plan/planLazy.test.ts +++ b/src/plan/planLazy.test.ts @@ -1,5 +1,5 @@ // Lazy Plan ([K3d], `planLazy.ts`): `generatePlan` liest die Kern-Primitive erst bei Bedarf; die -// Verbraucher im Kern (Szene, Auswahl, SVG) und die Text-Einträge kommen ohne aus. +// Verbraucher im Kern (Szene, Auswahl, SVG, DXF, Druck-SVG) und die Text-Einträge kommen ohne aus. import { describe, expect, it } from "vitest"; import { generatePlan, generateVisibleLevelsPlan, materializeUnderlay, type Primitive } from "./generatePlan"; @@ -7,6 +7,8 @@ import { isLazyUnread, planCount, planPrimAt, planTextEntries, planWithExtra } f import { planSceneBin, planToRenderScene } from "./toRenderScene"; import { planToSvgString } from "../export/planToSvgString"; import { PlanPickIndex } from "./planView/planPick"; +import { collectPlanDrawing } from "../export/exportDxf"; +import { planToPrintSvg } from "../export/planToPrintSvg"; import { sampleProject } from "../model/sampleProject"; import { flattenCategories, type Project } from "../model/types"; @@ -31,8 +33,19 @@ describe("lazy Plan", () => { const ix = new PlanPickIndex(plan); ix.topPolygon({ x: 2, y: 2 }); ix.marquee("wallId", { minX: -100, minY: -100, maxX: 100, maxY: 100 }, false); - ix.drawingTextAt({ x: 1.2, y: 2 }); + expect(ix.drawingTextAt({ x: 1.2, y: 2 })).not.toBeNull(); ix.release(); + expect(collectPlanDrawing(plan, withText).stats().model.TEXT).toBeGreaterThan(0); + // Druck-SVG mit minimalem DOM-Ersatz (Node ohne DOM). + const el = (): Record => ({ setAttribute() {}, appendChild: (c: unknown) => c, insertBefore: (c: unknown) => c, querySelector: () => null, firstChild: null }); + const g = globalThis as { document?: unknown }; + const prev = g.document; + g.document = { createElementNS: () => el() }; + try { + planToPrintSvg(plan, { scaleDenominator: 100, pageWidthMm: 420, pageHeightMm: 297 }); + } finally { + g.document = prev; + } expect(planTextEntries(plan).length).toBeGreaterThan(0); expect(planPrimAt(plan, 0)).toBeDefined(); expect(isLazyUnread(plan)).toBe(true);