[K4][B5][C11] Merge: IFC- und Mesh-Export-Sammler im Kern (IFC grosses Projekt 82 s → 2.4 s), Dach-Innenhöfe bei Georeferenz

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-29 03:16:37 +00:00
commit 46a275bfc9
37 files changed
+3053 -2934

No files matched your search

+264
View File
@@ -0,0 +1,264 @@
//! Gemeinsames für die Export-Sammler im Kern ([K4], [B5], [C11]): der flache Puffer, den die
//! Schreiber in `src-tauri/fileio` lesen (Zahlen + Zeichenkettenliste, Kodierung dort in
//! `ifc_export.rs`/`mesh_export.rs`), die Byte-Hülle für die Übergabe an TS und Netz-Helfer
//! (Wicklung nach aussen, Volumen). Port von `src/export/meshOrient.ts` und den Puffer-Klassen aus
//! `exportIfc.ts`/`exportMesh.ts`; Rechenreihenfolge wie dort, damit die Dateien zeichengleich bleiben.
//!
//! Byte-Hülle (little endian, alles f64 bis auf die Zeichenketten):
//! `[MAGIC, nZahlen, nBytes, Zahlen…, UTF-8 der Zeichenketten durch \0 getrennt]`. Fehler kommen als
//! Fehlerpuffer des Plan-Puffers (`plan_buf::encode_error`, `[ERR_MAGIC, n, UTF-16…]`).
use std::collections::HashMap;
/// Kennung der Byte-Hülle ("DXEF").
pub const MAGIC: f64 = 1_146_635_590.0;
/// Zahlenpuffer + Zeichenkettenliste (`FlatIfc`/`encodeScene` in TS).
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Flat {
pub nums: Vec<f64>,
pub strings: Vec<String>,
}
impl Flat {
pub fn new(version: f64) -> Self {
Flat { nums: vec![version], strings: Vec::new() }
}
pub fn num(&mut self, v: f64) -> &mut Self {
self.nums.push(v);
self
}
pub fn nums(&mut self, v: &[f64]) -> &mut Self {
self.nums.extend_from_slice(v);
self
}
/// Zeichenkette anhängen (ohne `\0`, das trennt die Liste) und ihren Index liefern.
pub fn str(&mut self, s: &str) -> f64 {
self.strings.push(s.replace('\0', ""));
(self.strings.len() - 1) as f64
}
/// Byte-Hülle für TS (s. Modulkopf).
pub fn to_bytes(&self) -> Vec<u8> {
let text = self.strings.join("\0");
let mut out = Vec::with_capacity(24 + self.nums.len() * 8 + text.len());
out.extend_from_slice(&MAGIC.to_le_bytes());
out.extend_from_slice(&(self.nums.len() as f64).to_le_bytes());
out.extend_from_slice(&(text.len() as f64).to_le_bytes());
for v in &self.nums {
out.extend_from_slice(&v.to_le_bytes());
}
out.extend_from_slice(text.as_bytes());
out
}
}
/// Liest die Byte-Hülle zurück (Tests).
pub fn from_bytes(b: &[u8]) -> Option<(Vec<f64>, String)> {
let f = |i: usize| -> Option<f64> { Some(f64::from_le_bytes(b.get(i * 8..i * 8 + 8)?.try_into().ok()?)) };
if f(0)? != MAGIC {
return None;
}
let (n, len) = (f(1)? as usize, f(2)? as usize);
let nums = (0..n).map(|i| f(3 + i)).collect::<Option<Vec<f64>>>()?;
let at = 24 + n * 8;
let text = String::from_utf8(b.get(at..at + len)?.to_vec()).ok()?;
Some((nums, text))
}
/// Zahl als Schlüssel wie `String(v)` in JS: −0 = 0, alle NaN gleich.
pub fn js_key(v: f64) -> u64 {
if v.is_nan() {
f64::NAN.to_bits()
} else {
(v + 0.0).to_bits()
}
}
/// Volumen eines geschlossenen Dreiecks-Netzes (Betrag der Summe der Tetraeder zum Ursprung, `meshVolume`).
pub fn mesh_volume(positions: &[f64], indices: &[u32]) -> f64 {
let p = |i: usize| positions.get(i).copied().unwrap_or(f64::NAN);
let mut v = 0.0;
let mut i = 0;
while i + 2 < indices.len() {
let a = indices[i] as usize * 3;
let b = indices[i + 1] as usize * 3;
let c = indices[i + 2] as usize * 3;
v += p(a) * (p(b + 1) * p(c + 2) - p(b + 2) * p(c + 1)) - p(a + 1) * (p(b) * p(c + 2) - p(b + 2) * p(c)) + p(a + 2) * (p(b) * p(c + 1) - p(b + 1) * p(c));
i += 3;
}
v.abs() / 6.0
}
/// Richtet ein Dreiecks-Netz (Weltkoordinaten) so aus, dass die Flächennormalen nach AUSSEN zeigen
/// (`orientOutward`): Dreiecke werden über gemeinsame Kanten (Eckpunkte auf 0,01 mm verschweisst)
/// zu Zusammenhangs-Komponenten verbunden, jede Komponente zuerst in sich widerspruchsfrei gewickelt
/// (Nachbarn durchlaufen eine gemeinsame Kante gegenläufig) und dann nach dem Vorzeichen ihres
/// Volumens gedreht. Kanten mit mehr als zwei Dreiecken (Verschneidungen) verbinden nicht.
/// Indizes ausserhalb des Netzes lassen das Netz unverändert (kein Panic).
pub fn orient_outward(pos: &[f64], idx: &[u32]) -> Vec<u32> {
let n_tri = idx.len() / 3;
let n_vert = pos.len() / 3;
if idx[..n_tri * 3].iter().any(|&i| i as usize >= n_vert) {
return idx.to_vec();
}
let q = |v: f64| js_key(crate::jsnum::round(v * 1e5));
let mut weld: HashMap<(u64, u64, u64), usize> = HashMap::new();
let mut canon = vec![0usize; n_vert];
for (i, c) in canon.iter_mut().enumerate() {
let key = (q(pos[3 * i]), q(pos[3 * i + 1]), q(pos[3 * i + 2]));
let next = weld.len();
*c = *weld.entry(key).or_insert(next);
}
let n = weld.len() + 1;
// Kante (min, max) → Einträge (Dreieck · 2 + vorwärts?), in der Reihenfolge des ersten Auftretens.
let mut edge_at: HashMap<usize, usize> = HashMap::new();
let mut edges: Vec<Vec<usize>> = Vec::new();
let corner = |t: usize, k: usize| canon[idx[3 * t + k] as usize];
for t in 0..n_tri {
for k in 0..3 {
let a = corner(t, k);
let b = corner(t, (k + 1) % 3);
if a == b {
continue;
}
let key = a.min(b) * n + a.max(b);
let entry = t * 2 + usize::from(a < b);
match edge_at.get(&key) {
Some(&e) => edges[e].push(entry),
None => {
edge_at.insert(key, edges.len());
edges.push(vec![entry]);
}
}
}
}
// Nachbarschaft über Kanten mit genau zwei Dreiecken: Wicklungs-Parität (1 = gegenläufig nötig).
let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n_tri];
for list in &edges {
if list.len() != 2 {
continue;
}
let (e1, e2) = (list[0], list[1]);
let (t1, t2) = (e1 >> 1, e2 >> 1);
if t1 == t2 {
continue;
}
let parity = usize::from((e1 & 1) == (e2 & 1));
adj[t1].push(t2 * 2 + parity);
adj[t2].push(t1 * 2 + parity);
}
let mut flip: Vec<i8> = vec![-1; n_tri];
let mut out = idx.to_vec();
for s in 0..n_tri {
if flip[s] >= 0 {
continue;
}
let mut comp = vec![s];
flip[s] = 0;
let mut h = 0;
while h < comp.len() {
let t = comp[h];
for &e in &adj[t] {
let u = e >> 1;
if flip[u] < 0 {
flip[u] = flip[t] ^ (e & 1) as i8;
comp.push(u);
}
}
h += 1;
}
let mut vol = 0.0;
for &t in &comp {
let (a, b, c) = if flip[t] != 0 { (idx[3 * t], idx[3 * t + 2], idx[3 * t + 1]) } else { (idx[3 * t], idx[3 * t + 1], idx[3 * t + 2]) };
let (a, b, c) = (a as usize * 3, b as usize * 3, c as usize * 3);
vol += pos[a] * (pos[b + 1] * pos[c + 2] - pos[b + 2] * pos[c + 1]) - pos[a + 1] * (pos[b] * pos[c + 2] - pos[b + 2] * pos[c]) + pos[a + 2] * (pos[b] * pos[c + 1] - pos[b + 1] * pos[c]);
}
let turn = i8::from(vol < 0.0);
for &t in &comp {
if flip[t] ^ turn != 0 {
out[3 * t + 1] = idx[3 * t + 2];
out[3 * t + 2] = idx[3 * t + 1];
}
}
}
out
}
/// `String.prototype.trim` (JS-Leerraum: Zs, Tab, VT, FF, BOM und Zeilenenden; anders als Rust ohne U+0085).
pub fn js_trim(s: &str) -> &str {
let ws = |c: char| (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}';
s.trim_matches(ws)
}
#[cfg(test)]
mod tests {
use super::*;
/// Würfel mit gemischter Wicklung (je zweites Dreieck gedreht).
fn cube(mixed: bool) -> (Vec<f64>, Vec<u32>) {
let pos = vec![0., 0., 0., 1., 0., 0., 1., 1., 0., 0., 1., 0., 0., 0., 1., 1., 0., 1., 1., 1., 1., 0., 1., 1.];
let quads = [[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]];
let mut idx = Vec::new();
for (k, q) in quads.iter().enumerate() {
idx.extend([q[0], q[1], q[2]]);
if mixed && k % 2 == 1 {
idx.extend([q[0], q[3], q[2]]);
} else {
idx.extend([q[0], q[2], q[3]]);
}
}
(pos, idx)
}
fn signed_volume(pos: &[f64], idx: &[u32]) -> f64 {
let mut v = 0.0;
for t in idx.chunks_exact(3) {
let (a, b, c) = (t[0] as usize * 3, t[1] as usize * 3, t[2] as usize * 3);
v += pos[a] * (pos[b + 1] * pos[c + 2] - pos[b + 2] * pos[c + 1]) - pos[a + 1] * (pos[b] * pos[c + 2] - pos[b + 2] * pos[c]) + pos[a + 2] * (pos[b] * pos[c + 1] - pos[b + 1] * pos[c]);
}
v / 6.0
}
#[test]
fn wuerfel_wird_nach_aussen_gewickelt() {
let (pos, idx) = cube(true);
let out = orient_outward(&pos, &idx);
assert!((signed_volume(&pos, &out) - 1.0).abs() < 1e-12);
assert!((mesh_volume(&pos, &out) - 1.0).abs() < 1e-12);
// Ganz umgedreht → wieder aussen.
let rev: Vec<u32> = idx.chunks_exact(3).flat_map(|t| [t[0], t[2], t[1]]).collect();
assert!((signed_volume(&pos, &orient_outward(&pos, &rev)) - 1.0).abs() < 1e-12);
}
#[test]
fn unsinn_ohne_panik() {
assert_eq!(orient_outward(&[0.0; 9], &[0, 1, 7]), vec![0, 1, 7]);
assert!(orient_outward(&[], &[]).is_empty());
assert_eq!(orient_outward(&[f64::NAN; 9], &[0, 1, 2]), vec![0, 1, 2]);
assert!(mesh_volume(&[0.0; 3], &[0, 5, 9]).is_nan());
}
#[test]
fn huelle_hin_und_zurueck() {
let mut f = Flat::new(4.0);
let a = f.str("Wand\0«ä»");
f.num(a).nums(&[1.5, f64::NAN]);
let i = f.str("x");
f.num(i);
let (nums, text) = from_bytes(&f.to_bytes()).unwrap();
assert_eq!(nums.len(), 5);
assert_eq!(nums[1], 0.0);
assert!(nums[3].is_nan());
assert_eq!(text, "Wand«ä»\0x");
}
#[test]
fn trim_wie_js() {
assert_eq!(js_trim("\u{feff} 20\t\n"), "20");
assert_eq!(js_trim("\u{85}20"), "\u{85}20");
}
}
+193
View File
@@ -0,0 +1,193 @@
//! Ursprungs-Verschiebung des ganzen Projekts für georeferenzierte Modell-Exporte ([K4], Gegenstück
//! zu `projectToWorldCoords` in `src/model/geoRebase.ts`, das für DXF und den Befehl „Neuer
//! Bezugspunkt" in TS bleibt): reine, verlustfreie Translation aller Modell-Koordinaten um einen
//! festen Vektor. `geoAnchor` wandert mit, damit der LV95-Bezug exakt erhalten bleibt. Nur
//! Translation — keine Rotation (Achsen- und Winkelfelder blieben sonst falsch). Richtungsvektoren
//! (z. B. `Stair.dir`) bleiben unangetastet. Dazu LV95 → WGS84 (`lv95ToWgs84` aus `src/io/lv95.ts`).
use crate::model::*;
fn shift(p: Vec2, dx: f64, dy: f64) -> Vec2 {
Vec2 { x: p.x + dx, y: p.y + dy }
}
fn shift_all(pts: &mut [Vec2], dx: f64, dy: f64) {
for p in pts {
*p = shift(*p, dx, dy);
}
}
fn shift_geom(g: &mut Drawing2DGeom, dx: f64, dy: f64) {
use Drawing2DGeom::*;
match g {
Line { a, b } | Xline { a, b } | Ray { a, b } => {
*a = shift(*a, dx, dy);
*b = shift(*b, dx, dy);
}
Polyline { pts, .. } | Bezier { pts } | Spline { pts, .. } | Dimension { pts, .. } => shift_all(pts, dx, dy),
Rect { min, max } | Image { min, max, .. } => {
*min = shift(*min, dx, dy);
*max = shift(*max, dx, dy);
}
Circle { center, .. } | Arc { center, .. } | Ellipse { center, .. } => *center = shift(*center, dx, dy),
Kote { at, .. } | Detailref { at, .. } | Scalebar { at, .. } | Pointmarker { at } | Block { at, .. } => *at = shift(*at, dx, dy),
Text { at, leader_target, leader_bend_points, path_pts, .. } => {
*at = shift(*at, dx, dy);
if let Some(t) = leader_target {
*t = shift(*t, dx, dy);
}
if let Some(v) = leader_bend_points {
shift_all(v, dx, dy);
}
if let Some(v) = path_pts {
shift_all(v, dx, dy);
}
}
}
}
fn shift_context(o: &mut ContextObject, dx: f64, dy: f64) {
match o {
ContextObject::ContourSet(s) => {
for c in &mut s.contours {
shift_all(&mut c.pts, dx, dy);
if let Some(cv) = &mut c.curve {
cv.cx += dx;
cv.cy += dy;
}
}
}
ContextObject::Image(i) => {
i.min = shift(i.min, dx, dy);
i.max = shift(i.max, dx, dy);
}
ContextObject::ImportedMesh(m) => shift_positions(&mut m.positions, dx, dy),
ContextObject::TerrainMesh(m) => shift_positions(&mut m.positions, dx, dy),
}
}
/// Nur x/y (Grundriss) verschieben, die Höhe bleibt.
fn shift_positions(pos: &mut [f64], dx: f64, dy: f64) {
for c in pos.chunks_exact_mut(3) {
c[0] += dx;
c[1] += dy;
}
}
/// Verschiebt sämtliche Modell-Koordinaten (`translateProject`), auch die Innenhöfe der Dächer.
pub fn translate_project(p: &Project, dx: f64, dy: f64) -> Project {
if dx == 0.0 && dy == 0.0 {
return p.clone();
}
let mut out = p.clone();
for w in &mut out.walls {
w.start = shift(w.start, dx, dy);
w.end = shift(w.end, dx, dy);
}
for c in out.ceilings.iter_mut().flatten() {
shift_all(&mut c.outline, dx, dy);
for h in c.openings.iter_mut().flatten() {
shift_all(h, dx, dy);
}
}
for r in out.roofs.iter_mut().flatten() {
shift_all(&mut r.outline, dx, dy);
for h in r.holes.iter_mut().flatten() {
shift_all(h, dx, dy);
}
}
for s in out.stairs.iter_mut().flatten() {
s.start = shift(s.start, dx, dy);
s.center = s.center.map(|c| shift(c, dx, dy));
}
for r in out.rooms.iter_mut().flatten() {
shift_all(&mut r.boundary, dx, dy);
r.stamp_anchor = r.stamp_anchor.map(|a| shift(a, dx, dy));
}
for c in out.columns.iter_mut().flatten() {
c.position = shift(c.position, dx, dy);
}
for s in out.extruded_solids.iter_mut().flatten() {
shift_all(&mut s.points, dx, dy);
if let Some(c) = &mut s.circle {
c.center = shift(c.center, dx, dy);
}
}
for d in &mut out.drawings2d {
shift_geom(&mut d.geom, dx, dy);
}
for o in out.context.iter_mut().flatten() {
shift_context(o, dx, dy);
}
for l in &mut out.drawing_levels {
if let Some(pts) = &mut l.line_points {
pts[0] = shift(pts[0], dx, dy);
pts[1] = shift(pts[1], dx, dy);
}
}
if let Some(a) = &mut out.geo_anchor {
a.model = shift(a.model, dx, dy);
}
out
}
/// LV95-Ursprung: die reale Landeskoordinate, die auf den Modell-Nullpunkt abgebildet wird.
pub fn project_geo_origin(p: &Project) -> Option<(f64, f64)> {
let a = p.geo_anchor.as_ref()?;
Some((a.lv95.e - a.model.x, a.lv95.n - a.model.y))
}
/// Kopie mit Geometrie in realen Weltkoordinaten (LV95) für Modell-Exporte; ohne Bezug unverändert.
pub fn project_to_world_coords(p: &Project) -> Project {
match project_geo_origin(p) {
Some((e, n)) => translate_project(p, e, n),
None => p.clone(),
}
}
/// LV95 → WGS84 (swisstopo-Näherungsformeln; Rechenreihenfolge wie `lv95ToWgs84` in TS):
/// `(Breite, Länge)` in Dezimalgrad.
pub fn lv95_to_wgs84(e: f64, n: f64) -> (f64, f64) {
let y = (e - 2600000.0) / 1000000.0;
let x = (n - 1200000.0) / 1000000.0;
let y2 = y * y;
let x2 = x * x;
let lam = 2.6779094 + 4.728982 * y + 0.791484 * y * x + 0.1306 * y * x2 - 0.0436 * y * y2;
let phi = 16.9023892 + 3.238272 * x - 0.270978 * y2 - 0.002528 * x2 - 0.0447 * y2 * x - 0.014 * x * x2;
((phi * 100.0) / 36.0, (lam * 100.0) / 36.0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn verschiebt_alles_und_haelt_den_anker() {
let mut p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap();
p.geo_anchor = Some(ProjectGeoAnchor { lv95: ProjectGeoAnchorLv95 { e: 2_600_000.0, n: 1_200_000.0, ..Default::default() }, model: Vec2 { x: 1.0, y: 2.0 }, ..Default::default() });
let w = project_to_world_coords(&p);
assert_eq!(w.walls[0].start.x, p.walls[0].start.x + 2_599_999.0);
assert_eq!(w.walls[0].start.y, p.walls[0].start.y + 1_199_998.0);
// Der Anker wandert mit: das verschobene Modell liegt bereits in Landeskoordinaten (Ursprung 0, 0).
assert_eq!(project_geo_origin(&w), Some((0.0, 0.0)));
assert_eq!(project_to_world_coords(&Project { geo_anchor: None, ..p.clone() }), Project { geo_anchor: None, ..p });
}
#[test]
fn dach_innenhoefe_wandern_mit() {
let mut p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap();
let roofs = p.roofs.as_mut().unwrap();
roofs[0].holes = Some(vec![vec![Vec2 { x: 1.0, y: 1.0 }, Vec2 { x: 2.0, y: 1.0 }, Vec2 { x: 2.0, y: 2.0 }]]);
let t = translate_project(&p, 10.0, -5.0);
let r = &t.roofs.as_ref().unwrap()[0];
assert_eq!(r.outline[0], Vec2 { x: p.roofs.as_ref().unwrap()[0].outline[0].x + 10.0, y: p.roofs.as_ref().unwrap()[0].outline[0].y - 5.0 });
assert_eq!(r.holes.as_ref().unwrap()[0][2], Vec2 { x: 12.0, y: -3.0 });
}
#[test]
fn lv95_bern() {
// Bezugspunkt Bern (alte Sternwarte): 46°57'08.66" N, 7°26'22.50" E.
let (lat, lon) = lv95_to_wgs84(2600000.0, 1200000.0);
assert!((lat - 46.951082).abs() < 1e-5 && (lon - 7.438637).abs() < 1e-5, "{lat} {lon}");
}
}
File diff suppressed because it is too large. Load diff
+371
View File
@@ -0,0 +1,371 @@
//! Basismengen (Qto_*BaseQuantities) für den IFC-Export ([B5], [K4]; Port von
//! `src/export/ifcQuantities.ts`): Längen, Flächen und Volumen aus derselben Geometrie, die in die
//! Datei geschrieben wird — für Kostenplanung (eBKP-H/BKP) und Mengenermittlung. Reine Rechnung auf
//! einfachen Eingaben (Bänder, Ringe, Netze); `ifc_data.rs` sammelt, `fileio` schreibt die
//! IfcElementQuantity. Rechenreihenfolge und Zahlsemantik wie in TS (`Math.hypot/min/max`).
//!
//! Netto = abzüglich Öffnungen (Wand, Decke). Fehlt einer Menge die Grundlage (z. B. Höhe bei
//! schräger Wandoberkante: „nur angeben, wenn konstant"), fällt sie weg statt geraten zu werden.
use crate::jsmath::{hypot, hypot2};
use crate::jsnum::{max, min};
use crate::model::Vec2;
use crate::model3d::RWall;
/// Art einer Menge (Code in der flachen Kodierung: 3 Länge, 4 Fläche, 5 Volumen).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QtyKind {
Length,
Area,
Volume,
}
/// Eine Menge: Name nach IFC4-Vorlage, Art und Wert (immer endlich und ≥ 0, ausser nachträglich gesetzt).
#[derive(Debug, Clone, PartialEq)]
pub struct Qty {
pub name: &'static str,
pub kind: QtyKind,
pub value: f64,
}
/// Rundungsfehler und kaputte Eingaben (NaN) auf 0, nie negativ.
fn clean(v: f64) -> f64 {
if v.is_finite() && v > 0.0 {
v
} else {
0.0
}
}
fn q(name: &'static str, kind: QtyKind, value: f64) -> Qty {
Qty { name, kind, value: clean(value) }
}
fn len(name: &'static str, v: f64) -> Qty {
q(name, QtyKind::Length, v)
}
fn area(name: &'static str, v: f64) -> Qty {
q(name, QtyKind::Area, v)
}
fn vol(name: &'static str, v: f64) -> Qty {
q(name, QtyKind::Volume, v)
}
/// Fläche eines Rings (Shoelace, unabhängig vom Umlaufsinn); offener Ring.
pub fn ring_area(pts: &[Vec2]) -> f64 {
let mut a = 0.0;
let n = pts.len();
for i in 0..n {
let j = if i == 0 { n - 1 } else { i - 1 };
a += pts[j].x * pts[i].y - pts[i].x * pts[j].y;
}
a.abs() / 2.0
}
/// Umfang eines geschlossenen Rings.
pub fn ring_perimeter(pts: &[Vec2]) -> f64 {
let mut p = 0.0;
let n = pts.len();
for i in 0..n {
let j = if i == 0 { n - 1 } else { i - 1 };
p += hypot2(pts[i].x - pts[j].x, pts[i].y - pts[j].y);
}
p
}
/// Öffnung einer Wand: Achs-Intervall (ab Wandanfang) und absolute Höhen.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Cutout {
pub from: f64,
pub to: f64,
pub z_bottom: f64,
pub z_top: f64,
}
fn overlap(a0: f64, a1: f64, b0: f64, b1: f64) -> f64 {
max(0.0, min(a1, b1) - max(a0, b0))
}
fn sloped_band(b: &RWall) -> bool {
b.top_drop.is_some_and(|d| d[0].abs() > 1e-9 || d[1].abs() > 1e-9)
}
/// Wand-Basismengen aus den Schicht-Bändern (dieselben wie im 3D) und den Öffnungen.
/// • Length: Achslänge; Width: Gesamtdicke quer zur Achse; Height: nur bei konstanter Höhe.
/// • GrossSideArea: Achslänge × Wandhöhe (schräge Oberkante: höchste mittlere Bandhöhe);
/// NetSideArea: abzüglich der Öffnungsflächen.
/// • GrossVolume: Summe der Band-Quader; NetVolume: abzüglich der Öffnungen je Band — oder
/// `net_volume`, wenn die Wand als Netz mit schon ausgestanzten Öffnungen geschrieben wird.
pub fn wall_quantities(start: Vec2, end: Vec2, bands: &[&RWall], cutouts: &[Cutout], net_volume: Option<f64>) -> Vec<Qty> {
if bands.is_empty() {
return Vec::new();
}
let axis_len = hypot2(end.x - start.x, end.y - start.y);
let ux = if axis_len > 0.0 { (end.x - start.x) / axis_len } else { 1.0 };
let uy = if axis_len > 0.0 { (end.y - start.y) / axis_len } else { 0.0 };
let (mut n_lo, mut n_hi) = (f64::INFINITY, f64::NEG_INFINITY);
let (mut z_min, mut z_max) = (f64::INFINITY, f64::NEG_INFINITY);
let mut sloped = false;
let mut gross = 0.0;
let mut tallest = 0.0;
for b in bands {
let l = hypot2(b.end[0] - b.start[0], b.end[1] - b.start[1]);
let off = -(b.start[0] - start.x) * uy + (b.start[1] - start.y) * ux;
n_lo = min(n_lo, off - b.thickness / 2.0);
n_hi = max(n_hi, off + b.thickness / 2.0);
z_min = min(z_min, b.base_elevation);
z_max = max(z_max, b.base_elevation + b.height);
let drop = b.top_drop.map_or(0.0, |d| (d[0] + d[1]) / 2.0);
if sloped_band(b) {
sloped = true;
}
gross += l * b.thickness * (b.height - drop);
tallest = max(tallest, b.height - drop);
}
let gross_side = axis_len * (if sloped { tallest } else { z_max - z_min });
let mut cut_side = 0.0;
let mut cut_volume = 0.0;
for c in cutouts {
cut_side += (c.to - c.from) * overlap(c.z_bottom, c.z_top, z_min, z_max);
for b in bands {
let a0 = (b.start[0] - start.x) * ux + (b.start[1] - start.y) * uy;
let a1 = (b.end[0] - start.x) * ux + (b.end[1] - start.y) * uy;
let ox = overlap(min(a0, a1), max(a0, a1), c.from, c.to);
cut_volume += ox * overlap(c.z_bottom, c.z_top, b.base_elevation, b.base_elevation + b.height) * b.thickness;
}
}
// Netto aus dem Netz kann den Band-Quader um Rundung/Gehrungsdetails überschreiten: Brutto nie unter Netto.
let net = net_volume.unwrap_or_else(|| max(0.0, gross - cut_volume));
gross = max(gross, net);
let mut out = vec![len("Length", axis_len), len("Width", n_hi - n_lo)];
if !sloped && z_max - z_min > 0.0 {
out.push(len("Height", z_max - z_min));
}
out.extend([
area("GrossSideArea", gross_side),
area("NetSideArea", max(0.0, gross_side - cut_side)),
vol("GrossVolume", gross),
vol("NetVolume", net),
]);
out
}
/// Brutto-Volumen der Löcher in den Bändern (für Netz-Wände ohne dichtes Netz).
pub fn hole_volume(bands: &[&RWall]) -> f64 {
let mut v = 0.0;
for b in bands {
for h in b.holes.as_deref().unwrap_or(&[]) {
v += (h.to - h.from) * overlap(h.z_bottom, h.z_top, b.base_elevation, b.base_elevation + b.height) * b.thickness;
}
}
v
}
/// Platten-Basismengen (Decke, Podest): Dicke, Umfang der Aussenkontur, Flächen und Volumen; Netto
/// zieht die Aussparungen ab.
pub fn slab_quantities(outline: &[Vec2], openings: &[&[Vec2]], thickness: f64) -> Vec<Qty> {
let gross = ring_area(outline);
let mut holes = 0.0;
for r in openings {
holes += ring_area(r);
}
let net = max(0.0, gross - holes);
vec![
len("Width", thickness),
len("Perimeter", ring_perimeter(outline)),
area("GrossArea", gross),
area("NetArea", net),
vol("GrossVolume", gross * thickness),
vol("NetVolume", net * thickness),
]
}
/// Dach-Basismengen aus den geneigten Dachflächen (Aussenseite): geneigte Fläche (brutto = netto)
/// und Grundrissprojektion (Newell: Vektorfläche je Polygon).
pub fn roof_quantities(planes: &[Vec<[f64; 3]>]) -> Vec<Qty> {
let mut sloped = 0.0;
let mut projected = 0.0;
for pts in planes {
let (mut nx, mut ny, mut nz) = (0.0, 0.0, 0.0);
let n = pts.len();
for i in 0..n {
let c = pts[if i == 0 { n - 1 } else { i - 1 }];
let d = pts[i];
nx += (c[1] - d[1]) * (c[2] + d[2]);
ny += (c[2] - d[2]) * (c[0] + d[0]);
nz += (c[0] - d[0]) * (c[1] + d[1]);
}
sloped += hypot(&[nx, ny, nz]) / 2.0;
projected += nz.abs() / 2.0;
}
vec![area("GrossArea", sloped), area("NetArea", sloped), area("ProjectedArea", projected)]
}
/// Stützen-Basismengen: Länge, Querschnitt, Mantel, Oberfläche und Volumen.
pub fn column_quantities(footprint: &[Vec2], length: f64) -> Vec<Qty> {
let cross = ring_area(footprint);
let outer = ring_perimeter(footprint) * length;
vec![
len("Length", length),
area("CrossSectionArea", cross),
area("OuterSurfaceArea", outer),
area("NetSurfaceArea", outer + 2.0 * cross),
vol("GrossVolume", cross * length),
vol("NetVolume", cross * length),
]
}
/// Tür-/Fenster-Basismengen (lichte Öffnung): Breite, Höhe, Umfang, Fläche.
pub fn opening_quantities(width: f64, height: f64) -> Vec<Qty> {
let w = clean(width);
let h = clean(height);
vec![len("Width", w), len("Height", h), len("Perimeter", 2.0 * (w + h)), area("Area", w * h)]
}
/// Treppenlauf: Lauflänge entlang der Lauflinie und Volumen.
pub fn flight_quantities(length: f64, volume: f64) -> Vec<Qty> {
vec![len("Length", length), vol("GrossVolume", volume), vol("NetVolume", volume)]
}
/// Geländer: Länge.
pub fn railing_quantities(length: f64) -> Vec<Qty> {
vec![len("Length", length)]
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model3d::RHole;
fn v(x: f64, y: f64) -> Vec2 {
Vec2 { x, y }
}
fn band(start: [f64; 2], end: [f64; 2], thickness: f64, base: f64, height: f64) -> RWall {
RWall {
start,
end,
thickness,
height,
base_elevation: base,
top_drop: None,
color: [0.5, 0.5, 0.5],
layers: vec![],
wall_id: "w".into(),
holes: None,
hatch: None,
material_index: None,
cut: None,
}
}
fn get(q: &[Qty], name: &str) -> Option<f64> {
q.iter().find(|x| x.name == name).map(|x| x.value)
}
fn close(a: Option<f64>, b: f64) -> bool {
a.is_some_and(|a| (a - b).abs() < 1e-9)
}
#[test]
fn ringe() {
let r = [v(0.0, 0.0), v(4.0, 0.0), v(4.0, 3.0), v(0.0, 3.0)];
assert_eq!(ring_area(&r), 12.0);
assert_eq!(ring_perimeter(&r), 14.0);
let mut rev = r.to_vec();
rev.reverse();
assert_eq!(ring_area(&rev), 12.0);
assert_eq!(ring_area(&[]), 0.0);
}
#[test]
fn wand_sonderfaelle() {
let (s, e) = (v(0.0, 0.0), v(5.0, 0.0));
// Innere Schicht endet unter der Decke: Seitenfläche mit voller Wandhöhe, Volumen je Schicht.
let outer = band([0.0, 0.0], [5.0, 0.0], 0.2, 0.0, 2.6);
let inner = band([0.1, 0.0], [4.9, 0.0], 0.1, 0.0, 2.3);
let q = wall_quantities(s, e, &[&outer, &inner], &[], None);
assert!(close(get(&q, "Height"), 2.6) && close(get(&q, "GrossSideArea"), 13.0));
assert!(close(get(&q, "GrossVolume"), 5.0 * 0.2 * 2.6 + 4.8 * 0.1 * 2.3));
// Gehrung/Anschluss: kürzeres Band ändert das Volumen, nicht die Wandlänge.
let q = wall_quantities(s, e, &[&inner], &[], None);
assert_eq!(get(&q, "Length"), Some(5.0));
assert_eq!(get(&q, "NetVolume"), get(&q, "GrossVolume"));
// Öffnung grösser als die Wand: netto nie negativ; Öffnung ausserhalb zieht nichts ab.
let big = [Cutout { from: -1.0, to: 6.0, z_bottom: -1.0, z_top: 5.0 }, Cutout { from: 8.0, to: 9.0, z_bottom: 0.0, z_top: 2.0 }];
let q = wall_quantities(s, e, &[&outer], &big, None);
assert_eq!(get(&q, "NetSideArea"), Some(0.0));
assert!(close(get(&q, "NetVolume"), 0.0));
// Netz-Wand: Netto aus dem Netz, Brutto bleibt der Quader.
let q = wall_quantities(s, e, &[&outer], &[], Some(1.5));
assert_eq!(get(&q, "NetVolume"), Some(1.5));
assert!(close(get(&q, "GrossVolume"), 13.0 * 0.2));
assert!(wall_quantities(s, e, &[], &[], None).is_empty());
}
#[test]
fn satteldach_30_grad() {
let h = (std::f64::consts::PI / 6.0).tan() * 2.0;
let planes = vec![vec![[0.0, 0.0, 0.0], [5.0, 0.0, 0.0], [5.0, 2.0, h], [0.0, 2.0, h]], vec![[0.0, 4.0, 0.0], [0.0, 2.0, h], [5.0, 2.0, h], [5.0, 4.0, 0.0]]];
let q = roof_quantities(&planes);
assert!((get(&q, "ProjectedArea").unwrap() - 20.0).abs() < 1e-9);
assert!((get(&q, "GrossArea").unwrap() - 20.0 / (std::f64::consts::PI / 6.0).cos()).abs() < 1e-9);
assert_eq!(get(&q, "NetArea"), get(&q, "GrossArea"));
}
#[test]
fn wand_brutto_netto() {
// Wand 5 m, zwei Schichten (0.2 + 0.1) übereinander-bündig, 2.6 m hoch, eine Öffnung 1×1.2 m.
let b1 = band([0.0, -0.05], [5.0, -0.05], 0.2, 0.0, 2.6);
let b2 = band([0.0, 0.1], [5.0, 0.1], 0.1, 0.0, 2.5);
let cut = Cutout { from: 1.0, to: 2.0, z_bottom: 0.9, z_top: 2.1 };
let q = wall_quantities(v(0.0, 0.0), v(5.0, 0.0), &[&b1, &b2], &[cut], None);
assert!(close(get(&q, "Length"), 5.0));
assert!(close(get(&q, "Width"), 0.3));
assert!(close(get(&q, "Height"), 2.6));
assert!(close(get(&q, "GrossSideArea"), 13.0));
assert!(close(get(&q, "NetSideArea"), 13.0 - 1.2));
let gross = 5.0 * 0.2 * 2.6 + 5.0 * 0.1 * 2.5;
assert!(close(get(&q, "GrossVolume"), gross));
assert!(close(get(&q, "NetVolume"), gross - 1.2 * 0.3));
// Netz-Volumen übersteuert, Brutto nie darunter.
let q = wall_quantities(v(0.0, 0.0), v(5.0, 0.0), &[&b1], &[], Some(99.0));
assert!(close(get(&q, "NetVolume"), 99.0) && close(get(&q, "GrossVolume"), 99.0));
}
#[test]
fn schraege_wand_ohne_hoehe() {
let mut b = band([0.0, 0.0], [4.0, 0.0], 0.3, 0.0, 3.0);
b.top_drop = Some([0.0, 1.0]);
let q = wall_quantities(v(0.0, 0.0), v(4.0, 0.0), &[&b], &[], None);
assert!(get(&q, "Height").is_none());
assert!(close(get(&q, "GrossSideArea"), 4.0 * 2.5));
assert!(close(get(&q, "GrossVolume"), 4.0 * 0.3 * 2.5));
}
#[test]
fn loch_volumen() {
let mut b = band([0.0, 0.0], [4.0, 0.0], 0.3, 0.0, 2.5);
b.holes = Some(vec![RHole { from: 1.0, to: 2.0, z_bottom: 2.0, z_top: 3.0 }]);
assert!((hole_volume(&[&b]) - 0.5 * 0.3).abs() < 1e-12);
}
#[test]
fn platte_dach_stuetze_oeffnung() {
let outline = [v(0.0, 0.0), v(10.0, 0.0), v(10.0, 5.0), v(0.0, 5.0)];
let hole = [v(1.0, 1.0), v(2.0, 1.0), v(2.0, 2.0), v(1.0, 2.0)];
let q = slab_quantities(&outline, &[&hole], 0.2);
assert!(close(get(&q, "NetArea"), 49.0) && close(get(&q, "Perimeter"), 30.0) && close(get(&q, "GrossVolume"), 10.0));
// Satteldach-Hälfte: 10 × 5 m Grundriss, 3 m hoch.
let plane = vec![[0.0, 0.0, 0.0], [10.0, 0.0, 0.0], [10.0, 5.0, 3.0], [0.0, 5.0, 3.0]];
let q = roof_quantities(&[plane]);
assert!(close(get(&q, "ProjectedArea"), 50.0));
assert!(close(get(&q, "GrossArea"), 10.0 * 34f64.sqrt()));
let q = column_quantities(&[v(0.0, 0.0), v(0.3, 0.0), v(0.3, 0.3), v(0.0, 0.3)], 2.5);
assert!(close(get(&q, "NetVolume"), 0.225));
let q = opening_quantities(f64::NAN, 2.0);
assert_eq!(get(&q, "Width"), Some(0.0));
assert!(close(get(&q, "Perimeter"), 4.0));
assert_eq!(flight_quantities(-1.0, 2.0)[0].value, 0.0);
assert_eq!(railing_quantities(3.0)[0].value, 3.0);
}
}
+299
View File
@@ -0,0 +1,299 @@
//! Treppen im IFC-Export ([B5], [K4]; Port von `src/export/ifcStairs.ts`): statt eines
//! Fussabdruck-Quaders die Teile der Treppe wie im 3D — Läufe (IfcStairFlight), Podest (IfcSlab
//! LANDING) und Handlauf/Pfosten (IfcRailing), zusammengefasst von der IfcStair. Quelle sind
//! dieselben Ableitungen wie im 3D (`emit_stairs` Tritt-Prismen und Podest, `emit_stair_meshes`
//! glatte Ortbeton-Laufplatte, `emit_stair_railings`), je Treppe mit einem Projekt aufgerufen, das
//! nur diese Treppe enthält (die Ableitungen liefern keine ids). Hier: Zuordnung und Basismengen;
//! die Entitäten schreibt `fileio` (`ifc_export.rs`, STAIR).
//!
//! Zuordnung der Tritt-Prismen: bei "L" ist das Podest das Prisma mit dem Umriss des Podest-Polygons
//! der Treppengeometrie; Tritte bis zur Podest-Oberkante gehören zum ersten, die darüber zum
//! zweiten Lauf. Gerade und Wendeltreppen haben einen Lauf (die Wendel-Mitte bleibt Teil davon).
use crate::export_flat::{js_key, mesh_volume, orient_outward};
use crate::ifc_quantities::{flight_quantities, railing_quantities, ring_area, slab_quantities, Qty};
use crate::jsmath::hypot2;
use crate::jsnum::round;
use crate::model::*;
use crate::model3d::{self, RMesh, RSlab};
/// Ein Prisma (Profil in Welt-XY, Unterkante relativ zum Geschoss, Tiefe).
#[derive(Debug, Clone, PartialEq)]
pub struct StairSolid {
pub pts: Vec<Vec2>,
pub z_rel: f64,
pub depth: f64,
}
/// Ein Netz (IFC: x, y, z-hoch, Z relativ zum Geschoss).
#[derive(Debug, Clone, PartialEq)]
pub struct IfcMesh {
pub positions: Vec<f64>,
pub indices: Vec<u32>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum FlightBody {
Solids(Vec<StairSolid>),
Mesh(IfcMesh),
}
#[derive(Debug, Clone, PartialEq)]
pub struct StairFlightParts {
pub name: String,
pub risers: f64,
pub treads: f64,
pub riser_height: f64,
pub tread_length: f64,
/// IfcStairFlightTypeEnum.
pub predefined: &'static str,
pub quantities: Vec<Qty>,
pub body: FlightBody,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Landing {
pub pts: Vec<Vec2>,
pub z_rel: f64,
pub depth: f64,
pub quantities: Vec<Qty>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Rail {
pub mesh: IfcMesh,
pub quantities: Vec<Qty>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct StairParts {
pub flights: Vec<StairFlightParts>,
pub landing: Option<Landing>,
pub rail: Option<Rail>,
}
const EPS: f64 = 1e-6;
/// Gleicher Umriss (gleiche Punktmenge, auch bei anderer Reihenfolge/Startpunkt).
fn same_ring(a: &[[f64; 2]], b: &[kernel2d::Vec2]) -> bool {
a.len() == b.len() && a.iter().all(|p| b.iter().any(|q| (p[0] - q.x).abs() < EPS && (p[1] - q.y).abs() < EPS))
}
fn centroid(pts: &[Vec2]) -> Vec2 {
let (mut x, mut y) = (0.0, 0.0);
for p in pts {
x += p.x;
}
for p in pts {
y += p.y;
}
Vec2 { x: x / pts.len() as f64, y: y / pts.len() as f64 }
}
/// Netze aneinanderhängen (Indizes verschoben).
fn concat(meshes: &[RMesh]) -> (Vec<f64>, Vec<u32>) {
let (mut positions, mut indices) = (Vec::new(), Vec::new());
for m in meshes {
let at = (positions.len() / 3) as u32;
positions.extend_from_slice(&m.positions);
indices.extend(m.indices.iter().map(|i| at + i));
}
(positions, indices)
}
/// Netz (Modell x, y, z-hoch) nach IFC: Z relativ zum Geschoss, Wicklung nach aussen.
fn ifc_mesh(mut positions: Vec<f64>, indices: &[u32], base: f64) -> IfcMesh {
let mut i = 2;
while i < positions.len() {
positions[i] -= base;
i += 3;
}
let indices = orient_outward(&positions, indices);
IfcMesh { positions, indices }
}
fn solid_of(s: &RSlab, base: f64) -> StairSolid {
StairSolid { pts: s.outline.iter().map(|p| Vec2 { x: p[0], y: p[1] }).collect(), z_rel: s.z_bottom - base, depth: s.z_top - s.z_bottom }
}
/// Teile einer Treppe für den IFC-Export. `one` = Projekt, das NUR diese Treppe enthält (sonst wie
/// das ganze Projekt), `base` = Geschoss-UK, auf die Z-Werte bezogen werden. Leere Teile ergeben
/// `flights: []`, `landing: None`, `rail: None`.
pub fn stair_parts(one: &Project, stair: &Stair, base: f64) -> StairParts {
let (z_bottom, z_top) = one.stair_vertical_extent(stair);
let rise = z_top - z_bottom;
let geo = crate::stair::decode_geometry(&crate::stair::geometry(&stair.encode(), rise));
let (riser_height, tread_depth, n_treads) = geo.as_ref().map_or((0.0, 0.0, 0), |g| (g.riser_height, g.tread_depth, g.treads.len()));
let geo_landing = geo.as_ref().and_then(|g| g.landing.as_ref());
let slabs = model3d::emit_stairs(one, false);
let meshes = model3d::emit_stair_meshes(one);
let predefined = if stair.shape == StairShape::Spiral { "SPIRAL" } else { "STRAIGHT" };
// Podest nur bei "L" (bei der Wendel ist das Polygon die Treppenmitte, Teil des Laufs).
let landing_idx = match (stair.shape, geo_landing) {
(StairShape::L, Some(l)) => slabs.iter().position(|s| same_ring(&s.outline, l)),
_ => None,
};
let tread_slabs: Vec<&RSlab> = slabs.iter().enumerate().filter(|(i, _)| Some(*i) != landing_idx).map(|(_, s)| s).collect();
let mut groups: Vec<Vec<&RSlab>> = Vec::new();
if let Some(li) = landing_idx {
let top = slabs[li].z_top + EPS;
let lower: Vec<&RSlab> = tread_slabs.iter().copied().filter(|s| s.z_top <= top).collect();
let upper: Vec<&RSlab> = tread_slabs.iter().copied().filter(|s| s.z_top > top).collect();
for g in [lower, upper] {
if !g.is_empty() {
groups.push(g);
}
}
} else if !tread_slabs.is_empty() {
groups.push(tread_slabs);
}
let mut flights: Vec<StairFlightParts> = Vec::new();
let n_groups = groups.len();
for (k, g) in groups.iter().enumerate() {
// Tritte = verschiedene Oberkanten (Setzstufen-Platten und Nasen teilen die Höhe ihres Tritts).
let mut tops: Vec<u64> = Vec::new();
for s in g {
let key = js_key(round(s.z_top / 1e-4));
if !tops.contains(&key) {
tops.push(key);
}
}
let treads = tops.len() as f64;
// Lauflänge: Weg zwischen erstem und letztem Tritt (Schwerpunkte) plus eine Trittiefe, mit der Steigung.
let mut lowest = g[0];
let mut highest = g[0];
for s in g {
if s.z_top < lowest.z_top {
lowest = s;
}
if s.z_top > highest.z_top {
highest = s;
}
}
let c0 = centroid(&solid_of(lowest, base).pts);
let c1 = centroid(&solid_of(highest, base).pts);
let run = hypot2(c1.x - c0.x, c1.y - c0.y) + tread_depth;
let lift = highest.z_top - lowest.z_top + riser_height;
let solids: Vec<StairSolid> = g.iter().map(|s| solid_of(s, base)).collect();
let mut volume = 0.0;
for x in g {
let pts: Vec<Vec2> = x.outline.iter().map(|p| Vec2 { x: p[0], y: p[1] }).collect();
volume += ring_area(&pts) * (x.z_top - x.z_bottom);
}
flights.push(StairFlightParts {
name: if n_groups > 1 { format!("Lauf {}", k + 1) } else { "Lauf".to_string() },
risers: treads,
treads,
riser_height,
tread_length: tread_depth,
predefined,
quantities: flight_quantities(hypot2(run, lift), volume),
body: FlightBody::Solids(solids),
});
}
// Glatte Ortbeton-Laufplatte (gerade Betontreppe): ein Lauf als Netz.
if !meshes.is_empty() {
let (positions, indices) = concat(&meshes);
let mesh = ifc_mesh(positions, &indices, base);
let volume = mesh_volume(&mesh.positions, &mesh.indices);
flights.push(StairFlightParts {
name: if flights.is_empty() { "Lauf".to_string() } else { format!("Lauf {}", flights.len() + 1) },
risers: n_treads as f64,
treads: n_treads as f64,
riser_height,
tread_length: tread_depth,
predefined,
quantities: flight_quantities(hypot2(stair.run_length, rise), volume),
body: FlightBody::Mesh(mesh),
});
}
let landing = landing_idx.map(|li| {
let s = solid_of(&slabs[li], base);
let quantities = slab_quantities(&s.pts, &[], s.depth);
Landing { pts: s.pts, z_rel: s.z_rel, depth: s.depth, quantities }
});
let rail_meshes = model3d::emit_stair_railings(one);
let rail = (!rail_meshes.is_empty()).then(|| {
let (positions, indices) = concat(&rail_meshes);
let sides = if one.stair_type(stair).and_then(|t| t.railing) == Some(StairTypeRailing::Beide) { 2.0 } else { 1.0 };
Rail { mesh: ifc_mesh(positions, &indices, base), quantities: railing_quantities(hypot2(stair.run_length, rise) * sides) }
});
StairParts { flights, landing, rail }
}
#[cfg(test)]
mod tests {
use super::*;
fn project_with(stair: Stair, ty: Option<StairType>) -> Project {
let mut p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap();
if let Some(t) = ty {
p.stair_types.get_or_insert_with(Vec::new).push(t);
}
p.stairs = Some(vec![stair]);
p
}
fn stair(shape: StairShape, type_id: Option<&str>) -> Stair {
Stair {
id: "S".into(),
floor_id: "eg".into(),
shape,
start: Vec2 { x: 0.0, y: 0.0 },
dir: Vec2 { x: 1.0, y: 0.0 },
run_length: 3.0,
run2_length: (shape == StairShape::L).then_some(2.0),
turn: (shape == StairShape::L).then_some(1.0),
width: 1.0,
total_rise: Some(2.6),
step_count: 15.0,
type_id: type_id.map(String::from),
..Default::default()
}
}
#[test]
fn gerade_massivtreppe_ein_lauf() {
let st = stair(StairShape::Straight, None);
let p = project_with(st.clone(), None);
let parts = stair_parts(&p, &st, 0.0);
assert_eq!(parts.flights.len(), 1);
let f = &parts.flights[0];
assert_eq!(f.name, "Lauf");
assert!(f.treads > 0.0 && f.riser_height > 0.0);
assert!(matches!(&f.body, FlightBody::Solids(s) if !s.is_empty()));
assert!(parts.landing.is_none() && parts.rail.is_none());
}
#[test]
fn l_treppe_zwei_laeufe_und_podest() {
let st = stair(StairShape::L, None);
let p = project_with(st.clone(), None);
let parts = stair_parts(&p, &st, 0.0);
assert_eq!(parts.flights.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["Lauf 1", "Lauf 2"]);
let l = parts.landing.expect("Podest");
assert!(l.depth > 0.0 && l.quantities.iter().any(|q| q.name == "NetArea" && q.value > 0.0));
}
#[test]
fn betontreppe_mit_handlauf_beidseitig() {
let ty = StairType { id: "beton2".into(), structure: StairTypeStructure::Beton, closed_risers: true, tread_thickness: 0.05, railing: Some(StairTypeRailing::Beide), default_width: 1.0, ..Default::default() };
let st = stair(StairShape::Straight, Some("beton2"));
let p = project_with(st.clone(), Some(ty));
let parts = stair_parts(&p, &st, 0.5);
let m = parts.flights.iter().find_map(|f| match &f.body {
FlightBody::Mesh(m) => Some(m),
_ => None,
});
let m = m.expect("Laufplatte als Netz");
assert!(mesh_volume(&m.positions, &m.indices) > 0.0);
let rail = parts.rail.expect("Handlauf");
let len = rail.quantities[0].value;
assert!((len - 2.0 * hypot2(3.0, 2.6)).abs() < 1e-9);
}
}
+6
View File
@@ -65,6 +65,12 @@ pub mod snap;
pub mod plan_svg;
pub mod plan_dxf;
pub mod plan_print_svg;
pub mod export_flat;
pub mod geo_rebase;
pub mod ifc_quantities;
pub mod ifc_stairs;
pub mod ifc_data;
pub mod mesh_data;
#[cfg(feature = "web")]
mod web;
+525
View File
@@ -0,0 +1,525 @@
//! OBJ-/STL-/glTF-Export: Sammler im Kern ([K4] S2, [C11]; vorher `buildScene` in
//! `src/export/exportMesh.ts`). Liest das Projekt-Dokument und erzeugt die Szene als flachen Puffer
//! für den Schreiber `src-tauri/fileio/src/mesh_export.rs` (Kodierung dort, FLAT_VERSION 1): ein
//! Knoten je Bauteil-Vorkommen mit Teil-Netzen je Material, Materialtabelle, Geschosse.
//!
//! Dreiecks-Quelle wie im 3D-Viewer:
//! • Wände: Schicht-Bänder (`emit_walls`), gelochte Bänder öffnungsgenau (`wall_cut_mesh`, inkl.
//! Laibungen), lochlose als 8-Ecken-Box.
//! • Decken und Extrusionen: Umriss-Prisma (Ear-Clipping-Kappen + Mantel); Extrusionen mit `taper`
//! (oberer Ring zum Schwerpunkt verjüngt) — bewusst die Prisma-Näherung, nicht die truck-Körper.
//! • Dächer, Stützen, Treppen (Tritte, Laufplatte, Handlauf), Öffnungsteile (je Öffnung ein
//! Knoten): dieselben `emit_*`-Ableitungen wie das 3D, je Bauteil mit einem Projekt aufgerufen,
//! das nur dieses Bauteil enthält (die Ableitungen liefern keine ids).
//! • Gelände und importierte Meshes (Farbe der Quelle, falls gesetzt).
//! Achsen intern Modell (x, y, z-hoch) → Welt (x, z, y); der Schreiber stellt die Rechtshändigkeit
//! her (Datei (x, z, −y), Norden = −Z). Geschlossene Teile werden nach aussen gewickelt
//! (`orient_outward`), da render3d doppelseitig zeichnet. Zahlsemantik und Reihenfolge wie die
//! frühere TS-Fassung: die Dateien bleiben zeichengleich.
use crate::export_flat::{orient_outward, Flat};
use crate::jsmath::hypot2;
use crate::jsnum::{max, min};
use crate::model::*;
use crate::model3d::{self, RMesh, RWall};
use crate::style::{hex_to_rgb, Rgb};
use crate::wall_mesh_cut::{wall_cut_mesh_checked, CutWall};
use std::collections::HashMap;
const FLAT_VERSION: f64 = 1.0;
/// Was in die Szene kommt (Standard: alles).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MeshOptions {
/// Verglasung und Rahmenteile je Öffnung als eigener Knoten.
pub opening_parts: bool,
/// Gelände und importierte Kontext-Meshes.
pub context: bool,
/// Geschoss als Eltern-Knoten (nur glTF; OBJ/STL: aus).
pub by_level: bool,
}
impl Default for MeshOptions {
fn default() -> Self {
MeshOptions { opening_parts: true, context: true, by_level: true }
}
}
/// Teil-Netz mit EINEM Material, lokale Indizes.
struct Prim {
material: f64,
positions: Vec<f64>,
indices: Vec<f64>,
}
/// Ein Bauteil-Vorkommen mit ≥ 1 Teil-Netz.
struct Group {
name: String,
kind: &'static str,
id: String,
level: f64,
prims: Vec<Prim>,
}
impl Group {
fn new(name: String, kind: &'static str, id: &str, level: f64) -> Self {
Group { name, kind, id: id.to_string(), level, prims: Vec::new() }
}
fn prim(&mut self, material: f64) -> &mut Prim {
self.prims.push(Prim { material, positions: Vec::new(), indices: Vec::new() });
self.prims.last_mut().unwrap()
}
}
/// Material der Szene: Farbe sRGB 0..1, Alpha < 1 = transparent (Glas).
struct Material {
name: String,
rgba: [f64; 4],
metallic: f64,
roughness: f64,
}
/// Materialtabelle: gleiche Farbe + Name = ein Material (Schlüssel wie in TS als Text).
#[derive(Default)]
struct Materials {
list: Vec<Material>,
by_key: HashMap<String, usize>,
}
impl Materials {
fn get(&mut self, name: &str, rgb: Rgb, alpha: f64, metallic: f64, roughness: f64) -> f64 {
use crate::js_fmt::js_number as n;
let key = format!("{name}|{},{},{}|{}|{}|{}", n(rgb[0]), n(rgb[1]), n(rgb[2]), n(alpha), n(metallic), n(roughness));
if let Some(&i) = self.by_key.get(&key) {
return i as f64;
}
let i = self.list.len();
self.list.push(Material { name: name.to_string(), rgba: [rgb[0], rgb[1], rgb[2], alpha], metallic, roughness });
self.by_key.insert(key, i);
i as f64
}
fn solid(&mut self, name: &str, rgb: Rgb) -> f64 {
self.get(name, rgb, 1.0, 0.0, 0.9)
}
}
/// OBJ-Gruppennamen ohne Leerraum/Sonderzeichen (je UTF-16-Einheit ein `_`, wie das JS-RegExp).
fn sanitize_name(id: &str) -> String {
let mut out = String::new();
for c in id.chars() {
if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
out.push(c);
} else {
for _ in 0..c.len_utf16() {
out.push('_');
}
}
}
if out.is_empty() {
"x".to_string()
} else {
out
}
}
/// Die 6 Quader-Seiten (Bits: 0 Achse, 1 Höhe, 2 Dicke), aussen gewunden; je Quadrupel 2 Dreiecke.
const BOX_QUADS: [[usize; 4]; 6] = [[4, 6, 7, 5], [1, 3, 2, 0], [2, 3, 7, 6], [4, 5, 1, 0], [1, 5, 7, 3], [2, 6, 4, 0]];
/// Voller Wand-Schicht-Quader ohne Öffnungen (lochlose Bänder); entartete Bänder fallen weg.
fn push_wall_box(g: &mut Prim, w: &RWall) {
let [sx, sy] = w.start;
let [ex, ey] = w.end;
let dx = ex - sx;
let dz = ey - sy;
let len = hypot2(dx, dz);
if len < 1e-9 || w.height <= 1e-9 || w.thickness <= 1e-9 {
return;
}
let ax = dx / len;
let az = dz / len;
// Normale = Welt-Hoch × Achse: (az, 0, −ax).
let nx = az;
let nz = -ax;
let half_len = len / 2.0;
let half_height = w.height / 2.0;
let half_thick = w.thickness / 2.0;
let cx = (sx + ex) / 2.0;
let cz = (sy + ey) / 2.0;
let cy = w.base_elevation + w.height / 2.0;
let base = (g.positions.len() / 3) as f64;
for i in 0..8 {
let sl = if i & 1 != 0 { 1.0 } else { -1.0 };
let sh = if i & 2 != 0 { 1.0 } else { -1.0 };
let st = if i & 4 != 0 { 1.0 } else { -1.0 };
g.positions.extend_from_slice(&[cx + sl * half_len * ax + st * half_thick * nx, cy + sh * half_height, cz + sl * half_len * az + st * half_thick * nz]);
}
for [a, b, c, d] in BOX_QUADS {
let (a, b, c, d) = (base + a as f64, base + b as f64, base + c as f64, base + d as f64);
g.indices.extend_from_slice(&[a, b, c, a, c, d]);
}
}
/// Signierte Fläche eines Modell-XY-Umrisses (Shoelace); ≥ 0 = CCW.
fn signed_area_xy(pts: &[Vec2]) -> f64 {
let mut a = 0.0;
let n = pts.len();
for i in 0..n {
let j = if i == 0 { n - 1 } else { i - 1 };
a += pts[j].x * pts[i].y - pts[i].x * pts[j].y;
}
a / 2.0
}
/// Extrudiertes Umriss-Prisma (Decke, Treppen-Tritt, Extrusion): Kappen + Mantel, aussen gewunden;
/// `taper` (0..1) verjüngt den oberen Ring linear zum Schwerpunkt.
fn push_prism(g: &mut Prim, outline: &[Vec2], z_bottom: f64, z_top: f64, taper: f64) {
if outline.len() < 3 || z_top - z_bottom <= 1e-9 {
return;
}
let ccw: Vec<Vec2> = if signed_area_xy(outline) >= 0.0 { outline.to_vec() } else { outline.iter().rev().copied().collect() };
let n = ccw.len();
let (mut cx, mut cy) = (0.0, 0.0);
for p in &ccw {
cx += p.x;
cy += p.y;
}
cx /= n as f64;
cy /= n as f64;
let t = min(1.0, max(0.0, taper));
let base = (g.positions.len() / 3) as f64;
for p in &ccw {
g.positions.extend_from_slice(&[p.x, z_bottom, p.y]);
}
for p in &ccw {
g.positions.extend_from_slice(&[cx + (p.x - cx) * (1.0 - t), z_top, cy + (p.y - cy) * (1.0 - t)]);
}
let nf = n as f64;
let cap = crate::gpu_compile::triangulate(&ccw.iter().map(|p| crate::hatch::v2(p.x, p.y)).collect::<Vec<_>>());
for tri in cap.chunks_exact(3) {
let (a, b, c) = (tri[0] as f64, tri[1] as f64, tri[2] as f64);
g.indices.extend_from_slice(&[base + a, base + b, base + c]);
g.indices.extend_from_slice(&[base + nf + a, base + nf + c, base + nf + b]);
}
for i in 0..n {
let j = (i + 1) % n;
let (bi, bj, ti, tj) = (base + i as f64, base + j as f64, base + nf + i as f64, base + nf + j as f64);
g.indices.extend_from_slice(&[bi, ti, tj, bi, tj, bj]);
}
}
/// Modell-Netz (x, y, z-hoch) anhängen: Achsen nach Welt (x, z, y), Wicklung umgekehrt (Spiegelung);
/// `closed` ⇒ nach aussen gewickelt. Indizes ausserhalb und NaN fallen weg.
fn append_model_mesh(prim: &mut Prim, positions: &[f64], indices: &[f64], closed: bool) {
let mut pos: Vec<f64> = Vec::with_capacity(positions.len());
let mut i = 0;
while i + 2 < positions.len() {
pos.extend_from_slice(&[positions[i], positions[i + 2], positions[i + 1]]);
i += 3;
}
let nv = (pos.len() / 3) as f64;
let ok = |v: f64| v >= 0.0 && v < nv;
let mut tri: Vec<f64> = Vec::new();
let mut i = 0;
while i + 2 < indices.len() {
let (a, b, c) = (indices[i], indices[i + 1], indices[i + 2]);
if ok(a) && ok(b) && ok(c) {
tri.extend_from_slice(&[a, c, b]);
}
i += 3;
}
let idx: Vec<f64> = if closed && tri.iter().all(|v| v.fract() == 0.0) {
let t: Vec<u32> = tri.iter().map(|&v| v as u32).collect();
orient_outward(&pos, &t).into_iter().map(f64::from).collect()
} else {
tri
};
let base = (prim.positions.len() / 3) as f64;
prim.positions.extend_from_slice(&pos);
prim.indices.extend(idx.iter().map(|i| base + i));
}
fn u32s(v: &[u32]) -> Vec<f64> {
v.iter().map(|&i| f64::from(i)).collect()
}
/// Standardfarbe der Extrusionen (wie `SLAB_RGB`).
const SLAB_COLOR: Rgb = [0.86, 0.86, 0.88];
/// Verglasung und Rahmenteile aus `emit_opening_meshes` (Farben `PART_RGB`).
const GLASS_COLOR: Rgb = [0.62, 0.76, 0.85];
const OPENING_PART_NAMES: [(Rgb, &str); 5] = [
([0.85, 0.85, 0.83], "Blendrahmen"),
([0.88, 0.88, 0.9], "Fluegelrahmen"),
([0.8, 0.8, 0.78], "Fensterbank/Zarge"),
([0.25, 0.27, 0.3], "Schwelle"),
([0.93, 0.9, 0.85], "Tuerblatt"),
];
const TERRAIN_RGB: Rgb = [169.0 / 255.0, 176.0 / 255.0, 162.0 / 255.0];
const IMPORTED_RGB: Rgb = [159.0 / 255.0, 166.0 / 255.0, 174.0 / 255.0];
fn same_rgb(a: &Rgb, b: &Rgb) -> bool {
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9)
}
/// Die Szene als flacher Puffer (s. Modulkopf).
pub fn mesh_export_data(src: &Project, opt: &MeshOptions) -> Result<Flat, String> {
let mut p = src.clone();
let mut groups: Vec<Group> = Vec::new();
let mut mats = Materials::default();
crate::ifc_data::pick_opening_check(&p)?;
let walls = model3d::emit_walls(&p, true)?;
let slabs = model3d::emit_slabs(&p);
let levels: Vec<(String, String)> = p.drawing_levels.iter().filter(|l| l.kind == DrawingLevelKind::Floor).map(|l| (l.id.clone(), l.name.clone())).collect();
let level_of = |floor_id: Option<&str>| -> f64 { floor_id.and_then(|id| levels.iter().position(|l| l.0 == id)).map_or(-1.0, |i| i as f64) };
let component_name = |p: &Project, id: Option<&str>, fallback: &str| -> String {
id.and_then(|id| p.component(id)).map(|c| c.name.as_str()).filter(|n| !n.is_empty()).unwrap_or(fallback).to_string()
};
// Wände: alle Schicht-Bänder DERSELBEN Wand-Id in EINE Gruppe.
let mut wall_group: HashMap<String, usize> = HashMap::new();
let mut wall_floor: HashMap<&str, &str> = HashMap::new();
for w in &p.walls {
wall_floor.insert(&w.id, &w.floor_id);
}
for w in &walls {
let gi = match wall_group.get(&w.wall_id) {
Some(&i) => i,
None => {
groups.push(Group::new(format!("Wand_{}", sanitize_name(&w.wall_id)), "wall", &w.wall_id, level_of(wall_floor.get(w.wall_id.as_str()).copied())));
wall_group.insert(w.wall_id.clone(), groups.len() - 1);
groups.len() - 1
}
};
let mat = mats.solid(&component_name(&p, w.cut.as_ref().and_then(|c| c.component_id.as_deref()), "Wand"), w.color);
let prim = groups[gi].prim(mat);
if w.holes.as_ref().is_some_and(|h| !h.is_empty()) {
// Öffnungsgenau inkl. Laibungen (Welt x, Höhe, y), wie im 3D.
let cut = wall_cut_mesh_checked(&CutWall {
start: w.start,
end: w.end,
thickness: w.thickness,
base_elevation: w.base_elevation,
height: w.height,
holes: w.holes.as_deref().unwrap_or(&[]).iter().map(|h| [h.from, h.to, h.z_bottom, h.z_top]).collect(),
});
let base = (prim.positions.len() / 3) as f64;
prim.positions.extend_from_slice(&cut);
prim.indices.extend((0..cut.len() / 3).map(|i| base + i as f64));
} else {
push_wall_box(prim, w);
}
}
// Decken: ein Prisma je Platte.
let mut ceiling_floor: HashMap<&str, &str> = HashMap::new();
for c in p.ceilings.as_deref().unwrap_or(&[]) {
ceiling_floor.insert(&c.id, &c.floor_id);
}
for s in &slabs {
let mut g = Group::new(format!("Decke_{}", sanitize_name(&s.ceiling_id)), "slab", &s.ceiling_id, level_of(ceiling_floor.get(s.ceiling_id.as_str()).copied()));
let outline: Vec<Vec2> = s.outline.iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect();
let mat = mats.solid(&component_name(&p, s.cut.as_ref().and_then(|c| c.component_id.as_deref()), "Decke"), s.color);
push_prism(g.prim(mat), &outline, s.z_bottom, s.z_top, 0.0);
groups.push(g);
}
// Extrudierte Profile: Prisma je Körper (Prisma-Näherung statt truck-Körper).
for s in p.extruded_solids.as_deref().unwrap_or(&[]) {
if s.points.len() < 3 || s.height <= 0.0 {
continue;
}
let base_z = p.floor(&s.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0));
let mut g = Group::new(format!("Extrusion_{}", sanitize_name(&s.id)), "extrusion", &s.id, level_of(Some(&s.level_id)));
let mat = mats.solid("Extrusion", SLAB_COLOR);
push_prism(g.prim(mat), &s.points, base_z, base_z + s.height, s.taper.unwrap_or(0.0));
groups.push(g);
}
// Dächer, Stützen, Treppen: je Bauteil EIN Aufruf der 3D-Ableitung mit nur diesem Bauteil.
let add_meshes = |g: &mut Group, mats: &mut Materials, meshes: &[RMesh], name: &str| {
for m in meshes {
if m.indices.is_empty() {
continue;
}
let mat = mats.solid(name, m.color);
append_model_mesh(g.prim(mat), &m.positions, &u32s(&m.indices), true);
}
};
let roofs = p.roofs.take();
for roof in roofs.as_deref().unwrap_or(&[]) {
let mut g = Group::new(format!("Dach_{}", sanitize_name(&roof.id)), "roof", &roof.id, level_of(Some(&roof.floor_id)));
p.roofs = Some(vec![roof.clone()]);
add_meshes(&mut g, &mut mats, &model3d::emit_roofs(&p, None)?, "Dach");
groups.push(g);
}
p.roofs = roofs;
let columns = p.columns.take();
for col in columns.as_deref().unwrap_or(&[]) {
let mut g = Group::new(format!("Stuetze_{}", sanitize_name(&col.id)), "column", &col.id, level_of(Some(&col.floor_id)));
p.columns = Some(vec![col.clone()]);
let name = component_name(&p, col.component_id.as_deref(), "Stuetze");
add_meshes(&mut g, &mut mats, &model3d::emit_columns(&p), &name);
groups.push(g);
}
p.columns = columns;
let stairs = p.stairs.take();
for st in stairs.as_deref().unwrap_or(&[]) {
let mut g = Group::new(format!("Treppe_{}", sanitize_name(&st.id)), "stair", &st.id, level_of(Some(&st.floor_id)));
p.stairs = Some(vec![st.clone()]);
for s in model3d::emit_stairs(&p, false) {
let outline: Vec<Vec2> = s.outline.iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect();
let mat = mats.solid("Treppe", s.color);
push_prism(g.prim(mat), &outline, s.z_bottom, s.z_top, 0.0);
}
add_meshes(&mut g, &mut mats, &model3d::emit_stair_meshes(&p), "Treppe");
add_meshes(&mut g, &mut mats, &model3d::emit_stair_railings(&p), "Handlauf");
groups.push(g);
}
p.stairs = stairs;
// Öffnungsteile: je Öffnung ein Knoten mit Glas und Rahmenteilen als Teil-Netze je Material;
// die Ableitung nur mit der Wirtswand und dieser Öffnung.
if opt.opening_parts {
let all_walls = std::mem::take(&mut p.walls);
let openings = p.openings.take();
for op in openings.as_deref().unwrap_or(&[]) {
let Some(host) = all_walls.iter().find(|w| w.id == op.host_wall_id) else { continue };
p.walls = vec![host.clone()];
p.openings = Some(vec![op.clone()]);
let parts = model3d::emit_opening_meshes(&p, 1.0);
if parts.is_empty() {
continue;
}
let (prefix, kind) = match op.kind {
ElementKind::Window => ("Fenster", "window"),
ElementKind::Door => ("Tuer", "door"),
ElementKind::Unknown => ("Tuer", ""),
};
let mut g = Group::new(format!("{prefix}_{}", sanitize_name(&op.id)), kind, &op.id, level_of(Some(&host.floor_id)));
let mut prims: HashMap<&str, usize> = HashMap::new();
for m in &parts {
let glass = same_rgb(&m.color, &GLASS_COLOR);
let name = if glass { "Glas" } else { OPENING_PART_NAMES.iter().find(|(c, _)| same_rgb(c, &m.color)).map_or("Oeffnungsteil", |x| x.1) };
let pi = match prims.get(name) {
Some(&i) => i,
None => {
// Glas transparent und glatt (BLEND), Rahmen matt.
let mat = if glass { mats.get(name, m.color, 0.35, 0.0, 0.05) } else { mats.get(name, m.color, 1.0, 0.0, 0.6) };
g.prim(mat);
prims.insert(name, g.prims.len() - 1);
g.prims.len() - 1
}
};
append_model_mesh(&mut g.prims[pi], &m.positions, &u32s(&m.indices), true);
}
groups.push(g);
}
p.walls = all_walls;
p.openings = openings;
}
// Gelände und importierte Meshes (IFC/DXF): Farbe der Quelle, falls gesetzt.
if opt.context {
for obj in p.context.as_deref().unwrap_or(&[]) {
let (terrain, id, name, color, positions, indices) = match obj {
ContextObject::TerrainMesh(m) => (true, &m.id, &m.name, None, &m.positions, &m.indices),
ContextObject::ImportedMesh(m) => (false, &m.id, &m.name, m.color.as_deref(), &m.positions, &m.indices),
_ => continue,
};
if positions.len() < 9 || indices.len() < 3 {
continue;
}
let rgb = match (terrain, color.filter(|c| !c.is_empty())) {
(false, Some(c)) => hex_to_rgb(c, IMPORTED_RGB),
(true, _) => TERRAIN_RGB,
_ => IMPORTED_RGB,
};
let mut g = Group::new(format!("{}_{}", if terrain { "Gelaende" } else { "Kontext" }, sanitize_name(id)), if terrain { "terrain" } else { "context" }, id, -1.0);
let mat_name = if terrain { "Gelaende" } else if name.is_empty() { "Kontext" } else { name.as_str() };
let mat = mats.solid(mat_name, rgb);
append_model_mesh(g.prim(mat), positions, indices, false);
groups.push(g);
}
}
// Flacher Puffer (Gegenstück zu `mesh_export.rs`).
let mut f = Flat::new(FLAT_VERSION);
f.num(if opt.by_level { 1.0 } else { 0.0 });
f.num(mats.list.len() as f64);
for m in &mats.list {
let n = f.str(&m.name);
f.nums(&[n, m.rgba[0], m.rgba[1], m.rgba[2], m.rgba[3], m.metallic, m.roughness]);
}
f.num(levels.len() as f64);
for (id, name) in &levels {
let (a, b) = (f.str(id), f.str(name));
f.nums(&[a, b]);
}
let groups: Vec<&Group> = groups.iter().filter(|g| g.prims.iter().any(|p| !p.indices.is_empty())).collect();
f.num(groups.len() as f64);
for g in groups {
let (name, kind, id) = (f.str(&g.name), f.str(g.kind), f.str(&g.id));
f.nums(&[name, kind, id, g.level, g.prims.len() as f64]);
for pr in &g.prims {
f.nums(&[pr.material, (pr.positions.len() / 3) as f64]);
f.nums(&pr.positions);
f.num((pr.indices.len() / 3) as f64);
f.nums(&pr.indices);
}
}
Ok(f)
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> Project {
serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap()
}
#[test]
fn namen_wie_js() {
assert_eq!(sanitize_name("W 1/ä"), "W_1__");
assert_eq!(sanitize_name("a😀b"), "a__b");
assert_eq!(sanitize_name(""), "x");
}
#[test]
fn beispielprojekt_knoten_und_materialien() {
let f = mesh_export_data(&sample(), &MeshOptions::default()).unwrap();
assert_eq!(f.nums[0], FLAT_VERSION);
for want in ["Wand_W1", "Decke_C1", "Dach_RF1", "Treppe_ST1", "Fenster_O1", "Tuer_D1", "Glas"] {
assert!(f.strings.iter().any(|s| s == want), "fehlt: {want}");
}
let f2 = mesh_export_data(&sample(), &MeshOptions { opening_parts: false, ..Default::default() }).unwrap();
assert!(!f2.strings.iter().any(|s| s == "Fenster_O1"));
assert!(f2.nums.len() < f.nums.len());
}
#[test]
fn prisma_aussen_gewickelt() {
let mut g = Group::new("x".into(), "slab", "x", -1.0);
let sq = [Vec2 { x: 0.0, y: 0.0 }, Vec2 { x: 0.0, y: 1.0 }, Vec2 { x: 1.0, y: 1.0 }, Vec2 { x: 1.0, y: 0.0 }];
push_prism(g.prim(0.0), &sq, 0.0, 1.0, 0.0);
let pr = &g.prims[0];
assert_eq!(pr.positions.len(), 8 * 3);
assert_eq!(pr.indices.len(), (2 * 2 + 4 * 2) * 3);
// Geschlossen und konsistent gewickelt: Betrag des Volumens = 1 (Einheitswürfel).
let idx: Vec<u32> = pr.indices.iter().map(|&i| i as u32).collect();
let mut v = 0.0;
for t in idx.chunks_exact(3) {
let q = |i: u32| &pr.positions[i as usize * 3..i as usize * 3 + 3];
let (a, b, c) = (q(t[0]), q(t[1]), q(t[2]));
v += a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0]);
}
assert!(((v / 6.0).abs() - 1.0).abs() < 1e-12, "{v}");
}
#[test]
fn kaputtes_kontext_netz_ohne_panik() {
let mut p = Project { id: "k".into(), ..Default::default() };
p.context = Some(vec![ContextObject::ImportedMesh(ImportedMesh { id: "m".into(), positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, f64::NAN], indices: vec![0.0, 1.0, 9.0, 0.0, 1.0, 2.0, f64::NAN, 0.0, 1.0], ..Default::default() })]);
let f = mesh_export_data(&p, &MeshOptions::default()).unwrap();
assert!(f.strings.iter().any(|s| s == "Kontext_m"));
}
}
+9
View File
@@ -49,6 +49,15 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
pub fn run_bin(p: &Project, name: &str, args: &[f64], text: &str) -> Result<Vec<u8>, String> {
match (name, args.len()) {
("planDomains", 1) => crate::plan::domains::plan_domains_buf(p, &crate::plan::domains::PlanArgs::parse(args[0], text)?),
// Export-Sammler ([K4], [B5], [C11]): flacher Puffer für `fileio` (Byte-Hülle `export_flat.rs`).
("ifcExportData", 4) => {
let opt = crate::ifc_data::IfcOptions { now: args[0], ifc2x3: args[1] != 0.0, ebkph: args[2] != 0.0, layer_codes: args[3] != 0.0, iso: text.to_string() };
crate::ifc_data::ifc_export_data(p, &opt).map(|f| f.to_bytes())
}
("meshExportData", 3) => {
let opt = crate::mesh_data::MeshOptions { opening_parts: args[0] != 0.0, context: args[1] != 0.0, by_level: args[2] != 0.0 };
crate::mesh_data::mesh_export_data(p, &opt).map(|f| f.to_bytes())
}
_ => Err(format!("Unbekannte Abfrage: {name}")),
}
}
+18 -55
View File
@@ -2,14 +2,14 @@
//! aus EINEM Wandband (`RWall`: Achse, Dicke, UK, Höhe, rechteckige Löcher) entsteht das
//! Dreiecksnetz mit ausgestanzten Öffnungen samt Laibungsflächen — dieselbe Zerlegung wie
//! `render3d/src/mesh.rs::extrude_layer_segment_with_holes`, aber ohne Gehrung (die Bänder aus
//! [`crate::wall_bands`] sind an den Enden schon gekürzt). Portiert aus `src/plan/wallMeshCut.ts`.
//! [`crate::wall_bands`] sind an den Enden schon gekürzt). Portiert aus `src/plan/wallMeshCut.ts` (gelöscht);
//! Verbraucher sind die Export-Sammler `ifc_data.rs` und `mesh_data.rs`.
//!
//! Achsen: Modell (x, y) → Welt (x, Höhe, y), Y-up. Jedes Dreieck hat drei eigene Ecken; die
//! Indizes sind daher fortlaufend `0, 1, 2, …` und werden nicht übertragen.
//!
//! Bitgleich zur früheren TS-Fassung (gleiche Operationsreihenfolge, `Math.hypot` wie V8).
use crate::flat_read::Reader;
use crate::joins::js_hypot;
use crate::openings3d::{jmax, jmin};
use kernel2d::{add, left_normal, scale, Vec2};
@@ -259,51 +259,18 @@ pub fn is_watertight(positions: &[f64], indices: &[u32], eps: f64) -> bool {
js_hypot3(ax, ay, az) < eps && vol6 > eps
}
// ── Flache Kodierung ─────────────────────────────────────────────────────────
//
// Eingabe: `[nBänder, (sx, sy, ex, ey, Dicke, UK, Höhe, nLöcher, (from, to, zb, zt)…)…]`.
// Ausgabe: `[nBänder, (nZahlen, x, Höhe, y, …)…]` — je Band die Weltpunkte, drei je Dreiecksecke.
// Kaputte Eingabe ⇒ `[0]`; ein Band mit NaN/∞ ⇒ leeres Mesh.
fn decode(buf: &[f64]) -> Option<Vec<CutWall>> {
let mut r = Reader::new(buf);
let n = r.count()?;
let mut out = Vec::with_capacity(n.min(1 << 16));
for _ in 0..n {
let start = [r.num()?, r.num()?];
let end = [r.num()?, r.num()?];
let (thickness, base_elevation, height) = (r.num()?, r.num()?, r.num()?);
let nh = r.count()?;
let mut holes = Vec::with_capacity(nh.min(1024));
for _ in 0..nh {
holes.push([r.num()?, r.num()?, r.num()?, r.num()?]);
}
out.push(CutWall { start, end, thickness, base_elevation, height, holes });
}
Some(out)
}
fn finite(w: &CutWall) -> bool {
[w.start[0], w.start[1], w.end[0], w.end[1], w.thickness, w.base_elevation, w.height].iter().all(|v| v.is_finite())
&& w.holes.iter().flatten().all(|v| v.is_finite())
}
/// Flache Bindung für viele Bänder auf einmal; nie ein Panic.
pub fn wall_cut_meshes_flat(buf: &[f64]) -> Vec<f64> {
let Some(walls) = decode(buf) else { return vec![0.0] };
let mut out = vec![walls.len() as f64];
for w in &walls {
let m = if finite(w) { wall_cut_mesh(w) } else { Vec::new() };
out.push(m.len() as f64);
out.extend_from_slice(&m);
/// [`wall_cut_mesh`] mit Eingabeprüfung (Export-Sammler `ifc_data`/`mesh_data`): NaN/∞ ⇒ leer.
pub fn wall_cut_mesh_checked(w: &CutWall) -> Vec<f64> {
if finite(w) {
wall_cut_mesh(w)
} else {
Vec::new()
}
out
}
/// Flache Bindung von [`solid_subrects`]: `holes` als `[from, to, zb, zt, …]`; Ausgabe ebenso.
pub fn solid_subrects_flat(u_lo: f64, u_hi: f64, z_lo: f64, z_hi: f64, holes: &[f64]) -> Vec<f64> {
let hs: Vec<[f64; 4]> = holes.chunks_exact(4).map(|c| [c[0], c[1], c[2], c[3]]).collect();
solid_subrects(u_lo, u_hi, z_lo, z_hi, &hs).into_iter().flatten().collect()
}
#[cfg(test)]
@@ -373,27 +340,23 @@ mod tests {
}
#[test]
fn flach_viele_baender() {
let buf = [2.0, 0.0, 0.0, 5.0, 0.0, 0.4, 0.0, 2.6, 0.0, 0.0, 0.0, 0.0, 0.0, 0.4, 0.0, 2.6, 1.0, 1.0, 2.0, 0.0, 2.0];
let out = wall_cut_meshes_flat(&buf);
assert_eq!(out[0], 2.0);
assert_eq!(out[1], 108.0);
assert_eq!(out[2 + 108], 0.0); // Nullwand ⇒ leer
assert_eq!(solid_subrects_flat(0.0, 5.0, 0.0, 2.6, &[2.0, 3.0, 0.0, 2.1, 9.0]).len(), 5 * 4);
fn tuer_am_boden_ohne_untere_laibung() {
// 5 Teilrechtecke × 2 Seiten + Deckel + 2 Boden-Stücke + 2 Kappen + 3 Laibungen = 18 Quads = 36 Dreiecke.
let tuer = wall_cut_mesh(&band(vec![[2.0, 3.0, 0.0, 2.1]]));
assert_eq!(tuer.len(), 36 * 9);
assert_eq!(wall_cut_mesh_checked(&band(vec![[2.0, 3.0, 0.0, 2.1]])), tuer);
let null = CutWall { end: [0.0, 0.0], ..band(vec![]) };
assert!(wall_cut_mesh_checked(&null).is_empty());
}
#[test]
fn unsinn_ohne_panic() {
assert_eq!(wall_cut_meshes_flat(&[]), vec![0.0]);
assert_eq!(wall_cut_meshes_flat(&[f64::NAN]), vec![0.0]);
assert_eq!(wall_cut_meshes_flat(&[1e300]), vec![0.0]);
assert_eq!(wall_cut_meshes_flat(&[1.0, 0.0, 0.0, 5.0]), vec![0.0]);
let out = wall_cut_meshes_flat(&[1.0, 0.0, 0.0, f64::NAN, 0.0, 0.4, 0.0, 2.6, 0.0]);
assert_eq!(out, vec![1.0, 0.0]);
let w = CutWall { end: [f64::NAN, 0.0], ..band(vec![]) };
assert!(wall_cut_mesh_checked(&w).is_empty());
assert!(wall_cut_mesh_checked(&band(vec![[f64::INFINITY, 1.0, 0.0, 1.0]])).is_empty());
// Löcher verkehrt herum, riesig, negativ.
let w = band(vec![[3.0, 1.0, 2.0, 0.5], [-1e9, 1e9, -1e9, 1e9], [f64::NAN, 1.0, 0.0, 1.0]]);
let _ = wall_cut_mesh(&w);
let _ = solid_subrects(f64::NAN, 1.0, 0.0, f64::INFINITY, &[[f64::NAN; 4]]);
let _ = solid_subrects_flat(0.0, 1.0, 0.0, 1.0, &[1.0, 2.0]);
}
}
-1
View File
@@ -16,7 +16,6 @@ mod room_area;
mod room_boundary;
mod polygon_holes;
mod drawing2d_3d;
mod wall_mesh_cut;
mod plan_buf;
mod project_format;
mod gpu_compile;
-21
View File
@@ -1,21 +0,0 @@
//! Bindungen des Wand-Loch-Mesh (`crate::wall_mesh_cut`). Kodierung s. dort.
use wasm_bindgen::prelude::wasm_bindgen;
/// Viele Wandbänder flach → je Band die Weltpunkte der Dreiecke; nie ein Panic.
#[wasm_bindgen]
pub fn wall_cut_meshes_flat(buf: &[f64]) -> Vec<f64> {
crate::wall_mesh_cut::wall_cut_meshes_flat(buf)
}
/// Rechteck minus Löcher als Teilrechtecke (`[u0, u1, z0, z1, …]`).
#[wasm_bindgen]
pub fn solid_subrects_flat(u_lo: f64, u_hi: f64, z_lo: f64, z_hi: f64, holes: &[f64]) -> Vec<f64> {
crate::wall_mesh_cut::solid_subrects_flat(u_lo, u_hi, z_lo, z_hi, holes)
}
/// Geschlossenes, nach aussen gewundenes Mesh? (Gauss-Kriterium.)
#[wasm_bindgen]
pub fn is_watertight_flat(positions: &[f64], indices: &[u32], eps: f64) -> bool {
crate::wall_mesh_cut::is_watertight(positions, indices, eps)
}