[146] Linienenden und -ecken: Kern und render2d (Zwischenstand)

Projekt-Felder lineCap/lineJoin (Standard flach + Gehrung, Grenze 4), Kodierung cap | join << 2
über die WASM-Grenze. render2d: Gehrung/Fase/rund an Ecken, flache/vorstehende/runde Kappen
(Linien, Strich-Shader, Bögen), Szenenkopf trägt die Einstellung. Kern: gpu_compile (Metal-Chunks)
gleich, volle Einzel-Linien und Kantenläufe werden an gemeinsamen Enden zu Zügen genäht (keine
Kerbe an Wandecken) — auch in Szene, Plan-SVG und Druck-SVG.
This commit is contained in:
Claude committed 2026-11-06 01:17:51 +00:00
1 parent 4e0a376ef8
commit 726904edd6
21 files changed
+784 -124

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
//! Linienenden und -ecken ([146]): EINE Projekt-Einstellung (`Project.lineCap`/`lineJoin`) für alle
//! Ausgabewege — Bildschirm (render2d-Szene, GPU-Chunks), Plan-SVG, Druck-SVG/PDF, DXF. Über die
//! WASM-Grenze als kleine Zahl `cap | join << 2` (0 = flach + Gehrung, der Standard).
use crate::model::{LineCap, LineJoin, Project};
/// Gehrungsgrenze (Gehrungslänge / Strichbreite, wie SVG `stroke-miterlimit`); darüber gefast.
pub const MITER_LIMIT: f64 = 4.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct LineEnds {
/// 0 flach (butt), 1 rund, 2 vorstehend (square).
pub cap: u8,
/// 0 Gehrung (miter), 1 rund, 2 gefast (bevel).
pub join: u8,
}
impl LineEnds {
pub fn of(p: &Project) -> Self {
let cap = match p.line_cap {
Some(LineCap::Round) => 1,
Some(LineCap::Square) => 2,
_ => 0,
};
let join = match p.line_join {
Some(LineJoin::Round) => 1,
Some(LineJoin::Bevel) => 2,
_ => 0,
};
Self { cap, join }
}
/// Aus der Kodierung `cap | join << 2`; Unsinn (NaN, ausserhalb) → Standard.
pub fn from_code(c: f64) -> Self {
if !c.is_finite() || !(0.0..16.0).contains(&c) {
return Self::default();
}
let c = c as u32;
let cap = (c & 3) as u8;
let join = ((c >> 2) & 3) as u8;
Self { cap: if cap > 2 { 0 } else { cap }, join: if join > 2 { 0 } else { join } }
}
pub fn code(self) -> u32 {
self.cap as u32 | (self.join as u32) << 2
}
pub fn svg_cap(self) -> &'static str {
["butt", "round", "square"][self.cap as usize]
}
pub fn svg_join(self) -> &'static str {
["miter", "round", "bevel"][self.join as usize]
}
/// SVG-Attribute für einen umschliessenden `<g>` (Kinder erben sie).
pub fn svg_attrs(self) -> String {
format!("stroke-linecap=\"{}\" stroke-linejoin=\"{}\" stroke-miterlimit=\"{}\"", self.svg_cap(), self.svg_join(), MITER_LIMIT)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kodierung_rundreise_und_unsinn() {
for cap in 0..3 {
for join in 0..3 {
let e = LineEnds { cap, join };
assert_eq!(LineEnds::from_code(e.code() as f64), e);
}
}
assert_eq!(LineEnds::from_code(f64::NAN), LineEnds::default());
assert_eq!(LineEnds::from_code(3.0), LineEnds::default());
assert_eq!(LineEnds::from_code(-1.0), LineEnds::default());
let mut p = Project::default();
assert_eq!(LineEnds::of(&p), LineEnds { cap: 0, join: 0 });
p.line_cap = Some(LineCap::Square);
p.line_join = Some(LineJoin::Bevel);
assert_eq!(LineEnds::of(&p).code(), 2 | 2 << 2);
assert_eq!(LineEnds::of(&p).svg_attrs(), "stroke-linecap=\"square\" stroke-linejoin=\"bevel\" stroke-miterlimit=\"4\"");
}
}
+1
View File
@@ -32,3 +32,4 @@ pub mod elevation_geom;
pub mod pick;
pub mod sketch;
pub mod ceiling_plan;
pub mod line_ends;
+70 -25
View File
@@ -65,17 +65,61 @@ fn dash_attr(d: &[f64]) -> String {
/// Anweisungsliste.
struct Out {
s: String,
first: bool,
recs: Vec<String>,
/// Volle Einzel-Linien je (Farbe, Stift, Deckkraft) zum Zusammennähen ([146]): Wand-Umrisse zweier
/// Wände treffen sich als EIN Zug mit Ecke; jeder Zug steht an der Stelle seiner spätesten Linie.
solid: Vec<((String, String, String), Vec<Vec<V2>>, Vec<usize>)>,
}
impl Out {
fn rec(&mut self, fields: &[&str]) {
if !self.first {
self.s.push('\u{1e}');
self.recs.push(fields.join("\u{1f}"));
}
fn defer_solid(&mut self, key: (String, String, String), a: V2, b: V2) {
self.recs.push(String::new());
let slot = self.recs.len() - 1;
let gi = match self.solid.iter().position(|g| g.0 == key) {
Some(g) => g,
None => {
self.solid.push((key, Vec::new(), Vec::new()));
self.solid.len() - 1
}
};
self.solid[gi].1.push(vec![a, b]);
self.solid[gi].2.push(slot);
}
fn finish(mut self) -> String {
for ((color, pen, o), runs, slots) in std::mem::take(&mut self.solid) {
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;
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())]
};
if !o.is_empty() {
attrs.push(("opacity", o.clone()));
}
let tag = if line { "line" } else if closed { "polygon" } else { "polyline" };
let mut f: Vec<&str> = vec!["E", "0", tag];
for (k, v) in &attrs {
f.push(k);
f.push(v);
}
let r = f.join("\u{1f}");
if self.recs[slot].is_empty() {
self.recs[slot] = r;
} else {
self.recs[slot].push('\u{1e}');
self.recs[slot].push_str(&r);
}
}
}
self.first = false;
self.s.push_str(&fields.join("\u{1f}"));
self.recs.retain(|r| !r.is_empty());
self.recs.join("\u{1e}")
}
/// Datensatz aus festen Feldern und Name/Wert-Paaren.
@@ -140,7 +184,6 @@ fn poly_node(pts: &str, fill: &str, stroke: &str, stroke_mm: f64) -> Vec<(&'stat
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()));
}
@@ -155,11 +198,8 @@ fn line_attrs(a: V2, b: V2, color: &str, stroke_mm: f64, dash: Option<&[f64]>) -
("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)));
}
push_dash(&mut v, dash);
v
}
@@ -169,16 +209,13 @@ fn polyline_attrs(pts: &[V2], color: &str, stroke_mm: f64, dash: Option<&[f64]>)
("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)));
}
push_dash(&mut v, dash);
v
}
/// Strichmuster + runde Kappe bei Punkten (Bögen, Kreise).
/// Strichmuster + runde Kappe bei Punkten. Sonst erben Enden und Ecken die Projekt-Einstellung
/// ([146]) vom `<svg>`, das TS anlegt (`planToPrintSvg.ts`).
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)));
@@ -392,6 +429,11 @@ fn entry(out: &mut Out, view: &View, i: usize, hatches: &[(i32, Hatch, i32)], m:
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 {
let o = opacity_of(greyed, obj(3));
if d.as_deref().is_none_or(|d| d.is_empty()) && pen > 0.0 {
out.defer_solid((color, js_number(pen), o), a, b);
return Some(());
}
line_attrs(a, b, &color, pen, d.as_deref())
};
let tag = if rec.zigzag.is_some() || rec.motif.is_some() { "polyline" } else { "line" };
@@ -601,14 +643,14 @@ pub fn print_svg_ops(parts: &mut [Part], o: &PrintOptions) -> Option<String> {
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 out = Out { recs: Vec::new(), solid: Vec::new() };
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, &hatches, m)?;
}
}
Some(out.s)
Some(out.finish())
}
#[cfg(test)]
@@ -646,9 +688,10 @@ 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 { s: String::new(), first: true };
let mut out = Out { recs: Vec::new(), solid: Vec::new() };
text_node(&mut out, &t, m, "0.5".into());
let recs: Vec<Vec<&str>> = out.s.split('\u{1e}').map(|r| r.split('\u{1f}').collect()).collect();
let s = out.finish();
let recs: Vec<Vec<&str>> = s.split('\u{1e}').map(|r| r.split('\u{1f}').collect()).collect();
// Drehung um den Anker (10, 80 mm), eine Zeile (Spalte 20 mm), je Wort/Leerraum ein Run.
assert_eq!(recs[0], ["X", "transform", "rotate(-28.648 10 80)", "opacity", "0.5"]);
assert_eq!(recs[1], ["L", "", "x", "10", "y", "80", "text-anchor", "start"]);
@@ -664,9 +707,10 @@ 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 { s: String::new(), first: true };
let mut out = Out { recs: Vec::new(), solid: Vec::new() };
text_node(&mut out, &t, m, String::new());
let recs: Vec<Vec<&str>> = out.s.split('\u{1e}').map(|r| r.split('\u{1f}').collect()).collect();
let s = out.finish();
let recs: Vec<Vec<&str>> = s.split('\u{1e}').map(|r| r.split('\u{1f}').collect()).collect();
let lines: Vec<&Vec<&str>> = recs.iter().filter(|r| r[0] == "L").collect();
assert_eq!(lines.len(), 2);
// Absatz-Zeilenhöhe 2 × Basisgrösse (2.5 mm).
@@ -680,9 +724,10 @@ 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 { s: String::new(), first: true };
let mut out = Out { recs: Vec::new(), solid: Vec::new() };
stamp_node(&mut out, &t, m, "0.3".into());
let recs: Vec<Vec<&str>> = out.s.split('\u{1e}').map(|r| r.split('\u{1f}').collect()).collect();
let s = out.finish();
let recs: Vec<Vec<&str>> = s.split('\u{1e}').map(|r| r.split('\u{1f}').collect()).collect();
assert_eq!(recs[0], ["X", "opacity", "0.3"]);
// Anker (40, 140 mm); 10 pt = 3.528 mm, Live-Zeile 0.8 ×; Block um den Anker zentriert.
assert_eq!(&recs[1][..4], ["L", "", "x", "40"]);
+36 -9
View File
@@ -95,6 +95,8 @@ pub struct Scene {
pub polylines: Vec<SStroke>,
pub arcs: Vec<SArc>,
pub lines: Vec<SLine>,
/// Linienenden und -ecken ([146], `LineEnds::code`), im Kopfwort der Binärszene.
pub line_ends: u32,
}
// ── Farben (wie `toRgba`/`withOpacity` der TS-Fassung) ──────────────────────────────────────────
@@ -259,8 +261,14 @@ fn stitch_key(p: V2) -> (u64, u64) {
/// Ergebnis: (Punkte, geschlossen). Gleiche Wahl wie die lineare Suche der TS-Fassung (der
/// erste passende Lauf in Pool-Reihenfolge); ein Raster über den Endpunkten findet die Kandidaten.
pub fn stitch_runs(runs: Vec<Vec<V2>>) -> Vec<(Vec<V2>, bool)> {
stitch_runs_members(&runs).into_iter().map(|(c, closed, _)| (c, closed)).collect()
}
/// Wie [`stitch_runs`], zusätzlich die Indizes der beteiligten Läufe je Zug ([146]: Zeichen-
/// Reihenfolge je Zug statt je Gruppe).
pub fn stitch_runs_members(runs: &[Vec<V2>]) -> Vec<(Vec<V2>, bool, Vec<usize>)> {
let mut end_count: HashMap<(u64, u64), u32> = HashMap::new();
for r in &runs {
for r in runs {
for p in [r[0], r[r.len() - 1]] {
*end_count.entry(stitch_key(p)).or_insert(0) += 1;
}
@@ -291,6 +299,7 @@ pub fn stitch_runs(runs: Vec<Vec<V2>>) -> Vec<(Vec<V2>, bool)> {
continue;
}
used[seed] = true;
let mut members = vec![seed];
let mut chain = runs[seed].clone();
let mut extended = true;
while extended && !(chain.len() > 2 && same_pt(chain[0], chain[chain.len() - 1])) {
@@ -337,6 +346,7 @@ pub fn stitch_runs(runs: Vec<Vec<V2>>) -> Vec<(Vec<V2>, bool)> {
continue;
}
used[ci] = true;
members.push(ci);
extended = true;
break;
}
@@ -345,7 +355,7 @@ pub fn stitch_runs(runs: Vec<Vec<V2>>) -> Vec<(Vec<V2>, bool)> {
if closed {
chain.pop();
}
out.push((chain, closed));
out.push((chain, closed, members));
}
out
}
@@ -365,7 +375,8 @@ struct EdgeGroup {
color: Rgba,
width_mm: f64,
runs: Vec<Vec<V2>>,
z: f64,
/// Zeichen-Stelle je Lauf; ein genähter Zug liegt an der spätesten seiner Läufe ([146]).
zs: Vec<f64>,
}
struct Builder {
@@ -409,14 +420,14 @@ impl Builder {
let gi = match self.group_of.get(&k) {
Some(&g) => g,
None => {
self.groups.push(EdgeGroup { color, width_mm, runs: Vec::new(), z });
self.groups.push(EdgeGroup { color, width_mm, runs: Vec::new(), zs: Vec::new() });
self.group_of.insert(k, self.groups.len() - 1);
self.groups.len() - 1
}
};
let g = &mut self.groups[gi];
g.runs.push(run);
g.z = jsnum::max(g.z, z);
g.zs.push(z);
}
}
@@ -562,7 +573,18 @@ pub fn build_scene(parts: &mut [Part], greyed_ranges: &[(usize, usize)]) -> Opti
b.flush();
let col = with_opacity(stroke_color_for(cls.as_deref(), col_s.as_deref()), cls.as_deref(), greyed);
let z = b.z();
b.s.lines.push(SLine { a, b: bb, color: col, width_mm: w, dash, z });
let solid = match &dash {
SDash::List(d) => d.is_empty(),
_ => true,
};
if solid && w > 0.0 {
// [146] Volle Einzel-Linien (Wand-Umrisse im Raster-Pfad u. a.) mit den
// Kantenläufen gleicher Farbe/Breite zusammennähen: an Ecken EIN Zug mit
// Gehrung statt zweier flacher Enden (keine Kerbe).
b.edge_run(vec![a, bb], col, w, z);
} else {
b.s.lines.push(SLine { a, b: bb, color: col, width_mm: w, dash, z });
}
}
}
}
@@ -605,11 +627,12 @@ pub fn build_scene(parts: &mut [Part], greyed_ranges: &[(usize, usize)]) -> Opti
b.flush();
let groups = std::mem::take(&mut b.groups);
for g in groups {
for (pts, closed) in stitch_runs(g.runs) {
for (pts, closed, members) in stitch_runs_members(&g.runs) {
if pts.len() < 2 {
continue;
}
let s = SStroke { pts, color: g.color, width_mm: g.width_mm, dash: SDash::Absent, z: g.z, width_screen: false };
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 };
if closed {
b.s.outlines.push(s);
} else {
@@ -742,7 +765,7 @@ pub fn encode_scene_bin(s: &Scene, texts: &[SText]) -> Vec<u8> {
}
let mut out = Vec::with_capacity(total);
out.extend_from_slice(b"DR2S");
for v in [1u32, s.fills.len() as u32, s.outlines.len() as u32, s.polylines.len() as u32, s.arcs.len() as u32, s.lines.len() as u32, texts.len() as u32, n_pts as u32, n_dash as u32, str_bytes as u32, 0] {
for v in [1u32, s.fills.len() as u32, s.outlines.len() as u32, s.polylines.len() as u32, s.arcs.len() as u32, s.lines.len() as u32, texts.len() as u32, n_pts as u32, n_dash as u32, str_bytes as u32, s.line_ends] {
out.extend_from_slice(&v.to_le_bytes());
}
out.extend_from_slice(&pts);
@@ -830,6 +853,7 @@ mod tests {
],
arcs: vec![SArc { center: v2(1.0, 1.0), from: v2(2.0, 1.0), to: v2(1.0, 2.0), r: 1.0, color: [1.0, 0.0, 0.0, 1.0], width_mm: 0.125, dash: SDash::Absent }],
lines: vec![SLine { a: v2(0.0, 0.0), b: v2(2600000.5, 1200000.25), color: [0.0, 0.5, 0.0, 1.0], width_mm: 0.35, dash: SDash::List(vec![3.0, 1.0, 0.5, 1.0]), z: 4.0 }],
line_ends: 0,
};
let t = |x: f64, y: f64, content: &str, size_mm: f64, color: Rgba, align: u32| SText { pos: v2(x, y), size_mm, color, align, content: content.as_bytes().to_vec() };
let texts = vec![
@@ -847,6 +871,9 @@ mod tests {
assert_eq!(encode_scene_bin(&s, &t), FIXTURE);
// Leere Szene = reiner Kopf; Landeskoordinaten bleiben f64.
assert_eq!(encode_scene_bin(&Scene::default(), &[]).len(), 48);
// [146] Linienenden im letzten Kopfwort (früher 0).
let le = encode_scene_bin(&Scene { line_ends: 9, ..Scene::default() }, &[]);
assert_eq!(&le[44..48], &9u32.to_le_bytes());
let mut l = Scene::default();
l.lines.push(SLine { a: v2(2600000.123456, 1200000.654321), b: v2(0.0, 0.0), color: [0.0; 4], width_mm: 0.1, dash: SDash::Null, z: 0.0 });
let b = encode_scene_bin(&l, &[]);
+85 -33
View File
@@ -10,7 +10,10 @@ use crate::hatch::{self, Pattern, V2};
use crate::jsnum;
use crate::plan::print_svg::{hatch_dash_paper, hatch_lines, is_generated, quantize_pen};
use crate::plan::buf::{whole, F_COLOR, F_DASH_LIST, F_GREYED, F_OPACITY, T_ARC, T_CIRCLE, T_DRAWING_ARC, T_DRAWING_TEXT, T_LINE, T_POLYGON, T_TEXT};
use crate::plan::line_ends::LineEnds;
use crate::plan::parts::Part;
use crate::plan::scene::stitch_runs_members;
use std::collections::HashMap;
use serde_json::Value;
use std::f64::consts::PI;
@@ -48,6 +51,53 @@ pub struct SvgOptions {
pub max_y: f64,
/// Schraffurlinien ausbreiten (wie der Druckpfad, an der Fläche beschnitten); Standard aus.
pub hatch: bool,
/// Linienenden und -ecken ([146]) als Attribute eines umschliessenden `<g>`.
pub line_ends: LineEnds,
}
/// Volle, offene Striche gleicher Farbe/Breite/Deckkraft, am Ende zusammengenäht ([146]): Wand-Umrisse
/// zweier Wände treffen sich an der Ecke als EIN Zug mit Ecke (Gehrung) statt mit zwei flachen Enden.
/// Jeder Zug steht an der Stelle seines spätesten Laufs (Zeichen-Reihenfolge wie bisher).
#[derive(Default)]
struct Stitcher {
groups: Vec<(String, Vec<Vec<V2>>, Vec<usize>)>,
of: HashMap<String, usize>,
}
impl Stitcher {
/// `attrs` = ` stroke=… stroke-width=…{op}`; `slot` = Platzhalter in `out`.
fn add(&mut self, attrs: String, run: Vec<V2>, slot: usize) {
let gi = *self.of.entry(attrs.clone()).or_insert_with(|| {
self.groups.push((attrs, Vec::new(), Vec::new()));
self.groups.len() - 1
});
self.groups[gi].1.push(run);
self.groups[gi].2.push(slot);
}
fn finish(self, out: &mut [String], xs: &dyn Fn(f64) -> String, ys: &dyn Fn(f64) -> String) {
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!("<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\"{attrs}/>", 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::<Vec<_>>().join(" ");
let tag = if closed { "polygon" } else { "polyline" };
format!("<{tag} points=\"{pl}\" fill=\"none\"{attrs}/>")
};
if out[slot].is_empty() {
out[slot] = el;
} else {
out[slot].push('\n');
out[slot].push_str(&el);
}
}
}
}
}
/// Zahl aus JSON (null/fehlend → NaN wie `undefined`/`NaN` in JS-Rechnungen).
@@ -91,6 +141,7 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option<String> {
let xs = |x: f64| num(x);
let ys = |y: f64| num(top - y);
let mut out: Vec<String> = Vec::new();
let mut stitch = Stitcher::default();
for part in parts.iter_mut() {
let hatches = if o.hatch { part.view.hatch_table()? } else { Vec::new() };
for i in part.from..part.to {
@@ -128,30 +179,18 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option<String> {
None => Vec::new(),
};
if !nse.is_empty() && stroke != "none" && !stroke.is_empty() {
let k = pts.len();
let mut d = String::new();
for e in 0..k {
if nse.contains(&e) {
continue;
}
if e == 0 || nse.contains(&(e - 1)) {
d.push_str(&format!("M{},{}", xs(pts[e].x), ys(pts[e].y)));
}
let q = pts[(e + 1) % k];
d.push_str(&format!(" L{},{}", xs(q.x), ys(q.y)));
}
out.push(format!("<polygon points=\"{pl}\" fill=\"{fill}\" stroke=\"none\"{}/>", op(greyed, opacity(4))));
if !d.is_empty() {
out.push(format!(
"<path d=\"{d}\" fill=\"none\" stroke=\"{stroke}\" stroke-width=\"{}\" stroke-linejoin=\"round\" stroke-linecap=\"round\"{}/>",
num(f[2] * mm_to_m),
op(greyed, opacity(4))
));
// Sichtbare Kantenläufe zum Zusammennähen ([146]), Kanten in Ring-Reihenfolge.
let nse_f: Vec<f64> = 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)));
for run in crate::plan::scene::visible_edge_runs(&pts, &nse_f) {
out.push(String::new());
stitch.add(attrs.clone(), run, out.len() - 1);
}
continue;
}
out.push(format!(
"<polygon points=\"{pl}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"{}\" stroke-linejoin=\"round\"{}/>",
"<polygon points=\"{pl}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"{}\"{}/>",
num(f[2] * mm_to_m),
op(greyed, opacity(4))
));
@@ -196,11 +235,14 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option<String> {
}
T_LINE => {
let color = if fl & F_COLOR != 0 { esc(part.str(f[1]).unwrap_or("")) } else { "#000".into() };
let mut dash = dash_attr(part)?;
// [141] Volle Linien mit runder Kappe wie Bildschirm (render2d) und Druck: Wand-Umrisse
// zweier Wände treffen sich an der Ecke ohne Kerbe (Stumpf-Kappe liess sie offen).
if dash.is_empty() {
dash = " stroke-linecap=\"round\"".into();
let dash = dash_attr(part)?;
// [146] Volle Linien: mit Kantenläufen gleicher Farbe/Breite zusammennähen (Ecke statt
// zweier Enden); Enden und Ecken erben die Projekt-Einstellung vom `<g>`.
if dash.is_empty() && f[2] > 0.0 {
out.push(String::new());
let attrs = format!(" stroke=\"{color}\" stroke-width=\"{}\"{}", num(f[2] * mm_to_m), op(greyed, opacity(3)));
stitch.add(attrs, vec![V2 { x: f[4], y: f[5] }, V2 { x: f[6], y: f[7] }], out.len() - 1);
continue;
}
out.push(format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{color}\" stroke-width=\"{}\"{dash}{}/>",
@@ -326,8 +368,10 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option<String> {
}
}
}
stitch.finish(&mut out, &xs, &ys);
out.retain(|s| !s.is_empty());
Some(format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"{} 0 {} {}\" width=\"{}mm\" height=\"{}mm\">\n<rect x=\"{}\" y=\"0\" width=\"{}\" height=\"{}\" fill=\"#ffffff\"/>\n{}\n</svg>\n",
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"{} 0 {} {}\" width=\"{}mm\" height=\"{}mm\">\n<rect x=\"{}\" y=\"0\" width=\"{}\" height=\"{}\" fill=\"#ffffff\"/>\n<g {}>\n{}\n</g>\n</svg>\n",
num(x0),
num(w),
num(h),
@@ -336,6 +380,7 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option<String> {
num(x0),
num(w),
num(h),
o.line_ends.svg_attrs(),
out.join("\n")
))
}
@@ -355,10 +400,11 @@ mod tests {
assert_eq!(op(false, Some(1.0)), "");
}
/// [141] Wand-Umrisse als volle Linien bzw. offene Kantenläufe (Stossfugen nicht gestrichen) tragen
/// runde Kappen: an der Ecke zweier Wände bleibt keine Kerbe (Stumpf-Kappe, halbe Strichbreite).
/// [146] Wand-Umrisse als volle Linie bzw. offene Kantenläufe (Stossfugen nicht gestrichen) werden
/// an der gemeinsamen Ecke zu EINEM Zug genäht (Gehrung statt zweier flacher Enden = keine Kerbe);
/// Enden und Ecken stehen einmal am umschliessenden `<g>`.
#[test]
fn umriss_mit_runder_kappe() {
fn umriss_ecke_als_zug() {
use crate::model::Vec2;
use crate::plan::buf::{View, Writer};
use crate::plan::prim::Primitive;
@@ -392,10 +438,16 @@ mod tests {
let view = View::parse(&bytes).unwrap();
let n = view.len();
let mut parts = vec![Part::new(view, 0, n).unwrap()];
let svg = plan_svg(&mut parts, &SvgOptions { scale_denominator: 50.0, margin_m: 0.5, min_x: 0.0, min_y: 0.0, max_x: 4.0, max_y: 4.0, hatch: false }).unwrap();
let path = svg.lines().find(|l| l.starts_with("<path")).unwrap();
assert!(path.contains("stroke-linecap=\"round\""), "{path}");
let line = svg.lines().find(|l| l.starts_with("<line")).unwrap();
assert!(line.contains("stroke-linecap=\"round\""), "{line}");
let opts = |line_ends| SvgOptions { scale_denominator: 50.0, margin_m: 0.5, min_x: 0.0, min_y: 0.0, max_x: 4.0, max_y: 4.0, hatch: false, line_ends };
let svg = plan_svg(&mut parts, &opts(LineEnds::default())).unwrap();
assert!(svg.contains("<g stroke-linecap=\"butt\" stroke-linejoin=\"miter\" stroke-miterlimit=\"4\">"), "{svg}");
assert!(!svg.contains("<path"), "keine einzelnen Kantenläufe mehr: {svg}");
// Lauf (4,0)→(0,0) des Polygons und die Linie (0,0)→(0,4) bilden einen Zug mit Ecke in (0,0).
let pl = svg.lines().find(|l| l.starts_with("<polyline")).unwrap();
assert!(pl.contains("points=\"4,4.5 0,4.5 0,0.5\"") || pl.contains("points=\"0,0.5 0,4.5 4,4.5\""), "{pl}");
assert!(!pl.contains("linecap"), "{pl}");
let mut parts = vec![Part::new(View::parse(&bytes).unwrap(), 0, n).unwrap()];
let svg = plan_svg(&mut parts, &opts(LineEnds { cap: 1, join: 2 })).unwrap();
assert!(svg.contains("<g stroke-linecap=\"round\" stroke-linejoin=\"bevel\""), "{svg}");
}
}