diff --git a/scripts/gen-rust-model.py b/scripts/gen-rust-model.py index 6c2f7649..13d283cd 100644 --- a/scripts/gen-rust-model.py +++ b/scripts/gen-rust-model.py @@ -14,6 +14,7 @@ MANUAL = {"Vec2", "Drawing2DGeom", "VerticalAnchor", "ColumnProfile", "LayoutAnn "LayoutAnnotationPatch", "ContextObject", "BuiltinPaletteBank", "SiaKey", "SiaAggregate", "BoolMark", "TextRange"} TAGGED = {"GridRule", "ModuleRule", "ConditionalThicknessRule", "ReferenceLineRule", "SequenceRule", "ImportedMesh", "ContourSet", "TerrainMesh", "ContextImage"} +RENAMES = {"OpeningKind2": "ElementKind"} ONLY = None # alle Interfaces aus SRC, die erreichbar sind def strip_comments(s): @@ -256,4 +257,7 @@ print("// GENERIERT von scripts/gen-rust-model.py aus den TS-Typen (Stand 28.10. "// Rust-Gegenstück zu src/model/types.ts ([K4] S2). Union-Typen mit Tag stehen in model/manual.rs.\n" "#![allow(clippy::large_enum_variant)]\n" "use super::manual::*;\nuse serde::{Deserialize, Serialize};\n") -print("\n".join(out_items)) +body = "\n".join(out_items) +for a, b in RENAMES.items(): + body = body.replace(a, b) +print(body) diff --git a/src-tauri/core/src/flat_write.rs b/src-tauri/core/src/flat_write.rs new file mode 100644 index 00000000..2719dfa0 --- /dev/null +++ b/src-tauri/core/src/flat_write.rs @@ -0,0 +1,64 @@ +//! Schreibhilfe für flache `f64`-Puffer (Gegenstück zu `FlatWriter` in `src/geometry/coreFlat.ts` +//! und zu `flat_read::Reader`): Rust-Sammler bauen damit dieselben Puffer, die die bestehenden +//! Kern-Funktionen (`ceilings3d`, `wall_bands` …) lesen. + +use crate::model::Vec2; + +#[derive(Default)] +pub struct FlatWriter { + buf: Vec, +} + +impl FlatWriter { + pub fn new() -> Self { + Self::default() + } + + pub fn num(&mut self, v: f64) -> &mut Self { + self.buf.push(v); + self + } + + pub fn nums(&mut self, v: &[f64]) -> &mut Self { + self.buf.extend_from_slice(v); + self + } + + /// Platz für eine erst später bekannte Zahl; mit [`set`](Self::set) nachtragen. + pub fn slot(&mut self) -> usize { + self.buf.push(0.0); + self.buf.len() - 1 + } + + pub fn set(&mut self, slot: usize, v: f64) -> &mut Self { + self.buf[slot] = v; + self + } + + /// Nur die Punkte `x0, y0, x1, y1, …`. + pub fn pts(&mut self, pts: &[Vec2]) -> &mut Self { + for p in pts { + self.buf.push(p.x); + self.buf.push(p.y); + } + self + } + + /// Anzahl, dann die Punkte. + pub fn ring(&mut self, pts: &[Vec2]) -> &mut Self { + self.buf.push(pts.len() as f64); + self.pts(pts) + } + + pub fn done(self) -> Vec { + self.buf + } + + pub fn len(&self) -> usize { + self.buf.len() + } + + pub fn is_empty(&self) -> bool { + self.buf.is_empty() + } +} diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 4d29f885..13bf1902 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -5,6 +5,7 @@ //! Datenübergabe: flache `f64`-Puffer (s. [`flat`]), kein JSON — schnell und ohne Serde-Kosten. pub mod flat; +pub mod flat_write; pub mod polygon_bool; pub mod roof; pub mod roof_skeleton; @@ -41,6 +42,8 @@ pub mod delaunay; pub mod document; pub mod mesh_section; pub mod model; +pub mod model3d; +pub mod style; pub mod plan_elevation; pub mod plan_misc; pub mod plan_section; diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs index 0495ba60..661166bd 100644 --- a/src-tauri/core/src/model/generated.rs +++ b/src-tauri/core/src/model/generated.rs @@ -940,7 +940,7 @@ pub struct Roof { } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub enum OpeningKind2 { +pub enum ElementKind { #[serde(rename = "window")] Window, #[serde(rename = "door")] @@ -1021,7 +1021,7 @@ pub struct Opening { pub category_code: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub locked: Option, - pub kind: OpeningKind2, + pub kind: ElementKind, pub position: f64, pub width: f64, pub height: f64, diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs new file mode 100644 index 00000000..b6193674 --- /dev/null +++ b/src-tauri/core/src/model3d.rs @@ -0,0 +1,549 @@ +//! 3D-Ableitung aus dem Projekt-Dokument ([K4] S2): Rust-Gegenstück zu `src/plan/toWalls3d.ts` und +//! `toWalls3d/*.ts`. Liefert das Modell-Bündel (`RModel3d`) für render3d, die Schnitt-Eingabe und +//! die Ansicht. Die Geometrie rechnen die bestehenden Kern-Module (`ceilings3d`, `columns3d`, +//! `wall_bands` …); hier werden sie aus dem typisierten `Project` gespeist und die Ergebnisse mit +//! Farbe, Schraffur und Ids versehen. + +use crate::flat_write::FlatWriter; +use crate::jsnum::{cos, sin}; +use crate::model::*; +use crate::style::{self, hex_to_rgb, resolve_component_hatch, resolve_cut_line_style, Rgb, SLAB_RGB}; +use serde::Serialize; + +pub type RVec2 = [f64; 2]; + +/// Schnitt-Verschneidungs-/Linienstil-Metadaten eines Bandes (`RCutMeta`). +#[derive(Debug, Clone, PartialEq, Serialize, Default)] +#[serde(rename_all = "camelCase")] +pub struct RCutMeta { + #[serde(skip_serializing_if = "Option::is_none")] + pub join_priority: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub component_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub line_color: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub line_weight: Option, +} + +/// Eine extrudierte Deckenplatte (`RSlab`). +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RSlab { + pub outline: Vec, + pub z_bottom: f64, + pub z_top: f64, + pub color: Rgb, + pub ceiling_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub hatch: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cut: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub monolith: Option, +} + +/// Ein rohes Dreiecks-Mesh (`RMesh`). +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RMesh { + pub positions: Vec, + pub indices: Vec, + pub kind: &'static str, + pub color: Rgb, + #[serde(skip_serializing_if = "Option::is_none")] + pub vertex_colors: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub material_index: Option, +} + +// ── Decken ────────────────────────────────────────────────────────────────── + +fn ceiling_layers<'a>(p: &'a Project, c: &Ceiling) -> Option<&'a [Layer]> { + if let Some(id) = c.ceiling_type_id.as_deref() { + if let Some(t) = p.ceiling_types.as_deref().and_then(|v| v.iter().find(|t| t.id == id)) { + return Some(&t.layers); + } + } + p.wall_types.iter().find(|t| t.id == c.wall_type_id).map(|t| t.layers.as_slice()) +} + +/// Deckenplatten (`emitSlabs`): eine Platte je Materiallage, oben→unten gestapelt. +pub fn emit_slabs(p: &Project) -> Vec { + let mut ceilings: Vec<&Ceiling> = Vec::new(); + let mut layers_of: Vec> = Vec::new(); + let mut w = FlatWriter::new(); + let count = w.slot(); + for c in p.ceilings.as_deref().unwrap_or(&[]) { + if c.outline.len() < 3 { + continue; + } + let (z_bottom, z_top) = p.ceiling_vertical_extent(c); + let layers = ceiling_layers(p, c); + w.ring(&c.outline); + let openings = c.openings.as_deref().unwrap_or(&[]); + w.num(openings.len() as f64); + for o in openings { + w.ring(o); + } + w.num(z_bottom).num(z_top).num(layers.map_or(0, |l| l.len()) as f64); + for l in layers.unwrap_or(&[]) { + w.num(l.thickness); + } + ceilings.push(c); + layers_of.push(layers); + } + if ceilings.is_empty() { + return vec![]; + } + w.set(count, ceilings.len() as f64); + let mut out = Vec::new(); + for d in crate::ceilings3d::ceilings(&w.done()) { + let c = ceilings[d.ceiling]; + let layers = layers_of[d.ceiling]; + let outline: Vec = d.ring.clone(); + for (layer_idx, z_bottom, z_top) in d.slabs { + let Some(layers) = layers.filter(|_| layer_idx >= 0) else { + out.push(RSlab { outline: outline.clone(), z_bottom, z_top, color: SLAB_RGB, ceiling_id: c.id.clone(), hatch: None, cut: None, monolith: None }); + continue; + }; + 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()); + ( + 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), + }), + ) + } + None => (SLAB_RGB, None), + }; + out.push(RSlab { + outline: outline.clone(), + z_bottom, + z_top, + color, + ceiling_id: c.id.clone(), + hatch: resolve_component_hatch(p, &l.component_id, None), + cut, + monolith: None, + }); + } + } + out +} + +// ── Stützen ───────────────────────────────────────────────────────────────── + +const COLUMN_ROUND_SEGMENTS: usize = 32; +const COLUMN_RGB: Rgb = [0.7, 0.7, 0.72]; + +/// Grundriss-Querschnitt einer Stütze (`columnFootprint`). +pub fn column_footprint(col: &Column) -> Vec { + let (cx, cy) = (col.position.x, col.position.y); + match &col.profile { + ColumnProfile::Round { radius } => (0..COLUMN_ROUND_SEGMENTS) + .map(|i| { + let t = (i as f64 / COLUMN_ROUND_SEGMENTS as f64) * std::f64::consts::PI * 2.0; + Vec2 { x: cx + radius * cos(t), y: cy + radius * sin(t) } + }) + .collect(), + ColumnProfile::Rect { width, depth } => { + let (hw, hd) = (width / 2.0, depth / 2.0); + let rot = col.rotation; + let (c, s) = (cos(rot), sin(rot)); + [(-hw, -hd), (hw, -hd), (hw, hd), (-hw, hd)] + .iter() + .map(|&(x, y)| Vec2 { x: cx + x * c - y * s, y: cy + x * s + y * c }) + .collect() + } + } +} + +/// Stützen als Prisma-Meshes (`emitColumns`). +pub fn emit_columns(p: &Project) -> Vec { + let mut cols: Vec<&Column> = Vec::new(); + let mut w = FlatWriter::new(); + let count = w.slot(); + for col in p.columns.as_deref().unwrap_or(&[]) { + if col.height <= 0.0 { + continue; + } + let (z_bottom, z_top) = p.column_vertical_extent(col); + let foot = column_footprint(col); + w.num(z_bottom).num(z_top).ring(&foot); + cols.push(col); + } + if cols.is_empty() { + return vec![]; + } + w.set(count, cols.len() as f64); + crate::columns3d::columns(&w.done()) + .into_iter() + .map(|m| { + let col = cols[m.src]; + let color = col + .component_id + .as_deref() + .and_then(|id| p.component(id)) + .map_or(COLUMN_RGB, |c| hex_to_rgb(&c.color, COLUMN_RGB)); + RMesh { positions: m.positions, indices: m.indices, kind: "extrusion", color, vertex_colors: None, material_index: None } + }) + .collect() +} + +// ── Wände ─────────────────────────────────────────────────────────────────── + +use crate::joins::{self, JoinLayer, JoinWall, Reference, WallCuts}; +use crate::jsmath::hypot2; +use crate::jsnum::atan2; +use crate::opening_geom::{self, WallRef}; +use crate::style::{dominant_layer, dominant_layer_color, dominant_layer_hatch, WALL_RGB}; +use crate::wall_bands::{self, BandIn, CeilingIn, FloorContext, OpeningIn, RoofIn, Termination}; +use kernel2d::Vec2 as KVec; +use std::collections::HashMap; + +/// Absenkung der Oberkante (`topDrop`), Löcher und Metadaten je Wandkörper (`RWall`). +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RHole { + pub from: f64, + pub to: f64, + pub z_bottom: f64, + pub z_top: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RWall { + pub start: RVec2, + pub end: RVec2, + pub thickness: f64, + pub height: f64, + pub base_elevation: f64, + #[serde(skip_serializing_if = "Option::is_none")] + pub top_drop: Option<[f64; 2]>, + pub color: Rgb, + pub layers: Vec<()>, + pub wall_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub holes: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub hatch: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub material_index: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cut: Option, +} + +/// Textur-Karten-URLs der Bauteile in der Reihenfolge des ersten Auftretens: Wandtypen, dann +/// Decken, dann Dächer (`wallMaterialColorMaps`). +pub fn wall_material_color_maps(p: &Project) -> Vec { + let mut seen = std::collections::HashSet::new(); + let mut list = Vec::new(); + let mut consider = |id: &str| { + if let Some(url) = p.component(id).and_then(|c| c.material.as_ref()).and_then(|m| m.color.as_deref()).filter(|u| !u.is_empty()) { + if seen.insert(url.to_owned()) { + list.push(url.to_owned()); + } + } + }; + for w in &p.walls { + if let Some(t) = p.wall_type(w) { + for l in &t.layers { + consider(&l.component_id); + } + } + } + for c in p.ceilings.as_deref().unwrap_or(&[]) { + if let Some(layers) = ceiling_layers(p, c) { + for l in layers { + consider(&l.component_id); + } + } + } + for r in p.roofs.as_deref().unwrap_or(&[]) { + for l in p.roof_layers(r) { + if !l.component_id.is_empty() { + consider(&l.component_id); + } + } + } + list +} + +/// Textur-Ebene (1-basiert) der Farbkarte eines Bauteils (`resolveComponentMaterialLayer`). +fn material_layer(p: &Project, maps: &[String], component_id: &str) -> Option { + let url = p.component(component_id)?.material.as_ref()?.color.as_deref().filter(|u| !u.is_empty())?; + maps.iter().position(|m| m == url).map(|i| (i + 1) as f64) +} + +struct WallBand { + thickness: f64, + color: Rgb, + hatch: Option, + material_index: Option, + priority: Option, + component_id: Option, + cut_line_color: Option, + cut_line_weight: Option, +} + +const SECTION_WALL_AXIS_ANGLE_DEG: f64 = 90.0; + +fn plain_band(thickness: f64) -> WallBand { + WallBand { thickness, color: WALL_RGB, hatch: None, material_index: None, priority: None, component_id: None, cut_line_color: None, cut_line_weight: None } +} + +/// Schichtstapel EINER Wand als Bänder (`resolveWallBands`); `stacked` = Lagen einzeln gestapelt. +fn resolve_wall_bands(p: &Project, maps: &[String], wall: &Wall, layered: bool) -> (Vec, bool) { + let fallback = || (vec![plain_band(0.2)], false); + let Some(wt) = p.wall_type(wall) else { return fallback() }; + if wt.layers.is_empty() { + return (vec![plain_band(Project::type_thickness(&wt.layers))], false); + } + if !layered { + let total = Project::type_thickness(&wt.layers); + let dominant = dominant_layer(&wt.layers).expect("nicht leer"); + return ( + vec![WallBand { + thickness: total, + color: dominant_layer_color(p, &wt.layers, WALL_RGB), + hatch: dominant_layer_hatch(p, &wt.layers, Some(SECTION_WALL_AXIS_ANGLE_DEG)), + material_index: material_layer(p, maps, &dominant.component_id), + ..plain_band(0.0) + }], + false, + ); + } + 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()); + bands.push(WallBand { + thickness: l.thickness, + color: hex_to_rgb(&comp.color, WALL_RGB), + hatch: resolve_component_hatch(p, &l.component_id, Some(SECTION_WALL_AXIS_ANGLE_DEG)), + 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), + }); + } + (bands, true) +} + +fn band_cut_meta(b: &WallBand) -> Option { + if b.priority.is_none() && b.component_id.is_none() && b.cut_line_color.is_none() && b.cut_line_weight.is_none() { + return None; + } + Some(RCutMeta { join_priority: b.priority, component_id: b.component_id.clone(), line_color: b.cut_line_color, line_weight: b.cut_line_weight }) +} + +fn with_top_angle(mut h: style::RHatch, dx: f64, dy: f64) -> style::RHatch { + let wall_angle = (atan2(dy, dx) * 180.0) / std::f64::consts::PI; + let svg_angle = if h.relative_to_wall { h.base_angle - wall_angle } else { h.base_angle }; + let quarter = if h.pattern == 2.0 || h.pattern == 3.0 { 90.0 } else { 0.0 }; + h.top_angle = Some(-svg_angle + quarter); + h +} + +fn kv(v: Vec2) -> KVec { + KVec::new(v.x, v.y) +} + +fn wall_reference(w: &Wall) -> Reference { + match (w.reference_offset, w.reference_line) { + (Some(v), _) => Reference::Offset(v), + (None, Some(WallReferenceLine::Left)) => Reference::Left, + (None, Some(WallReferenceLine::Right)) => Reference::Right, + _ => Reference::Center, + } +} + +fn wall_ref(p: &Project, w: &Wall) -> WallRef { + let total = p.wall_thickness(w, 0.2); + WallRef { start: opening_geom::v(w.start.x, w.start.y), end: opening_geom::v(w.end.x, w.end.y), total, ref_off: joins::reference_offset(wall_reference(w), total) } +} + +/// Öffnungs-Intervall und vertikale Lage aller Öffnungen einer Wand. +fn wall_openings(p: &Project, w: &Wall, with_recess: bool) -> Vec { + let wr = wall_ref(p, w); + let (zb, zt) = p.wall_vertical_extent(w); + let mut out = Vec::new(); + for o in p.openings_of_wall(&w.id) { + let Some((from, to)) = opening_geom::opening_interval(&wr, o.position, o.width) else { continue }; + let o_bottom = zb + o.sill_height.max(0.0); + let o_top = zt.min(o_bottom + o.height); + let recess = with_recess && o.kind == ElementKind::Window && p.window_type(o).and_then(|t| t.inner_layer_recess) == Some(true); + out.push(OpeningIn { from, to, z_bottom: o_bottom, z_top: o_top, recess_inner_layer: recess }); + } + out +} + +/// Verschneidung je Geschoss (`computeJoinsByFloor`); Fehler = unbekannter Wandtyp/Bauteil. +fn compute_joins_by_floor(p: &Project) -> Result, String> { + let mut groups: Vec<(String, Vec<&Wall>)> = Vec::new(); + for w in &p.walls { + match groups.iter_mut().find(|g| g.0 == w.floor_id) { + Some(g) => g.1.push(w), + None => groups.push((w.floor_id.clone(), vec![w])), + } + } + let mut merged = HashMap::new(); + for (_, walls) in &groups { + let mut comp_index: HashMap<&str, u32> = HashMap::new(); + let mut jw: Vec = Vec::with_capacity(walls.len()); + let mut finite = true; + for w in walls { + let layers = p.wall_type(w).map(|wt| { + wt.layers + .iter() + .map(|l| { + let comp = p.component(&l.component_id); + let idx = comp.map(|c| { + let n = comp_index.len() as u32; + *comp_index.entry(c.id.as_str()).or_insert(n) + }); + JoinLayer { thickness: l.thickness, component: idx, priority: comp.map_or(f64::NAN, |c| c.join_priority) } + }) + .collect::>() + }); + let reference = wall_reference(w); + finite &= [w.start.x, w.start.y, w.end.x, w.end.y].iter().all(|v| v.is_finite()) + && !matches!(reference, Reference::Offset(v) if !v.is_finite()) + && layers.as_ref().is_none_or(|l| l.iter().all(|x| x.thickness.is_finite())); + jw.push(JoinWall { start: kv(w.start), end: kv(w.end), reference, layers }); + } + if !finite { + for w in walls { + merged.insert(w.id.clone(), WallCuts::default()); + } + continue; + } + match joins::compute_joins(&jw) { + Ok(cuts) => { + for (w, c) in walls.iter().zip(cuts) { + merged.insert(w.id.clone(), c); + } + } + Err(joins::JoinError::UnknownWallType(i)) => return Err(format!("Unbekannter Wandtyp: {}", walls[i].wall_type_id)), + Err(joins::JoinError::UnknownComponent(i)) => { + let bad = walls[i]; + let missing = p.wall_type(bad).and_then(|t| t.layers.iter().find(|l| p.component(&l.component_id).is_none())).map(|l| l.component_id.clone()).unwrap_or_default(); + return Err(format!("Unbekanntes Bauteil-Material: {missing}")); + } + } + } + Ok(merged) +} + +fn floor_context(p: &Project, floor_id: &str) -> FloorContext { + let ceilings: Vec = p + .ceilings + .as_deref() + .unwrap_or(&[]) + .iter() + .filter(|c| c.floor_id == floor_id && c.outline.len() >= 3) + .map(|c| { + let (z_bottom, z_top) = p.ceiling_vertical_extent(c); + CeilingIn { + z_bottom, + z_top, + outline: c.outline.iter().map(|v| kv(*v)).collect(), + layers: ceiling_layers(p, c).map(|ls| ls.iter().map(|l| (l.thickness, p.component(&l.component_id).map(|k| k.join_priority))).collect()), + } + }) + .collect(); + let roofs: Vec = p + .roofs + .as_deref() + .unwrap_or(&[]) + .iter() + .filter(|r| r.floor_id == floor_id) + .map(|r| { + let eaves_z = p.roof_base_elevation(r); + let geo = crate::roof::roof_geometry(&r.params(), eaves_z); + let total: f64 = p.roof_layers(r).iter().fold(0.0, |s, l| s + l.thickness.max(0.0)); + RoofIn { eaves_z, total_thickness: total, eaves: geo.eaves, planes: geo.planes } + }) + .collect(); + FloorContext::new(ceilings, roofs) +} + +/// Wandkörper (`projectToWalls3d`): `layered` = ein Körper je Schicht mit Löchern (3D-Viewer), +/// sonst Pfeiler/Brüstung/Sturz-Segmente (Schnitt-Eingabe). +pub fn emit_walls(p: &Project, layered: bool) -> Result, String> { + let joins = if layered { Some(compute_joins_by_floor(p)?) } else { None }; + let maps = wall_material_color_maps(p); + let mut contexts: HashMap<&str, FloorContext> = HashMap::new(); + let empty = FloorContext::default(); + let mut out = Vec::new(); + for wall in &p.walls { + let (bands, stacked) = resolve_wall_bands(p, &maps, wall, layered); + let (z_bottom, z_top) = p.wall_vertical_extent(wall); + let ctx = if layered { + contexts.entry(wall.floor_id.as_str()).or_insert_with(|| floor_context(p, &wall.floor_id)) + } else { + &empty + }; + let win = wall_bands::WallIn { + start: kv(wall.start), + end: kv(wall.end), + z_bottom, + z_top, + layered, + stacked, + reference: wall_reference(wall), + thickness_safe: p.wall_thickness(wall, 0.2), + termination: match wall.slice_termination { + Some(SliceTermination::Below) => Termination::Below, + Some(SliceTermination::Above) => Termination::Above, + _ => Termination::Both, + }, + bands: bands.iter().map(|b| BandIn { thickness: b.thickness, priority: b.priority }).collect(), + openings: wall_openings(p, wall, true), + cuts: if layered { joins.as_ref().and_then(|j| j.get(&wall.id)).cloned().unwrap_or_default() } else { WallCuts::default() }, + }; + let (dx, dy) = (wall.end.x - wall.start.x, wall.end.y - wall.start.y); + for piece in wall_bands::wall_bands(&win, ctx) { + let Some(b) = bands.get(piece.band) else { continue }; + out.push(RWall { + start: [piece.start.x, piece.start.y], + end: [piece.end.x, piece.end.y], + thickness: b.thickness, + height: piece.z_top - piece.z_bottom, + base_elevation: piece.z_bottom, + top_drop: piece.top_drop, + color: b.color, + layers: vec![], + wall_id: wall.id.clone(), + holes: (!piece.holes.is_empty()).then(|| piece.holes.iter().map(|h| RHole { from: h[0], to: h[1], z_bottom: h[2], z_top: h[3] }).collect()), + hatch: b.hatch.clone().map(|h| with_top_angle(h, dx, dy)), + material_index: b.material_index, + cut: band_cut_meta(b), + }); + } + } + let _ = hypot2; + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn beispielprojekt_hat_decken_und_gueltige_farben() { + let p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap(); + let slabs = emit_slabs(&p); + assert!(!slabs.is_empty()); + assert!(slabs.iter().all(|s| s.z_top > s.z_bottom && s.outline.len() >= 3)); + } +} diff --git a/src-tauri/core/src/style.rs b/src-tauri/core/src/style.rs new file mode 100644 index 00000000..2a60c14c --- /dev/null +++ b/src-tauri/core/src/style.rs @@ -0,0 +1,123 @@ +//! Darstellungs-Auflösung aus dem Modell ([K4] S2): Farben, Schraffur und Schnitt-Linienstil, wie sie +//! `src/plan/generatePlan/shared.ts` und `src/plan/toWalls3d/shared.ts` aus dem `Project` ableiten. + +use crate::model::{HatchPattern, Project}; +use serde::Serialize; + +pub type Rgb = [f64; 3]; + +/// Warmer, neutraler Wand-Grundton (wie render3d). +pub const WALL_RGB: Rgb = [0.82, 0.8, 0.76]; +/// Etwas hellerer, kühlerer Ton für Deckenplatten. +pub const SLAB_RGB: Rgb = [0.86, 0.86, 0.88]; +/// Fallback-Farbe für Linien ohne Farbe ("#888888"). +pub const DRAWING_LINE_FALLBACK_RGB: Rgb = [0x88 as f64 / 255.0, 0x88 as f64 / 255.0, 0x88 as f64 / 255.0]; + +/// "#rrggbb" → RGB 0..1; ungültiges Format → `fallback`. +pub fn hex_to_rgb(hex: &str, fallback: Rgb) -> Rgb { + let h = hex.strip_prefix('#').unwrap_or(hex); + if h.len() != 6 || !h.bytes().all(|b| b.is_ascii_hexdigit()) { + return fallback; + } + let v = u32::from_str_radix(h, 16).unwrap_or(0); + [((v >> 16) & 0xff) as f64 / 255.0, ((v >> 8) & 0xff) as f64 / 255.0, (v & 0xff) as f64 / 255.0] +} + +/// Schnitt-Schraffur eines Bauteil-Bandes für den 3D-Live-Schnitt (`RHatch` in TS). +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RHatch { + pub pattern: f64, + pub angle: f64, + pub scale: f64, + pub line_weight: f64, + pub base_angle: f64, + pub relative_to_wall: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub top_angle: Option, +} + +fn pattern_id(p: HatchPattern) -> f64 { + match p { + HatchPattern::Solid => 1.0, + HatchPattern::Diagonal => 2.0, + HatchPattern::Crosshatch => 3.0, + HatchPattern::Insulation => 4.0, + _ => 0.0, + } +} + +/// Aufgelöste Schraffur (Kern von `resolveHatch`): Muster, Massstab, Endwinkel, Musterlinien-Stärke. +/// `None`, wenn Schraffur oder ihr Linienstil fehlen (TS wirft dort). +pub struct HatchCore { + pub pattern: HatchPattern, + pub scale: f64, + pub angle: f64, + pub line_weight: f64, +} + +pub fn resolve_hatch_core(p: &Project, hatch_id: &str, wall_angle_deg: Option) -> Option { + let h = p.hatch(hatch_id)?; + let ls = match h.line_style_id.as_deref().filter(|s| !s.is_empty()) { + Some(id) => Some(p.line_style(id)?), + None => None, + }; + 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) }) +} + +/// Schnitt-Schraffur eines Bauteils (`resolveComponentHatch`); `axis_angle_deg` 90 für Wand-Bänder, +/// `None` für Decken. +pub fn resolve_component_hatch(p: &Project, component_id: &str, axis_angle_deg: Option) -> Option { + let comp = p.component(component_id)?; + if comp.hatch_id.is_empty() { + return None; + } + let hr = resolve_hatch_core(p, &comp.hatch_id, axis_angle_deg)?; + let abs = resolve_hatch_core(p, &comp.hatch_id, None)?; + let relative = resolve_hatch_core(p, &comp.hatch_id, Some(90.0))?.angle != abs.angle; + Some(RHatch { + pattern: pattern_id(hr.pattern), + angle: hr.angle, + scale: hr.scale, + line_weight: hr.line_weight, + base_angle: abs.angle, + relative_to_wall: relative, + top_angle: None, + }) +} + +/// Schnitt-Schraffur der dicksten Schicht (`dominantLayerHatch`). +pub fn dominant_layer_hatch(p: &Project, layers: &[crate::model::Layer], axis_angle_deg: Option) -> Option { + let dominant = dominant_layer(layers)?; + resolve_component_hatch(p, &dominant.component_id, axis_angle_deg) +} + +/// Dickste Schicht (bei Gleichstand die erste). +pub fn dominant_layer(layers: &[crate::model::Layer]) -> Option<&crate::model::Layer> { + let mut best = layers.first()?; + for l in layers { + if l.thickness > best.thickness { + best = l; + } + } + Some(best) +} + +/// Repräsentative Farbe der dicksten Schicht (`dominantLayerColor`). +pub fn dominant_layer_color(p: &Project, layers: &[crate::model::Layer], fallback: Rgb) -> Rgb { + match dominant_layer(layers).and_then(|d| p.component(&d.component_id)) { + Some(c) => hex_to_rgb(&c.color, fallback), + None => fallback, + } +} + +/// 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)) +} diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index 4fc4a1cb..6b6ac772 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -83,6 +83,9 @@ pub fn doc_query_args(h: u32, name: &str, args: &[f64]) -> String { "siteCheck" => serde_json::to_string(&site_rules::check_project(&p)), "buildingFootprint" => serde_json::to_string(&site_rules::building_footprint(&p)), "modelTop" => serde_json::to_string(&site_rules::model_top(&p)), + "walls" if args.len() == 1 => crate::model3d::emit_walls(&p, args[0] != 0.0).map_err(|_| ()).and_then(|w| serde_json::to_string(&w).map_err(|_| ())).map_err(|_| serde_json::Error::io(std::io::Error::other("walls"))), + "slabs" => serde_json::to_string(&crate::model3d::emit_slabs(&p)), + "columnMeshes" => serde_json::to_string(&crate::model3d::emit_columns(&p)), "shadows" if args.len() == 2 => { let polys = sun::shadow_polygons_project(&p, sun::SunPosition { azimuth: args[0], elevation: args[1] }); serde_json::to_string(&site_rules::area_out(&polys)) diff --git a/src/core/document.ts b/src/core/document.ts index 9df4ad03..a94ebb31 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -49,7 +49,7 @@ export class ProjectDocument { * Abfrage auf dem typisierten Projekt im Kern. Das Ergebnis ist JSON; ein Fehler (Projekt passt * nicht zum Modell, unbekannte Abfrage) wirft. */ - query(name: "kennzahlen" | "siteCheck" | "buildingFootprint" | "modelTop" | "shadows", args: number[] = []): T { + query(name: "kennzahlen" | "siteCheck" | "buildingFootprint" | "modelTop" | "shadows" | "slabs" | "columnMeshes" | "walls", args: number[] = []): T { const text = this.handle ? core().doc_query_args(this.handle, name, Float64Array.from(args)) : ""; if (!text) throw new Error(`Kern-Abfrage „${name}": Projekt passt nicht zum Kern-Modell`); return JSON.parse(text) as T; diff --git a/src/plan/model3d.parity.tmp.test.ts b/src/plan/model3d.parity.tmp.test.ts new file mode 100644 index 00000000..902dbedd --- /dev/null +++ b/src/plan/model3d.parity.tmp.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it } from "vitest"; +import { sampleProject } from "../model/sampleProject"; +import { documentFor } from "../core/document"; +import { emitSlabs } from "./toWalls3d/ceilings"; +import { emitColumns } from "./toWalls3d/columns"; +import { projectToWalls3d } from "./toWalls3d"; + +const plain = (v: T): T => JSON.parse(JSON.stringify(v)); +let seed = 21; +const rnd = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296); +const pick = (a: T[]) => a[Math.floor(rnd() * a.length)]; + +describe("model3d walls", () => { + it("sample project both paths", () => { + const doc = documentFor(sampleProject); + for (const layered of [true, false]) { + expect(doc.query("walls", [layered ? 1 : 0])).toEqual(plain(projectToWalls3d(sampleProject, layered))); + } + }); + it("random walls/openings/ceilings/roofs", () => { + let n = 0; + for (let t = 0; t < 150; t++) { + const lvl = sampleProject.drawingLevels.filter((l) => l.kind === "floor"); + const pts = [[0, 0], [6, 0], [6, 4], [0, 4], [3, 0], [3, 4], [8, 2], [-2, 2]]; + const walls = Array.from({ length: 2 + Math.floor(rnd() * 6) }, (_, k) => { + const a = pick(pts), b = pick(pts); + return { ...sampleProject.walls[0], id: "w" + k, floorId: pick(lvl).id, start: { x: a[0], y: a[1] }, end: { x: b[0], y: b[1] + (a[1] === b[1] && a[0] === b[0] ? 1 : 0) }, + wallTypeId: pick(sampleProject.wallTypes).id, + ...(rnd() < 0.3 ? { referenceLine: pick(["left", "right", "center"]) } : {}), + ...(rnd() < 0.15 ? { referenceOffset: rnd() * 0.3 - 0.15 } : {}), + ...(rnd() < 0.2 ? { sliceTermination: pick(["below", "above", "both"]) } : {}), + height: pick([2.5, 2.6, 3]) }; + }); + const openings = walls.flatMap((w, k) => rnd() < 0.6 ? [{ id: "o" + k, type: "opening", hostWallId: w.id, categoryCode: "21", kind: pick(["window", "door"]), + ...(rnd() < 0.5 ? { typeId: pick(["window-standard", "window-double", "door-standard", "door-entry"]) } : {}), + position: rnd() * 2, width: 0.6 + rnd(), height: 1.2 + rnd(), sillHeight: pick([0, 0.9]) }] : []); + const ceilings = Array.from({ length: Math.floor(rnd() * 3) }, (_, k) => ({ id: "c" + k, type: "ceiling", floorId: pick(lvl).id, categoryCode: "20", + outline: [{ x: -1, y: -1 }, { x: 7, y: -1 }, { x: 7, y: 5 }, { x: -1, y: 5 }], wallTypeId: sampleProject.wallTypes[0].id, + ...(sampleProject.ceilingTypes?.length && rnd() < 0.5 ? { ceilingTypeId: pick(sampleProject.ceilingTypes).id } : {}) })); + const roofs = rnd() < 0.5 ? [{ id: "R1", type: "roof", floorId: pick(lvl).id, categoryCode: "35", outline: [{ x: -1, y: -1 }, { x: 7, y: -1 }, { x: 7, y: 5 }, { x: -1, y: 5 }], + shape: pick(["sattel", "walm", "pult", "flach"]), pitchDeg: 30, overhang: 0.3, ridgeAxis: pick(["x", "y"]), thickness: 0.2 }] : []; + const project: any = { ...sampleProject, walls, openings, ceilings, roofs }; + const doc = documentFor(project); + for (const layered of [true, false]) { + let want: unknown; + try { want = plain(projectToWalls3d(project, layered)); } catch { want = undefined; } + if (want === undefined) { expect(() => doc.query("walls", [layered ? 1 : 0])).toThrow(); continue; } + expect(doc.query("walls", [layered ? 1 : 0])).toEqual(want); + n += (want as unknown[]).length; + } + } + expect(n).toBeGreaterThan(500); + }); +}); + +describe("model3d slabs/columns", () => { + it("random", () => { + let ns = 0, nc = 0; + for (let t = 0; t < 200; t++) { + const lvl = sampleProject.drawingLevels.filter((l) => l.kind === "floor"); + const ceilings = Array.from({ length: Math.floor(rnd() * 4) }, (_, k) => ({ + id: "c" + k, type: "ceiling", floorId: pick(lvl).id, categoryCode: "20", + outline: [{ x: 0, y: 0 }, { x: 5 + k, y: 0 }, { x: 5 + k, y: 4 }, { x: 0, y: 4 }], + ...(rnd() < 0.5 ? { openings: [[{ x: 1, y: 1 }, { x: 2, y: 1 }, { x: 2, y: 2 }, { x: 1, y: 2 }]] } : {}), + wallTypeId: sampleProject.wallTypes[0].id, + ...(rnd() < 0.5 && sampleProject.ceilingTypes?.length ? { ceilingTypeId: pick(sampleProject.ceilingTypes).id } : {}), + ...(rnd() < 0.3 ? { thickness: 0.25 } : {}), + ...(rnd() < 0.2 ? { top: { mode: "custom", z: 3.1 } } : {}), + })); + const columns = Array.from({ length: Math.floor(rnd() * 4) }, (_, k) => ({ + id: "k" + k, type: "column", floorId: pick(lvl).id, categoryCode: "20", + position: { x: k, y: 1 }, rotation: rnd() * 3, height: pick([0, 2.5, 3]), + profile: pick([{ kind: "rect", width: 0.3, depth: 0.4 }, { kind: "round", radius: 0.2 }]), + ...(rnd() < 0.5 ? { componentId: pick(sampleProject.components).id } : {}), + ...(rnd() < 0.3 ? { componentId: "nope" } : {}), + })); + const project: any = { ...sampleProject, ceilings, columns }; + const doc = documentFor(project); + const a = doc.query("slabs"); + const b = plain(emitSlabs(project)); + expect(a).toEqual(b); + const c = doc.query("columnMeshes"); + const d = plain(emitColumns(project)); + expect(c).toEqual(d); + ns += b.length; nc += d.length; + } + expect(ns).toBeGreaterThan(100); + expect(nc).toBeGreaterThan(100); + }); +});