diff --git a/TODO.md b/TODO.md index 132f7e80..b42c6a1d 100644 --- a/TODO.md +++ b/TODO.md @@ -1588,6 +1588,31 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). Offen: Verschieben/Griffe und Objekt-Info für Dach-Öffnungen (Info zeigt Wand-Felder), Fenster-/Türliste (Geschoss aus der Wand), Löschen des Dachs löscht die Fenster nicht mit (Prüfung meldet den fehlenden Wirt), Eindeckrahmen nur als flacher Ring, Lukarnen, nicht in der Tauri-App geprüft. · M +- ◐ **[110] Linientyp ohne Strichstärke.** (30.10., Wunsch Maintainer: „Volllinie 0.5/0.35 soll es nicht + geben") Ein Linienstil ist nur Muster (Volllinie, Strich, Punkt, Zickzack, Motiv) + Farbe; die Stärke trägt + das Element (`Drawing2D.weightMm`, sonst Ebene), die Schraffur (neu `HatchStyle.lineWeight`, Default 0.13), + die Schichtfuge (neu `Layer.jointWeightMm`) bzw. Override (`lineweight`). `LineStyle.weight` nur noch für + die Migration gelesen (Format 4, `migrate_line_weights`): Stärke an die Verwender, Stile, die sich nur in + der Stärke unterscheiden, zusammengeführt („Volllinie 0.02/0.13/0.25/0.5" → „Volllinie"). Musterhaus, + Standards (keine „Schraffurlinie 0.10" mehr; „Strichlinie", „Strichlinie lang", „Strichlinie kurz"), + PDF-Import (Strichlinien als 0.02-Element), Ressourcen-Manager (Linien ohne Stärke; Schraffur: Strichstärke; + Aufbau: Fugen-Strichstärke). Geprüft: Rust-/vitest-Tests; CLI-Szenen (Grundriss 1:50/1:100, Schnitte) und + DXF von Musterhaus und einem Format-3-Projekt mit allen Standards vor/nach der Migration bytegleich (Linux). + Offen: nicht in der Tauri-App geprüft. · S +- ◐ **[109] SIA-400-Schraffuren überarbeitet.** (30.10., Maintainer: „einige Schraffuren sehen trashy aus, + Dämmung ist ein spezieller Sinus") Kern-Generator (`hatch.rs`) kennt Schicht-Muster, die über die GANZE + Schichtdicke spannen und entlang der Schicht laufen (breite Flächen in Bänder à ~0.3 m geteilt): Dämmschlange + (`insulation`, Schlaufenlinie u = a·t + R·sin t, v = h·cos t, Steigung 0.45·Dicke), Hartschaum-Zickzack + (`insulationHard`), Holzfaser-Welle (`insulationWave`), Holz im Querschnitt als Diagonalkreuz je Feld + (`timber`); dazu Naturstein-Doppellinien (`stone`), Erdreich-Flechtmuster (`earth`), Kies-Kreise + (`gravel`). Standards neu abgestimmt (Abstände im Modell 0.025–0.09 m ≈ 0.5–1.8 mm Papier in 1:50/1:100; + Musterlinien 0.10/0.13 mm). Schnitt: Dachschichten-Muster folgen der Dachneigung, Deckenschichten liegen + (Achse 0°, vorher 90°), einschalige Wände wie Schicht-Bänder (vorher Grundriss-Winkel). DXF: Kurven-Muster + als Polylinien; Ressourcen-Vorschau zeichnet Vektor-Schraffuren mit dem Kern-Generator. Geprüft: Rust- + Tests, CLI-Grundriss 1:50/1:100 und Schnitte (Wand, Decke, Dach) aller Standard-Baustoffe angesehen + (Linux). Offen: 3D-Live-Schnitt (render3d) zeigt neue Muster vereinfacht (Zickzack/Kreuz/Diagonal); + Projekte mit Standards vom 29.10. behalten die alten Schraffur-Definitionen (Standards laden ergänzt nur); + Alt-Pfade `planToPrintSvg`/SVG-PlanView zeichnen neue Muster als Diagonale; nicht in der Tauri-App geprüft. · M - ◐ **[105] Fenster/Türen: Rahmen-Detail, Anschlag je Seite, Türzargen-Arten.** (29.10., Wunsch Maintainer „so tief wie ArchiCAD“) Neue optionale Modellfelder (nur Rust-Modell): `frameDetail` am Fenster-/Türtyp und feldweise an der Öffnung (`Opening.frameDetail`): Blendrahmen-Breite je Seite, Tiefe/Lage, Flügelrahmen (Breite, Tiefe, Überschlag), Pfosten/ diff --git a/src-tauri/core/src/document.rs b/src-tauri/core/src/document.rs index be44b25a..19b74fd0 100644 --- a/src-tauri/core/src/document.rs +++ b/src-tauri/core/src/document.rs @@ -819,7 +819,7 @@ mod tests { assert_eq!(d.project().unwrap().walls.len(), 0); assert_eq!(d.field("openings").unwrap()[0]["kind"], "door"); assert!(d.undo().is_none()); - assert!(d.serialize().starts_with("{\n \"formatVersion\": 3,\n \"id\": \"q\"")); + assert!(d.serialize().starts_with("{\n \"formatVersion\": 4,\n \"id\": \"q\"")); } #[test] diff --git a/src-tauri/core/src/hatch.rs b/src-tauri/core/src/hatch.rs index 89e4f794..d3abd9a7 100644 --- a/src-tauri/core/src/hatch.rs +++ b/src-tauri/core/src/hatch.rs @@ -1,6 +1,7 @@ //! Schraffur- und Linienmuster-Geometrie des Grundrisses ([K3b], früher `glPlanHatch.ts`): //! Linie/Segment/Polylinie gegen ein (konkaves) Polygon clippen (even-odd, halb-offene Kanten), -//! Geradenscharen (diagonal/kreuz/eigenes Motiv), Dämmungswelle, deterministische Random- +//! Geradenscharen (diagonal/kreuz/Doppellinie/eigenes Motiv), Schicht-Muster über die ganze Dicke +//! (Dämmschlange, Zickzack, Welle, Holzkreuz, [109]), Erdreich, Kies, deterministische Random- //! Schraffur (mulberry32, modellraum-stabil), Strichmuster (`apply_dash_runs`), Zickzack und //! Motiv-Kachelung entlang einer Strecke. //! @@ -43,6 +44,12 @@ pub enum Pattern { Crosshatch = 3, Insulation = 4, Custom = 5, + InsulationHard = 6, + InsulationWave = 7, + Timber = 8, + Earth = 9, + Gravel = 10, + Stone = 11, } impl Pattern { @@ -53,6 +60,12 @@ impl Pattern { 3 => Pattern::Crosshatch, 4 => Pattern::Insulation, 5 => Pattern::Custom, + 6 => Pattern::InsulationHard, + 7 => Pattern::InsulationWave, + 8 => Pattern::Timber, + 9 => Pattern::Earth, + 10 => Pattern::Gravel, + 11 => Pattern::Stone, _ => Pattern::Diagonal, } } @@ -397,8 +410,14 @@ pub fn build_hatch_runs(poly: &[V2], hatch: &Hatch) -> Vec { if hatch.kind == HatchKind::Vector && hatch.random { return build_random_hatch_runs(poly, hatch, Some(scale)); } - if pattern == Pattern::Insulation { - return insulation_runs(poly, hatch, scale); + match pattern { + Pattern::Insulation => return insulation_runs(poly, hatch, scale), + Pattern::InsulationHard => return zigzag_band_runs(poly, hatch, scale), + Pattern::InsulationWave => return wave_band_runs(poly, hatch, scale), + Pattern::Timber => return timber_band_runs(poly, hatch, scale), + Pattern::Earth => return earth_runs(poly, hatch, scale), + Pattern::Gravel => return gravel_runs(poly, hatch, scale), + _ => {} } let spacing_m = 8.0 * scale * PX_TO_M; let rot = to_model_angle_rad(hatch.angle); @@ -417,69 +436,225 @@ pub fn build_hatch_runs(poly: &[V2], hatch: &Hatch) -> Vec { runs.push(vec![a, b]); } } + // Naturstein: jede Musterlinie als Doppellinie (zweite um 18 % des Abstands versetzt). + if pattern == Pattern::Stone { + for (a, b) in hatch_line_family(poly, a1, spacing_m, 0.18 * spacing_m, anchor) { + runs.push(vec![a, b]); + } + } runs } -/// Dämmungswelle (Kachel 14×10·scale px, zwei quadratische Béziers je Welle). -fn insulation_runs(poly: &[V2], hatch: &Hatch, scale: f64) -> Vec { +// ── Schicht-Muster (SIA 400, [109]) ────────────────────────────────────────── +// +// Dämmschlange, Zickzack, Welle und Holzkreuz spannen über die GANZE Schichtdicke: das Polygon wird +// im Musterrahmen (u = Laufrichtung = Schraffurwinkel, bei Wänden wandbezogen also die Wandachse; +// v quer dazu) vermessen, die Dicke ist seine Ausdehnung in v. Sehr breite Flächen (keine Schicht, +// z. B. eine freie 2D-Fläche) werden in Bänder von etwa `BAND_ROW_M` geteilt. + +/// Bis zu dieser Dicke (m · scale) zeichnet ein Schichtmuster EINE Schlange über die ganze Dicke. +const BAND_MAX_M: f64 = 0.6; +/// Bandhöhe (m · scale) beim Teilen breiter Flächen. +const BAND_ROW_M: f64 = 0.3; +/// Kleinste Musterlänge (m): dünne Schichten werden nicht zu Brei. +const BAND_MIN_PITCH_M: f64 = 0.012; +/// Grenze der Stützpunkte je Muster (Schutz gegen entartete Eingaben). +const BAND_MAX_POINTS: f64 = 400_000.0; + +/// Musterrahmen eines Polygons: Achsen, Ausdehnung in u, Bänder (Mitte v, halbe Höhe). +struct Band { + u: V2, + v: V2, + u0: f64, + u1: f64, + /// Phase entlang u (Projektion des Ankers): benachbarte Flächen setzen gleich an. + ua: f64, + rows: Vec<(f64, f64)>, +} + +impl Band { + fn at(&self, u: f64, v: f64) -> V2 { + v2(self.u.x * u + self.v.x * v, self.u.y * u + self.v.y * v) + } +} + +fn band_frame(poly: &[V2], hatch: &Hatch, scale: f64) -> Option { let rot = to_model_angle_rad(hatch.angle); - let wavelength = 14.0 * scale * PX_TO_M; - let row_gap = 10.0 * scale * PX_TO_M; - let u_dir = rotate(v2(1.0, 0.0), rot); - let v_dir = rotate(v2(0.0, 1.0), rot); - let (mut u_min, mut u_max, mut v_min, mut v_max) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY); + let u = rotate(v2(1.0, 0.0), rot); + let v = rotate(v2(0.0, 1.0), rot); + let (mut u0, mut u1, mut v0, mut v1) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY); for p in poly { - let u = p.x * u_dir.x + p.y * u_dir.y; - let v = p.x * v_dir.x + p.y * v_dir.y; - if u < u_min { - u_min = u; - } - if u > u_max { - u_max = u; - } - if v < v_min { - v_min = v; - } - if v > v_max { - v_max = v; - } + let pu = p.x * u.x + p.y * u.y; + let pv = p.x * v.x + p.y * v.y; + u0 = u0.min(pu); + u1 = u1.max(pu); + v0 = v0.min(pv); + v1 = v1.max(pv); } - if !(u_max > u_min) || !(v_max > v_min) { + let t = v1 - v0; + if !(u1 > u0) || !(t > 1e-6) || !(u1 - u0).is_finite() || !t.is_finite() { + return None; + } + let n = if t <= BAND_MAX_M * scale { 1.0 } else { (t / (BAND_ROW_M * scale)).ceil() }; + if !(n.is_finite()) || n > 10_000.0 { + return None; + } + let h = t / n; + let rows = (0..n as usize).map(|i| (v0 + (i as f64 + 0.5) * h, h / 2.0)).collect(); + let anchor = hatch.origin.unwrap_or(v2(0.0, 0.0)); + Some(Band { u, v, u0, u1, ua: anchor.x * u.x + anchor.y * u.y, rows }) +} + +/// Linienzug aus `f(x) → (Δu, v)` über die Bandlänge, `x` in Schritten `dx`, geclippt. +fn band_curve(poly: &[V2], b: &Band, vc: f64, margin: f64, dx: f64, f: impl Fn(f64) -> (f64, f64)) -> Vec { + let x0 = ((b.u0 - b.ua - margin) / dx).floor() * dx; + let x1 = b.u1 - b.ua + margin; + if !(dx > 1e-9) || (x1 - x0) / dx > BAND_MAX_POINTS { return Vec::new(); } - const STEPS: f64 = 22.0; - let du = wavelength / STEPS; - let to_world = |u: f64, v: f64| v2(u_dir.x * u + v_dir.x * v, u_dir.y * u + v_dir.y * v); - let first_row = (v_min / row_gap - 0.5).floor() - 1.0; - let last_row = (v_max / row_gap - 0.5).ceil() + 1.0; - let u_start = ((u_min - wavelength) / du).floor() * du; - let u_end = u_max + wavelength; - if !(last_row - first_row).is_finite() || !(u_end - u_start).is_finite() { - return Vec::new(); + let mut pts = Vec::new(); + let mut x = x0; + while x <= x1 + 1e-12 { + let (du, dv) = f(x); + pts.push(b.at(b.ua + du, vc + dv)); + x += dx; } - let half = wavelength / 2.0; - let wave_at = |u: f64| -> f64 { - let phase = ((u % wavelength) + wavelength) % wavelength; - let t = (phase % half) / half; - let mag = 12.0 * scale * PX_TO_M * t * (1.0 - t); - if phase < half { - mag - } else { - -mag - } - }; + clip_polyline_to_polygon(&pts, poly) +} + +/// Dämmschlange (SIA 400, weiche Dämmung): fortlaufende, sich überlappende Schlaufen über die +/// ganze Schichtdicke — eine „Sinuslinie mit Schlaufen" (projizierte Schraubenlinie): +/// `u = a·t + R·sin t`, `v = h·cos t`, Steigung `P = 2πa` ≈ 0.45 · Dicke, Schlaufenbreite `R` = ⅔ P. +fn insulation_runs(poly: &[V2], hatch: &Hatch, scale: f64) -> Vec { + let Some(b) = band_frame(poly, hatch, scale) else { return Vec::new() }; let mut runs = Vec::new(); - let mut r = first_row; - while r <= last_row { - let v_base = (r + 0.5) * row_gap; - let mut wave_pts = Vec::new(); - let mut u = u_start; - while u <= u_end + 1e-9 { - wave_pts.push(to_world(u, v_base + wave_at(u))); - u += du; + for &(vc, half) in &b.rows { + let pitch = (0.45 * 2.0 * half * scale).max(BAND_MIN_PITCH_M); + let a = pitch / (2.0 * PI); + let r = pitch * (2.0 / 3.0); + // Parameter t läuft gleichmässig; 36 Stützpunkte je Schlaufe. + let dt = 2.0 * PI / 36.0; + runs.extend(band_curve(poly, &b, vc, r + pitch, a * dt, |x| { + let t = x / a; + (a * t + r * jsnum::sin(t), half * jsnum::cos(t)) + })); + } + runs +} + +/// Hartschaum (EPS/XPS): Zickzack über die ganze Dicke, halbe Periode = 0.5 · Dicke · scale. +fn zigzag_band_runs(poly: &[V2], hatch: &Hatch, scale: f64) -> Vec { + let Some(b) = band_frame(poly, hatch, scale) else { return Vec::new() }; + let mut runs = Vec::new(); + for &(vc, half) in &b.rows { + let hp = (0.5 * 2.0 * half * scale).max(BAND_MIN_PITCH_M); + runs.extend(band_curve(poly, &b, vc, hp, hp, |x| { + let k = jsnum::round(x / hp); + (x, if (k as i64).rem_euclid(2) == 0 { half } else { -half }) + })); + } + runs +} + +/// Holzfaser-Dämmung: Sinuswelle über die ganze Dicke, Periode = 1.2 · Dicke · scale. +fn wave_band_runs(poly: &[V2], hatch: &Hatch, scale: f64) -> Vec { + let Some(b) = band_frame(poly, hatch, scale) else { return Vec::new() }; + let mut runs = Vec::new(); + for &(vc, half) in &b.rows { + let period = (1.2 * 2.0 * half * scale).max(BAND_MIN_PITCH_M); + let w = 2.0 * PI / period; + runs.extend(band_curve(poly, &b, vc, period, period / 32.0, |x| (x, half * jsnum::cos(w * x)))); + } + runs +} + +/// Holz im Querschnitt: Diagonalkreuz je quadratischem Feld (Seite = Dicke · scale) — zwei +/// gegenläufige Zickzacks über die ganze Dicke. +fn timber_band_runs(poly: &[V2], hatch: &Hatch, scale: f64) -> Vec { + let Some(b) = band_frame(poly, hatch, scale) else { return Vec::new() }; + let mut runs = Vec::new(); + for &(vc, half) in &b.rows { + let side = (2.0 * half * scale).max(BAND_MIN_PITCH_M); + for sign in [1.0, -1.0] { + runs.extend(band_curve(poly, &b, vc, side, side, |x| { + let k = jsnum::round(x / side); + (x, if (k as i64).rem_euclid(2) == 0 { sign * half } else { -sign * half }) + })); } - runs.extend(clip_polyline_to_polygon(&wave_pts, poly)); - r += 1.0; + } + runs +} + +/// Rasterzellen (i, j) über das Polygon im Musterrahmen (Zellgrösse `cell`), mit Zellen-Grenze. +fn cells_over(poly: &[V2], u: V2, v: V2, cell: f64) -> Option<(f64, f64, f64, f64)> { + let (mut u0, mut u1, mut v0, mut v1) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY); + for p in poly { + let pu = p.x * u.x + p.y * u.y; + let pv = p.x * v.x + p.y * v.y; + u0 = u0.min(pu); + u1 = u1.max(pu); + v0 = v0.min(pv); + v1 = v1.max(pv); + } + let (i0, i1, j0, j1) = ((u0 / cell).floor(), (u1 / cell).floor(), (v0 / cell).floor(), (v1 / cell).floor()); + let n = (i1 - i0 + 1.0) * (j1 - j0 + 1.0); + (n.is_finite() && n <= 250_000.0 && cell > 1e-9).then_some((i0, i1, j0, j1)) +} + +/// Erdreich: Flechtmuster — je Zelle drei kurze parallele Striche, von Zelle zu Zelle um 90° +/// gewechselt (mit dem Schraffurwinkel gedreht, Standard 45°). Zelle 0.15 m · scale. +fn earth_runs(poly: &[V2], hatch: &Hatch, scale: f64) -> Vec { + let rot = to_model_angle_rad(hatch.angle); + let (u, v) = (rotate(v2(1.0, 0.0), rot), rotate(v2(0.0, 1.0), rot)); + let cell = 0.15 * scale; + let Some((i0, i1, j0, j1)) = cells_over(poly, u, v, cell) else { return Vec::new() }; + let at = |a: f64, b: f64| v2(u.x * a + v.x * b, u.y * a + v.y * b); + let mut runs = Vec::new(); + let mut j = j0; + while j <= j1 { + let mut i = i0; + while i <= i1 { + let along_u = (i + j).rem_euclid(2.0) == 0.0; + for k in [0.25, 0.5, 0.75] { + let (a, b) = if along_u { + (at((i + 0.15) * cell, (j + k) * cell), at((i + 0.85) * cell, (j + k) * cell)) + } else { + (at((i + k) * cell, (j + 0.15) * cell), at((i + k) * cell, (j + 0.85) * cell)) + }; + for (sa, sb) in clip_segment_to_polygon(a, b, poly) { + runs.push(vec![sa, sb]); + } + } + i += 1.0; + } + j += 1.0; + } + runs +} + +/// Kies: kleine Kreise (Ø 25–55 % der Zelle) auf gestreutem Raster, modellraum-stabil. +/// Zelle 0.05 m · scale. +fn gravel_runs(poly: &[V2], hatch: &Hatch, scale: f64) -> Vec { + let cell = 0.05 * scale; + let Some((i0, i1, j0, j1)) = cells_over(poly, v2(1.0, 0.0), v2(0.0, 1.0), cell) else { return Vec::new() }; + let seed = hatch.seed.unwrap_or(0.0); + let mut runs = Vec::new(); + let mut j = j0; + while j <= j1 { + let mut i = i0; + while i <= i1 { + let mut rnd = Mulberry32 { a: hash_cell(i, j, seed) }; + let r = cell * (0.125 + 0.15 * rnd.next()); + let cx = (i + 0.5) * cell + (rnd.next() - 0.5) * (cell - 2.0 * r); + let cy = (j + 0.5) * cell + (rnd.next() - 0.5) * (cell - 2.0 * r); + let ring: Vec = (0..=12).map(|k| { + let a = k as f64 * PI / 6.0; + v2(cx + r * jsnum::cos(a), cy + r * jsnum::sin(a)) + }).collect(); + runs.extend(clip_polyline_to_polygon(&ring, poly)); + i += 1.0; + } + j += 1.0; } runs } @@ -761,6 +936,86 @@ mod tests { assert!(build_hatch_runs(&p, &hatch(Pattern::Insulation)).is_empty()); } + fn band(len: f64, t: f64) -> Vec { + vec![v2(0.0, 0.0), v2(len, 0.0), v2(len, t), v2(0.0, t)] + } + + fn extent(runs: &[Run], f: impl Fn(&V2) -> f64) -> (f64, f64) { + runs.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(f(p)), hi.max(f(p)))) + } + + /// [109] Schicht-Muster spannen über die ganze Schichtdicke und laufen entlang der Schicht. + #[test] + fn schichtmuster_ueber_ganze_dicke() { + for pat in [Pattern::Insulation, Pattern::InsulationHard, Pattern::InsulationWave, Pattern::Timber] { + let mut h = hatch(pat); + h.angle = 0.0; + let runs = build_hatch_runs(&band(1.0, 0.16), &h); + assert!(!runs.is_empty(), "{pat:?}"); + let (lo, hi) = extent(&runs, |p| p.y); + assert!(lo < 0.005 && hi > 0.155, "{pat:?}: {lo}..{hi}"); + let (ulo, uhi) = extent(&runs, |p| p.x); + assert!(ulo < 0.02 && uhi > 0.98, "{pat:?}: {ulo}..{uhi}"); + // Wand senkrecht (Winkel −90°): Muster läuft in y, spannt die Dicke in x. + h.angle = -90.0; + let vert: Vec = band(1.0, 0.16).iter().map(|p| v2(p.y, p.x)).collect(); + let (xlo, xhi) = extent(&build_hatch_runs(&vert, &h), |p| p.x); + assert!(xlo < 0.005 && xhi > 0.155, "{pat:?} senkrecht: {xlo}..{xhi}"); + } + } + + /// Die Dämmschlange bildet Schlaufen (läuft stellenweise zurück), Steigung ≈ 0.45 · Dicke. + #[test] + fn daemmschlange_hat_schlaufen() { + let mut h = hatch(Pattern::Insulation); + h.angle = 0.0; + let runs = build_hatch_runs(&band(2.0, 0.2), &h); + let back = runs.iter().any(|r| r.windows(2).any(|w| w[1].x < w[0].x - 1e-6)); + assert!(back, "Schlaufen fehlen"); + // Scheitel oben: Anzahl Annäherungen an die Oberkante ≈ Länge / Steigung (2.0 / 0.09 ≈ 22). + let tops = runs.iter().flat_map(|r| r.windows(3)).filter(|w| w[1].y > w[0].y && w[1].y >= w[2].y && w[1].y > 0.199).count(); + assert!((19..=25).contains(&tops), "{tops}"); + } + + /// Breite Flächen werden in Bänder geteilt (keine riesige Schlange). + #[test] + fn breite_flaeche_in_baender() { + let mut h = hatch(Pattern::InsulationHard); + h.angle = 0.0; + let runs = build_hatch_runs(&band(1.0, 1.2), &h); + let max_rise = runs.iter().flat_map(|r| r.windows(2)).map(|w| (w[1].y - w[0].y).abs()).fold(0.0, f64::max); + assert!(max_rise < 0.31 && max_rise > 0.29, "{max_rise}"); + } + + #[test] + fn erdreich_kies_naturstein() { + let sq = band(1.0, 1.0); + for pat in [Pattern::Earth, Pattern::Gravel, Pattern::Stone] { + let runs = build_hatch_runs(&sq, &hatch(pat)); + assert!(!runs.is_empty(), "{pat:?}"); + let (lo, hi) = extent(&runs, |p| p.x); + assert!(lo >= -1e-9 && hi <= 1.0 + 1e-9, "{pat:?} ausserhalb"); + } + // Kies: geschlossene Kreise, gleiche Fläche → gleiche Steine (modellraum-stabil). + let a = build_hatch_runs(&sq, &hatch(Pattern::Gravel)); + assert_eq!(a, build_hatch_runs(&sq, &hatch(Pattern::Gravel))); + assert!(a.iter().filter(|r| r.len() == 13 && r[0] == r[12]).count() > 300); + // Naturstein: doppelt so viele Linien wie Diagonal. + let d = build_hatch_runs(&sq, &hatch(Pattern::Diagonal)).len() as f64; + let st = build_hatch_runs(&sq, &hatch(Pattern::Stone)).len() as f64; + assert!((st / d - 2.0).abs() < 0.1, "{st} / {d}"); + } + + #[test] + fn schichtmuster_entartet_leer() { + let p = vec![v2(0.0, 0.0), v2(f64::INFINITY, 0.0), v2(1.0, 1.0)]; + for pat in [Pattern::InsulationHard, Pattern::InsulationWave, Pattern::Timber, Pattern::Earth, Pattern::Gravel, Pattern::Stone] { + assert!(build_hatch_runs(&p, &hatch(pat)).is_empty(), "{pat:?}"); + } + // Linie ohne Dicke + assert!(build_hatch_runs(&[v2(0.0, 0.0), v2(1.0, 0.0), v2(2.0, 0.0)], &hatch(Pattern::Insulation)).is_empty()); + } + #[test] fn strichmuster_zerlegt() { let run = vec![v2(0.0, 0.0), v2(1.0, 0.0)]; diff --git a/src-tauri/core/src/import_drawing.rs b/src-tauri/core/src/import_drawing.rs index 18458797..655329da 100644 --- a/src-tauri/core/src/import_drawing.rs +++ b/src-tauri/core/src/import_drawing.rs @@ -745,7 +745,7 @@ fn plan_dash_styles(dashes: &[(String, Vec)], existing: &[Value], name_temp } used.insert(id.clone()); let name = name_template.replace("{pattern}", &label); - created.push(json!({"id": id, "name": name, "weight": 0.02, "color": "#1a1a1a", "dash": dash.iter().map(|&d| js_num(d)).collect::>()})); + created.push(json!({"id": id, "name": name, "color": "#1a1a1a", "dash": dash.iter().map(|&d| js_num(d)).collect::>()})); by_layer.insert(layer.clone(), id); } (created, by_layer) @@ -897,6 +897,8 @@ pub fn import_ops(root: &Map, d: &DrawingImport, dec: &Decision, o.insert("geom".into(), geom); if let Some(s) = style_by_layer.get(&c.layer).filter(|s| !s.is_empty()) { o.insert("lineStyleId".into(), s.clone().into()); + // Strichlinien aus dem PDF als Haarlinie (die Stärke trägt das Element, nicht der Linienstil, [110]). + o.insert("weightMm".into(), json!(0.02)); } if c.filled && is_polyline { let fill = d.layer_fill_colors.get(&c.layer).and_then(Value::as_str).unwrap_or(DXF_HATCH_FILL); diff --git a/src-tauri/core/src/import_drawing_tests.rs b/src-tauri/core/src/import_drawing_tests.rs index 47b2e8dc..4c3e9744 100644 --- a/src-tauri/core/src/import_drawing_tests.rs +++ b/src-tauri/core/src/import_drawing_tests.rs @@ -136,7 +136,7 @@ fn pdf_mit_strichmuster() { let dec = decision(json!({"target": {"kind": "existing", "levelId": "eg"}, "categoryMode": "byLayer", "activeCategoryCode": "20", "dashStyleTemplate": "PDF-Strich {pattern}"})); let r = import_ops(&project(), &d, &dec, 0.0); let ops: Vec = r.ops.iter().map(Op::to_json).collect(); - assert_eq!(ops[0]["items"][0], json!({"id": "pdf-dash-1_05_0_7", "name": "PDF-Strich 1.05/0.7", "weight": 0.02, "color": "#1a1a1a", "dash": [1.05, 0.7]})); + assert_eq!(ops[0]["items"][0], json!({"id": "pdf-dash-1_05_0_7", "name": "PDF-Strich 1.05/0.7", "color": "#1a1a1a", "dash": [1.05, 0.7]})); assert_eq!(ops[1]["items"][0]["lineStyleId"], json!("pdf-dash-1_05_0_7")); let info = pdf_page_info(&page); assert_eq!(info["layers"], json!({"PDF 0.18 #ff0000 (Strich 1.05/0.7)": 1, "PDF Fläche #ffffff": 1})); @@ -147,15 +147,15 @@ fn strichmuster_zu_linienstilen() { assert!(same_dash(&[1.05, 0.7], &[1.0, 0.7])); assert!(!same_dash(&[3.0, 1.0], &[1.0, 3.0])); assert!(!same_dash(&[1.0, 1.0], &[1.0, 1.0, 1.0, 1.0])); - let solid = json!({"id": "thin", "name": "Volllinie", "weight": 0.13, "color": "#111", "dash": null}); - let dashed = json!({"id": "d", "name": "Strich", "weight": 0.02, "color": "#111", "dash": [1, 0.7]}); + let solid = json!({"id": "thin", "name": "Volllinie", "color": "#111", "dash": null}); + let dashed = json!({"id": "d", "name": "Strich", "color": "#111", "dash": [1, 0.7]}); let dashes: Vec<(String, Vec)> = vec![("a".into(), vec![1.05, 0.7]), ("b".into(), vec![2.8, 1.4]), ("c".into(), vec![2.8, 1.4]), ("d".into(), vec![0.05, 0.7, 2.8, 0.7])]; let (created, by_layer) = plan_dash_styles(&dashes, &[solid.clone(), dashed], "S {pattern}"); assert_eq!(by_layer["a"], "d"); assert_eq!(created.len(), 2); assert_eq!(by_layer["b"], by_layer["c"]); - assert_eq!(created[0], json!({"id": "pdf-dash-2_8_1_4", "name": "S 2.8/1.4", "weight": 0.02, "color": "#1a1a1a", "dash": [2.8, 1.4]})); + assert_eq!(created[0], json!({"id": "pdf-dash-2_8_1_4", "name": "S 2.8/1.4", "color": "#1a1a1a", "dash": [2.8, 1.4]})); assert_eq!(created[1]["dash"], json!([0.05, 0.7, 2.8, 0.7])); // Gleiche id schon vergeben → Zähler. let taken = json!({"id": "pdf-dash-2_8_1_4", "kind": "dot", "dash": [2.8, 1.4]}); diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs index c4ec39d4..7b838ee9 100644 --- a/src-tauri/core/src/model/generated.rs +++ b/src-tauri/core/src/model/generated.rs @@ -46,15 +46,14 @@ pub struct LineStyleMotif { pub struct LineStyle { pub id: String, pub name: String, - /// @deprecated Die Strichstärke gehört NICHT mehr in den Linienstil — es gibt nur - /// „Vollinie/Strich", die tatsächliche Dicke wird per Element-Attribut (bzw. - /// Ebene/Default) aufgelöst. Das Feld bleibt für die Backward-Compat-Auflösung - /// erhalten und dient den Renderern noch als Fallback für die Muster-/Fugen-Stärke - /// (siehe `resolveHatch` → `HatchRender.lineWeight`). Der Linien-Detail-Editor - /// zeigt es nicht mehr an; neue Linienstile bekommen einen Haarlinien-Default. - /// Die echte per-Element-Strichstärken-Auflösung (Attribut → Ebene → Default) - /// folgt separat mit dem By-Layer/By-Object-Refactor — NICHT hier. - pub weight: f64, + /// @deprecated Nur noch für die Migration alter Dateien gelesen ([110], Format 4): Ein Linienstil + /// legt nur das Muster (Volllinie, Strich, Punkt, Zickzack …) und die Farbe fest — die Strichstärke + /// kommt vom Element (`Drawing2D.weightMm`), der Schraffur (`HatchStyle.lineWeight`), der + /// Schichtfuge (`Layer.jointWeightMm`) bzw. Ebene/Stift. Die Migration trägt das alte Gewicht dort + /// ein und entfernt es hier; die Renderer werten es nicht mehr aus. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub weight: Option, /// Farbe (hex). pub color: String, /// Strichmuster in Millimetern, alternierend AN/AUS (`[on, off, on, off, …]`), @@ -233,6 +232,24 @@ pub enum HatchPattern { Crosshatch, #[serde(rename = "custom")] Custom, + /// Hartschaum (EPS/XPS, [109]): Zickzack über die ganze Schichtdicke. + #[serde(rename = "insulationHard")] + InsulationHard, + /// Holzfaser-Dämmung ([109]): Sinuswelle über die ganze Schichtdicke. + #[serde(rename = "insulationWave")] + InsulationWave, + /// Holz im Querschnitt ([109]): Diagonalkreuz je Querschnittsfeld über die Schichtdicke. + #[serde(rename = "timber")] + Timber, + /// Erdreich ([109]): Gruppen kurzer Striche, wechselnd ±45° (Flechtmuster). + #[serde(rename = "earth")] + Earth, + /// Kies/Geröll ([109]): kleine Kreise auf gestreutem Raster. + #[serde(rename = "gravel")] + Gravel, + /// Naturstein ([109]): Diagonale in Doppellinien. + #[serde(rename = "stone")] + Stone, #[serde(other)] #[ts(skip)] Unknown, @@ -315,10 +332,14 @@ pub struct HatchStyle { /// `plan/generatePlan.ts` → `resolveHatch`). Bei `pattern==="solid"` ist es die /// Vollfüllfarbe, bei `pattern==="none"` ungenutzt. pub color: String, - /// Optionaler Linienstil für die Musterlinien (Line Manager). + /// Optionaler Linienstil für die Musterlinien (Line Manager): nur Muster/Farbe. #[serde(rename = "lineStyleId", default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub line_style_id: Option, + /// Strichstärke der Musterlinien in Papier-mm ([110]); fehlt sie, gilt 0.13. + #[serde(rename = "lineWeight", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub line_weight: Option, /// Steuer-Parameter der Random-Vektor-Schraffur (`kind`/"vector" + `lines`=== /// "random", z. B. Kies/Splitt). ALLE additiv & optional — fehlen sie, gilt das /// bestehende deterministische Streu-Verhalten (Seed aus der Flächen-Bounding-Box, @@ -604,6 +625,10 @@ pub struct Layer { #[serde(rename = "jointLineStyleId", default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub joint_line_style_id: Option, + /// Strichstärke der Schichtfuge in Papier-mm ([110]); fehlt sie, gilt die Standard-Fuge. + #[serde(rename = "jointWeightMm", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub joint_weight_mm: Option, #[serde(flatten)] #[ts(skip)] pub extra: Extra, @@ -3285,7 +3310,7 @@ pub struct Drawing2D { #[ts(optional)] pub fill_color: Option, /// Optionale direkte Strichstärke-Übersteuerung in Millimetern; hat Vorrang - /// vor dem LineStyle-Gewicht und der Kategorie-Strichstärke. + /// vor der Kategorie-Strichstärke (Linienstile tragen keine Stärke, [110]). #[serde(rename = "weightMm", default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub weight_mm: Option, @@ -3301,8 +3326,8 @@ pub struct Drawing2D { #[ts(optional)] pub background_source: Option, /// Quelle der Strichstärke, wenn kein explizites `weightMm` gesetzt ist: - /// "layer" erzwingt `LayerCategory.lw` (unter Umgehung des LineStyle-Gewichts), - /// "object"/`undefined` (Default) = heutige Kette (LineStyle.weight ?? Kategorie). + /// "layer" erzwingt `LayerCategory.lw`, + /// "object"/`undefined` (Default) = Kategorie-Strichstärke. #[serde(rename = "strokeWeightSource", default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub stroke_weight_source: Option, diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index bc365158..93da7a63 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -136,14 +136,14 @@ pub fn emit_slabs(p: &Project) -> Vec { let l = &layers[layer_idx as usize]; let (color, cut) = match p.component(&l.component_id) { Some(comp) => { - let line = resolve_cut_line_style(p, l.joint_line_style_id.as_deref()); + let line = resolve_cut_line_style(p, l); ( hex_to_rgb(&comp.color, style::WALL_RGB), Some(RCutMeta { join_priority: Some(comp.join_priority), component_id: Some(comp.id.clone()), - line_color: line.map(|x| x.0), - line_weight: line.map(|x| x.1), + line_color: line.0, + line_weight: line.1, }), ) } @@ -367,7 +367,7 @@ fn resolve_wall_bands(p: &Project, maps: &[String], wall: &Wall, layered: bool) let mut bands = Vec::with_capacity(wt.layers.len()); for l in &wt.layers { let Some(comp) = p.component(&l.component_id) else { return fallback() }; - let line = resolve_cut_line_style(p, l.joint_line_style_id.as_deref()); + let line = resolve_cut_line_style(p, l); bands.push(WallBand { thickness: l.thickness, color: hex_to_rgb(&comp.color, WALL_RGB), @@ -375,8 +375,8 @@ fn resolve_wall_bands(p: &Project, maps: &[String], wall: &Wall, layered: bool) material_index: material_layer(p, maps, &l.component_id), priority: Some(comp.join_priority), component_id: Some(comp.id.clone()), - cut_line_color: line.map(|x| x.0), - cut_line_weight: line.map(|x| x.1), + cut_line_color: line.0, + cut_line_weight: line.1, }); } (bands, true) @@ -1606,8 +1606,8 @@ pub fn emit_roof_cut_layers(p: &Project) -> Result, String> { continue; } let color = roof_color(p, override_color, &layer.component_id)?; - let line = resolve_cut_line_style(p, layer.joint_line_style_id.as_deref()); - let cut = line.map(|(c, w)| RCutMeta { line_color: Some(c), line_weight: Some(w), ..Default::default() }); + let line = resolve_cut_line_style(p, &layer); + let cut = (line.0.is_some() || line.1.is_some()).then(|| RCutMeta { line_color: line.0, line_weight: line.1, ..Default::default() }); for (i, plane) in g.planes.iter().enumerate() { let nrm = plane_normal_up(plane); let polygon: Vec = plane.iter().map(|q| [q[0] - nrm[0] * offset_above, q[1] - nrm[1] * offset_above, q[2] - nrm[2] * offset_above]).collect(); diff --git a/src-tauri/core/src/plan/drawings.rs b/src-tauri/core/src/plan/drawings.rs index b2f41ef6..067663dd 100644 --- a/src-tauri/core/src/plan/drawings.rs +++ b/src-tauri/core/src/plan/drawings.rs @@ -575,7 +575,7 @@ fn emit_inner(c: &Ctx, d: &Drawing2D, attrs: Attrs, geom: &Drawing2DGeom, greyed let ls_idx = attrs.line_style_id.filter(|s| !s.is_empty()).and_then(|id| p.line_styles.iter().position(|l| l.id == id)); let ls = ls_idx.map(|i| &p.line_styles[i]); let color = attrs.color.or(ls.map(|l| l.color.as_str())).or(category.map(|k| k.color.as_str())).unwrap_or(MONO_INK); - let weight = resolve_stroke_weight(attrs.weight, d.stroke_weight_source, category, ls.map(|l| l.weight).or(category.map(|k| k.lw)).unwrap_or(WALL_FALLBACK_MM)); + let weight = resolve_stroke_weight(attrs.weight, d.stroke_weight_source, category, category.map(|k| k.lw).unwrap_or(WALL_FALLBACK_MM)); let dash_scale = match d.dash_scale { Some(s) if s > 0.0 => s, _ => 1.0, diff --git a/src-tauri/core/src/plan/section.rs b/src-tauri/core/src/plan/section.rs index 7a79494d..8a2847c0 100644 --- a/src-tauri/core/src/plan/section.rs +++ b/src-tauri/core/src/plan/section.rs @@ -26,7 +26,9 @@ const SECTION_HIDDEN_MM: f64 = 0.13; const SECTION_HIDDEN_DASH: [f64; 2] = [0.12, 0.08]; /// Achswinkel geschnittener Wände/Decken für wandrelative Muster (s. `toSection.ts`). const SECTION_WALL_AXIS_ANGLE_DEG: f64 = 90.0; -const SECTION_SLAB_AXIS_ANGLE_DEG: f64 = 90.0; +/// Decken liegen: wandbezogene Muster laufen waagrecht entlang der Schicht ([109]; vorher 90° wie Wände, +/// dann lagen Querstriche der Dämmung längs und die Dämmschlange stand quer). +const SECTION_SLAB_AXIS_ANGLE_DEG: f64 = 0.0; /// Seitenrand (m) der Geländelinie um den Inhalt des Schnitts. const TERRAIN_MARGIN: f64 = 6.0; /// Neutrale Füllung geschnittener freier Körper. @@ -434,7 +436,9 @@ fn wall_section_style(p: &Project, wall: &Wall) -> Option<(String, HatchRender)> } let best = best?; let category = p.layer_category(&wall.category_code); - let angle = atan2(wall.end.y - wall.start.y, wall.end.x - wall.start.x) * 180.0 / std::f64::consts::PI; + // Im Schnitt steht die geschnittene Wand senkrecht — wandbezogene Muster wie bei den Schicht-Bändern + // (`split_wall_layers`), nicht nach dem Grundriss-Winkel der Wand ([109]). + let angle = SECTION_WALL_AXIS_ANGLE_DEG; let hatch_id = resolve_hatch_id(wall.hatch_id.as_deref(), wall.hatch_source, category, Some(&best.hatch_id)).unwrap_or(&best.hatch_id); let hatch = resolve_hatch(p, hatch_id, Some(angle), resolve_foreground(best, wall.foreground.as_deref(), category, wall.foreground_source), None)?; Some((poche_fill(hatch.pattern).to_string(), hatch)) @@ -902,7 +906,9 @@ fn append_roof_sections(cuts: &mut Vec, p: &Project, plane: &Plane) { for h in &holes { pieces = pieces.iter().flat_map(|pc| crate::opening_shape::subtract_convex(pc, h)).collect(); } - let hatch = if layer.component_id.is_empty() { None } else { p.component(&layer.component_id).and_then(|comp| resolve_hatch(p, &comp.hatch_id, None, None, None)) }; + // Wandbezogene Muster laufen entlang der Dachneigung ([109]: Dämmschlange über die Schichtdicke). + let slope_deg = atan2(z1 - z0, t_hi - t_lo) * 180.0 / std::f64::consts::PI; + let hatch = if layer.component_id.is_empty() { None } else { p.component(&layer.component_id).and_then(|comp| resolve_hatch(p, &comp.hatch_id, Some(slope_deg), None, None)) }; for pts in pieces { let mut c = Cut::new(Kind::Roof, index, pts); if let Some(h) = &hatch { diff --git a/src-tauri/core/src/plan/style.rs b/src-tauri/core/src/plan/style.rs index cff86d36..dcac22f7 100644 --- a/src-tauri/core/src/plan/style.rs +++ b/src-tauri/core/src/plan/style.rs @@ -101,7 +101,7 @@ pub fn resolve_hatch(p: &Project, hatch_id: &str, wall_angle_deg: Option, f angle, origin: p_origin, color: foreground.unwrap_or(HATCH_INK).to_string(), - line_weight: ls.map_or(0.13, |l| l.weight), + line_weight: h.line_weight.unwrap_or(0.13), dash: ls.and_then(|l| l.dash.clone()), kind: h.kind, lines: h.lines, diff --git a/src-tauri/core/src/plan/walls.rs b/src-tauri/core/src/plan/walls.rs index c6267a09..0749542c 100644 --- a/src-tauri/core/src/plan/walls.rs +++ b/src-tauri/core/src/plan/walls.rs @@ -236,7 +236,7 @@ fn wall_poche(c: &Ctx, out: &mut Vec, e: &EffWall, gaps: &[(f64, f64) a, b, "layer-joint", - jls.map_or(layer_mm, |s| s.weight * detail.layer_factor()), + wt.layers.get(li).and_then(|l| l.joint_weight_mm).filter(|w| w.is_finite() && *w > 0.0).map_or(layer_mm, |w| w * detail.layer_factor()), Some(jls.and_then(|s| s.dash.clone())), Some(jls.map_or(stroke, |s| s.color.as_str())), greyed, diff --git a/src-tauri/core/src/plan_buf.rs b/src-tauri/core/src/plan_buf.rs index fb8842ee..27305ebf 100644 --- a/src-tauri/core/src/plan_buf.rs +++ b/src-tauri/core/src/plan_buf.rs @@ -2045,6 +2045,12 @@ fn write_hatch_words(out: &mut Vec, h: &HatchRender, color: f64) { HatchPattern::Crosshatch => 3.0, HatchPattern::Insulation => 4.0, HatchPattern::Custom => 5.0, + HatchPattern::InsulationHard => 6.0, + HatchPattern::InsulationWave => 7.0, + HatchPattern::Timber => 8.0, + HatchPattern::Earth => 9.0, + HatchPattern::Gravel => 10.0, + HatchPattern::Stone => 11.0, _ => 2.0, }; let kind = match h.kind { diff --git a/src-tauri/core/src/plan_dxf.rs b/src-tauri/core/src/plan_dxf.rs index d27dfc0b..6b16a7da 100644 --- a/src-tauri/core/src/plan_dxf.rs +++ b/src-tauri/core/src/plan_dxf.rs @@ -523,10 +523,18 @@ fn dash_seg(a: V2, b: V2, cycle: &[f64]) -> Vec<(V2, V2)> { out } +/// Muster, die nicht als DXF-Linienscharen gehen und als Polylinien geschrieben werden ([109]). +fn is_curve_pattern(p: Pattern) -> bool { + matches!( + p, + Pattern::Insulation | Pattern::InsulationHard | Pattern::InsulationWave | Pattern::Timber | Pattern::Earth | Pattern::Gravel | Pattern::Stone + ) +} + /// Linienscharen einer Vektor-Schraffur als (Winkel rad, Abstand m) (`hatchFamilies`). fn hatch_families(h: &Hatch) -> Vec<(f64, f64)> { let unit_m = 1.0 / 90.0; - let tile_m = (if h.pattern == Pattern::Insulation { 10.0 } else { 8.0 }) * h.scale * unit_m; + let tile_m = 8.0 * h.scale * unit_m; let spacing = jsnum::max(0.02, tile_m); if !spacing.is_finite() { return Vec::new(); @@ -536,9 +544,6 @@ fn hatch_families(h: &Hatch) -> Vec<(f64, f64)> { if h.pattern == Pattern::Crosshatch { out.push((angle + PI / 2.0, spacing)); } - if h.pattern == Pattern::Insulation { - out.push((angle - PI / 4.0, spacing)); - } out } @@ -929,6 +934,14 @@ impl Ctx<'_> { None => self.flat.add_line(b, hatch_layer, a, q), } } + } else if is_curve_pattern(pattern) { + // Schicht-/Kurvenmuster ([109]: Dämmschlange, Zickzack, Welle, Holzkreuz, Erdreich, + // Kies, Naturstein) kennt DXF-HATCH nicht: als Polylinien aus dem Kern-Generator. + let runs = hatch::apply_dash_runs(hatch::build_hatch_runs(pts, &h.h), &hatch::hatch_dash(&h.h)); + self.flat.set_pen(b, -1.0); + for run in runs.iter().filter(|r| r.len() >= 2) { + self.flat.add_polyline(b, hatch_layer, run, false); + } } else if pattern != Pattern::None { let families = hatch_families(&h.h); if !families.is_empty() { diff --git a/src-tauri/core/src/project_format.rs b/src-tauri/core/src/project_format.rs index c375c80e..d6bc2bac 100644 --- a/src-tauri/core/src/project_format.rs +++ b/src-tauri/core/src/project_format.rs @@ -9,7 +9,7 @@ use serde_json::{Map, Value}; /// Aktuelle Version des Dateiformats. Bei jeder Formatänderung erhöhen + Migration anhängen. -pub const PROJECT_FORMAT_VERSION: u64 = 3; +pub const PROJECT_FORMAT_VERSION: u64 = 4; const REQUIRED_ARRAYS: [&str; 3] = ["walls", "layers", "drawingLevels"]; const DEFAULT_ARRAYS: [&str; 5] = ["lineStyles", "hatches", "components", "wallTypes", "drawings2d"]; @@ -236,6 +236,128 @@ pub fn parse_project_file(text: &str, now_ms: f64) -> Parsed { } } +/// Name ohne angehängte Strichstärke („Volllinie 0.13" → „Volllinie", „Schraffurlinie 0.10 mm" → +/// „Schraffurlinie"); sonst unverändert. +fn strip_weight_suffix(name: &str) -> String { + let t = name.trim_end(); + let t = t.strip_suffix("mm").map_or(t, str::trim_end); + let Some(pos) = t.rfind(' ') else { return name.to_string() }; + let tail = &t[pos + 1..]; + if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit() || c == '.' || c == ',') && tail.chars().any(|c| c.is_ascii_digit()) { + t[..pos].trim_end().to_string() + } else { + name.to_string() + } +} + +/// 3 → 4 ([110]): Linienstile tragen keine Strichstärke mehr. Das alte `LineStyle.weight` wandert an +/// die Verwender — Schraffur (`lineWeight`), Schichtfuge der Aufbauten (`jointWeightMm`), 2D-Element +/// (`weightMm`, nur wo es vorher galt: kein eigenes `weightMm`, Quelle nicht „layer") und Override- +/// Aktion (`lineweight`) —, damit Pläne gleich aussehen. Danach werden Stile, die sich nur in der +/// Stärke unterschieden, zu einem zusammengeführt (erster gewinnt, Name ohne Stärke-Anhang). +fn migrate_line_weights(mut raw: Map) -> Map { + let Some(Value::Array(styles)) = raw.get("lineStyles").cloned() else { return raw }; + let mut weight: std::collections::HashMap = std::collections::HashMap::new(); + // Gruppen gleicher Stile ohne id/Name/Stärke → kanonische id. + let mut canon: std::collections::HashMap = std::collections::HashMap::new(); + let mut by_key: Vec<(String, String)> = Vec::new(); + let mut kept: Vec = Vec::new(); + for st in styles { + let Value::Object(mut o) = st else { + kept.push(st); + continue; + }; + let id = o.get("id").and_then(Value::as_str).unwrap_or("").to_string(); + if let Some(w) = o.get("weight").and_then(Value::as_f64).filter(|w| w.is_finite()) { + weight.insert(id.clone(), w); + } + o.shift_remove("weight"); + let mut key_obj = o.clone(); + key_obj.shift_remove("id"); + key_obj.shift_remove("name"); + if key_obj.get("dash").is_some_and(Value::is_null) { + key_obj.shift_remove("dash"); + } + let key = Value::Object(key_obj).to_string(); + if let Some((_, first)) = by_key.iter().find(|(k, _)| *k == key) { + if !id.is_empty() { + canon.insert(id, first.clone()); + } + continue; + } + if let Some(n) = o.get("name").and_then(Value::as_str) { + // Ohne Stärke-Anhang, solange der Name dadurch nicht doppelt wird. + let stripped = strip_weight_suffix(n); + if !kept.iter().any(|k| k.get("name").and_then(Value::as_str) == Some(stripped.as_str())) { + o.insert("name".into(), stripped.into()); + } + } + by_key.push((key, id)); + kept.push(Value::Object(o)); + } + raw.insert("lineStyles".into(), Value::Array(kept)); + let canon_of = |id: &str| canon.get(id).cloned().unwrap_or_else(|| id.to_string()); + let weight_of = |v: Option<&Value>| v.and_then(Value::as_str).filter(|s| !s.is_empty()).and_then(|id| weight.get(id).copied()); + let num = |w: f64| serde_json::Number::from_f64(w).map(Value::Number); + let redirect = |o: &mut Map, key: &str| { + if let Some(Value::String(id)) = o.get(key) { + let c = canon_of(id); + o.insert(key.into(), c.into()); + } + }; + // Schraffuren. + if let Some(Value::Array(hs)) = raw.get_mut("hatches") { + for h in hs.iter_mut().filter_map(Value::as_object_mut) { + if !h.contains_key("lineWeight") { + if let Some(w) = weight_of(h.get("lineStyleId")).and_then(num) { + h.insert("lineWeight".into(), w); + } + } + redirect(h, "lineStyleId"); + } + } + // Schichtfugen der Aufbauten. + for key in ["wallTypes", "ceilingTypes", "roofTypes"] { + let Some(Value::Array(ts)) = raw.get_mut(key) else { continue }; + for t in ts.iter_mut().filter_map(Value::as_object_mut) { + let Some(Value::Array(ls)) = t.get_mut("layers") else { continue }; + for l in ls.iter_mut().filter_map(Value::as_object_mut) { + if !l.contains_key("jointWeightMm") { + if let Some(w) = weight_of(l.get("jointLineStyleId")).and_then(num) { + l.insert("jointWeightMm".into(), w); + } + } + redirect(l, "jointLineStyleId"); + } + } + } + // 2D-Elemente. + if let Some(Value::Array(ds)) = raw.get_mut("drawings2d") { + for d in ds.iter_mut().filter_map(Value::as_object_mut) { + let layer_src = d.get("strokeWeightSource").and_then(Value::as_str) == Some("layer"); + if !layer_src && !d.get("weightMm").is_some_and(Value::is_number) { + if let Some(w) = weight_of(d.get("lineStyleId")).and_then(num) { + d.insert("weightMm".into(), w); + } + } + redirect(d, "lineStyleId"); + } + } + // Override-Regeln. + if let Some(Value::Array(rs)) = raw.get_mut("overrideRules") { + for r in rs.iter_mut().filter_map(Value::as_object_mut) { + let Some(Value::Object(a)) = r.get_mut("actions") else { continue }; + if !a.get("lineweight").is_some_and(Value::is_number) { + if let Some(w) = weight_of(a.get("linetypeId")).and_then(num) { + a.insert("lineweight".into(), w); + } + } + redirect(a, "linetypeId"); + } + } + raw +} + /// Wie [`parse_project_file`], für ein bereits geparstes Objekt. pub fn parse_project_object(raw: Value, now_ms: f64) -> Parsed { let Value::Object(mut obj) = raw else { return Parsed::Err("Die Datei enthält kein Dossier-Projekt.".into()) }; @@ -267,6 +389,7 @@ pub fn parse_project_object(raw: Value, now_ms: f64) -> Parsed { obj = match i { 1 => migrate_doors(obj), 2 => migrate_layout_annotations(obj), + 3 => migrate_line_weights(obj), _ => obj, // 0 → 1: Einführung von `formatVersion`; Inhalt unverändert. }; } @@ -456,11 +579,67 @@ mod tests { json!({"id":"p","name":"N","walls":[],"layers":[],"drawingLevels":[]}) } + /// [110]: Stärke wandert vom Linienstil an Schraffur, Fuge, Element und Override; Stile, die sich + /// nur in der Stärke unterscheiden, werden eins. + #[test] + fn linienstaerke_wandert_an_die_verwender() { + let v = json!({"formatVersion": 3, "id":"p","name":"N","walls":[],"layers":[],"drawingLevels":[], + "lineStyles": [ + {"id":"hair","name":"Volllinie 0.02","weight":0.02,"color":"#1a1a1a","dash":null}, + {"id":"thin","name":"Volllinie 0.13","weight":0.13,"color":"#1a1a1a","dash":null}, + {"id":"thick","name":"Volllinie 0.5 mm","weight":0.5,"color":"#1a1a1a"}, + {"id":"dash","name":"Strich","weight":0.02,"color":"#1a1a1a","dash":[1,0.7]}, + {"id":"dark","name":"Volllinie 0.5","weight":0.5,"color":"#0a0a0a","dash":null} + ], + "hatches": [ + {"id":"h1","name":"A","pattern":"diagonal","scale":1,"angle":45,"color":"#000","lineStyleId":"hair"}, + {"id":"h2","name":"B","pattern":"diagonal","scale":1,"angle":45,"color":"#000","lineStyleId":"thick","lineWeight":0.18}, + {"id":"h3","name":"C","pattern":"diagonal","scale":1,"angle":45,"color":"#000"} + ], + "wallTypes": [{"id":"w","name":"W","layers":[{"componentId":"c","thickness":0.1,"jointLineStyleId":"thin"},{"componentId":"c","thickness":0.1}]}], + "roofTypes": [{"id":"r","name":"R","layers":[{"componentId":"c","thickness":0.1,"jointLineStyleId":"dash"}]}], + "drawings2d": [ + {"id":"d1","lineStyleId":"thick"}, + {"id":"d2","lineStyleId":"thick","weightMm":0.7}, + {"id":"d3","lineStyleId":"thick","strokeWeightSource":"layer"} + ], + "overrideRules": [{"id":"o","actions":{"linetypeId":"thin"}}] + }); + let Parsed::Ok { project: p, migrated_from, .. } = parse_project_object(v, 0.0) else { panic!() }; + assert_eq!(migrated_from, Some(3)); + assert_eq!(p["lineStyles"], json!([ + {"id":"hair","name":"Volllinie","color":"#1a1a1a","dash":null}, + {"id":"dash","name":"Strich","color":"#1a1a1a","dash":[1,0.7]}, + {"id":"dark","name":"Volllinie 0.5","color":"#0a0a0a","dash":null} + ])); + assert_eq!(p["hatches"][0]["lineWeight"], json!(0.02)); + assert_eq!(p["hatches"][1]["lineWeight"], json!(0.18)); + assert_eq!(p["hatches"][1]["lineStyleId"], json!("hair")); + assert!(p["hatches"][2].get("lineWeight").is_none()); + let wl = &p["wallTypes"][0]["layers"]; + assert_eq!((wl[0]["jointWeightMm"].clone(), wl[0]["jointLineStyleId"].clone()), (json!(0.13), json!("hair"))); + assert!(wl[1].get("jointWeightMm").is_none()); + assert_eq!(p["roofTypes"][0]["layers"][0]["jointWeightMm"], json!(0.02)); + let d = &p["drawings2d"]; + assert_eq!((d[0]["weightMm"].clone(), d[0]["lineStyleId"].clone()), (json!(0.5), json!("hair"))); + assert_eq!(d[1]["weightMm"], json!(0.7)); + assert!(d[2].get("weightMm").is_none()); + assert_eq!(p["overrideRules"][0]["actions"], json!({"linetypeId":"hair","lineweight":0.13})); + } + + #[test] + fn staerke_anhang_im_namen() { + assert_eq!(strip_weight_suffix("Volllinie 0.13"), "Volllinie"); + assert_eq!(strip_weight_suffix("Schraffurlinie 0.10 mm"), "Schraffurlinie"); + assert_eq!(strip_weight_suffix("Strichlinie fein"), "Strichlinie fein"); + assert_eq!(strip_weight_suffix("PDF-Strich 1.05/0.7"), "PDF-Strich 1.05/0.7"); + } + #[test] fn alte_datei_wird_migriert_und_ergaenzt() { let Parsed::Ok { project, warnings, migrated_from } = parse_project_object(minimal(), 0.0) else { panic!() }; assert_eq!(migrated_from, Some(0)); - assert_eq!(project["formatVersion"], 3); + assert_eq!(project["formatVersion"], 4); assert_eq!(project["lineStyles"], json!([])); assert!(warnings.is_empty()); } @@ -604,6 +783,6 @@ mod tests { fn serialisierung_setzt_version_nach_vorn() { let Value::Object(m) = minimal() else { panic!() }; let s = serialize_project(&m); - assert!(s.starts_with("{\n \"formatVersion\": 3,\n \"id\": \"p\"")); + assert!(s.starts_with("{\n \"formatVersion\": 4,\n \"id\": \"p\"")); } } diff --git a/src-tauri/core/src/selection_info.rs b/src-tauri/core/src/selection_info.rs index 9caaed28..f42973f5 100644 --- a/src-tauri/core/src/selection_info.rs +++ b/src-tauri/core/src/selection_info.rs @@ -1150,7 +1150,6 @@ fn drawing_selection(root: &Map, d: &Value) -> J { let cat_lw = cat.and_then(|c| nn(field(c, "lw"))); let weight = nn(field(d, "weightMm")) .or_else(|| if str_of(field(d, "strokeWeightSource")) != Some("object") { cat_lw } else { None }) - .or_else(|| ls.and_then(|l| nn(field(l, "weight")))) .or(cat_lw) .cloned() .unwrap_or_else(|| js_num(WALL_FALLBACK_MM)); diff --git a/src-tauri/core/src/standards.rs b/src-tauri/core/src/standards.rs index 708fe1eb..7f7e1d02 100644 --- a/src-tauri/core/src/standards.rs +++ b/src-tauri/core/src/standards.rs @@ -34,29 +34,37 @@ fn material(id: &str, size_m: f64) -> Value { const INK: &str = "#1a1a1a"; -/// Linientypen (SIA 400 / ISO 128). Strichmuster in Papier-mm (AN/AUS, 0 = Punkt), unabhängig vom Massstab. +/// Linientypen (SIA 400 / ISO 128): nur Muster und Farbe — die Strichstärke kommt vom Element, der +/// Schraffur, der Schichtfuge bzw. Ebene/Stift ([110]). Strichmuster in Papier-mm (AN/AUS, 0 = Punkt), +/// unabhängig vom Massstab. pub fn line_styles() -> Vec { - let dash = |id: &str, name: &str, w: f64, d: Value| json!({"id": id, "name": name, "weight": w, "color": INK, "dash": d}); + let dash = |id: &str, name: &str, d: Value| json!({"id": id, "name": name, "color": INK, "dash": d}); vec![ - dash("std-ls-voll", "Volllinie", 0.25, Value::Null), - dash("std-ls-strich-fein", "Strichlinie fein", 0.18, json!([3, 1.5])), - dash("std-ls-strich-grob", "Strichlinie grob", 0.5, json!([6, 2])), - dash("std-ls-punkt", "Punktlinie", 0.25, json!([0, 1])), - dash("std-ls-strichpunkt", "Strichpunktlinie (Achse)", 0.18, json!([12, 1.5, 0, 1.5])), - dash("std-ls-strichzweipunkt", "Strich-Zweipunktlinie", 0.18, json!([12, 1.5, 0, 1.5, 0, 1.5])), - dash("std-ls-grundstueck", "Grundstücksgrenze", 0.5, json!([8, 1.5, 0, 1.5, 0, 1.5])), - dash("std-ls-bauteilgrenze", "Baulinie / Bauteilgrenze", 0.35, json!([8, 1.5, 0, 1.5])), - json!({"id": "std-ls-bruch", "name": "Bruchlinie (Zickzack)", "weight": 0.18, "color": INK, "dash": null, + dash("std-ls-voll", "Volllinie", Value::Null), + dash("std-ls-strich-fein", "Strichlinie", json!([3, 1.5])), + dash("std-ls-strich-grob", "Strichlinie lang", json!([6, 2])), + dash("std-ls-punkt", "Punktlinie", json!([0, 1])), + dash("std-ls-strichpunkt", "Strichpunktlinie (Achse)", json!([12, 1.5, 0, 1.5])), + dash("std-ls-strichzweipunkt", "Strich-Zweipunktlinie", json!([12, 1.5, 0, 1.5, 0, 1.5])), + dash("std-ls-grundstueck", "Grundstücksgrenze", json!([8, 1.5, 0, 1.5, 0, 1.5])), + dash("std-ls-bauteilgrenze", "Baulinie / Bauteilgrenze", json!([8, 1.5, 0, 1.5])), + json!({"id": "std-ls-bruch", "name": "Bruchlinie (Zickzack)", "color": INK, "dash": null, "kind": "zigzag", "zigzag": {"amplitude": 1.5, "wavelength": 4}}), - dash("std-ls-schraffur", "Schraffurlinie 0.10", 0.1, Value::Null), - dash("std-ls-schraffur-strich", "Schraffurlinie gestrichelt", 0.1, json!([1, 0.7])), + dash("std-ls-schraffur-strich", "Strichlinie kurz", json!([1, 0.7])), + dash("std-ls-schraffur-punkt", "Punktlinie kurz", json!([0.5, 1.6])), ] } -/// Schnittschraffuren (SIA 400). Abstand im Modell (Kachel 8·scale/90 m), Winkel in Grad. +/// Schnittschraffuren nach SIA 400 ([109]). Abstände im Modell (Linienschar: `spacing_m`, intern +/// `scale = spacing_m · 90 / 8`), gewählt für 1:50 (≈ 1–2 mm Papier) und noch ruhig in 1:100; Winkel in +/// Grad; Musterlinien 0.10 mm (dichte Muster) bzw. 0.13 mm (Dämmung, Holz, Backstein) — deutlich feiner als +/// die Schnittkante (0.35–0.5 mm). Schicht-Muster (Dämmschlange, Zickzack, Welle, Holzkreuz) spannen über +/// die ganze Schichtdicke und laufen entlang der Schicht (`relativeToWall`); `scale` streckt dort die +/// Musterlänge relativ zur Dicke. pub fn hatches() -> Vec { - let h = |id: &str, name: &str, pattern: &str, scale: f64, angle: f64, rel: bool, ls: &str| { - let mut v = json!({"id": id, "name": name, "pattern": pattern, "scale": scale, "angle": angle, "color": INK}); + let lines = |id: &str, name: &str, pattern: &str, spacing_m: f64, angle: f64, rel: bool, lw: f64, ls: &str| { + let scale = (spacing_m * 90.0 / 8.0 * 1e4).round() / 1e4; + let mut v = json!({"id": id, "name": name, "pattern": pattern, "scale": scale, "angle": angle, "color": INK, "lineWeight": lw}); if rel { v["relativeToWall"] = json!(true); } @@ -65,32 +73,47 @@ pub fn hatches() -> Vec { } v }; - let solid = |id: &str, name: &str, color: &str| json!({"id": id, "name": name, "pattern": "solid", "scale": 1, "angle": 0, "color": color}); - let random = |id: &str, name: &str, angle: f64, density: f64, lmin: f64, lmax: f64, seed: f64| { - json!({"id": id, "name": name, "kind": "vector", "lines": "random", "pattern": "diagonal", "scale": 1, "angle": angle, - "color": INK, "lineStyleId": "std-ls-schraffur", "density": density, "lengthMin": lmin, "lengthMax": lmax, "seed": seed}) + let layer = |id: &str, name: &str, pattern: &str, scale: f64| { + json!({"id": id, "name": name, "pattern": pattern, "scale": scale, "angle": 0, "relativeToWall": true, "color": INK, "lineWeight": 0.13}) }; + let solid = |id: &str, name: &str, color: &str| json!({"id": id, "name": name, "pattern": "solid", "scale": 1, "angle": 0, "color": color}); vec![ - h("std-h-ohne", "SIA Ohne Schraffur", "none", 1.0, 0.0, false, ""), - h("std-h-stahlbeton", "SIA Stahlbeton", "crosshatch", 0.5, 45.0, false, "std-ls-schraffur"), - h("std-h-beton", "SIA Beton unbewehrt", "crosshatch", 0.6, 45.0, false, "std-ls-schraffur-strich"), - h("std-h-backstein", "SIA Backstein", "diagonal", 0.5, 45.0, true, "std-ls-schraffur"), - h("std-h-kalksandstein", "SIA Kalksandstein", "diagonal", 0.35, 135.0, true, "std-ls-schraffur"), - h("std-h-porenbeton", "SIA Porenbeton", "diagonal", 0.5, 45.0, true, "std-ls-schraffur-strich"), - h("std-h-holz", "SIA Holz (Querschnitt)", "crosshatch", 0.6, 0.0, true, "std-ls-schraffur"), - h("std-h-bsp", "SIA Brettsperrholz", "diagonal", 0.3, 90.0, true, "std-ls-schraffur"), - random("std-h-holzwerkstoff", "SIA Holzwerkstoff", 30.0, 1.4, 0.6, 1.5, 7.0), - h("std-h-daemmung-weich", "SIA Dämmung weich", "insulation", 1.0, 0.0, true, "std-ls-schraffur"), - h("std-h-eps", "SIA Dämmung EPS", "diagonal", 0.45, 0.0, true, "std-ls-schraffur"), - h("std-h-xps", "SIA Dämmung XPS", "crosshatch", 0.45, 0.0, true, "std-ls-schraffur"), - h("std-h-holzfaser", "SIA Dämmung Holzfaser", "insulation", 0.8, 0.0, true, "std-ls-schraffur-strich"), + json!({"id": "std-h-ohne", "name": "SIA Ohne Schraffur", "pattern": "none", "scale": 1, "angle": 0, "color": INK}), + // Stahlbeton: Kreuzschraffur 45°/135°, bildschirmfest. + lines("std-h-stahlbeton", "SIA Stahlbeton", "crosshatch", 0.07, 45.0, false, 0.1, ""), + // Beton unbewehrt: Diagonale 45°, unterbrochen. + lines("std-h-beton", "SIA Beton unbewehrt", "diagonal", 0.07, 45.0, false, 0.1, "std-ls-schraffur-strich"), + // Mauerwerk Backstein: Diagonale 45° zur Wand. + lines("std-h-backstein", "SIA Backstein", "diagonal", 0.06, 45.0, true, 0.13, ""), + // Kalksandstein: Diagonale gegenläufig (135°), enger. + lines("std-h-kalksandstein", "SIA Kalksandstein", "diagonal", 0.045, 135.0, true, 0.1, ""), + // Porenbeton: Diagonale 45°, weit, lange Striche. + lines("std-h-porenbeton", "SIA Porenbeton", "diagonal", 0.09, 45.0, true, 0.1, "std-ls-strich-fein"), + // Holz im Querschnitt: Diagonalkreuz je Feld über die Dicke. + layer("std-h-holz", "SIA Holz (Querschnitt)", "timber", 1.0), + // Brettsperrholz: Lamellenfugen längs der Schicht. + lines("std-h-bsp", "SIA Brettsperrholz", "diagonal", 0.04, 90.0, true, 0.1, ""), + // Holzwerkstoff (Span-/OSB-Platte): kurze, gestreute Späne. + json!({"id": "std-h-holzwerkstoff", "name": "SIA Holzwerkstoff", "kind": "vector", "lines": "random", "pattern": "diagonal", "scale": 1, + "angle": 30, "color": INK, "lineWeight": 0.1, "density": 2, "lengthMin": 0.15, "lengthMax": 0.3, "seed": 7}), + // Dämmung weich (Mineral-/Steinwolle, Trittschall): Dämmschlange über die ganze Dicke. + layer("std-h-daemmung-weich", "SIA Dämmung weich", "insulation", 1.0), + // Hartschaum: Zickzack über die Dicke; XPS dichter als EPS (SIA 400 unterscheidet sie nicht). + layer("std-h-eps", "SIA Dämmung EPS", "insulationHard", 1.0), + layer("std-h-xps", "SIA Dämmung XPS", "insulationHard", 0.7), + // Holzfaser: Welle über die Dicke. + layer("std-h-holzfaser", "SIA Dämmung Holzfaser", "insulationWave", 1.0), solid("std-h-gips", "SIA Gips", "#cfcfcf"), - h("std-h-estrich", "SIA Estrich", "diagonal", 0.35, 45.0, false, "std-ls-schraffur-strich"), + // Estrich/Überzug: feines Punktfeld (punktierte Diagonale). + lines("std-h-estrich", "SIA Estrich", "diagonal", 0.025, 45.0, false, 0.1, "std-ls-schraffur-punkt"), solid("std-h-stahl", "SIA Stahl", INK), solid("std-h-alu", "SIA Aluminium", "#8c8c8c"), - h("std-h-naturstein", "SIA Naturstein", "diagonal", 0.8, 45.0, false, "std-ls-voll"), - random("std-h-erdreich", "SIA Erdreich", 45.0, 0.8, 1.5, 4.0, 11.0), - random("std-h-kies", "SIA Kies / Sauberkeitsschicht", 60.0, 1.8, 0.4, 0.9, 13.0), + // Naturstein: Diagonale in Doppellinien. + lines("std-h-naturstein", "SIA Naturstein", "stone", 0.08, 45.0, false, 0.1, ""), + // Erdreich: Flechtmuster kurzer Striche ±45°. + lines("std-h-erdreich", "SIA Erdreich", "earth", 0.0889, 45.0, false, 0.1, ""), + // Kies/Sauberkeitsschicht: kleine Kreise gestreut. + lines("std-h-kies", "SIA Kies / Sauberkeitsschicht", "gravel", 0.0889, 0.0, false, 0.1, ""), ] } @@ -333,7 +356,7 @@ mod tests { let tb = p.components.iter().find(|c| c.id == "std-c-trapezblech").unwrap().material.as_ref().unwrap(); assert!(tb.color.is_none() && tb.library_id.as_deref() == Some("CorrugatedSteel005")); // Linientypen - for name in ["Volllinie", "Strichlinie fein", "Strichlinie grob", "Punktlinie", "Strichpunktlinie (Achse)", "Strich-Zweipunktlinie", "Grundstücksgrenze", "Bruchlinie (Zickzack)"] { + for name in ["Volllinie", "Strichlinie", "Strichlinie lang", "Punktlinie", "Strichpunktlinie (Achse)", "Strich-Zweipunktlinie", "Grundstücksgrenze", "Bruchlinie (Zickzack)"] { assert!(p.line_styles.iter().any(|l| l.name == name), "{name}"); } } @@ -348,14 +371,14 @@ mod tests { fn gleichnamige_bleiben_und_verweise_zeigen_darauf() { let mut root = empty_root(); root.insert("components".into(), json!([{"id": "brick", "name": "backstein ", "color": "#8c5544", "hatchId": "x", "joinPriority": 50}])); - root.insert("lineStyles".into(), json!([{"id": "thin", "name": "Schraffurlinie 0.10", "weight": 0.1, "color": "#000", "dash": null}])); + root.insert("lineStyles".into(), json!([{"id": "thin", "name": "Strichlinie kurz", "color": "#000", "dash": [1, 0.7]}])); let r = apply(&root, &merge_ops(&root)); let comps = r["components"].as_array().unwrap(); assert_eq!(comps.iter().filter(|c| c["name"].as_str().unwrap().trim().eq_ignore_ascii_case("backstein")).count(), 1); assert_eq!(comps[0]["color"], "#8c5544", "vorhandenes Bauteil unverändert"); let iw = r["wallTypes"].as_array().unwrap().iter().find(|t| t["id"] == "std-wt-iw-backstein").unwrap(); assert_eq!(iw["layers"][1]["componentId"], "brick"); - let bs = r["hatches"].as_array().unwrap().iter().find(|h| h["id"] == "std-h-backstein").unwrap(); - assert_eq!(bs["lineStyleId"], "thin"); + let pb = r["hatches"].as_array().unwrap().iter().find(|h| h["id"] == "std-h-beton").unwrap(); + assert_eq!(pb["lineStyleId"], "thin"); } } diff --git a/src-tauri/core/src/style.rs b/src-tauri/core/src/style.rs index ab574047..87362bc4 100644 --- a/src-tauri/core/src/style.rs +++ b/src-tauri/core/src/style.rs @@ -42,7 +42,10 @@ fn pattern_id(p: HatchPattern) -> f64 { HatchPattern::Solid => 1.0, HatchPattern::Diagonal => 2.0, HatchPattern::Crosshatch => 3.0, - HatchPattern::Insulation => 4.0, + HatchPattern::Insulation | HatchPattern::InsulationHard | HatchPattern::InsulationWave => 4.0, + // 3D-Schnittflächen (render3d) kennen nur die Grundmuster: nächstliegendes ([109]). + HatchPattern::Timber | HatchPattern::Earth => 3.0, + HatchPattern::Gravel | HatchPattern::Stone => 2.0, _ => 0.0, } } @@ -58,13 +61,12 @@ pub struct HatchCore { pub fn resolve_hatch_core(p: &Project, hatch_id: &str, wall_angle_deg: Option) -> Option { let h = p.hatch(hatch_id)?; - let ls = h.line_style_id.as_deref().filter(|s| !s.is_empty()).and_then(|id| p.line_style(id)); let base = h.angle; let angle = match wall_angle_deg { Some(w) if h.relative_to_wall == Some(true) => base - w, _ => base, }; - Some(HatchCore { pattern: h.pattern, scale: h.scale * 1.0, angle, line_weight: ls.map_or(0.13, |l| l.weight) }) + Some(HatchCore { pattern: h.pattern, scale: h.scale * 1.0, angle, line_weight: h.line_weight.unwrap_or(0.13) }) } /// Schnitt-Schraffur eines Bauteils (`resolveComponentHatch`); `axis_angle_deg` 90 für Wand-Bänder, @@ -113,8 +115,10 @@ pub fn dominant_layer_color(p: &Project, layers: &[crate::model::Layer], fallbac } } -/// Stil der Schnitt-Umrisslinie einer Schicht (`resolveCutLineStyle`). -pub fn resolve_cut_line_style(p: &Project, joint_line_style_id: Option<&str>) -> Option<(Rgb, f64)> { - let ls = p.line_styles.iter().find(|l| Some(l.id.as_str()) == joint_line_style_id.filter(|s| !s.is_empty()))?; - Some((hex_to_rgb(&ls.color, DRAWING_LINE_FALLBACK_RGB), ls.weight)) +/// Stil der Schnitt-Umrisslinie einer Schicht (`resolveCutLineStyle`): Farbe aus dem Linienstil der +/// Fuge, Stärke aus der Schicht (`jointWeightMm`, [110]) — beide unabhängig optional. +pub fn resolve_cut_line_style(p: &Project, layer: &crate::model::Layer) -> (Option, Option) { + let id = layer.joint_line_style_id.as_deref().filter(|s| !s.is_empty()); + let ls = id.and_then(|id| p.line_styles.iter().find(|l| l.id == id)); + (ls.map(|ls| hex_to_rgb(&ls.color, DRAWING_LINE_FALLBACK_RGB)), layer.joint_weight_mm.filter(|w| w.is_finite() && *w > 0.0)) } diff --git a/src-tauri/core/tests/fixtures/sample_project.json b/src-tauri/core/tests/fixtures/sample_project.json index 86feb523..d818f057 100644 --- a/src-tauri/core/tests/fixtures/sample_project.json +++ b/src-tauri/core/tests/fixtures/sample_project.json @@ -2,38 +2,15 @@ "id": "demo", "name": "Demo-Haus", "lineStyles": [ - { - "id": "hatch-hair", - "name": "Volllinie 0.02", - "weight": 0.02, - "color": "#1a1a1a", - "dash": null - }, { "id": "thin", - "name": "Volllinie 0.13", - "weight": 0.13, + "name": "Volllinie", "color": "#1a1a1a", "dash": null }, - { - "id": "medium", - "name": "Volllinie 0.25", - "weight": 0.25, - "color": "#1a1a1a", - "dash": null - }, - { - "id": "thick", - "name": "Volllinie 0.5", - "weight": 0.5, - "color": "#0a0a0a", - "dash": null - }, { "id": "hatch-dash", "name": "Dämmungsstrich", - "weight": 0.02, "color": "#1a1a1a", "dash": [ 0.35, @@ -57,7 +34,7 @@ "scale": 1, "angle": 0, "color": "#1a1a1a", - "lineStyleId": "thin" + "lineWeight": 0.13 }, { "id": "diagonal", @@ -66,7 +43,7 @@ "scale": 1, "angle": 45, "color": "#1a1a1a", - "lineStyleId": "thin" + "lineWeight": 0.13 }, { "id": "crosshatch", @@ -75,7 +52,7 @@ "scale": 1, "angle": 0, "color": "#1a1a1a", - "lineStyleId": "thin" + "lineWeight": 0.13 }, { "id": "solid-concrete", @@ -84,7 +61,7 @@ "scale": 1, "angle": 0, "color": "#9aa0a6", - "lineStyleId": "thin" + "lineWeight": 0.13 }, { "id": "sia-concrete", @@ -93,7 +70,7 @@ "scale": 0.5, "angle": 45, "color": "#1a1a1a", - "lineStyleId": "hatch-hair" + "lineWeight": 0.02 }, { "id": "sia-brick", @@ -103,7 +80,7 @@ "angle": 45, "relativeToWall": true, "color": "#1a1a1a", - "lineStyleId": "hatch-hair" + "lineWeight": 0.02 }, { "id": "sia-insulation", @@ -113,7 +90,7 @@ "angle": 0, "relativeToWall": true, "color": "#1a1a1a", - "lineStyleId": "hatch-hair" + "lineWeight": 0.02 } ], "components": [ @@ -222,7 +199,8 @@ { "componentId": "insulation", "thickness": 0.16, - "jointLineStyleId": "thin" + "jointLineStyleId": "thin", + "jointWeightMm": 0.13 }, { "componentId": "brick", @@ -265,7 +243,8 @@ { "componentId": "insulation", "thickness": 0.04, - "jointLineStyleId": "thin" + "jointLineStyleId": "thin", + "jointWeightMm": 0.13 }, { "componentId": "concrete", @@ -286,7 +265,8 @@ { "componentId": "insulation", "thickness": 0.22, - "jointLineStyleId": "thin" + "jointLineStyleId": "thin", + "jointWeightMm": 0.13 }, { "componentId": "render-int", diff --git a/src/core/index.ts b/src/core/index.ts index e4dd06bb..b9c11082 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -131,6 +131,7 @@ export { export { DASH_MM_TO_M, buildRandomHatchRuns, + buildHatchRuns, motifPoints, zigzagPoints, } from "../plan/glPlan/glPlanHatch"; diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 4c049349..eace1109 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1204,6 +1204,9 @@ export const de = { "resources.col.component": "Bauteil", "resources.col.thickness": "Dicke (mm)", "resources.col.joint": "Fuge", + "resources.col.jointWeight": "Fugen-Strichstärke (mm, 0 = Standard)", + "resources.col.hatchLineWeight": "Strichstärke (mm)", + "resources.col.hatchLineWeight.hint": "Stärke der Musterlinien auf dem Papier; der Linienstil legt nur das Muster fest.", "resources.joint.default": "— (Haarlinie)", "resources.layer.add": "Schicht hinzufügen", "resources.layer.remove": "Schicht entfernen", @@ -1405,13 +1408,19 @@ export const de = { // Schraffur-Muster. "pattern.none": "Ohne", "pattern.solid": "Vollfläche", - "pattern.insulation": "Wärmedämmung", + "pattern.insulation": "Wärmedämmung weich (Dämmschlange)", + "pattern.insulationHard": "Wärmedämmung hart (Zickzack)", + "pattern.insulationWave": "Holzfaser-Dämmung (Welle)", + "pattern.timber": "Holz im Querschnitt", + "pattern.stone": "Naturstein", + "pattern.earth": "Erdreich", + "pattern.gravel": "Kies", "pattern.diagonal": "Diagonal", "pattern.crosshatch": "Kreuzschraffur", "pattern.custom": "Eigenes Motiv", // Linien. - "resources.lines.hint": "Strichstärke in Millimetern (Paper-Space). Strichmuster: durchgezogen, gestrichelt oder gepunktet.", + "resources.lines.hint": "Linientyp = Muster (durchgezogen, gestrichelt, gepunktet, Zickzack …) und Farbe. Die Strichstärke legt das Element, die Schraffur, die Schichtfuge oder die Ebene fest.", "resources.lines.empty": "Noch keine Linienstile.", "resources.lines.placeholder": "Linienstil", "resources.col.weight": "Stärke (mm)", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 9e94dc1d..583f894e 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1198,6 +1198,9 @@ export const en: Record = { "resources.col.component": "Component", "resources.col.thickness": "Thickness (mm)", "resources.col.joint": "Joint", + "resources.col.jointWeight": "Joint line weight (mm, 0 = default)", + "resources.col.hatchLineWeight": "Line weight (mm)", + "resources.col.hatchLineWeight.hint": "Weight of the pattern lines on paper; the line style only sets the pattern.", "resources.joint.default": "— (hairline)", "resources.layer.add": "Add layer", "resources.layer.remove": "Remove layer", @@ -1396,12 +1399,18 @@ export const en: Record = { "pattern.none": "None", "pattern.solid": "Solid", - "pattern.insulation": "Insulation", + "pattern.insulation": "Soft insulation (loop line)", + "pattern.insulationHard": "Rigid insulation (zigzag)", + "pattern.insulationWave": "Wood-fibre insulation (wave)", + "pattern.timber": "Timber cross-section", + "pattern.stone": "Natural stone", + "pattern.earth": "Earth", + "pattern.gravel": "Gravel", "pattern.diagonal": "Diagonal", "pattern.crosshatch": "Crosshatch", "pattern.custom": "Custom motif", - "resources.lines.hint": "Line weight in millimetres (paper space). Stroke: solid, dashed or dotted.", + "resources.lines.hint": "Line type = pattern (solid, dashed, dotted, zigzag …) and colour. The line weight is set by the element, the hatch, the layer joint or the layer.", "resources.lines.empty": "No line styles yet.", "resources.lines.placeholder": "Line style", "resources.col.weight": "Weight (mm)", diff --git a/src/io/projectFormat.ts b/src/io/projectFormat.ts index f9b3e1b9..d90b3367 100644 --- a/src/io/projectFormat.ts +++ b/src/io/projectFormat.ts @@ -21,7 +21,7 @@ import { documentFor, sharedDocument } from "../core/document"; import type { LoadFileResult } from "../core/document"; /** Aktuelle Version des Dateiformats (muss `PROJECT_FORMAT_VERSION` im Kern entsprechen — Test). */ -export const PROJECT_FORMAT_VERSION = 3; +export const PROJECT_FORMAT_VERSION = 4; export type ParseProjectResult = LoadFileResult; diff --git a/src/model/richProject.testing.ts b/src/model/richProject.testing.ts index 00d3bad5..53db5b5c 100644 --- a/src/model/richProject.testing.ts +++ b/src/model/richProject.testing.ts @@ -52,7 +52,7 @@ export function richProject(): Project { const lvl = sampleProject.drawingLevels[0].id; return { ...sampleProject, - formatVersion: 3, + formatVersion: 4, // Blatt-Ebene des Layouts „lay1" (2D-Zeichnung auf dem Blatt). drawingLevels: [...sampleProject.drawingLevels, { id: "sheet-lay1", name: "Blatt 1", kind: "drawing", visible: true, locked: false, layoutId: "lay1" }], textStyles: [{ id: "ts1", label: "Titel", marks: { bold: true, font: "Helvetica", sizePt: 14 } }], diff --git a/src/model/sampleProject.ts b/src/model/sampleProject.ts index 617e10b4..a7de1904 100644 --- a/src/model/sampleProject.ts +++ b/src/model/sampleProject.ts @@ -26,18 +26,13 @@ export const sampleProject: Project = { id: "demo", name: "Demo-Haus", // ── Ressourcen-Bibliotheken (zentral verwiesen per id) ────────────────── - // Linienstile: aufgeräumt auf kanonische VOLLLINIEN je Strichstärke (dash=null) - // + eine gestrichelte Linie. Früher gab es drei funktional identische 0.13- - // Volllinien ("thin"/"hatch-line"/"joint-massive") — zusammengeführt auf "thin" - // ("Volllinie 0.13"); Schraffur-/Schichtfugen-Referenzen zeigen jetzt darauf. - // (Die ids bleiben stabil, damit geladene Projekte + interne Referenzen halten.) + // Linienstile: nur Muster + Farbe ([110]) — die Strichstärke tragen Schraffur (`lineWeight`), + // Schichtfuge (`jointWeightMm`) bzw. Element/Ebene. Früher gab es „Volllinie 0.02/0.13/0.25/0.5"; + // zusammengeführt auf „thin" (Volllinie). Die ids bleiben stabil. lineStyles: [ - { id: "hatch-hair", name: "Volllinie 0.02", weight: 0.02, color: "#1a1a1a", dash: null }, - { id: "thin", name: "Volllinie 0.13", weight: 0.13, color: "#1a1a1a", dash: null }, - { id: "medium", name: "Volllinie 0.25", weight: 0.25, color: "#1a1a1a", dash: null }, - { id: "thick", name: "Volllinie 0.5", weight: 0.5, color: "#0a0a0a", dash: null }, - // Gestrichelte Haarlinie für die Dämmung (Striche quer durch die Wanddicke). - { id: "hatch-dash", name: "Dämmungsstrich", weight: 0.02, color: "#1a1a1a", dash: [0.35, 0.3] }, + { id: "thin", name: "Volllinie", color: "#1a1a1a", dash: null }, + // Gestrichelte Linie (z. B. Dämmung, Striche quer durch die Wanddicke). + { id: "hatch-dash", name: "Dämmungsstrich", color: "#1a1a1a", dash: [0.35, 0.3] }, ], // Schraffuren: color = Linien-/Vollfüllfarbe des Musters; angle in Grad. // "none" = keine Schraffur (nur Component-Füllung). @@ -52,7 +47,7 @@ export const sampleProject: Project = { scale: 1, angle: 0, color: "#1a1a1a", - lineStyleId: "thin", + lineWeight: 0.13, }, { id: "diagonal", @@ -61,7 +56,7 @@ export const sampleProject: Project = { scale: 1, angle: 45, color: "#1a1a1a", - lineStyleId: "thin", + lineWeight: 0.13, }, { id: "crosshatch", @@ -70,7 +65,7 @@ export const sampleProject: Project = { scale: 1, angle: 0, color: "#1a1a1a", - lineStyleId: "thin", + lineWeight: 0.13, }, { id: "solid-concrete", @@ -79,7 +74,7 @@ export const sampleProject: Project = { scale: 1, angle: 0, color: "#9aa0a6", - lineStyleId: "thin", + lineWeight: 0.13, }, // ── SIA-Schnittschraffuren (Haarlinie) ────────────────────────────────── // Dichte Teilung (scale < 1; Muster-Kachel = 8·scale) für den SIA-Look. @@ -91,7 +86,7 @@ export const sampleProject: Project = { scale: 0.5, angle: 45, color: "#1a1a1a", - lineStyleId: "hatch-hair", + lineWeight: 0.02, }, // Backstein: Diagonale, 45° RELATIV zur Wandachse (dreht mit der Wand mit). { @@ -102,7 +97,7 @@ export const sampleProject: Project = { angle: 45, relativeToWall: true, color: "#1a1a1a", - lineStyleId: "hatch-hair", + lineWeight: 0.02, }, // Dämmung: DURCHGEZOGENE (nicht gestrichelte) Linien QUER durch die Wanddicke // (senkrecht zur Wandachse), wandbezogen. Basiswinkel 0 = Musterlinie steht @@ -115,7 +110,7 @@ export const sampleProject: Project = { angle: 0, relativeToWall: true, color: "#1a1a1a", - lineStyleId: "hatch-hair", + lineWeight: 0.02, }, ], // Bauteil-Materialien: color = Poché-Füllung im Grundriss UND 3D-Diffusfarbe; @@ -182,7 +177,7 @@ export const sampleProject: Project = { layers: [ { componentId: "render-ext", thickness: 0.02 }, // Innere Fuge der Dämmung trifft auf den Backstein (massiv↔massiv) → 0.13 mm. - { componentId: "insulation", thickness: 0.16, jointLineStyleId: "thin" }, + { componentId: "insulation", thickness: 0.16, jointLineStyleId: "thin", jointWeightMm: 0.13 }, { componentId: "brick", thickness: 0.15 }, { componentId: "render-int", thickness: 0.015 }, ], @@ -209,7 +204,7 @@ export const sampleProject: Project = { // Estrich (schwimmend) → Trittschalldämmung. { componentId: "screed", thickness: 0.06 }, // Innere Fuge der Dämmung trifft auf die Betondecke (massiv) → 0.13 mm. - { componentId: "insulation", thickness: 0.04, jointLineStyleId: "thin" }, + { componentId: "insulation", thickness: 0.04, jointLineStyleId: "thin", jointWeightMm: 0.13 }, // Betondecke (Rohdecke, tragend) — innerste/unterste Schicht. { componentId: "concrete", thickness: 0.2 }, ], @@ -222,7 +217,7 @@ export const sampleProject: Project = { // Aussen (Eindeckung) → innen (Verkleidung); Bauteile aus der Bibliothek. layers: [ { componentId: "roof-tiles", thickness: 0.04 }, // Eindeckung (Tonziegel) - { componentId: "insulation", thickness: 0.22, jointLineStyleId: "thin" }, // Sparren/Dämmung + { componentId: "insulation", thickness: 0.22, jointLineStyleId: "thin", jointWeightMm: 0.13 }, // Sparren/Dämmung { componentId: "render-int", thickness: 0.0125 }, // Innenverkleidung (GK) ], }, diff --git a/src/model/types.generated.ts b/src/model/types.generated.ts index f626d9e9..18e17f88 100644 --- a/src/model/types.generated.ts +++ b/src/model/types.generated.ts @@ -728,7 +728,7 @@ export type Drawing2D = { fillColor?: string; /** * Optionale direkte Strichstärke-Übersteuerung in Millimetern; hat Vorrang - * vor dem LineStyle-Gewicht und der Kategorie-Strichstärke. + * vor der Kategorie-Strichstärke (Linienstile tragen keine Stärke, [110]). */ weightMm?: number; /** @@ -742,8 +742,8 @@ export type Drawing2D = { backgroundSource?: AttributeSource; /** * Quelle der Strichstärke, wenn kein explizites `weightMm` gesetzt ist: - * "layer" erzwingt `LayerCategory.lw` (unter Umgehung des LineStyle-Gewichts), - * "object"/`undefined` (Default) = heutige Kette (LineStyle.weight ?? Kategorie). + * "layer" erzwingt `LayerCategory.lw`, + * "object"/`undefined` (Default) = Kategorie-Strichstärke. */ strokeWeightSource?: AttributeSource; /** @@ -1190,7 +1190,19 @@ export type Group = { }; /** Mögliche Schraffur-Muster im Plan/Schnitt. */ -export type HatchPattern = "none" | "solid" | "insulation" | "diagonal" | "crosshatch" | "custom"; +export type HatchPattern = + | "none" + | "solid" + | "insulation" + | "diagonal" + | "crosshatch" + | "custom" + | "insulationHard" + | "insulationWave" + | "timber" + | "earth" + | "gravel" + | "stone"; /** Eine wiederverwendbare Schraffur (Hatch Manager). */ export type HatchStyle = { @@ -1259,8 +1271,10 @@ export type HatchStyle = { * Vollfüllfarbe, bei `pattern==="none"` ungenutzt. */ color: string; - /** Optionaler Linienstil für die Musterlinien (Line Manager). */ + /** Optionaler Linienstil für die Musterlinien (Line Manager): nur Muster/Farbe. */ lineStyleId?: string; + /** Strichstärke der Musterlinien in Papier-mm ([110]); fehlt sie, gilt 0.13. */ + lineWeight?: number; /** * Steuer-Parameter der Random-Vektor-Schraffur (`kind`/"vector" + `lines`=== * "random", z. B. Kies/Splitt). ALLE additiv & optional — fehlen sie, gilt das @@ -1335,6 +1349,8 @@ export type Layer = { * Fehlt das Feld, wird die Standard-Haarlinie (0.02 mm) gezeichnet. */ jointLineStyleId?: string; + /** Strichstärke der Schichtfuge in Papier-mm ([110]); fehlt sie, gilt die Standard-Fuge. */ + jointWeightMm?: number; }; /** @@ -1490,16 +1506,13 @@ export type LineStyle = { id: string; name: string; /** - * @deprecated Die Strichstärke gehört NICHT mehr in den Linienstil — es gibt nur - * „Vollinie/Strich", die tatsächliche Dicke wird per Element-Attribut (bzw. - * Ebene/Default) aufgelöst. Das Feld bleibt für die Backward-Compat-Auflösung - * erhalten und dient den Renderern noch als Fallback für die Muster-/Fugen-Stärke - * (siehe `resolveHatch` → `HatchRender.lineWeight`). Der Linien-Detail-Editor - * zeigt es nicht mehr an; neue Linienstile bekommen einen Haarlinien-Default. - * Die echte per-Element-Strichstärken-Auflösung (Attribut → Ebene → Default) - * folgt separat mit dem By-Layer/By-Object-Refactor — NICHT hier. + * @deprecated Nur noch für die Migration alter Dateien gelesen ([110], Format 4): Ein Linienstil + * legt nur das Muster (Volllinie, Strich, Punkt, Zickzack …) und die Farbe fest — die Strichstärke + * kommt vom Element (`Drawing2D.weightMm`), der Schraffur (`HatchStyle.lineWeight`), der + * Schichtfuge (`Layer.jointWeightMm`) bzw. Ebene/Stift. Die Migration trägt das alte Gewicht dort + * ein und entfernt es hier; die Renderer werten es nicht mehr aus. */ - weight: number; + weight?: number; /** Farbe (hex). */ color: string; /** diff --git a/src/plan/generatePlan.corner.test.ts b/src/plan/generatePlan.corner.test.ts index 4df43c69..421a844d 100644 --- a/src/plan/generatePlan.corner.test.ts +++ b/src/plan/generatePlan.corner.test.ts @@ -121,13 +121,14 @@ describe("generatePlan — Schichtfugen als stilisierbare Linien", () => { p.kind === "line" && p.cls === "layer-joint", ); - it("zieht die innere Fuge als eigene Linie und übernimmt Gewicht/Farbe des LineStyle", () => { + it("zieht die innere Fuge als eigene Linie: Farbe/Muster vom LineStyle, Stärke von der Schicht ([110])", () => { const proj = cornerProject(); proj.walls = [proj.walls[0]]; // nur W1, zwei Schichten → genau eine innere Fuge - proj.wallTypes[0].layers[0].jointLineStyleId = "thin"; // weight 0.13, color #111 + proj.wallTypes[0].layers[0].jointLineStyleId = "thin"; // color #111 + proj.wallTypes[0].layers[0].jointWeightMm = 0.13; const joints = jointLines(proj); expect(joints.length).toBe(1); - // LAYER_DETAIL_FACTOR["mittel"] == 1 → das LineStyle-Gewicht wirkt direkt. + // LAYER_DETAIL_FACTOR["mittel"] == 1 → die Fugen-Stärke der Schicht wirkt direkt. expect(joints[0].weightMm).toBeCloseTo(0.13, 6); expect(joints[0].color).toBe("#111"); expect(joints[0].dash ?? null).toBeNull(); diff --git a/src/plan/glPlan/glPlanHatch.ts b/src/plan/glPlan/glPlanHatch.ts index dd12cbf2..a33a7ae0 100644 --- a/src/plan/glPlan/glPlanHatch.ts +++ b/src/plan/glPlan/glPlanHatch.ts @@ -136,7 +136,8 @@ export function applyDashRuns(runs: HatchRun[], dash: number[] | null): HatchRun /** * Schraffur eines Polygons als zusammenhängende Läufe (Modell-Meter): diagonal (eine Schar), - * crosshatch (zwei Scharen), insulation (Welle), custom (Motiv je Musterlinie), Random-Untermodus + * crosshatch (zwei Scharen), Schicht-Muster über die Dicke (Dämmschlange, Zickzack, Welle, Holzkreuz), + * Naturstein, Erdreich, Kies, custom (Motiv je Musterlinie), Random-Untermodus * (gestreute Striche); solid/none sowie Bild/Verlauf liefern keine Linien-Geometrie des Musters. */ export function buildHatchRuns(poly: Vec2[], hatch: HatchRender): HatchRun[] { diff --git a/src/plan/planBuf.ts b/src/plan/planBuf.ts index f6106c2a..3be5be36 100644 --- a/src/plan/planBuf.ts +++ b/src/plan/planBuf.ts @@ -111,6 +111,12 @@ const PATTERN_CODE: Record = { crosshatch: 3, insulation: 4, custom: 5, + insulationHard: 6, + insulationWave: 7, + timber: 8, + earth: 9, + gravel: 10, + stone: 11, }; /** Ein Hatch-Datensatz (auch Eingabe der Einzel-Bindungen in `glPlanHatch.ts`). */ diff --git a/src/plan/toWalls3d.test.ts b/src/plan/toWalls3d.test.ts index e737aa71..cc3ffc99 100644 --- a/src/plan/toWalls3d.test.ts +++ b/src/plan/toWalls3d.test.ts @@ -12,7 +12,7 @@ import { selectionHighlightLines, projectToWalls3d, projectToModel3d, pickGeomet import { hexToRgb } from "./toWalls3d/shared"; import type { ToolDraft } from "../tools/types"; import { generatePlan } from "./generatePlan"; -import { getHatch, getLineStyle } from "../model/types"; +import { getHatch } from "../model/types"; import { roofGeometry, roofBaseElevation } from "../geometry/roof"; const RGB: [number, number, number] = [1, 0.5, 0.1]; @@ -1805,7 +1805,7 @@ describe("Schnitt-Schraffur-Orientierung: relativeToWall dreht bei Wand, nicht b const h = getHatch(p, id); return { angle: h.relativeToWall && wallAngleDeg != null ? h.angle - wallAngleDeg : h.angle, - lineWeight: (h.lineStyleId ? getLineStyle(p, h.lineStyleId) : null)?.weight ?? 0.13, + lineWeight: h.lineWeight ?? 0.13, }; }; // 2D-Referenz (verbindlich): splitWallLayers ruft resolveHatch(…, 90, …) (Wand @@ -1844,9 +1844,9 @@ describe("Schnitt-Schraffur-Orientierung: relativeToWall dreht bei Wand, nicht b expect(brick.hatch?.angle).toBeCloseTo(resolveHatch(sampleProject, "sia-brick", 90).angle, 6); }); - it("Musterlinien-Stärke kommt aus dem LineStyle des Hatch durch (2D-Parität)", () => { - // sia-insulation nutzt lineStyleId "hatch-hair" (0.02 mm). Der 3D-Hatch muss die - // resolveHatch-lineWeight (aus dem LineStyle) tragen — für Wand UND Decke gleich. + it("Musterlinien-Stärke kommt aus der Schraffur durch (2D-Parität)", () => { + // sia-insulation trägt lineWeight 0.02 mm ([110]). Der 3D-Hatch muss die + // resolveHatch-lineWeight (aus der Schraffur) tragen — für Wand UND Decke gleich. const expected = resolveHatch(sampleProject, "sia-insulation", 90).lineWeight; expect(wallInsul().hatch?.lineWeight).toBeCloseTo(expected, 6); expect(slabInsul().hatch?.lineWeight).toBeCloseTo(expected, 6); diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index a68375c7..48b1228c 100644 --- a/src/state/projectSlice.ts +++ b/src/state/projectSlice.ts @@ -894,7 +894,6 @@ export function createProjectSlice( const lineStyle: LineStyle = { id: `line-${Date.now()}`, name: t("default.lineStyleName"), - weight: 0.18, color: "#2b3039", dash: null, }; diff --git a/src/state/setProjectOps.test.ts b/src/state/setProjectOps.test.ts index eb4fa494..d61fa649 100644 --- a/src/state/setProjectOps.test.ts +++ b/src/state/setProjectOps.test.ts @@ -52,7 +52,7 @@ describe("Projekt laden ([K4] S4)", () => { st().undo(); expect(st().project).toBe(next); // Kern-Dokument = Leseansicht (Speichern aus dem Kern). - expect(JSON.parse(serializeProject(st().project))).toEqual({ ...next, formatVersion: 3 }); + expect(JSON.parse(serializeProject(st().project))).toEqual({ ...next, formatVersion: 4 }); }); it("openProjectFile: Kern liest, migriert und lädt direkt; Verlauf leer; kaputte Datei ändert nichts", () => { @@ -70,7 +70,7 @@ describe("Projekt laden ([K4] S4)", () => { expect(r.ok && r.migratedFrom).toBe(1); expect(st().undoDepth).toBe(0); expect(st().redoDepth).toBe(0); - expect(st().project.formatVersion).toBe(3); + expect(st().project.formatVersion).toBe(4); expect(st().project.openings?.some((o) => o.id === "TX" && o.kind === "door")).toBe(true); expect("doors" in st().project).toBe(false); // Danach normal weiterarbeiten: ein Schritt, Undo zurück auf den geladenen Stand. @@ -78,6 +78,6 @@ describe("Projekt laden ([K4] S4)", () => { st().setProject(opsMutation((p) => patchItem(p, "walls", p.walls[0].id, { height: 7 }))); st().undo(); expect(st().project).toEqual(loaded); - expect(serializeProject(st().project)).toBe(JSON.stringify({ formatVersion: 3, ...loaded }, null, 2)); + expect(serializeProject(st().project)).toBe(JSON.stringify({ formatVersion: 4, ...loaded }, null, 2)); }); }); diff --git a/src/ui/hatchPreview.tsx b/src/ui/hatchPreview.tsx index 60d70488..26098e30 100644 --- a/src/ui/hatchPreview.tsx +++ b/src/ui/hatchPreview.tsx @@ -1,72 +1,48 @@ -// Live-SVG-Vorschau (Swatch) für Schraffuren und Linienstile — eigenständig. +// Live-SVG-Vorschau (Swatch) für Schraffuren und Linienstile. // -// Bewusst OHNE Rückgriff auf die Plan-Renderer (generatePlan/toRenderScene): -// diese Datei zeichnet die Muster direkt aus den HatchStyle-/LineStyle-Parametern -// als SVG nach, damit die Vorschau im Ressourcen-Manager auch dann konsistent -// bleibt, während der Plan-Renderer separat umgebaut wird. Die Farbe kommt hier -// bewusst NICHT vom (deprecated) HatchStyle.color, sondern über `currentColor` -// aus dem umgebenden CSS (var(--ink)) — die echte Vordergrundfarbe stammt im Plan -// vom Bauteil/Attribut. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). +// Vektor-Schraffuren zeichnet die Vorschau mit DEMSELBEN Kern-Generator wie Plan, Schnitt und Druck +// (`buildHatchRuns`, [109]) — die Box wird als Fläche in Modell-Metern (`SWATCH_PX_PER_M`) übergeben, +// Schicht-Muster (Dämmschlange, Zickzack …) spannen also über das Band wie im Plan. Bild/Verlauf als +// SVG-Füllung. Die Farbe kommt bewusst NICHT vom (deprecated) HatchStyle.color, sondern über +// `currentColor` aus dem umgebenden CSS (var(--ink)) — die echte Vordergrundfarbe stammt im Plan vom +// Bauteil/Attribut. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import { useId } from "react"; import type { HatchStyle, LineStyle } from "../model/types"; -import { dashHasDot } from "../core"; +import { buildHatchRuns, dashHasDot } from "../core"; -// ── Kleiner deterministischer PRNG (mulberry32) ──────────────────────────── -// Für „random"-Striche: stabil pro Seed, damit die Vorschau bei gleichem -// Maßstab/Winkel nicht bei jedem Render „springt". -function mulberry32(seed: number): () => number { - let a = seed >>> 0; - return () => { - a |= 0; - a = (a + 0x6d2b79f5) | 0; - let t = Math.imul(a ^ (a >>> 15), 1 | a); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; -} +/** Vorschau-Massstab: px je Modell-Meter (128 px ≈ 0.43 m, etwa 1:10 am Bildschirm). */ +const SWATCH_PX_PER_M = 300; /** - * Parallele Linienschar über die Box (w×h) unter `angleDeg`, Abstand `spacing` - * px senkrecht zur Linienrichtung. Liefert fertige -Elemente, die die Box - * komplett überdecken (Clip übernimmt der Aufrufer). + * Musterlinien einer Vektor-Schraffur für eine Box `w`×`h` (px) aus dem Kern-Generator. `wallAngleDeg` + * dreht wandbezogene Muster wie im Plan (Wand senkrecht = 90). */ -function parallelLines( - w: number, - h: number, - angleDeg: number, - spacing: number, - strokeWidth: number, - keyPrefix: string, -): React.ReactNode[] { - const a = (angleDeg * Math.PI) / 180; - const cos = Math.cos(a); - const sin = Math.sin(a); - // Senkrechte zur Linienrichtung. - const px = -sin; - const py = cos; - const cx = w / 2; - const cy = h / 2; - const half = Math.hypot(w, h); // Linien lang genug, um die Box zu überdecken. - const step = Math.max(spacing, 1.2); - const n = Math.ceil(half / step) + 2; - const out: React.ReactNode[] = []; - for (let k = -n; k <= n; k++) { - const mx = cx + k * step * px; - const my = cy + k * step * py; - out.push( - , - ); - } - return out; +function vectorRuns(hatch: HatchStyle, w: number, h: number, wallAngleDeg: number | undefined): string[] { + const k = SWATCH_PX_PER_M; + const poly = [ + { x: 0, y: 0 }, + { x: w / k, y: 0 }, + { x: w / k, y: h / k }, + { x: 0, y: h / k }, + ]; + const angle = hatch.relativeToWall && wallAngleDeg != null ? hatch.angle - wallAngleDeg : hatch.angle; + const runs = buildHatchRuns(poly, { + pattern: hatch.pattern, + scale: hatch.scale, + angle, + color: "#000", + lineWeight: hatch.lineWeight ?? 0.13, + dash: null, + kind: hatch.kind, + lines: hatch.lines, + seed: hatch.seed, + density: hatch.density, + lengthMin: hatch.lengthMin, + lengthMax: hatch.lengthMax, + motif: hatch.motif, + }); + return runs.map((r) => r.map((p, i) => `${i ? "L" : "M"}${(p.x * k).toFixed(1)} ${(h - p.y * k).toFixed(1)}`).join("")); } /** @@ -76,14 +52,9 @@ function parallelLines( * Band DASSELBE Muster zeichnet. `uid` macht interne -IDs eindeutig * (mehrere Bänder je SVG). */ -function hatchInner(hatch: HatchStyle, w: number, h: number, uid: string): React.ReactNode { +function hatchInner(hatch: HatchStyle, w: number, h: number, uid: string, wallAngleDeg?: number): React.ReactNode { const patId = `hsp_${uid}`; - // Grundabstand der Musterlinien (px), über den Maßstab moduliert. - const scale = hatch.scale > 0 ? hatch.scale : 1; - const spacing = Math.max(3, 8 / Math.sqrt(scale)); - const angle = hatch.angle || 0; - let inner: React.ReactNode = null; if (hatch.kind === "image") { @@ -172,106 +143,11 @@ function hatchInner(hatch: HatchStyle, w: number, h: number, uid: string): React inner = ; } else if (hatch.pattern === "none") { inner = null; - } else if (hatch.lines === "random") { - // Zufällig verteilte kurze Striche (deterministisch geseedet). Dichte, Länge - // und der explizite Seed spiegeln die Plan-Parameter (HatchStyle) — so ändert - // „Neu würfeln"/Dichte/Länge die Vorschau wie im Plan. Rein schematisch (px), - // NICHT deckungsgleich mit der Modell-Streuung, aber qualitativ konsistent. - const density = hatch.density != null && hatch.density > 0 ? hatch.density : 1; - const seed = (Math.round(scale * 1000) + Math.round(angle) + Math.round(hatch.seed ?? 0)) >>> 0; - const rnd = mulberry32(seed); - const count = Math.min(400, Math.max(4, Math.round((18 * Math.min(2, scale) + 6) * density))); - // mm-Papier → Vorschau-px (wie das Dash-Muster im LineSwatch: ·4). - const PX_PER_MM = 4; - const hasRange = - hatch.lengthMin != null && hatch.lengthMax != null && - hatch.lengthMin > 0 && hatch.lengthMax >= hatch.lengthMin; - const baseLen = Math.max(3, 6 / Math.sqrt(scale)); - const out: React.ReactNode[] = []; - for (let i = 0; i < count; i++) { - const cx = rnd() * w; - const cy = rnd() * h; - const ang = rnd() * Math.PI; - const lr = rnd(); - const len = hasRange - ? (hatch.lengthMin! + lr * (hatch.lengthMax! - hatch.lengthMin!)) * PX_PER_MM - : baseLen; - const dx = (Math.cos(ang) * len) / 2; - const dy = (Math.sin(ang) * len) / 2; - out.push( - , - ); - } - inner = out; - } else if (hatch.pattern === "crosshatch") { - inner = [ - ...parallelLines(w, h, angle, spacing, 0.8, "a"), - ...parallelLines(w, h, angle + 90, spacing, 0.8, "b"), - ]; - } else if (hatch.pattern === "insulation") { - // Dämmung: eine gewellte Schar quer über die Box (angenähert als Zickzack). - const rows = Math.max(2, Math.round(h / Math.max(6, spacing))); - const out: React.ReactNode[] = []; - for (let r = 0; r < rows; r++) { - const y = ((r + 0.5) / rows) * h; - const amp = Math.min(h / rows / 2, 3); - const waves = Math.max(2, Math.round(w / 6)); - let d = `M 0 ${y}`; - for (let i = 1; i <= waves; i++) { - const x = (i / waves) * w; - const yy = y + (i % 2 === 0 ? -amp : amp); - d += ` L ${x.toFixed(1)} ${yy.toFixed(1)}`; - } - out.push( - , - ); - } - inner = out; - } else if (hatch.pattern === "custom" && hatch.motif && hatch.motif.points.length >= 2 && hatch.motif.length > 1e-6) { - // Eigenes Motiv: EINE Wiederhollänge als -Kachel (analog zur - // Bild-Schraffur oben) — motif.x (0..length) läuft entlang der Kachel- - // Höhe (wie die Musterlinie bei diagonal/crosshatch), motif.y (Versatz - // quer) entlang der Kachelbreite. Bewusst eigenständig tesseliert (KEIN - // Import aus glPlanHatch, s. Moduldoc oben) — schematisch/px, wie der - // übrige Swatch, nicht deckungsgleich mit dem Plan-Renderer. - const PX_PER_MM = 2; - const rowSpacing = Math.max(3, 8 / Math.sqrt(scale)); - const period = Math.max(4, hatch.motif.length * scale * PX_PER_MM); - const d = hatch.motif.points - .map((p, i) => { - const x = (p.y * scale * PX_PER_MM).toFixed(1); - const y = (p.x * scale * PX_PER_MM).toFixed(1); - return `${i === 0 ? "M" : "L"} ${x} ${y}`; - }) - .join(" "); - inner = ( - <> - - - - - - - - ); } else { - // "diagonal" (Default, auch "custom" ohne gesetztes Motiv): eine parallele Schar. - inner = parallelLines(w, h, angle, spacing, 0.8, "d"); + // Vektor (parallel, Kreuz, Schicht-Muster, Motiv, gestreut): Kern-Generator. + inner = vectorRuns(hatch, w, h, wallAngleDeg).map((d, i) => ( + + )); } return inner; @@ -412,7 +288,7 @@ export function WallTypeSwatch({ transform={`translate(${b.bx.toFixed(2)},${b.by.toFixed(2)})`} clipPath={`url(#${clipId}_b${i})`} > - {b.hatch && hatchInner(b.hatch, b.bw, b.bh, `${rawId}_${i}`)} + {b.hatch && hatchInner(b.hatch, b.bw, b.bh, `${rawId}_${i}`, orientation === "wall" ? 90 : undefined)} ))} {/* Fugen: dünne Trennlinie an jeder INNEREN Bandgrenze. */} @@ -471,7 +347,8 @@ export function LineSwatch({ width?: number; height?: number; }) { - const px = Math.max(1, Math.min(6, style.weight * 6)); + // Linienstile tragen keine Stärke mehr ([110]): Vorschau mit einheitlicher Linie. + const px = 1.5; const midY = height / 2; const x0 = 4; const x1 = width - 4; diff --git a/src/ui/resourceManager/HatchesTab.tsx b/src/ui/resourceManager/HatchesTab.tsx index 70528818..21c89134 100644 --- a/src/ui/resourceManager/HatchesTab.tsx +++ b/src/ui/resourceManager/HatchesTab.tsx @@ -26,6 +26,12 @@ const PATTERN_OPTIONS: { value: HatchPattern; labelKey: string }[] = [ { value: "insulation", labelKey: "pattern.insulation" }, { value: "diagonal", labelKey: "pattern.diagonal" }, { value: "crosshatch", labelKey: "pattern.crosshatch" }, + { value: "insulationHard", labelKey: "pattern.insulationHard" }, + { value: "insulationWave", labelKey: "pattern.insulationWave" }, + { value: "timber", labelKey: "pattern.timber" }, + { value: "stone", labelKey: "pattern.stone" }, + { value: "earth", labelKey: "pattern.earth" }, + { value: "gravel", labelKey: "pattern.gravel" }, { value: "custom", labelKey: "pattern.custom" }, ]; @@ -212,6 +218,14 @@ function HatchDetail({ options={lineOptions} /> + + onPatch({ lineWeight: Math.max(0.01, w) })} + step={0.01} + min={0.01} + /> + {lines === "random" && ( <> @@ -327,8 +341,8 @@ function patToHatches(text: string): Omit[] { scale: 1, angle: p.families[0]?.angle ?? 45, color: "#1a1a1a", - // Kanonische Volllinie 0.13 (früher "hatch-line", zusammengeführt auf "thin"). - lineStyleId: "thin", + // Volllinie (Muster); die Stärke trägt die Schraffur ([110]). + lineWeight: 0.13, })); } diff --git a/src/ui/resourceManager/LayeredStylesTab.tsx b/src/ui/resourceManager/LayeredStylesTab.tsx index d329ef82..a5b0e6b6 100644 --- a/src/ui/resourceManager/LayeredStylesTab.tsx +++ b/src/ui/resourceManager/LayeredStylesTab.tsx @@ -166,6 +166,16 @@ function LayeredStyleDetail({ /> )} + {!isInner && ( + + patchLayer(i, { jointWeightMm: w > 0 ? w : undefined })} + step={0.01} + min={0} + /> + + )} removeLayer(i)} diff --git a/src/ui/resourceManager/LinesTab.tsx b/src/ui/resourceManager/LinesTab.tsx index 0bd9679b..43e97e26 100644 --- a/src/ui/resourceManager/LinesTab.tsx +++ b/src/ui/resourceManager/LinesTab.tsx @@ -4,7 +4,6 @@ import { useState } from "react"; import type { LineStyle, Project } from "../../model/types"; -import { PEN_WEIGHTS } from "../../model/types"; import { parseLin } from "../../io/linParser"; import { LineSwatch } from "../hatchPreview"; import { segmentsToDash, dashToSegments, presetOfDash, LINE_PRESETS, type LineSegment, type LineSegmentType, type LinePresetKey } from "../../core"; @@ -249,11 +248,10 @@ function LineStyleDetail({ ); } -/** .lin-Text → id-lose Linienstile (schwarze Haarlinie 0.18 als Default). */ +/** .lin-Text → id-lose Linienstile (nur Muster; die Stärke trägt das Element, [110]). */ function linToStyles(text: string): Omit[] { return parseLin(text).map((p) => ({ name: p.name, - weight: 0.18, color: "#1a1a1a", dash: p.dash, })); @@ -278,12 +276,6 @@ export function LinesTab({ return (
- {/* Vorschlagswerte für die Strichstärke (Standard-Stiftbreiten in mm). */} - - {PEN_WEIGHTS.map((w) => ( -
{t("resources.lines.hint")}