//! Grundriss-Zutaten rund um die Domänen ([K3a]/[K4]): Schattenstudie und Baurecht (zuunterst; die //! Verstösse zuoberst), Abzugskörper (aus Wand-, Stützen- und Decken-Poché), Schwarz-Weiss und //! Strichstärken nach Massstab sowie das Ausmass des Plans — früher in TS //! (`generatePlan/{sunShadow,siteRules}.ts`, `voids.ts::subtractVoidsInPlan`, `toMono`, //! `lineWeightScale.ts`, `computeBounds`). Rechenreihenfolge wie dort. use super::domains::Bounds; use super::prim::{HatchRender, Primitive}; use super::style::*; use crate::jsnum; use crate::model::*; use std::collections::HashMap; /// [137] Pick-Ids der abgeleiteten Lage-Darstellung (im Feld `contextObjectId`, mit `@` — keine Element-Id /// beginnt so): Schattenflächen wählen den Sonnenstand, die Baurechtslinien (unsichtbare Bänder) das Baurecht. pub const SITE_PICK_SUN: &str = "@sunStudy"; pub const SITE_PICK_RULES: &str = "@siteRules"; /// [137] Schlagschatten der Ansicht (Ebenen-Schalter `shadows`). pub const SITE_PICK_VIEW_SHADOWS: &str = "@viewShadows"; /// Füllfarbe der Schattenflächen. /// [140] Schatten grau (Tusche-Darstellung), nicht blau. pub const SUN_SHADOW_FILL: &str = "#3c3c3c"; /// [140] Schatten heller (0.28 → 0.16): Bemassung und Stempel darüber bleiben lesbar. const SUN_SHADOW_OPACITY: f64 = 0.16; /// Linien-Klassen und Füllfarbe des Baurechts. pub const SITE_PARCEL_CLS: &str = "site-parcel"; pub const SITE_ALLOWED_CLS: &str = "site-allowed"; pub const SITE_VIOLATION_FILL: &str = "#d0342c"; const SITE_VIOLATION_OPACITY: f64 = 0.45; /// Profilverstösse ([63]): gleiches Rot, schwächer gefüllt (Bauteil ragt über das Gebäudeprofil). const SITE_PROFILE_OPACITY: f64 = 0.25; /// [140] Baurecht in Grautönen (Parzelle dunkel, zulässiger Baukörper mittel); Verstösse bleiben rot. const PARCEL_COLOR: &str = "#3a3a3a"; const ALLOWED_COLOR: &str = "#6e6e6e"; const PARCEL_DASH: [f64; 4] = [6.0, 1.5, 0.5, 1.5]; const ALLOWED_DASH: [f64; 2] = super::line_pattern::HIDDEN; /// Geschoss, auf dem Boden-Schatten und Baurecht erscheinen: Basishöhe am nächsten bei 0 (das erste /// bei Gleichstand). pub fn ground_floor_id(p: &Project) -> Option<&str> { let mut best: Option<(&str, f64)> = None; for l in &p.drawing_levels { if l.kind != DrawingLevelKind::Floor { continue; } let d = l.base_elevation.unwrap_or(0.0).abs(); if best.is_none_or(|b| d < b.1) { best = Some((&l.id, d)); } } best.map(|b| b.0) } /// Fläche ohne Strich, mit Deckkraft (Schatten, Baurechts-Verstoss). fn flat_polygon(pts: Vec, fill: &str, opacity: f64) -> Primitive { Primitive::Polygon { pts, fill: fill.into(), stroke: "none".into(), stroke_width_mm: 0.0, hatch: no_hatch(), greyed: None, opacity: Some(opacity), no_stroke_edges: None, wall_id: None, drawing_id: None, ceiling_id: None, opening_id: None, stair_id: None, room_id: None, extruded_solid_id: None, context_object_id: None, column_id: None, roof_id: None, section_line_id: None, } } fn ring_pts(r: &[[f64; 2]]) -> Vec { r.iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect() } /// Breite/Länge des Projekts aus `geoAnchor` (LV95), sonst Zürich. fn project_lat_lon(p: &Project) -> (f64, f64) { match &p.geo_anchor { Some(a) => crate::geo_rebase::lv95_to_wgs84(a.lv95.e, a.lv95.n), None => (47.3769, 8.5417), } } /// Schatten zum Zeitpunkt `when_ms` (Unix-ms der Studie, `None`/NaN = ungültig) als /// halbtransparente Flächen; nur mit sichtbarer Studie, in Geschoss-Grundrissen. [142] Auf den im /// Grundriss sichtbaren Flächen im Freien (Terrassen, Dächer tieferer Geschosse unter dem Schnitt), /// auf dem Gelände nur im Geschoss nächst ±0.00. pub fn sun_shadow(p: &Project, floor: &str, when_ms: Option, out: &mut Vec) { let Some(study) = &p.sun_study else { return }; if !study.show || !p.drawing_levels.iter().any(|l| l.id == floor && l.kind == DrawingLevelKind::Floor) { return; } let Some(t) = when_ms.filter(|t| !t.is_nan()) else { return }; let (lat, lon) = project_lat_lon(p); let sun = crate::sun::sun_position(lat, lon, t); let with_ground = ground_floor_id(p) == Some(floor); // [171] Flächen unter der Unterkante des Ansichtsbereichs (samt „darunter sichtbar bis“) zeigt der // Grundriss nicht — auch ihren Schatten nicht. let range = super::view_range::ViewRange::of(p, floor); let min_top = range.bottom.map_or(f64::NEG_INFINITY, |b| b - range.depth); for poly in crate::sun::shadow_polygons_plan_in(p, sun, cut_z(p, floor), min_top, with_ground) { for r in crate::sun::without_holes(&poly) { let mut q = flat_polygon(ring_pts(&r), SUN_SHADOW_FILL, SUN_SHADOW_OPACITY); if let Primitive::Polygon { context_object_id, .. } = &mut q { *context_object_id = Some(SITE_PICK_SUN.into()); } out.push(q); } } } /// Baurecht im Geschoss nächst ±0.00 (ohne `show: false`): Prüfung des Modells, `None` ohne /// gültiges Baurecht. fn site_check(p: &Project, floor: &str) -> Option { let rules = p.site_rules.as_ref()?; if rules.show == Some(false) || ground_floor_id(p) != Some(floor) { return None; } crate::site_rules::check_project(p) } /// Linien eines geschlossenen Rings (ein Strichmuster je Ring: Linienzug über die Ecken). fn ring_lines(out: &mut Vec<(Primitive, u32)>, pts: &[Vec2], cls: &str, color: &str, w: f64, dash: &[f64], dash_ref: u32) { let n = pts.len(); for i in 0..n { let line = Primitive::Line { a: pts[i], b: pts[(i + 1) % n], cls: cls.into(), weight_mm: w, dash: Some(Some(dash.to_vec())), zigzag: None, motif: None, color: Some(color.into()), drawing_id: None, opening_id: None, stair_id: None, greyed: None, opacity: None, }; out.push((line, dash_ref)); } } /// [137] Unsichtbares Rechteck der halben Breite `half` um die Strecke a–b mit der Pick-Id des Baurechts. fn seg_band(a: Vec2, b: Vec2, half: f64) -> Option { let (dx, dy) = (b.x - a.x, b.y - a.y); let l = dx.hypot(dy); if !(l > 1e-9) { return None; } let (nx, ny) = (-dy / l * half, dx / l * half); let pts = vec![Vec2 { x: a.x + nx, y: a.y + ny }, Vec2 { x: b.x + nx, y: b.y + ny }, Vec2 { x: b.x - nx, y: b.y - ny }, Vec2 { x: a.x - nx, y: a.y - ny }]; let mut q = flat_polygon(pts, "none", 1.0); if let Primitive::Polygon { context_object_id, opacity, .. } = &mut q { *context_object_id = Some(SITE_PICK_RULES.into()); *opacity = None; } Some(q) } /// Unterste Gruppe: Schatten, dann Parzellengrenze (Strich-Punkt) und zulässige Fläche /// (gestrichelt); mit Strichmuster-Kennung je Primitiv. Dazu die Verstösse (Gebäude-Grundfläche /// ausserhalb der zulässigen Fläche) für die oberste Gruppe. /// Kategorie der Vermessung; ist sie im Projekt und ausgeblendet, entfällt das Baurecht im Grundriss ([66]). pub const SITE_CATEGORY: &str = "01"; /// `site = false`: nur der Schatten, ohne Baurecht. pub fn site_and_shadow(p: &Project, floor: &str, when_ms: Option, scale: f64, site: bool) -> (Vec<(Primitive, u32)>, Vec) { let mut shadow = Vec::new(); sun_shadow(p, floor, when_ms, &mut shadow); let mut under: Vec<(Primitive, u32)> = shadow.into_iter().map(|q| (q, 0)).collect(); let mut violations = Vec::new(); if !site { return (under, violations); } if let (Some(check), Some(rules)) = (site_check(p, floor), p.site_rules.as_ref()) { let mut r = 1; ring_lines(&mut under, &rules.parcel, SITE_PARCEL_CLS, PARCEL_COLOR, 0.35, &PARCEL_DASH, r); for poly in &check.allowed { for ring in poly { r += 1; ring_lines(&mut under, ring, SITE_ALLOWED_CLS, ALLOWED_COLOR, 0.25, &ALLOWED_DASH, r); } } // [137] Unsichtbare Pick-Bänder (±1.5 mm Papier) über den Linien: ein Klick wählt das Baurecht. let half = 0.0015 * if scale.is_finite() && scale > 0.0 { scale } else { 100.0 }; let rings = std::iter::once(rules.parcel.as_slice()).chain(check.allowed.iter().flatten().map(|r| r.as_slice())); for ring in rings { for i in 0..ring.len() { if let Some(band) = seg_band(ring[i], ring[(i + 1) % ring.len()], half) { under.push((band, 0)); } } } for poly in &check.violations { let rings: Vec> = poly.iter().map(|r| r.iter().map(|q| [q.x, q.y]).collect()).collect(); for ring in crate::sun::without_holes(&rings) { violations.push(flat_polygon(ring_pts(&ring), SITE_VIOLATION_FILL, SITE_VIOLATION_OPACITY)); } } for poly in &check.profile_violations { let rings: Vec> = poly.iter().map(|r| r.iter().map(|q| [q.x, q.y]).collect()).collect(); for ring in crate::sun::without_holes(&rings) { violations.push(flat_polygon(ring_pts(&ring), SITE_VIOLATION_FILL, SITE_PROFILE_OPACITY)); } } } (under, violations) } // ── Abzugskörper ──────────────────────────────────────────────────────────────────────────────── const EPS: f64 = 1e-7; /// Ein Abzugskörper als Prisma (Welt-Höhen). pub(crate) struct VoidPrism { pub(crate) pts: Vec, pub(crate) z0: f64, pub(crate) z1: f64, } /// Abzugskörper des Projekts (`voidPrisms`): `operation: "subtract"`, ohne B-Rep, ohne Verjüngung, /// gültiges Profil und Höhe. pub(crate) fn void_prisms(p: &Project) -> Vec { let mut out = Vec::new(); for s in p.extruded_solids.as_deref().unwrap_or(&[]) { let is_void = s.operation.as_deref() == Some("subtract") && s.brep.is_none() && s.taper.unwrap_or(0.0) < 1e-6 && s.points.len() >= 3 && s.height > 0.0; if !is_void { continue; } let z0 = p.floor(&s.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0)) + s.base_offset.unwrap_or(0.0); out.push(VoidPrism { pts: s.points.clone(), z0, z1: z0 + s.height }); } out } /// Ringe flach wie `encodeRings` in TS: `[n, (k, x, y …) × n]`. fn encode_rings(rings: &[&[Vec2]]) -> Vec { let mut b = vec![rings.len() as f64]; for r in rings { b.push(r.len() as f64); for q in r.iter() { b.push(q.x); b.push(q.y); } } b } /// Linien-Klassen der Wand-Poché, die ein Abzugskörper auf Schnitthöhe unterbricht. const WALL_LINE_CLS: [&str; 3] = ["wall-outline", "layer-joint", "layer-joint-l"]; /// Zieht die Abzugskörper von den Bauteil-Primitiven eines Grundrisses ab (`subtractVoidsInPlan`): /// Wände (Poché und ihre Linien), wenn der Körper die Schnitthöhe `cut_z` durchdringt; Stützen /// ebenso über ihren Höhenbereich; Decken, wenn der Körper die Platte durchdringt. Ohne /// Abzugskörper unverändert. Gleiche Rechnung wie der frühere Weg über die flachen Bindungen. pub fn subtract_voids(prims: Vec, p: &Project, cut_z: f64) -> Vec { let voids = void_prisms(p); if voids.is_empty() { return prims; } // Maps wie in TS: bei doppelter id gewinnt der letzte Eintrag. let ceilings: HashMap<&str, &Ceiling> = p.ceilings.as_deref().unwrap_or(&[]).iter().map(|c| (c.id.as_str(), c)).collect(); let columns: HashMap<&str, &Column> = p.columns.as_deref().unwrap_or(&[]).iter().map(|c| (c.id.as_str(), c)).collect(); let cutters_for = |z0: f64, z1: f64| -> Vec<&[Vec2]> { voids.iter().filter(|v| v.z0 < z1 - EPS && v.z1 > z0 + EPS).map(|v| v.pts.as_slice()).collect() }; let wall_cutters = cutters_for(cut_z - 1e-4, cut_z + 1e-4); let wall_flat = encode_rings(&wall_cutters); // [159] Nichts zu tun (z. B. Kontext mit zehntausenden Höhenlinien): die Liste unverändert, ohne Umkopieren. let nonempty = |s: &Option| s.as_deref().is_some_and(|s| !s.is_empty()); let touched = |q: &Primitive| match q { Primitive::Line { cls, .. } => WALL_LINE_CLS.contains(&cls.as_str()) && !wall_cutters.is_empty(), Primitive::Polygon { wall_id, ceiling_id, column_id, extruded_solid_id, .. } => !nonempty(extruded_solid_id) && (nonempty(wall_id) || nonempty(ceiling_id) || nonempty(column_id)), _ => false, }; if !prims.iter().any(touched) { return prims; } let mut out = Vec::with_capacity(prims.len()); for pr in prims { if let Primitive::Line { a, b, cls, .. } = &pr { if WALL_LINE_CLS.contains(&cls.as_str()) && !wall_cutters.is_empty() { let f = crate::voids::segment_outside_flat(&[a.x, a.y, b.x, b.y], &wall_flat); let n = f.first().copied().unwrap_or(0.0) as usize; let parts: Vec<(f64, f64)> = (0..n).map(|k| (f[1 + 2 * k], f[2 + 2 * k])).collect(); if parts.len() == 1 && parts[0].0 == 0.0 && parts[0].1 == 1.0 { out.push(pr); } else { let (a, b) = (*a, *b); let at = |t: f64| Vec2 { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }; for (t0, t1) in parts { let mut q = pr.clone(); if let Primitive::Line { a: qa, b: qb, .. } = &mut q { *qa = at(t0); *qb = at(t1); } out.push(q); } } continue; } } let Primitive::Polygon { pts, no_stroke_edges, wall_id, ceiling_id, column_id, extruded_solid_id, .. } = &pr else { out.push(pr); continue; }; // Ids zählen wie in JS nur, wenn nicht leer. let id = |s: &Option| s.as_deref().filter(|s| !s.is_empty()).map(str::to_owned); let (wall_id, ceiling_id, column_id) = (id(wall_id), id(ceiling_id), id(column_id)); if id(extruded_solid_id).is_some() { out.push(pr); continue; } let cutters: Option> = if wall_id.is_some() { Some(wall_cutters.clone()) } else if let Some(id) = &ceiling_id { ceilings.get(id.as_str()).map(|c| { let (zb, zt) = p.ceiling_vertical_extent(c); cutters_for(zb, zt) }) } else if let Some(id) = &column_id { columns.get(id.as_str()).map(|c| { let (zb, zt) = p.column_vertical_extent(c); if zb <= cut_z && zt >= cut_z { wall_cutters.clone() } else { cutters_for(zb, zt) } }) } else { None }; let Some(cutters) = cutters.filter(|c| !c.is_empty()) else { out.push(pr); continue; }; if pts.len() < 3 { out.push(pr); continue; } // [159] Weit neben allen Abzugskörpern (Rechtecke getrennt): unverändert wie mit leerer Schnittmenge // (`subtract_rings` → `None`), ohne die Booleans je Polygon. let pb = bbox_of(pts.iter().map(|q| [q.x, q.y])); if cutters.iter().all(|c| apart(pb, bbox_of(c.iter().map(|q| [q.x, q.y])))) { out.push(pr); continue; } let ring = encode_rings(&[pts]); let ns = no_stroke_edges.as_deref().unwrap_or(&[]); let mut nsf = vec![ns.len() as f64]; nsf.extend_from_slice(ns); let f = crate::voids::subtract_rings_flat(&ring[1..], &encode_rings(&cutters), &nsf); if f.is_empty() || f[0] < 0.0 { out.push(pr); continue; } let mut i = 1; for _ in 0..f[0] as usize { let n = f[i] as usize; i += 1; let rp: Vec = (0..n).map(|j| Vec2 { x: f[i + 2 * j], y: f[i + 2 * j + 1] }).collect(); i += 2 * n; let m = f[i] as usize; i += 1; let rn: Vec = f[i..i + m].to_vec(); i += m; let mut q = pr.clone(); if let Primitive::Polygon { pts, no_stroke_edges, .. } = &mut q { *pts = rp; *no_stroke_edges = (!rn.is_empty()).then_some(rn); } out.push(q); } } out } /// [159] Rechteck `[x0, y0, x1, y1]` um die Punkte (NaN bleibt NaN, s. [`apart`]). fn bbox_of(pts: impl Iterator) -> [f64; 4] { let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; for q in pts { if !(q[0].is_finite() && q[1].is_finite()) { return [f64::NAN; 4]; } b = [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[0]), b[3].max(q[1])]; } b } /// [159] Zwei Rechtecke mit sicherem Abstand (1 mm, über dem Raster der Booleans) getrennt; NaN → nein. fn apart(a: [f64; 4], b: [f64; 4]) -> bool { const GAP: f64 = 1e-3; a[2] + GAP < b[0] || b[2] + GAP < a[0] || a[3] + GAP < b[1] || b[3] + GAP < a[1] } /// Schnitthöhe des Geschosses (Welt): Basis + Schnitthöhe (Standard 1 m). pub fn cut_z(p: &Project, floor: &str) -> f64 { // Deckenspiegel ([100]): Schnitthöhe des Bezugsgeschosses. let l = super::ceiling_plan::source_floor(p, floor).or_else(|| p.floor(floor)); l.and_then(|l| l.base_elevation).unwrap_or(0.0) + l.and_then(|l| l.cut_height).unwrap_or(1.0) } // ── Schwarz-Weiss und Strichstärken ───────────────────────────────────────────────────────────── const REFERENCE_SCALE: f64 = 100.0; const MIN_FACTOR: f64 = 0.4; const MAX_FACTOR: f64 = 2.0; /// [140] Sockel (Papier-mm), der nicht mit dem Massstab wächst/schrumpft: feine Linien (Schraffur, /// Bemassung) ändern sich kaum, Haarlinien darunter gar nicht. const FINE_MM: f64 = 0.09; /// Strichstärken-Faktor für 1:`scale` ([32], nur mit `Project.scaleLineWeights`): (100/n)^0.5 (1:50 ≈ 1.41, /// 1:200 ≈ 0.71, 1:500 ≈ 0.45), begrenzt auf 0,4–2; sonst 1. Wirkt über [`scale_weight`] je nach Stärke. pub fn line_weight_factor(p: &Project, scale: f64) -> f64 { if p.scale_line_weights != Some(true) || !(scale > 0.0) || !scale.is_finite() { return 1.0; } let f = jsnum::pow(REFERENCE_SCALE / scale, 0.5); jsnum::min(MAX_FACTOR, jsnum::max(MIN_FACTOR, f)) } /// [140] Stärke `w` (Papier-mm, bezogen auf 1:100) beim Massstabsfaktor `f`: nur der Anteil über dem /// Sockel [`FINE_MM`] skaliert (w' = 0.09 + (w − 0.09)·f). Schwere Linien folgen dem Massstab fast ganz /// (Schnittkante 0.5 → 0.67 bei 1:50, → 0.38 bei 1:200), feine kaum (0.13 → 0.15 / 0.12) — die Rangfolge /// bleibt in jedem Massstab erhalten (linear, steigend), und Schraffuren fallen in 1:200/1:500 nicht unter /// die Druckgrenze. Linien bis 0.09 (Haarlinien) bleiben unverändert. pub fn scale_weight(w: f64, f: f64) -> f64 { if f == 1.0 || !(w > FINE_MM) || !f.is_finite() { return w; } FINE_MM + (w - FINE_MM) * f } /// Nachbearbeitung beim Schreiben (`plan::buf::Writer::post`): Schwarz-Weiss (alle Farben auf Tinte /// bzw. Papier; eine Vollpoché bleibt schwarz) und Strichstärken-Faktor — in dieser Reihenfolge wie /// früher `toMono` und `scalePrimitiveWeights`. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Post { pub mono: bool, pub lw: f64, /// Skizzenstil ([67], `plan/sketch.rs`): Meter Modell je Papier-mm; 0 = aus. pub sketch: f64, } impl Post { /// Wirkt sie auf etwas? pub fn active(&self) -> bool { self.mono || self.lw != 1.0 || self.sketch > 0.0 } fn hatch(&self, h: &mut HatchRender) { if self.mono && h.pattern != HatchPattern::None { if h.pattern == HatchPattern::Solid { h.color = HATCH_INK.into(); } else if !is_neutral(&h.color) { h.color = MONO_INK.into(); } } if self.lw != 1.0 { h.line_weight = scale_weight(h.line_weight, self.lw); } } /// Ein Primitiv (ohne Linien, die nimmt [`Post::line`]). pub fn apply(&self, p: &mut Primitive) { match p { Primitive::Polygon { fill, stroke, stroke_width_mm, hatch, .. } => { if self.mono { let solid = hatch.pattern == HatchPattern::Solid; if *fill != "none" { if solid { *fill = HATCH_INK.into(); } else if !is_neutral(fill) { *fill = "#ffffff".into(); } } // [140] „none" bleibt (Wandschichten ohne Umriss: sonst Kontur statt Schraffur). if *stroke != "none" && !is_neutral(stroke) { *stroke = MONO_INK.into(); } } self.hatch(hatch); if self.lw != 1.0 { *stroke_width_mm = scale_weight(*stroke_width_mm, self.lw); } } Primitive::Text { color, doc, .. } => { if self.mono { *color = MONO_INK.into(); // [140] Raumstempel in Tusche: farbige Auszeichnungen im Stempel-Text werden Tinte. for r in doc.paragraphs.iter_mut().flat_map(|q| q.runs.iter_mut()) { if r.marks.color.as_deref().is_some_and(|c| !is_neutral(c)) { r.marks.color = Some(MONO_INK.into()); } } } } Primitive::Line { weight_mm, color, .. } => { if self.mono && !color.as_deref().is_some_and(is_neutral) { *color = Some(MONO_INK.into()); } if self.lw != 1.0 { *weight_mm = scale_weight(*weight_mm, self.lw); } } Primitive::Arc { weight_mm, .. } | Primitive::DrawingCircle { weight_mm, .. } | Primitive::DrawingArc { weight_mm, .. } => { if self.lw != 1.0 { *weight_mm = scale_weight(*weight_mm, self.lw); } } Primitive::DrawingText { .. } | Primitive::DrawingTextPath { .. } | Primitive::DrawingImage { .. } => {} } } /// Farbe und Stärke einer Linie. pub fn line<'a>(&self, color: Option<&'a str>, w: f64) -> (Option<&'a str>, f64) { (if self.mono && !color.is_some_and(is_neutral) { Some(MONO_INK) } else { color }, scale_weight(w, self.lw)) } } /// [140] Unbunte Farbe (Grau/Schwarz/Weiss, `#rgb`/`#rrggbb`/`#rrggbbaa`): bleibt in Schwarz-Weiss erhalten /// (Schatten, Gelände-Grau, Treppen-Grau); bunte Farben werden Tinte bzw. Papier. pub fn is_neutral(c: &str) -> bool { let h = c.trim().trim_start_matches('#'); let ch = |i: usize, n: usize| u8::from_str_radix(h.get(i..i + n)?, 16).ok().map(|v| if n == 1 { v * 17 } else { v }); let rgb = match h.len() { 3 | 4 => (ch(0, 1), ch(1, 1), ch(2, 1)), 6 | 8 => (ch(0, 2), ch(2, 2), ch(4, 2)), _ => return false, }; let (Some(r), Some(g), Some(b)) = rgb else { return false }; r.max(g).max(b) - r.min(g).min(b) <= 20 } /// [32] Strichstärken nach Massstab auf Schnitt-/Ansichts-Primitive (wie im Grundriss über [`post_for`]): /// Faktor [`line_weight_factor`] auf Linien, Umrisse und Schraffurlinien; ohne Projekt-Option nichts. pub fn scale_line_weights(p: &Project, scale: f64, prims: &mut [Primitive]) { let lw = line_weight_factor(p, scale); if lw == 1.0 { return; } let post = Post { mono: false, lw, sketch: 0.0 }; for q in prims.iter_mut() { match q { Primitive::Line { weight_mm, .. } => *weight_mm = scale_weight(*weight_mm, lw), _ => post.apply(q), } } } /// Nachbearbeitung eines Plans: Schwarz-Weiss und Strichstärken-Faktor; `None`, wenn sie nichts tut. /// Auf einer Blatt-Ebene (`layoutId`) gelten die Strichstärken unverändert (Papier 1:1). pub fn post_for(p: &Project, a: &super::domains::PlanArgs) -> Option { let level = p.floor(&a.floor); let sheet = level.is_some_and(|l| l.layout_id.is_some()); let sketch = if sheet { 0.0 } else { sketch_k(level.and_then(|l| l.sketch), a.scale) }; Some(Post { mono: a.mono, lw: if sheet { 1.0 } else { line_weight_factor(p, a.scale) }, sketch }).filter(Post::active) } /// [67] Skizzenstil einer Ebene beim Massstab 1:`scale`: Meter je Papier-mm, 0 = aus. pub fn sketch_k(on: Option, scale: f64) -> f64 { if on == Some(true) && scale > 0.0 && scale.is_finite() { scale / 1000.0 } else { 0.0 } } /// [67] Nachbearbeitung nur mit Skizzenstil (Schnitt/Ansicht; `None` = aus). pub fn sketch_post(on: Option, scale: f64) -> Option { Some(Post { mono: false, lw: 1.0, sketch: sketch_k(on, scale) }).filter(Post::active) } // ── Ausmass ───────────────────────────────────────────────────────────────────────────────────── /// Ausmass der Zutaten, die „Einpassen" und Druck ganz zeigen sollen: Schatten und Baurechts-Linien /// (`extra`) und die ganze Kontext-Schicht (Konturen, Netze, Luftbilder) — Rohwerte für /// [`plan_bounds`]. /// Kontext-Objekte zählen nur, wenn ihre Kategorie gezeigt wird (`shown`, wie `plan_context`; ohne Kategorie /// immer) — sonst bestimmt ein ausgeblendetes Gelände Zoom und Viewport-Grösse ([66]). pub fn extra_bounds(p: &Project, extra: &[(Primitive, u32)], shown: impl Fn(&str) -> bool) -> Bounds { let mut b = Bounds::new(); for (e, _) in extra { match e { Primitive::Polygon { pts, .. } => { for q in pts { b.acc(q.x, q.y); } } Primitive::Line { a, b: e, .. } => { b.acc(a.x, a.y); b.acc(e.x, e.y); } _ => {} } } for obj in p.context.as_deref().unwrap_or(&[]) { let code = match obj { ContextObject::ImportedMesh(m) => m.category_code.as_deref(), ContextObject::ContourSet(s) => s.category_code.as_deref(), ContextObject::TerrainMesh(t) => t.category_code.as_deref(), ContextObject::Image(i) => i.category_code.as_deref(), ContextObject::Excavation(e) => e.category_code.as_deref(), }; if code.is_some_and(|k| !shown(k)) { continue; } match obj { ContextObject::ContourSet(cs) => { for c in &cs.contours { for q in &c.pts { b.acc(q.x, q.y); } } } ContextObject::Image(im) => { b.acc(im.min.x, im.min.y); b.acc(im.max.x, im.max.y); } ContextObject::ImportedMesh(m) => mesh_bounds(&m.positions, &mut b), ContextObject::TerrainMesh(m) => mesh_bounds(&m.positions, &mut b), ContextObject::Excavation(e) => { for q in &e.outline { b.acc(q.x, q.y); } } } } b } fn mesh_bounds(pos: &[f64], b: &mut Bounds) { let mut i = 0; while i + 1 < pos.len() { b.acc(pos[i], pos[i + 1]); i += 3; } } /// Ausmass des Plans (`computeBounds`): Ausmass der Domänen (falls vorhanden, als zwei Ecken), dann /// die Zutaten; ohne Punkte `[0, 0, 1, 1]`. pub fn plan_bounds(domains: &Bounds, extra: &Bounds) -> [f64; 4] { let mut b = Bounds::new(); if let Some(d) = domains.get() { b.acc(d[0], d[1]); b.acc(d[2], d[3]); } b.merge(extra.raw()); b.get().unwrap_or([0.0, 0.0, 1.0, 1.0]) } #[cfg(test)] mod tests { use super::*; fn sample() -> Project { serde_json::from_str(include_str!("../../tests/fixtures/sample_project.json")).unwrap() } /// [66] Ausgeblendete Kontext-Kategorien (Höhenlinien) bestimmen das Ausmass nicht mit. #[test] fn ausmass_ohne_ausgeblendeten_kontext() { let mut p = sample(); p.context = Some(vec![serde_json::from_value(serde_json::json!({ "type": "contourSet", "id": "hl", "name": "HL", "categoryCode": "14", "contours": [{"z": 0.0, "pts": [{"x": -100.0, "y": -100.0}, {"x": 100.0, "y": 100.0}]}] })) .unwrap()]); let on = extra_bounds(&p, &[], |_| true).get().unwrap(); assert_eq!(on, [-100.0, -100.0, 100.0, 100.0]); assert!(extra_bounds(&p, &[], |k| k != "14").get().is_none()); } /// [63] Profilverstösse erscheinen im Grundriss (schwächeres Rot); ohne Profil nichts. #[test] fn profilverstoesse_im_grundriss() { let mut p = sample(); let floor = ground_floor_id(&p).unwrap().to_string(); let rules = |extra: serde_json::Value| { let mut v = serde_json::json!({"parcel": [{"x": -1, "y": -1}, {"x": 6, "y": -1}, {"x": 6, "y": 5}, {"x": -1, "y": 5}], "defaultSetback": 0.0}); v.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); serde_json::from_value(v).unwrap() }; p.site_rules = Some(rules(serde_json::json!({}))); let n0 = site_and_shadow(&p, &floor, None, 100.0, true).1.len(); p.site_rules = Some(rules(serde_json::json!({"profileAngle": 10.0, "profileHeight": 0.01}))); let c = crate::site_rules::check_project(&p).unwrap(); assert!(c.profile_exceeded); let n1 = site_and_shadow(&p, &floor, None, 100.0, true).1.len(); assert!(n1 > n0, "{n0} {n1}"); // [66] Ohne Vermessung (Kategorie aus) kein Baurecht. let (under, viol) = site_and_shadow(&p, &floor, None, 100.0, false); assert!(under.is_empty() && viol.is_empty()); } /// Oberste Fläche mit Pick-Id unter dem Punkt (wie `PickIndex::polygons_at`, Maske „Kontext"). fn top_pick(prims: &[(Primitive, u32)], x: f64, y: f64) -> Option { prims.iter().rev().find_map(|(q, _)| match q { Primitive::Polygon { pts, context_object_id: Some(id), .. } => { let flat: Vec = pts.iter().flat_map(|v| [v.x, v.y]).collect(); crate::plan::pick::point_in_polygon(x, y, &flat).then(|| id.clone()) } _ => None, }) } /// [137] Schattenflächen tragen die Pick-Id des Sonnenstands, die Baurechtslinien unsichtbare Bänder mit der /// des Baurechts (Klick darauf öffnet deren Einstellungen); ohne sichtbare Studie bzw. in einem anderen /// Geschoss nichts. #[test] fn klick_auf_schatten_und_baurecht() { let mut p = sample(); let floor = ground_floor_id(&p).unwrap().to_string(); p.sun_study = Some(SunStudy { when: "2026-12-21T09:00:00Z".into(), show: true, ..Default::default() }); let when = Some(1_797_843_600_000.0); // 2026-12-21T09:00:00Z let (under, _) = site_and_shadow(&p, &floor, when, 100.0, true); let shadows: Vec<&Primitive> = under.iter().map(|(q, _)| q).filter(|q| matches!(q, Primitive::Polygon { fill, .. } if fill == SUN_SHADOW_FILL)).collect(); assert!(!shadows.is_empty()); assert!(shadows.iter().all(|q| matches!(q, Primitive::Polygon { context_object_id: Some(id), .. } if id == SITE_PICK_SUN))); // Ein Punkt in der ersten Schattenfläche (Raster über ihr Ausmass). let Primitive::Polygon { pts, .. } = shadows[0] else { panic!() }; let flat: Vec = pts.iter().flat_map(|v| [v.x, v.y]).collect(); let (x0, x1) = pts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |a, v| (a.0.min(v.x), a.1.max(v.x))); let (y0, y1) = pts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |a, v| (a.0.min(v.y), a.1.max(v.y))); let inside = (0..400).map(|k| (x0 + (x1 - x0) * ((k % 20) as f64 + 0.5) / 20.0, y0 + (y1 - y0) * ((k / 20) as f64 + 0.5) / 20.0)).find(|q| crate::plan::pick::point_in_polygon(q.0, q.1, &flat)).unwrap(); assert_eq!(top_pick(&under, inside.0, inside.1).as_deref(), Some(SITE_PICK_SUN)); assert_eq!(top_pick(&under, 1e4, 1e4), None); assert!(site_and_shadow(&p, "anderes-geschoss", when, 100.0, true).0.is_empty()); p.sun_study.as_mut().unwrap().show = false; assert_eq!(top_pick(&site_and_shadow(&p, &floor, when, 100.0, true).0, inside.0, inside.1), None); // Baurecht: Parzellengrenze bei x = −30, Grenzabstand 3 m → zulässige Fläche ab x = −27; Band ±0.15 m bei 1:100. p.site_rules = Some(serde_json::from_value(serde_json::json!({"parcel": [{"x": -30, "y": -30}, {"x": 40, "y": -30}, {"x": 40, "y": 40}, {"x": -30, "y": 40}], "defaultSetback": 3.0})).unwrap()); let (under, _) = site_and_shadow(&p, &floor, when, 100.0, true); assert_eq!(top_pick(&under, -30.1, 5.0).as_deref(), Some(SITE_PICK_RULES)); assert_eq!(top_pick(&under, -27.0, 5.0).as_deref(), Some(SITE_PICK_RULES), "zulässige Fläche"); assert_eq!(top_pick(&under, -28.5, 5.0), None); // Massstab 1:500: Band ±0.75 m. assert_eq!(top_pick(&site_and_shadow(&p, &floor, when, 500.0, true).0, -29.4, 5.0).as_deref(), Some(SITE_PICK_RULES)); } #[test] fn strichstaerken_faktor() { let mut on = sample(); on.scale_line_weights = Some(true); assert_eq!(line_weight_factor(&on, 100.0), 1.0); assert!((line_weight_factor(&on, 200.0) - 0.5f64.sqrt()).abs() < 1e-12); assert!((line_weight_factor(&on, 50.0) - 2f64.sqrt()).abs() < 1e-12); assert_eq!(line_weight_factor(&on, 100000.0), 0.4); assert_eq!(line_weight_factor(&on, 1.0), 2.0); assert_eq!(line_weight_factor(&sample(), 200.0), 1.0); assert_eq!(line_weight_factor(&on, f64::NAN), 1.0); } /// [32] Schnitt/Ansicht: Faktor auch auf Linien; ohne Option unverändert. #[test] fn strichstaerken_in_schnitt_und_ansicht() { let mut on = sample(); on.scale_line_weights = Some(true); let lines = || vec![Primitive::Line { a: Vec2 { x: 0.0, y: 0.0 }, b: Vec2 { x: 1.0, y: 0.0 }, cls: "x".into(), weight_mm: 0.5, dash: None, zigzag: None, motif: None, color: None, drawing_id: None, opening_id: None, stair_id: None, greyed: None, opacity: None }]; let mut a = lines(); scale_line_weights(&on, 200.0, &mut a); let Primitive::Line { weight_mm, .. } = &a[0] else { unreachable!() }; assert!((weight_mm - (0.09 + 0.41 * 0.5f64.sqrt())).abs() < 1e-12); let mut b = lines(); scale_line_weights(&sample(), 200.0, &mut b); let Primitive::Line { weight_mm, .. } = &b[0] else { unreachable!() }; assert_eq!(*weight_mm, 0.5); } /// [140] Rangfolge der Strichstärken je Massstab: Schnittkante 0.5 (1:100) → ≈ 0.67 (1:50) / ≈ 0.38 /// (1:200); feine Linien (Schraffur 0.1, Bemassung 0.13) ändern sich kaum, nie unter 0.09; die /// Reihenfolge schwer > mittel > fein > Schraffur bleibt in jedem Massstab. #[test] fn strichstaerken_rangfolge_je_massstab() { let mut on = sample(); on.scale_line_weights = Some(true); let at = |w: f64, s: f64| scale_weight(w, line_weight_factor(&on, s)); assert!((at(0.5, 50.0) - 0.67).abs() < 0.01); assert!((at(0.5, 200.0) - 0.38).abs() < 0.01); assert_eq!(at(0.5, 100.0), 0.5); // [140] Grösste Standard-Stärke 0.25 bei 1:100 (Wand-Schnittkante): 1:50 kräftiger, 1:200 feiner. assert_eq!(at(0.25, 100.0), 0.25); assert!(at(0.25, 50.0) > 0.3 && at(0.25, 200.0) < 0.21 && at(0.25, 200.0) > at(0.13, 200.0)); assert!((at(0.13, 50.0) - 0.13).abs() < 0.02 && (at(0.13, 200.0) - 0.13).abs() < 0.02); for s in [20.0, 50.0, 100.0, 200.0, 500.0, 1000.0] { let class = [0.7, 0.5, 0.35, 0.25, 0.18, 0.13, 0.1].map(|w| at(w, s)); assert!(class.windows(2).all(|p| p[0] > p[1]), "1:{s}: {class:?}"); assert!(at(0.1, s) >= 0.09 && at(0.13, s) >= 0.09, "1:{s}: feine Linien druckbar"); } assert_eq!(scale_weight(0.02, 0.5), 0.02, "Haarlinien bleiben"); assert_eq!(scale_weight(f64::NAN, 2.0).is_nan(), true); } #[test] fn blatt_ebene_ohne_strichstaerken_faktor() { let mut p = sample(); p.scale_line_weights = Some(true); let mut sheet = p.drawing_levels[0].clone(); sheet.id = "blatt".into(); sheet.kind = crate::model::DrawingLevelKind::Drawing; sheet.layout_id = Some("L1".into()); p.drawing_levels.push(sheet); let args = |floor: &str| super::super::domains::PlanArgs::parse(1.0, &serde_json::json!({"floor": floor, "scale": 1}).to_string()).unwrap(); assert_eq!(post_for(&p, &args("blatt")), None, "Papier 1:1: Stärken unverändert"); assert!(post_for(&p, &args("eg")).is_some_and(|q| q.lw > 1.0)); } #[test] fn abzugskoerper_spart_wand_aus() { let mut v: serde_json::Value = serde_json::from_str(include_str!("../../tests/fixtures/sample_project.json")).unwrap(); let walls = |v: &serde_json::Value| { let p: Project = serde_json::from_value(v.clone()).unwrap(); let codes: Vec = p.flat_categories().iter().map(|c| c.code.clone()).collect(); let a = super::super::domains::PlanArgs::parse(1.0, &serde_json::json!({"floor": "eg", "show": codes}).to_string()).unwrap(); let (prims, _, _) = crate::plan::buf::decode(&super::super::domains::plan_domains_buf(&p, &a).unwrap()).unwrap(); prims.into_iter().filter(|q| matches!(q, Primitive::Polygon { wall_id: Some(_), .. })).collect::>() }; let before = walls(&v); v["extrudedSolids"] = serde_json::json!([{"id": "void1", "type": "extrudedSolid", "levelId": "eg", "operation": "subtract", "height": 3, "points": [{"x": 1.95, "y": -0.5}, {"x": 2.15, "y": -0.5}, {"x": 2.15, "y": 0.5}, {"x": 1.95, "y": 0.5}]}]); let after = walls(&v); assert_ne!(before, after); assert!(after.len() > before.len(), "{} → {}", before.len(), after.len()); } #[test] fn erdgeschoss_naechst_null() { let p = sample(); assert_eq!(ground_floor_id(&p), Some("eg")); } #[test] fn mono_poche_bleibt_schwarz() { let post = Post { mono: true, lw: 1.0, sketch: 0.0 }; let mut solid = HatchRender { pattern: HatchPattern::Solid, ..no_hatch() }; solid.color = "#123456".into(); let mut p = flat_polygon(vec![], "#abcdef", 1.0); if let Primitive::Polygon { hatch, stroke, .. } = &mut p { *hatch = solid; *stroke = "#ff0000".into(); } post.apply(&mut p); match &p { Primitive::Polygon { fill, stroke, hatch, .. } => { assert_eq!(fill, HATCH_INK); assert_eq!(stroke, MONO_INK); assert_eq!(hatch.color, HATCH_INK); } _ => unreachable!(), } assert_eq!(post.line(None, 0.25), (Some(MONO_INK), 0.25)); } /// [140] Raumstempel in Tusche: auch farbige Auszeichnungen im Stempel-Text (Run-Farbe) werden Tinte, /// Grautöne bleiben; „Farbig" behält die Auszeichnung. #[test] fn mono_raumstempel_ohne_farbige_auszeichnung() { let run = |text: &str, color: &str| TextRun { text: text.into(), marks: Marks { color: Some(color.into()), ..Default::default() }, ..Default::default() }; let doc = RichTextDoc { version: 1.0, paragraphs: vec![Paragraph { runs: vec![run("E.01 ", "#808080"), run("Zimmer", "#d0342c")], ..Default::default() }], ..Default::default() }; let stamp = || Primitive::Text { at: Vec2 { x: 0.0, y: 0.0 }, doc: doc.clone(), extra_lines: vec![], base_pt: 10.0, color: "#2255cc".into(), room_id: Some("r".into()), greyed: None, opacity: None }; let colors = |p: &Primitive| match p { Primitive::Text { doc, color, .. } => (color.clone(), doc.paragraphs[0].runs.iter().map(|r| r.marks.color.clone()).collect::>()), _ => unreachable!(), }; let mut p = stamp(); Post { mono: true, lw: 1.0, sketch: 0.0 }.apply(&mut p); assert_eq!(colors(&p), (MONO_INK.to_string(), vec![Some("#808080".into()), Some(MONO_INK.into())])); let mut p = stamp(); Post { mono: false, lw: 0.8, sketch: 0.0 }.apply(&mut p); assert_eq!(colors(&p), ("#2255cc".to_string(), vec![Some("#808080".into()), Some("#d0342c".into())])); } /// [140] Schwarz-Weiss als Tusche-Standard: Wandschichten ohne Umriss bleiben ohne Umriss (sonst verdrängt /// die Kontur die Schraffur), Grautöne (Schatten, Gelände, Treppe) bleiben, bunte Farben werden Tinte/Papier. #[test] fn mono_behaelt_grau_und_ohne_umriss() { let post = Post { mono: true, lw: 1.0, sketch: 0.0 }; let mut p = flat_polygon(vec![], "#3c3c3c", 0.0); if let Primitive::Polygon { stroke, hatch, .. } = &mut p { *stroke = "none".into(); *hatch = HatchRender { pattern: HatchPattern::Diagonal, color: "#808080".into(), ..no_hatch() }; } post.apply(&mut p); match &p { Primitive::Polygon { fill, stroke, hatch, .. } => { assert_eq!(fill, "#3c3c3c"); assert_eq!(stroke, "none"); assert_eq!(hatch.color, "#808080"); } _ => unreachable!(), } let mut q = flat_polygon(vec![], "#e8dcc0", 0.0); if let Primitive::Polygon { stroke, hatch, .. } = &mut q { *stroke = "#b06030".into(); *hatch = HatchRender { pattern: HatchPattern::Diagonal, color: "#c04020".into(), ..no_hatch() }; } post.apply(&mut q); match &q { Primitive::Polygon { fill, stroke, hatch, .. } => { assert_eq!(fill, "#ffffff"); assert_eq!(stroke, MONO_INK); assert_eq!(hatch.color, MONO_INK); } _ => unreachable!(), } assert_eq!(post.line(Some("#8a8a8a"), 0.13), (Some("#8a8a8a"), 0.13)); assert_eq!(post.line(Some("#a05a2c"), 0.13), (Some(MONO_INK), 0.13)); assert!(is_neutral("#fff") && is_neutral("#1a1a1aff") && !is_neutral("#ff0000") && !is_neutral("rot")); } }