[K4][B5][C11] Export-Sammler im Kern: IFC- und Mesh-Puffer direkt aus dem Dokument
Der Kern erzeugt den flachen Puffer fuer die fileio-Schreiber selbst (Abfragen ifcExportData/meshExportData, Byte-Huelle export_flat.rs); TS gibt nur noch Optionen und Zeitstempel weiter und reicht die Bytes an fileio (zwei WASM-Module). Neu in src-tauri/core: ifc_data.rs (Waende Extrusion/Netz, Decken, Oeffnungen mit Fuellungs-Parametern, Treppen, Extrusionen, Raeume, SIA-416-Zonen, Geschoss-Kennwerte, Daecher, Stuetzen, eBKP-H/Ebenen-Klassifikation), ifc_quantities.rs (Basismengen), ifc_stairs.rs (Laeufe/Podest/Handlauf), mesh_data.rs (Szene OBJ/STL/glTF), export_flat.rs (Puffer, orient_outward, Volumen), geo_rebase.rs (LV95-Verschiebung, lv95_to_wgs84). Geloescht (TS): exportIfc-/exportMesh-Sammler, ifcQuantities, ifcStairs, ifcClassification, ifcOpenings, meshOrient, model3dParts, plan/wallMeshCut samt Bindungen (wall_cut_meshes_flat, solid_subrects_flat, is_watertight_flat). Ihre Faelle als Rust-Tests; Wand-Volumen-Vergleiche lesen die Mesh-Szene. Gleichheit: 1396 Ausgaben (171 aufgezeichnete Exporte der Test-Suite mit Varianten, Beispielprojekt IFC4/IFC2x3 x eBKP-H x Ebenen, mit Georeferenz, 80 Zufallsprojekte, bigSample(3)) zeichengleich zur TS-Fassung, inkl. Fehlermeldungen. Messung bigSample(20): IFC 82,5 s -> 2,4 s, GLB 212 s -> 1,9 s. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
33 files changed
+2987
-2925
No files matched your search
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
//! 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`). Wie dort bleiben die Innenhöfe der
|
||||
/// Dächer (`Roof.holes`) liegen.
|
||||
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 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 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
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,12 @@ pub mod plan_scene;
|
||||
pub mod plan_pick;
|
||||
pub mod snap;
|
||||
pub mod plan_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;
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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}")),
|
||||
}
|
||||
}
|
||||
@@ -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]);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -36,6 +36,8 @@ export type QueryName =
|
||||
| "pickGeometry"
|
||||
| "model3dParts"
|
||||
| "planDomains"
|
||||
| "ifcExportData"
|
||||
| "meshExportData"
|
||||
| "modelJson";
|
||||
|
||||
export class ProjectDocument {
|
||||
|
||||
@@ -8,7 +8,6 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import "../engine/fileioWasm.setup";
|
||||
import { exportIfcSpf } from "./exportIfc";
|
||||
import { EBKPH_GROUPS, ebkphGroup, layerClassification } from "./ifcClassification";
|
||||
import { readIfcElements } from "../io/ifcElements";
|
||||
import { classificationSuffix, ifcToImportedMeshes, readIfc } from "../io/ifcImport";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
@@ -35,27 +34,7 @@ function houseWithRooms(): Project {
|
||||
};
|
||||
}
|
||||
|
||||
describe("eBKP-H-Standardzuordnung", () => {
|
||||
it("nur gesicherte Hauptgruppen, Tür und Raum bleiben unklassifiziert", () => {
|
||||
expect(Object.keys(EBKPH_GROUPS)).toEqual(["C", "E", "F"]);
|
||||
expect(ebkphGroup("wall")).toEqual({ code: "C", name: "Konstruktion Gebäude" });
|
||||
expect(ebkphGroup("slab")?.code).toBe("C");
|
||||
expect(ebkphGroup("column")?.code).toBe("C");
|
||||
expect(ebkphGroup("stair")?.code).toBe("C");
|
||||
expect(ebkphGroup("roof")).toEqual({ code: "F", name: "Bedachung Gebäude" });
|
||||
expect(ebkphGroup("window")).toEqual({ code: "E", name: "Äussere Wandbekleidung Gebäude" });
|
||||
expect(ebkphGroup("door")).toBeNull();
|
||||
expect(ebkphGroup("space")).toBeNull();
|
||||
});
|
||||
|
||||
it("Ebene: Name aus dem Ebenenbaum, unbekannter Code bleibt Code, ohne Code nichts", () => {
|
||||
expect(layerClassification(sampleProject, "20")?.code).toBe("20");
|
||||
expect(layerClassification(sampleProject, "25")?.name).toBe("Stützen"); // Unterkategorie
|
||||
expect(layerClassification(sampleProject, "777")).toEqual({ code: "777", name: "777" });
|
||||
expect(layerClassification(sampleProject, undefined)).toBeNull();
|
||||
expect(layerClassification(sampleProject, " ")).toBeNull();
|
||||
});
|
||||
});
|
||||
// Zuordnungstabelle eBKP-H und Ebenen-Auflösung: Rust-Tests in `src-tauri/core/src/ifc_data.rs`.
|
||||
|
||||
describe("IFC-Export: Zonen und Geschoss-Kennwerte (SIA 416)", () => {
|
||||
it("je Kategorie eine IfcZone mit ihren Räumen, Kategorie und Fläche als Eigenschaft", () => {
|
||||
|
||||
@@ -701,3 +701,17 @@ describe("[B5] Pset_*Common mit den Werten aus dem Modell", () => {
|
||||
expect(kueche).toContain(".INTERNAL.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Sammler im Kern ([K4], 29.10.)", () => {
|
||||
it("Fehler des Kerns kommen mit dessen Meldung (unbekannter Wandtyp)", () => {
|
||||
const p = fixtureProject();
|
||||
const broken: Project = { ...p, walls: p.walls.map((w, i) => (i === 0 ? { ...w, wallTypeId: "fehlt" } : w)) };
|
||||
expect(() => exportIfcSpf(broken)).toThrow("Unbekannter Wandtyp: fehlt");
|
||||
});
|
||||
|
||||
it("zweimal exportieren gibt dieselbe Datei (bis auf den Zeitstempel)", () => {
|
||||
const strip = (s: string) => s.replace(/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d/g, "T").replace(/IFCOWNERHISTORY\([^;]*;/g, "");
|
||||
const p = fixtureProject();
|
||||
expect(strip(exportIfcSpf(p, { ebkph: true, layerCodes: true }))).toBe(strip(exportIfcSpf(p, { ebkph: true, layerCodes: true })));
|
||||
});
|
||||
});
|
||||
+53
-1060
File diff suppressed because it is too large.
Load diff
@@ -9,8 +9,7 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import "../engine/fileioWasm.setup";
|
||||
import { exportIfcSpf, ifcGuid } from "./exportIfc";
|
||||
import { pickGeometry } from "../plan/toWalls3d";
|
||||
import { wallCutMeshes } from "../plan/wallMeshCut";
|
||||
import { wallMeshVolumes } from "./meshScene.testutil";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Project } from "../model/types";
|
||||
|
||||
@@ -202,17 +201,8 @@ describe.skipIf(!hasIfcOpenShell)("IFC-Export gegen ifcopenshell", { timeout: 60
|
||||
});
|
||||
it("[B5] Demo-Haus: jede Wand hat nach ifcopenshell (Öffnungen abgezogen) das Volumen des 3D-Meshes", () => {
|
||||
const project = sampleProject;
|
||||
const bands = pickGeometry(project).walls;
|
||||
const meshVolume = new Map<string, number>();
|
||||
wallCutMeshes(bands).forEach((m, i) => {
|
||||
let v6 = 0;
|
||||
for (let k = 0; k < m.indices.length; k += 3) {
|
||||
const [a, b, c] = [m.indices[k], m.indices[k + 1], m.indices[k + 2]].map((j) => m.positions.slice(j * 3, j * 3 + 3));
|
||||
v6 += a[0] * (b[1] * c[2] - b[2] * c[1]) + a[1] * (b[2] * c[0] - b[0] * c[2]) + a[2] * (b[0] * c[1] - b[1] * c[0]);
|
||||
}
|
||||
const id = bands[i].wallId;
|
||||
meshVolume.set(id, (meshVolume.get(id) ?? 0) + Math.abs(v6) / 6);
|
||||
});
|
||||
// Vergleichswert: dieselben öffnungsgenauen Wand-Netze wie im 3D/OBJ (Kern, `mesh_data.rs`).
|
||||
const meshVolume = wallMeshVolumes(project);
|
||||
const walls = wallVolumes("demo-volumen", exportIfcSpf(project));
|
||||
let swept = 0;
|
||||
for (const wall of project.walls) {
|
||||
|
||||
@@ -1,13 +1,23 @@
|
||||
// Mesh-Export vollständig ([C11], 28.10.): Dächer, Treppen, Stützen, Kontext-Meshes, ein Knoten je Öffnung,
|
||||
// rechtshändige Achsen in OBJ/STL/glTF, Dreieckszahl wie die 3D-Ableitung, Khronos-Validator.
|
||||
// rechtshändige Achsen in OBJ/STL/glTF, Dreieckszahl wie die 3D-Ableitung, Khronos-Validator. Die Wicklung
|
||||
// (`orient_outward`) prüfen die Rust-Tests in `export_flat.rs`, hier das Volumen je Bauteil in der Datei.
|
||||
import { describe, it, expect } from "vitest";
|
||||
import "../engine/fileioWasm.setup";
|
||||
import validator from "gltf-validator";
|
||||
import { exportGlb, exportGltf, exportObj, exportStl } from "./exportMesh";
|
||||
import { orientOutward } from "./meshOrient";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Column, ImportedMesh, Project, TerrainMesh } from "../model/types";
|
||||
import { emitColumns, emitOpeningMeshes, emitRoofs, emitStairMeshes, emitStairRailings, emitStairs } from "./model3dParts";
|
||||
import { ProjectDocument, type QueryName } from "../core/document";
|
||||
|
||||
/** 3D-Ableitung des Kerns (`queries.rs`) auf einem eigenen Dokument — Vergleichswert für die Dreieckszahl. */
|
||||
function derive<T>(project: Project, name: QueryName, args: number[] = []): T {
|
||||
const doc = new ProjectDocument(project);
|
||||
try {
|
||||
return doc.query<T>(name, args);
|
||||
} finally {
|
||||
doc.close();
|
||||
}
|
||||
}
|
||||
|
||||
interface Gltf {
|
||||
nodes: { name: string; mesh?: number; children?: number[]; extras?: { type: string; id: string } }[];
|
||||
@@ -85,31 +95,6 @@ function objVolumes(obj: string): Map<string, number> {
|
||||
return out;
|
||||
}
|
||||
|
||||
describe("orientOutward", () => {
|
||||
it("dreht einen innen gewickelten Würfel nach aussen und gleicht gemischte Wicklung an", () => {
|
||||
const pos = CUBE_POS;
|
||||
const mixed = CUBE_IDX.slice();
|
||||
// ein Dreieck umdrehen ⇒ widersprüchliche Wicklung
|
||||
[mixed[1], mixed[2]] = [mixed[2], mixed[1]];
|
||||
const inward: number[] = [];
|
||||
for (let i = 0; i < CUBE_IDX.length; i += 3) inward.push(CUBE_IDX[i], CUBE_IDX[i + 2], CUBE_IDX[i + 1]);
|
||||
const vol = (idx: number[]) => {
|
||||
let v = 0;
|
||||
for (let i = 0; i < idx.length; i += 3) {
|
||||
const [a, b, c] = [idx[i] * 3, idx[i + 1] * 3, idx[i + 2] * 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]);
|
||||
}
|
||||
return v / 6;
|
||||
};
|
||||
expect(vol(CUBE_IDX)).toBeCloseTo(8, 9);
|
||||
expect(vol(orientOutward(pos, inward))).toBeCloseTo(8, 9);
|
||||
expect(vol(orientOutward(pos, mixed))).toBeCloseTo(8, 9);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Mesh-Export vollständig", () => {
|
||||
const project = withContext(sampleProject);
|
||||
|
||||
@@ -182,14 +167,15 @@ describe("Mesh-Export vollständig", () => {
|
||||
it("Dreieckszahl je Bauteilart = Summe der 3D-Ableitungen (Dach, Treppe, Stütze, Öffnungsteile)", () => {
|
||||
const g = glbJson(exportGlb(project));
|
||||
const tris = (type: string) => g.nodes.filter((n) => n.extras?.type === type).reduce((s, n) => s + nodeTris(g, n), 0);
|
||||
const meshTris = (ms: { indices: number[] }[]) => ms.reduce((s, m) => s + m.indices.length / 3, 0);
|
||||
expect(tris("roof")).toBe(meshTris(emitRoofs(project)));
|
||||
expect(tris("column")).toBe(meshTris(emitColumns(project)));
|
||||
expect(tris("window") + tris("door")).toBe(meshTris(emitOpeningMeshes(project, "mittel")));
|
||||
const stairMeshes = meshTris(emitStairMeshes(project)) + meshTris(emitStairRailings(project));
|
||||
const meshTris = (name: QueryName, args: number[] = []) => derive<{ indices: number[] }[]>(project, name, args).reduce((s, m) => s + m.indices.length / 3, 0);
|
||||
expect(tris("roof")).toBe(meshTris("roofMeshes"));
|
||||
expect(tris("column")).toBe(meshTris("columnMeshes"));
|
||||
expect(tris("window") + tris("door")).toBe(meshTris("openingMeshes", [1]));
|
||||
const stairMeshes = meshTris("stairMeshes") + meshTris("stairRailings");
|
||||
// Stufen-Prismen: jede Stufe wird zu einem Prisma (2 Kappen + Mantel) — mindestens die Mesh-Dreiecke.
|
||||
expect(emitStairs(project).length).toBeGreaterThan(0);
|
||||
expect(tris("stair")).toBeGreaterThanOrEqual(stairMeshes + emitStairs(project).length * 12);
|
||||
const steps = derive<unknown[]>(project, "stairSlabs", [0]).length;
|
||||
expect(steps).toBeGreaterThan(0);
|
||||
expect(tris("stair")).toBeGreaterThanOrEqual(stairMeshes + steps * 12);
|
||||
// OBJ und glTF enthalten dieselben Dreiecke
|
||||
const faces = exportObj(project).split("\n").filter((l) => l.startsWith("f ")).length;
|
||||
const all = g.nodes.reduce((s, n) => s + nodeTris(g, n), 0);
|
||||
|
||||
+16
-477
@@ -1,317 +1,17 @@
|
||||
// OBJ-/STL-/glTF-Export des 3D-Gebäudemodells als Dreiecks-Mesh. Seit [C4] (28.10.) schreibt Rust die
|
||||
// Datei (`src-tauri/fileio/src/mesh_export.rs`, Format-Modul pkgFileIo, vorher `await loadFileio()`):
|
||||
// buildScene() liest das Projekt und sammelt Dreiecke, Materialien und Geschosse flach, exportObj()/
|
||||
// exportStl()/exportGlb()/exportGltf() rufen den Schreiber synchron auf. Kein Datei-IO hier.
|
||||
// OBJ-/STL-/glTF-Export des 3D-Gebäudemodells als Dreiecks-Mesh. Seit [K4]/[C11] (29.10.) rechnet alles
|
||||
// in Rust: der Kern sammelt aus dem Projekt-Dokument die Szene (`src-tauri/core/src/mesh_data.rs`,
|
||||
// Abfrage `meshExportData`: ein Knoten je Bauteil, Teil-Netze je Material, Materialtabelle,
|
||||
// Geschosse; Wicklung nach aussen), das Format-Modul schreibt daraus die Datei
|
||||
// (`src-tauri/fileio/src/mesh_export.rs`). TS gibt nur die Optionen weiter und reicht die Bytes vom
|
||||
// Kern an `fileio`. Verlangt das geladene Format-Modul (`await loadFileio()`). Kein Datei-IO hier.
|
||||
//
|
||||
// TRIANGEL-QUELLE (bewusste v1-Entscheidung, siehe PENDENZEN):
|
||||
// • Wände: pickGeometry() aus toWalls3d.ts liefert dieselben Schicht-Bänder,
|
||||
// die auch der 3D-Viewer zeichnet (EIN RWall je Materiallage/Achsen-
|
||||
// Teilstück, bereits mit End-Cuts/Gehrungen/Decken-Dominanz aufgelöst).
|
||||
// Bänder mit Öffnungs-`holes` werden über den gemeinsamen Loch-Ausschnitt-
|
||||
// Generator (`plan/wallMeshCut.ts` → Rust-Kern, Gitter-Zerlegung wie render3ds
|
||||
// `extrude_layer_segment_with_holes`) ÖFFNUNGSGENAU trianguliert — die
|
||||
// Fenster/Türen sind sichtbar ausgestanzt inkl. Laibungsflächen, genau wie
|
||||
// im 3D-Viewer. Lochlose Bänder bleiben die klassische geteilte 8-Ecken-Box.
|
||||
// • Decken: pickGeometry() liefert den Umriss + zBottom/zTop je Decke;
|
||||
// der Umriss wird mit dem vorhandenen Ear-Clipping-Triangulator
|
||||
// (`triangulate` aus plan/glPlan/glPlanCompile.ts, bereits getestet und
|
||||
// konkav-fähig) zu Boden-/Deckenkappen trianguliert, dazwischen ein
|
||||
// Seitenmantel — ein einfaches Umriss-Prisma.
|
||||
// • ExtrudedSolids (truck-Profile): `src/engine/truckSolid.ts` liefert zwar
|
||||
// "echte" truck-Dreiecke, ABER nur asynchron über WASM
|
||||
// (`extrudePolygon`/`extrudeCircle` geben Promises zurück). Das würde die
|
||||
// geforderte SYNCHRONE, WASM-freie Signatur `exportObj(project): string`
|
||||
// brechen. Deshalb nutzt dieser Export stattdessen DIESELBE Prisma-
|
||||
// Triangulierung wie die Decken (Umriss aus `solid.points` — bei
|
||||
// Kreisprofilen bereits eine 48-Eck-Tessellierung, siehe
|
||||
// `ExtrudedSolid.points`-Doc) inkl. `taper`-Verjüngung (linear zum
|
||||
// Schwerpunkt skaliert, wie die truck-Extrusion es tut). Das ist eine
|
||||
// bewusste Abweichung vom ursprünglichen Plan ("truckSolid-Dreiecke") zu-
|
||||
// gunsten der pure-Modul-Architektur — ehrlich dokumentiert, kein
|
||||
// Stillschweigen.
|
||||
//
|
||||
// ACHSEN-KONVENTION (intern, Weg zum Schreiber): Modell (x, y, z-hoch) → Welt (x, z, y) wie die
|
||||
// Pick-/Highlight-Geometrie in toWalls3d.ts (`selectionHighlightLines`). Das ist eine Spiegelung
|
||||
// des Modells; der Rust-Schreiber stellt für ALLE Formate (OBJ, STL, glTF) die Rechtshändigkeit
|
||||
// her: Gesamtabbildung Modell (x, y, z-hoch) → Datei (x, z, −y), Norden = −Z.
|
||||
//
|
||||
// WEITERE BAUTEILE ([C11], 28.10.): Dächer, Treppen (Tritte, Laufplatte, Handlauf), Stützen,
|
||||
// Öffnungsteile (je Öffnung ein Knoten), Gelände und importierte Kontext-Meshes. Quelle sind
|
||||
// dieselben `emit*`-Ableitungen wie im 3D-Viewer (`projectToModel3d`). Diese liefern keine
|
||||
// Bauteil-ids; deshalb wird jede Ableitung je Bauteil mit einem Projekt aufgerufen, das nur dieses
|
||||
// Bauteil enthält (reines Lesen, `src/plan` bleibt unverändert). Die Ableitungen schreiben keine
|
||||
// verlässliche Wicklung (render3d zeichnet doppelseitig): {@link orientOutward} richtet jedes
|
||||
// geschlossene Teil nach aussen aus.
|
||||
// Achsen: Datei rechtshändig, Y-up — Modell (x, y, z-hoch) → (x, z, −y), Norden = −Z, Meter.
|
||||
// Dreiecks-Quelle, Prisma-Näherung der Extrusionen und Grenzen: Kopf von `mesh_data.rs`, `TODO.md` [C11].
|
||||
|
||||
import type { Project, Vec2 } from "../model/types";
|
||||
import { getFloor } from "../model/types";
|
||||
import { pickGeometry } from "../plan/toWalls3d";
|
||||
import type { RWall } from "../plan/toWalls3d";
|
||||
import { wallCutMeshes, type CutMesh } from "../plan/wallMeshCut";
|
||||
import { triangulate } from "../plan/glPlan/glPlanCompile";
|
||||
import type { RMesh } from "../plan/toWalls3d/shared";
|
||||
import { IMPORTED_RGB, TERRAIN_RGB, hexToRgb } from "../plan/toWalls3d/shared";
|
||||
import type { Project } from "../model/types";
|
||||
import { fileio } from "../engine/fileioWasm";
|
||||
import { orientOutward } from "./meshOrient";
|
||||
import { emitColumns, emitOpeningMeshes, emitRoofs, emitStairMeshes, emitStairRailings, emitStairs } from "./model3dParts";
|
||||
|
||||
/**
|
||||
* Ein Teil-Mesh mit EINEM Material und LOKALEN (0-basierten) Vertex-/Dreiecks-Indizes. Der Rust-Schreiber
|
||||
* (`mesh_export.rs`) verschiebt die Indizes beim Serialisieren auf die globale OBJ-Nummerierung.
|
||||
*/
|
||||
interface MeshPrim {
|
||||
/** Index in die Materialtabelle (`SceneBuilder.materials`), −1 = keins. */
|
||||
material: number;
|
||||
/** Flaches Weltkoordinaten-Array (x,y,z, x,y,z, …), Meter, Y-up. */
|
||||
positions: number[];
|
||||
/** Dreiecks-Indizes (3 je Dreieck), 0-basiert relativ zu `positions`. */
|
||||
indices: number[];
|
||||
}
|
||||
|
||||
/** Eine Mesh-Gruppe = ein Bauteil-Vorkommen (Wand, Decke, Dach, Treppe, Öffnung …) mit ≥ 1 Teil-Mesh. */
|
||||
interface MeshGroup {
|
||||
name: string;
|
||||
/** Bauteilart für glTF-`extras` ("wall", "slab", "extrusion", "roof", "stair", "column", "window", "door", "terrain", "context"). */
|
||||
kind: string;
|
||||
/** Bauteil-id im Modell ("" bei Sammelgruppen). */
|
||||
id: string;
|
||||
/** Index in `levels` oder −1. */
|
||||
level: number;
|
||||
prims: MeshPrim[];
|
||||
}
|
||||
|
||||
function newGroup(name: string, kind: string, id: string, level: number): MeshGroup {
|
||||
return { name, kind, id, level, prims: [] };
|
||||
}
|
||||
|
||||
function newPrim(group: MeshGroup, material: number): MeshPrim {
|
||||
const prim: MeshPrim = { material, positions: [], indices: [] };
|
||||
group.prims.push(prim);
|
||||
return prim;
|
||||
}
|
||||
|
||||
/** OBJ-Gruppennamen dürfen keine Whitespaces/Sonderzeichen enthalten. */
|
||||
function sanitizeName(id: string): string {
|
||||
return id.replace(/[^A-Za-z0-9_-]/g, "_") || "x";
|
||||
}
|
||||
|
||||
/**
|
||||
* Die 6 Quader-Seiten als Eckpunkt-Quadrupel (Index-Bits: bit0=Achse −/+,
|
||||
* bit1=Höhe −/+, bit2=Dicke −/+ — dieselbe Konvention wie `emitOpeningMeshes`/
|
||||
* `selectionHighlightLines` in toWalls3d.ts), in nach AUSSEN gewundener
|
||||
* Reihenfolge (für ein rechtshändiges Dreibein Achse×Höhe=Dicke-Normale, wie
|
||||
* es die Wandbox-Konstruktion unten aufspannt). Jedes Quadrupel wird zu 2
|
||||
* Dreiecken (0,1,2)+(0,2,3).
|
||||
*/
|
||||
const BOX_QUADS: Array<[number, number, number, number]> = [
|
||||
[4, 6, 7, 5], // Dicke +
|
||||
[1, 3, 2, 0], // Dicke −
|
||||
[2, 3, 7, 6], // Höhe + (Wandkopf)
|
||||
[4, 5, 1, 0], // Höhe − (Wand-UK)
|
||||
[1, 5, 7, 3], // Achse + (Wandende)
|
||||
[2, 6, 4, 0], // Achse − (Wandanfang)
|
||||
];
|
||||
|
||||
/**
|
||||
* Hängt EIN Wand-Schicht-Band (`RWall`, siehe toWalls3d.ts) an eine Mesh-Gruppe
|
||||
* an: hat das Band echte Öffnungs-`holes`, wird das öffnungsgenaue Loch-Ausschnitt-
|
||||
* Mesh `cut` (vorab für alle Bänder über {@link wallCutMeshes}) verwendet — die
|
||||
* Fenster/Türen sind sichtbar ausgestanzt inkl. Laibungen, exakt wie im 3D-Viewer.
|
||||
* Ohne Löcher bleibt es die klassische, geteilte 8-Ecken-Box ({@link pushWallBox})
|
||||
* (Joins/Gehrungen stecken schon in `start`/`end`).
|
||||
*/
|
||||
function pushWall(group: MeshPrim, w: RWall, cut: CutMesh | undefined): void {
|
||||
if (cut) {
|
||||
const base = group.positions.length / 3;
|
||||
for (const p of cut.positions) group.positions.push(p);
|
||||
for (const idx of cut.indices) group.indices.push(base + idx);
|
||||
return;
|
||||
}
|
||||
pushWallBox(group, w);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hängt EINEN vollen Wand-Schicht-Quader (`RWall`) an eine Mesh-Gruppe an — Box
|
||||
* über Achse×Höhe×Dicke, OHNE Öffnungs-Ausschnitt (nur für lochlose Bänder, siehe
|
||||
* {@link pushWall}). Degenerierte Bänder (Länge/Höhe/Dicke ≤ 0) werden übersprungen.
|
||||
*/
|
||||
function pushWallBox(group: MeshPrim, w: RWall): void {
|
||||
const [sx, sy] = w.start;
|
||||
const [ex, ey] = w.end;
|
||||
const dx = ex - sx;
|
||||
const dz = ey - sy;
|
||||
const len = Math.hypot(dx, dz);
|
||||
if (len < 1e-9 || w.height <= 1e-9 || w.thickness <= 1e-9) return;
|
||||
const ax = dx / len;
|
||||
const az = dz / len;
|
||||
// Normale = Welt-Hoch × Achse (rechtshändig), dieselbe Konvention wie
|
||||
// `selectionHighlightLines`: normal = (az, 0, −ax).
|
||||
const nx = az;
|
||||
const nz = -ax;
|
||||
const halfLen = len / 2;
|
||||
const halfHeight = w.height / 2;
|
||||
const halfThick = w.thickness / 2;
|
||||
const cx = (sx + ex) / 2;
|
||||
const cz = (sy + ey) / 2;
|
||||
const cy = w.baseElevation + w.height / 2;
|
||||
const base = group.positions.length / 3;
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const sL = i & 1 ? 1 : -1;
|
||||
const sH = i & 2 ? 1 : -1;
|
||||
const sT = i & 4 ? 1 : -1;
|
||||
group.positions.push(
|
||||
cx + sL * halfLen * ax + sT * halfThick * nx,
|
||||
cy + sH * halfHeight,
|
||||
cz + sL * halfLen * az + sT * halfThick * nz,
|
||||
);
|
||||
}
|
||||
for (const [a, b, c, d] of BOX_QUADS) {
|
||||
group.indices.push(base + a, base + b, base + c, base + a, base + c, base + d);
|
||||
}
|
||||
}
|
||||
|
||||
/** Signierte Fläche eines Modell-XY-Umrisses (Shoelace); ≥0 = CCW. */
|
||||
function signedAreaXY(pts: Vec2[]): number {
|
||||
let a = 0;
|
||||
for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {
|
||||
a += pts[j].x * pts[i].y - pts[i].x * pts[j].y;
|
||||
}
|
||||
return a / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hängt ein extrudiertes Umriss-Prisma (Decke ODER truck-Profil-Extrusion,
|
||||
* siehe Moduldoc) an eine Mesh-Gruppe an: Boden-/Deckkappe (Ear-Clipping-
|
||||
* Triangulierung via `triangulate`) + Seitenmantel. `taper` (0..1) verjüngt
|
||||
* den OBEREN Ring linear zum Flächenschwerpunkt — dieselbe Semantik wie
|
||||
* `ExtrudedSolid.taper`/die truck-Extrusion (0 = Prisma, 1 = Spitze/Pyramide).
|
||||
* Der Umriss wird intern auf CCW (Modell-XY) normalisiert, damit die
|
||||
* Seitenmantel-Normalen unabhängig von der Eingabe-Wicklung nach außen zeigen.
|
||||
*/
|
||||
function pushPrism(
|
||||
group: MeshPrim,
|
||||
outline: Vec2[],
|
||||
zBottom: number,
|
||||
zTop: number,
|
||||
taper = 0,
|
||||
): void {
|
||||
if (outline.length < 3 || zTop - zBottom <= 1e-9) return;
|
||||
const ccw = signedAreaXY(outline) >= 0 ? outline : [...outline].reverse();
|
||||
const n = ccw.length;
|
||||
let cx = 0;
|
||||
let cyModel = 0;
|
||||
for (const p of ccw) {
|
||||
cx += p.x;
|
||||
cyModel += p.y;
|
||||
}
|
||||
cx /= n;
|
||||
cyModel /= n;
|
||||
const t = Math.min(1, Math.max(0, taper));
|
||||
const base = group.positions.length / 3;
|
||||
// Unterer Ring (base + 0..n-1), oberer Ring (base + n..2n-1).
|
||||
for (const p of ccw) group.positions.push(p.x, zBottom, p.y);
|
||||
for (const p of ccw) {
|
||||
const tx = cx + (p.x - cx) * (1 - t);
|
||||
const ty = cyModel + (p.y - cyModel) * (1 - t);
|
||||
group.positions.push(tx, zTop, ty);
|
||||
}
|
||||
// Kappen: `triangulate` liefert bei CCW-Eingabe stets CCW-in-Modell-XY-
|
||||
// Dreiecke — eingebettet in die Weltebene (x, const, y) entspricht das einer
|
||||
// nach UNTEN (−Y) zeigenden Flächennormale (Kreuzprodukt-Herleitung siehe
|
||||
// Moduldoc-Kommentar oben). Die Bodenkappe nutzt diese Wicklung direkt
|
||||
// (Normale zeigt nach unten = nach außen), die Deckkappe braucht die
|
||||
// umgekehrte Wicklung (Normale nach oben).
|
||||
const capTris = triangulate(ccw);
|
||||
for (let i = 0; i < capTris.length; i += 3) {
|
||||
const a = capTris[i];
|
||||
const b = capTris[i + 1];
|
||||
const c = capTris[i + 2];
|
||||
group.indices.push(base + a, base + b, base + c);
|
||||
group.indices.push(base + n + a, base + n + c, base + n + b);
|
||||
}
|
||||
// Seitenmantel: je Umrisskante ein Quad (2 Dreiecke), Wicklung so, dass die
|
||||
// Normale nach außen zeigt (siehe Moduldoc-Herleitung).
|
||||
for (let i = 0; i < n; i++) {
|
||||
const j = (i + 1) % n;
|
||||
const bi = base + i;
|
||||
const bj = base + j;
|
||||
const ti = base + n + i;
|
||||
const tj = base + n + j;
|
||||
group.indices.push(bi, ti, tj);
|
||||
group.indices.push(bi, tj, bj);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hängt ein Modell-Mesh (x, y, z-hoch) an ein Teil-Mesh: Achsen nach Welt (x, z, y) und Wicklung
|
||||
* nach aussen. `closed`: geschlossener Körper ⇒ {@link orientOutward}; sonst (Gelände, offene
|
||||
* Importe) bleibt die Wicklung des Modells erhalten — die Achsenspiegelung kehrt sie um.
|
||||
*/
|
||||
function appendModelMesh(prim: MeshPrim, positions: readonly number[], indices: readonly number[], closed: boolean): void {
|
||||
const pos: number[] = [];
|
||||
for (let i = 0; i + 2 < positions.length; i += 3) pos.push(positions[i], positions[i + 2], positions[i + 1]);
|
||||
const nv = pos.length / 3;
|
||||
const tri: number[] = [];
|
||||
for (let i = 0; i + 2 < indices.length; i += 3) {
|
||||
const a = indices[i];
|
||||
const b = indices[i + 1];
|
||||
const c = indices[i + 2];
|
||||
// Indizes ausserhalb (kaputter Import) und entartete Dreiecke weglassen.
|
||||
if (!(a >= 0 && a < nv && b >= 0 && b < nv && c >= 0 && c < nv)) continue;
|
||||
tri.push(a, c, b);
|
||||
}
|
||||
const idx = closed ? orientOutward(pos, tri) : tri;
|
||||
const base = prim.positions.length / 3;
|
||||
for (const v of pos) prim.positions.push(v);
|
||||
for (const i of idx) prim.indices.push(base + i);
|
||||
}
|
||||
|
||||
type Rgb = [number, number, number];
|
||||
|
||||
/** Material der Szene: Farbe sRGB 0..1, `rgba[3]` < 1 = transparent (Glas). */
|
||||
interface SceneMaterial {
|
||||
name: string;
|
||||
rgba: [number, number, number, number];
|
||||
metallic: number;
|
||||
roughness: number;
|
||||
}
|
||||
|
||||
/** Materialtabelle: gleiche Farbe + Name = ein Material. */
|
||||
class Materials {
|
||||
readonly list: SceneMaterial[] = [];
|
||||
private readonly byKey = new Map<string, number>();
|
||||
|
||||
get(name: string, rgb: Rgb, alpha = 1, metallic = 0, roughness = 0.9): number {
|
||||
const key = `${name}|${rgb.join(",")}|${alpha}|${metallic}|${roughness}`;
|
||||
let i = this.byKey.get(key);
|
||||
if (i === undefined) {
|
||||
i = this.list.length;
|
||||
this.list.push({ name, rgba: [rgb[0], rgb[1], rgb[2], alpha], metallic, roughness });
|
||||
this.byKey.set(key, i);
|
||||
}
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
/** Die für den Rust-Schreiber gesammelte Szene. */
|
||||
interface MeshScene {
|
||||
groups: MeshGroup[];
|
||||
materials: SceneMaterial[];
|
||||
levels: { id: string; name: string }[];
|
||||
}
|
||||
|
||||
/** Standardfarbe der Extrusionen/Decken (wie `SLAB_RGB` in toWalls3d/shared.ts). */
|
||||
const SLAB_COLOR: Rgb = [0.86, 0.86, 0.88];
|
||||
/** Verglasung und Rahmenteile aus `emitOpeningMeshes` (Farben `PART_RGB` in toWalls3d/openings.ts). */
|
||||
const GLASS_COLOR: Rgb = [0.62, 0.76, 0.85];
|
||||
const OPENING_PART_NAMES: Array<[Rgb, string]> = [
|
||||
[[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 sameRgb = (a: readonly number[], b: readonly number[]) => a.length === 3 && b.length === 3 && a.every((v, i) => Math.abs(v - b[i]) < 1e-9);
|
||||
import { documentFor } from "../core/document";
|
||||
import { decodeExportFlat } from "./exportIfc";
|
||||
|
||||
/** Was in die Szene kommt. Alles standardmässig an (vollständiges 3D-Modell). */
|
||||
export interface MeshOptions {
|
||||
@@ -321,172 +21,11 @@ export interface MeshOptions {
|
||||
context?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut alle Mesh-Gruppen (Wände, Decken, Extrusionen, Dächer, Treppen, Stützen, Öffnungsteile,
|
||||
* Kontext-Meshes) und die Materialtabelle.
|
||||
*/
|
||||
function buildScene(project: Project, opts: MeshOptions = {}): MeshScene {
|
||||
const groups: MeshGroup[] = [];
|
||||
const mats = new Materials();
|
||||
const { walls, slabs } = pickGeometry(project);
|
||||
const levels = project.drawingLevels.filter((l) => l.kind === "floor").map((l) => ({ id: l.id, name: l.name }));
|
||||
const levelOf = (floorId: string | undefined): number => levels.findIndex((l) => l.id === floorId);
|
||||
const componentName = (id: string | undefined, fallback: string): string =>
|
||||
(id !== undefined && project.components.find((c) => c.id === id)?.name) || fallback;
|
||||
|
||||
// Wände: alle Schicht-Bänder DERSELBEN Wand-Id in EINE Gruppe (mehrere
|
||||
// Materiallagen ergeben mehrere Boxen im selben Bauteil-Vorkommen).
|
||||
const wallGroups = new Map<string, MeshGroup>();
|
||||
const wallFloor = new Map(project.walls.map((w) => [w.id, w.floorId]));
|
||||
// Loch-Ausschnitte aller gelochten Bänder in EINEM Kern-Aufruf.
|
||||
const holed = walls.filter((w) => w.holes && w.holes.length > 0);
|
||||
const cuts = new Map<RWall, CutMesh>();
|
||||
wallCutMeshes(holed).forEach((m, i) => cuts.set(holed[i], m));
|
||||
for (const w of walls) {
|
||||
let g = wallGroups.get(w.wallId);
|
||||
if (!g) {
|
||||
g = newGroup(`Wand_${sanitizeName(w.wallId)}`, "wall", w.wallId, levelOf(wallFloor.get(w.wallId)));
|
||||
wallGroups.set(w.wallId, g);
|
||||
groups.push(g);
|
||||
}
|
||||
const mat = mats.get(componentName(w.cut?.componentId, "Wand"), w.color);
|
||||
pushWall(newPrim(g, mat), w, cuts.get(w));
|
||||
}
|
||||
|
||||
// Decken: ein Prisma je Decke.
|
||||
const ceilingFloor = new Map((project.ceilings ?? []).map((c) => [c.id, c.floorId]));
|
||||
for (const s of slabs) {
|
||||
const g = newGroup(`Decke_${sanitizeName(s.ceilingId)}`, "slab", s.ceilingId, levelOf(ceilingFloor.get(s.ceilingId)));
|
||||
const outline: Vec2[] = s.outline.map(([x, y]) => ({ x, y }));
|
||||
pushPrism(newPrim(g, mats.get(componentName(s.cut?.componentId, "Decke"), s.color)), outline, s.zBottom, s.zTop);
|
||||
groups.push(g);
|
||||
}
|
||||
|
||||
// Extrudierte Profile (truck-Integration): eigenes Prisma je Körper (siehe
|
||||
// Moduldoc — bewusst NICHT die truck-WASM-Dreiecke, aus Sync-/Pure-Gründen).
|
||||
for (const solid of project.extrudedSolids ?? []) {
|
||||
if (solid.points.length < 3 || solid.height <= 0) continue;
|
||||
let baseZ = 0;
|
||||
try {
|
||||
baseZ = getFloor(project, solid.levelId).baseElevation ?? 0;
|
||||
} catch {
|
||||
// Geschoss nicht (mehr) auflösbar: bei UK 0 extrudieren (Fallback, wie toWalls3d).
|
||||
}
|
||||
const g = newGroup(`Extrusion_${sanitizeName(solid.id)}`, "extrusion", solid.id, levelOf(solid.levelId));
|
||||
pushPrism(newPrim(g, mats.get("Extrusion", SLAB_COLOR)), solid.points, baseZ, baseZ + solid.height, solid.taper ?? 0);
|
||||
groups.push(g);
|
||||
}
|
||||
|
||||
// Dächer, Stützen, Treppen: je Bauteil EIN Aufruf der 3D-Ableitung mit einem Projekt, das nur dieses
|
||||
// Bauteil enthält — so tragen die Meshes die Bauteil-id (die Ableitungen liefern keine).
|
||||
const addMeshes = (g: MeshGroup, meshes: RMesh[], name: string, closed = true) => {
|
||||
for (const m of meshes) {
|
||||
if (m.indices.length === 0) continue;
|
||||
appendModelMesh(newPrim(g, mats.get(name, m.color)), m.positions, m.indices, closed);
|
||||
}
|
||||
};
|
||||
for (const roof of project.roofs ?? []) {
|
||||
const g = newGroup(`Dach_${sanitizeName(roof.id)}`, "roof", roof.id, levelOf(roof.floorId));
|
||||
addMeshes(g, emitRoofs({ ...project, roofs: [roof] }), "Dach");
|
||||
groups.push(g);
|
||||
}
|
||||
for (const col of project.columns ?? []) {
|
||||
const g = newGroup(`Stuetze_${sanitizeName(col.id)}`, "column", col.id, levelOf(col.floorId));
|
||||
addMeshes(g, emitColumns({ ...project, columns: [col] }), componentName(col.componentId, "Stuetze"));
|
||||
groups.push(g);
|
||||
}
|
||||
for (const stair of project.stairs ?? []) {
|
||||
const one: Project = { ...project, stairs: [stair] };
|
||||
const g = newGroup(`Treppe_${sanitizeName(stair.id)}`, "stair", stair.id, levelOf(stair.floorId));
|
||||
for (const s of emitStairs(one)) {
|
||||
const outline: Vec2[] = s.outline.map(([x, y]) => ({ x, y }));
|
||||
pushPrism(newPrim(g, mats.get("Treppe", s.color)), outline, s.zBottom, s.zTop);
|
||||
}
|
||||
addMeshes(g, emitStairMeshes(one), "Treppe");
|
||||
addMeshes(g, emitStairRailings(one), "Handlauf");
|
||||
groups.push(g);
|
||||
}
|
||||
|
||||
// Öffnungsteile: je Öffnung ein Knoten (Name Fenster_<id>/Tuer_<id>) mit Glas und den Rahmenteilen als
|
||||
// Teil-Meshes je Material. Auch hier die Ableitung nur mit der Wirtswand und dieser Öffnung.
|
||||
if (opts.openingParts ?? true) {
|
||||
for (const op of project.openings ?? []) {
|
||||
const host = project.walls.find((w) => w.id === op.hostWallId);
|
||||
if (!host) continue;
|
||||
const parts = emitOpeningMeshes({ ...project, walls: [host], openings: [op] }, "mittel");
|
||||
if (parts.length === 0) continue;
|
||||
const g = newGroup(`${op.kind === "window" ? "Fenster" : "Tuer"}_${sanitizeName(op.id)}`, op.kind, op.id, levelOf(host.floorId));
|
||||
const prims = new Map<string, MeshPrim>();
|
||||
for (const m of parts) {
|
||||
const glass = sameRgb(m.color, GLASS_COLOR);
|
||||
const name = glass ? "Glas" : (OPENING_PART_NAMES.find(([c]) => sameRgb(c, m.color))?.[1] ?? "Oeffnungsteil");
|
||||
let prim = prims.get(name);
|
||||
if (!prim) {
|
||||
// Glas transparent und glatt (BLEND), Rahmen matt.
|
||||
const mat = glass ? mats.get(name, m.color, 0.35, 0, 0.05) : mats.get(name, m.color, 1, 0, 0.6);
|
||||
prim = newPrim(g, mat);
|
||||
prims.set(name, prim);
|
||||
}
|
||||
appendModelMesh(prim, m.positions, m.indices, true);
|
||||
}
|
||||
groups.push(g);
|
||||
}
|
||||
}
|
||||
|
||||
// Gelände und importierte Meshes (IFC/DXF): Farbe der Quelle, falls gesetzt.
|
||||
if (opts.context ?? true) {
|
||||
for (const obj of project.context ?? []) {
|
||||
if (obj.type !== "terrainMesh" && obj.type !== "importedMesh") continue;
|
||||
if (obj.positions.length < 9 || obj.indices.length < 3) continue;
|
||||
const terrain = obj.type === "terrainMesh";
|
||||
const rgb: Rgb = !terrain && obj.color ? hexToRgb(obj.color, IMPORTED_RGB) : terrain ? TERRAIN_RGB : IMPORTED_RGB;
|
||||
const g = newGroup(`${terrain ? "Gelaende" : "Kontext"}_${sanitizeName(obj.id)}`, terrain ? "terrain" : "context", obj.id, -1);
|
||||
const prim = newPrim(g, mats.get(terrain ? "Gelaende" : obj.name || "Kontext", rgb));
|
||||
appendModelMesh(prim, obj.positions, obj.indices, false);
|
||||
groups.push(g);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groups: groups.filter((g) => g.prims.some((p) => p.indices.length > 0)),
|
||||
materials: mats.list,
|
||||
levels,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Flacher Puffer (Gegenstück zu src-tauri/fileio/src/mesh_export.rs, dort die Kodierung) ─────
|
||||
|
||||
const FLAT_VERSION = 1;
|
||||
|
||||
/** Kodiert die Szene als `[Zahlenpuffer, Zeichenketten durch \0 getrennt]`. */
|
||||
function encodeScene(scene: MeshScene, byLevel: boolean): [Float64Array, string] {
|
||||
const nums: number[] = [FLAT_VERSION, byLevel ? 1 : 0];
|
||||
const strings: string[] = [];
|
||||
const str = (s: string): number => {
|
||||
strings.push(s.replace(/\0/g, ""));
|
||||
return strings.length - 1;
|
||||
};
|
||||
nums.push(scene.materials.length);
|
||||
for (const m of scene.materials) nums.push(str(m.name), m.rgba[0], m.rgba[1], m.rgba[2], m.rgba[3], m.metallic, m.roughness);
|
||||
nums.push(scene.levels.length);
|
||||
for (const l of scene.levels) nums.push(str(l.id), str(l.name));
|
||||
nums.push(scene.groups.length);
|
||||
for (const g of scene.groups) {
|
||||
nums.push(str(g.name), str(g.kind), str(g.id), g.level, g.prims.length);
|
||||
for (const p of g.prims) {
|
||||
nums.push(p.material, p.positions.length / 3);
|
||||
for (let i = 0; i < p.positions.length; i++) nums.push(p.positions[i]);
|
||||
nums.push(p.indices.length / 3);
|
||||
for (let i = 0; i < p.indices.length; i++) nums.push(p.indices[i]);
|
||||
}
|
||||
}
|
||||
return [new Float64Array(nums), strings.join("\0")];
|
||||
}
|
||||
|
||||
/** Ruft eine Rust-Bindung; leeres Ergebnis (kaputter Puffer) wird zum Fehler mit dem Grund. */
|
||||
function write<T extends string | Uint8Array>(project: Project, opts: MeshOptions, byLevel: boolean, run: (m: ReturnType<typeof fileio>, buf: Float64Array, strings: string) => T): T {
|
||||
const args = [(opts.openingParts ?? true) ? 1 : 0, (opts.context ?? true) ? 1 : 0, byLevel ? 1 : 0];
|
||||
const [buf, strings] = decodeExportFlat(documentFor(project).queryBin("meshExportData", args));
|
||||
const m = fileio();
|
||||
const [buf, strings] = encodeScene(buildScene(project, opts), byLevel);
|
||||
const out = run(m, buf, strings);
|
||||
if (out.length === 0) {
|
||||
const why = m.export_mesh_check_flat(buf, strings);
|
||||
@@ -497,9 +36,9 @@ function write<T extends string | Uint8Array>(project: Project, opts: MeshOption
|
||||
|
||||
/**
|
||||
* Baut einen vollständigen Wavefront-OBJ-String des 3D-Gebäudemodells (Meter, Y-up rechtshändig:
|
||||
* Modell (x, y, z-hoch) → (x, z, −y), siehe Moduldoc). Ein `o`-Objekt je Bauteil-Vorkommen (Wand, Decke,
|
||||
* Extrusion, Dach, Treppe, Stütze, Fenster/Tür, Kontext-Mesh). Leeres Projekt ⇒ gültige Datei nur mit
|
||||
* Kopf-Kommentaren. Verlangt das geladene Format-Modul (`await loadFileio()`).
|
||||
* Modell (x, y, z-hoch) → (x, z, −y)). Ein `o`-Objekt je Bauteil-Vorkommen (Wand, Decke, Extrusion, Dach,
|
||||
* Treppe, Stütze, Fenster/Tür, Kontext-Mesh). Leeres Projekt ⇒ gültige Datei nur mit Kopf-Kommentaren.
|
||||
* Verlangt das geladene Format-Modul (`await loadFileio()`).
|
||||
*/
|
||||
export function exportObj(project: Project, opts: MeshOptions = {}): string {
|
||||
return write(project, opts, false, (m, b, s) => m.export_mesh_obj_flat(b, s));
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
// Klassifikation im IFC-Export ([B5], 28.10.): welche Klassifikationssysteme das Modell hergibt und die
|
||||
// Standard-Zuordnung nach eBKP-H. Reine Tabellen/Funktionen, kein IFC-Schreiben (das macht Rust über
|
||||
// den Datensatz CLASSIFICATION, `ifc_export.rs`).
|
||||
//
|
||||
// Was das Modell führt: KEINEN eBKP-H-/BKP-Code. `categoryCode` an Bauteilen ist die Grafik-Ebene
|
||||
// („20" Wände, „30" Decken …, `LayerCategory`), kein Kostenschlüssel. Daher zwei getrennte Wege:
|
||||
// • `layerCodes` — die Ebene des Modells als eigenes System „Dossier-Ebenen" (Code = `categoryCode`,
|
||||
// Name = Ebenenname). Stammt aus dem Modell, behauptet keinen Standard.
|
||||
// • `ebkph` — Standardzuordnung je Bauteilart auf eBKP-H-HAUPTGRUPPEN (siehe `EBKPH_GROUPS`).
|
||||
//
|
||||
// Quelle eBKP-H: CRB, „eBKP-H Elementbasierter Baukostenplan Hochbau", SN 506 511 (Ausgabe 2020).
|
||||
// Gesichert sind nur die Hauptgruppen-Buchstaben und ihre Namen (A Grundstück, B Vorbereitung,
|
||||
// C Konstruktion Gebäude, D Technik Gebäude, E Äussere Wandbekleidung Gebäude, F Bedachung Gebäude,
|
||||
// G Ausbau Gebäude, H Nutzungsspezifische Anlagen Gebäude, I Umgebung Gebäude, J Ausstattung,
|
||||
// V Planungsleistungen, W Nebenkosten, Y Reserve, Z Mehrwertsteuer). Keine Untergruppen (C01 …):
|
||||
// die hängen von Konstruktionsart und Lage ab, die das Modell nicht trägt.
|
||||
//
|
||||
// Die Zuordnung ist deshalb bewusst grob und ein VORSCHLAG für die Kostenplanung, kein Ersatz für
|
||||
// die Einordnung durch die Kostenplanerin:
|
||||
// Wand → C (Wandkonstruktion; Aussen-/Innenbekleidung E/G und nichttragende Innenwände
|
||||
// unterscheidet das Modell nicht — dafür fehlt ein Feld am Wandtyp)
|
||||
// Decke → C (Deckenkonstruktion; Bodenbeläge/Unterdecken wären G)
|
||||
// Stütze → C
|
||||
// Treppe → C (Treppenkonstruktion; Belag/Geländer wären G)
|
||||
// Dach → F (Dachaufbau mit Eindeckung/Abdichtung; die reine Tragkonstruktion wäre C)
|
||||
// Fenster → E (Fenster der Gebäudehülle)
|
||||
// Tür → keine (Aussentür E, Innentür G — nicht unterscheidbar, daher nicht geraten)
|
||||
// Raum → keine (Räume sind Flächen, kein Bauteil; sie haben die SIA-416-Zonen)
|
||||
|
||||
import type { LayerCategory, Project } from "../model/types";
|
||||
|
||||
/** IFC-Schema der Ausgabe: IFC4 (Standard) oder IFC2x3 (Coordination View 2.0, TC1). */
|
||||
export type IfcSchema = "IFC4" | "IFC2X3";
|
||||
|
||||
/** Optionen des IFC-Exports: Schema und Klassifikation. */
|
||||
export interface IfcExportOptions {
|
||||
/** Schema der Datei; ohne Angabe IFC4. */
|
||||
schema?: IfcSchema;
|
||||
/** eBKP-H-Hauptgruppen je Bauteilart (Standardzuordnung, s. Dateikopf). */
|
||||
ebkph?: boolean;
|
||||
/** `categoryCode` (Ebene) des Modells als System „Dossier-Ebenen". */
|
||||
layerCodes?: boolean;
|
||||
}
|
||||
|
||||
/** Bauteilarten, die klassifiziert werden können. */
|
||||
export type ClassifiedKind = "wall" | "slab" | "roof" | "column" | "stair" | "window" | "door" | "space";
|
||||
|
||||
/** Ein Klassifikationssystem für IfcClassification. */
|
||||
export interface ClassificationSystem {
|
||||
name: string;
|
||||
source: string;
|
||||
/** Ausgabe; leer = keine Angabe. */
|
||||
edition: string;
|
||||
}
|
||||
|
||||
export const EBKPH_SYSTEM: ClassificationSystem = {
|
||||
name: "eBKP-H",
|
||||
source: "CRB Schweizerische Zentralstelle für Baurationalisierung",
|
||||
edition: "SN 506 511:2020",
|
||||
};
|
||||
|
||||
export const LAYER_SYSTEM: ClassificationSystem = {
|
||||
name: "Dossier-Ebenen",
|
||||
source: "Dossier",
|
||||
edition: "",
|
||||
};
|
||||
|
||||
/** Gesicherte eBKP-H-Hauptgruppen (nur die hier verwendeten). */
|
||||
export const EBKPH_GROUPS = {
|
||||
C: "Konstruktion Gebäude",
|
||||
E: "Äussere Wandbekleidung Gebäude",
|
||||
F: "Bedachung Gebäude",
|
||||
} as const;
|
||||
|
||||
const EBKPH_BY_KIND: Partial<Record<ClassifiedKind, keyof typeof EBKPH_GROUPS>> = {
|
||||
wall: "C",
|
||||
slab: "C",
|
||||
column: "C",
|
||||
stair: "C",
|
||||
roof: "F",
|
||||
window: "E",
|
||||
};
|
||||
|
||||
/** eBKP-H-Hauptgruppe zur Bauteilart, oder `null` (Tür, Raum: nicht eindeutig). */
|
||||
export function ebkphGroup(kind: ClassifiedKind): { code: string; name: string } | null {
|
||||
const code = EBKPH_BY_KIND[kind];
|
||||
return code ? { code, name: EBKPH_GROUPS[code] } : null;
|
||||
}
|
||||
|
||||
function findLayer(list: readonly LayerCategory[], code: string): LayerCategory | undefined {
|
||||
for (const c of list) {
|
||||
if (c.code === code) return c;
|
||||
const sub = c.children ? findLayer(c.children, code) : undefined;
|
||||
if (sub) return sub;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Ebene (Code + Name) eines Bauteils; ohne Code `null`, ohne bekannte Ebene der Code als Name. */
|
||||
export function layerClassification(project: Project, categoryCode: string | undefined): { code: string; name: string } | null {
|
||||
const code = categoryCode?.trim();
|
||||
if (!code) return null;
|
||||
return { code, name: findLayer(project.layers, code)?.name ?? code };
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
// Türen/Fenster im IFC-Export ([B5]): TS sammelt nur die Parameter aus Typ und Öffnung; die Geometrie
|
||||
// rechnet Rust (`src-tauri/fileio/src/ifc_openings.rs`, dort die Fälle Rahmen/Blatt/Glas/Ausführung).
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fillParams } from "./ifcOpenings";
|
||||
import type { DoorType, Opening, Project, Wall, WindowType } from "../model/types";
|
||||
|
||||
const wall = { id: "W", start: { x: 0, y: 0 }, end: { x: 5, y: 0 } } as Wall;
|
||||
const host = { nLo: -0.2, nHi: 0.2 };
|
||||
const proj = (over: { doorTypes?: DoorType[]; windowTypes?: WindowType[] }) =>
|
||||
({ doorTypes: over.doorTypes ?? [], windowTypes: over.windowTypes ?? [] }) as unknown as Project;
|
||||
const door = (over: Partial<Opening> = {}) =>
|
||||
({ id: "D", type: "opening", hostWallId: "W", categoryCode: "21", kind: "door", position: 1, width: 1, height: 2.1, sillHeight: 0, ...over }) as Opening;
|
||||
const win = (over: Partial<Opening> = {}) =>
|
||||
({ id: "F", type: "opening", hostWallId: "W", categoryCode: "21", kind: "window", position: 1, width: 1.2, height: 1.2, sillHeight: 0.9, ...over }) as Opening;
|
||||
const cut = (o: Opening) => ({ from: o.position, to: o.position + o.width, zBottom: o.sillHeight, zTop: o.sillHeight + o.height });
|
||||
const wt = (over: Partial<WindowType> = {}): WindowType =>
|
||||
({ id: "wt", name: "Fenster", kind: "dreh", wingCount: 1, glazing: "dreifach", frameThickness: 0.08, defaultSillHeight: 0.9, defaultWidth: 1.2, defaultHeight: 1.2, ...over }) as WindowType;
|
||||
const dtp = (over: Partial<DoorType> = {}): DoorType =>
|
||||
({ id: "dt", name: "Tür", kind: "dreh", leafCount: 1, leafStyle: "glatt", frameThickness: 0.06, defaultWidth: 1, defaultHeight: 2.1, ...over }) as DoorType;
|
||||
|
||||
describe("fillParams", () => {
|
||||
it("Fenster: Typwerte, Flügeltabelle, Flügelzahl der Öffnung vor dem Typ", () => {
|
||||
const t = wt({
|
||||
frameWidth: 0.09,
|
||||
frameDepth: 0.1,
|
||||
insetFromFace: 0.05,
|
||||
insetFace: "innen",
|
||||
wingCount: 3,
|
||||
sashes: [{ kind: "fluegel", autoWidth: false, width: 0.5 }, { kind: "pfosten", postWidth: 0.1 }, { kind: "fluegel" }],
|
||||
});
|
||||
const o = win({ typeId: "wt", wingCount: 2 });
|
||||
expect(fillParams(proj({ windowTypes: [t] }), wall, o, cut(o), host)).toMatchObject({
|
||||
from: 1,
|
||||
to: 2.2,
|
||||
zBottom: 0.9,
|
||||
zTop: 2.1,
|
||||
nLo: -0.2,
|
||||
nHi: 0.2,
|
||||
frameDepth: 0.1,
|
||||
frameWidth: 0.09,
|
||||
inset: 0.05,
|
||||
insetOutside: false,
|
||||
wingCount: 2,
|
||||
panes: 3,
|
||||
sashes: [
|
||||
{ post: false, fixed: true, width: 0.5 },
|
||||
{ post: true, postWidth: 0.1, fixed: false },
|
||||
{ post: false, fixed: false },
|
||||
],
|
||||
});
|
||||
// Ohne Typ: nichts vom Typ, zwei Scheiben, eine Flügel.
|
||||
const p = fillParams(proj({}), wall, win(), cut(win()), host);
|
||||
expect(p).toMatchObject({ frameDepth: undefined, frameWidth: undefined, insetOutside: true, wingCount: 1, panes: 2, sashes: [] });
|
||||
});
|
||||
|
||||
it("Tür: Art, Blätter, Aufschlag, Scharnier, Oberlicht, Glas", () => {
|
||||
const o = door({ typeId: "dt", hinge: "end", swing: "right", openingDir: "out" });
|
||||
const t = dtp({ kind: "schiebe", leafCount: 2, transomHeight: 0.4, leafStyle: "glas", glazingRatio: 0.36 });
|
||||
expect(fillParams(proj({ doorTypes: [t] }), wall, o, cut(o), host)).toMatchObject({
|
||||
doorKind: 1,
|
||||
leafCount: 2,
|
||||
swingSign: -1,
|
||||
dirSign: -1,
|
||||
hingeAtStart: false,
|
||||
transomHeight: 0.4,
|
||||
glazed: true,
|
||||
glazingRatio: 0.36,
|
||||
});
|
||||
const plain = fillParams(proj({}), wall, door(), cut(door()), host);
|
||||
expect(plain).toMatchObject({ doorKind: 0, leafCount: 1, swingSign: 1, dirSign: 1, hingeAtStart: true, transomHeight: 0, glazed: false });
|
||||
expect(fillParams(proj({}), wall, door({ doorType: "wandoeffnung" }), cut(door()), host).doorKind).toBe(2);
|
||||
expect(fillParams(proj({ doorTypes: [dtp({ kind: "wandoeffnung" })] }), wall, door({ typeId: "dt" }), cut(door()), host).doorKind).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -1,91 +0,0 @@
|
||||
// Türen und Fenster im IFC-Export ([B5]): sammelt die Parameter einer Füllung aus dem Modell (Typ und
|
||||
// Öffnung) für den Rust-Schreiber. Körper (Rahmen/Zarge, Türblatt, Glas), Füllungs-Placement und
|
||||
// OperationType/PartitioningType rechnet `src-tauri/fileio/src/ifc_openings.rs` (Port der früheren
|
||||
// TS-Rechnung, 28.10.; Kodierung FILL im Kopf von `ifc_export.rs`). Fehlende Typwerte bleiben `undefined`,
|
||||
// die Standardmasse (Rahmen 6 × 7 cm, Blatt 4 cm, Glaspakete) kennt nur Rust.
|
||||
|
||||
import type { Opening, Project, Vec2, Wall } from "../model/types";
|
||||
import { getDoorType, getWindowType, glazingPanesOf } from "../model/types";
|
||||
|
||||
/** Ein Eintrag der Flügeltabelle, wie im Modell (`SashDef`). */
|
||||
export interface FillSash {
|
||||
post: boolean;
|
||||
postWidth?: number;
|
||||
fixed: boolean;
|
||||
width?: number;
|
||||
}
|
||||
|
||||
/** Parameter einer Füllung (Reihenfolge der Kodierung: `FlatIfc.opening` in `exportIfc.ts`). */
|
||||
export interface FillParams {
|
||||
wallStart: Vec2;
|
||||
wallEnd: Vec2;
|
||||
/** Achs-Intervall (Abstand ab `wall.start`) und absolute Höhen der Öffnung. */
|
||||
from: number;
|
||||
to: number;
|
||||
zBottom: number;
|
||||
zTop: number;
|
||||
/** Querausdehnung der ganzen Wand entlang der linken Normalen ab `wall.start` (`nLo` = Aussenseite). */
|
||||
nLo: number;
|
||||
nHi: number;
|
||||
frameDepth?: number;
|
||||
inset?: number;
|
||||
insetOutside: boolean;
|
||||
frameWidth?: number;
|
||||
/** Fenster: Flügelzahl, Scheiben (1–3), Flügeltabelle. */
|
||||
wingCount: number;
|
||||
panes: number;
|
||||
sashes: FillSash[];
|
||||
/** Tür: 0 Dreh, 1 Schiebe, 2 reine Wandöffnung. */
|
||||
doorKind: 0 | 1 | 2;
|
||||
leafCount: number;
|
||||
/** +1 Aufschlag links der Achse, −1 rechts; Richtung +1 innen, −1 aussen. */
|
||||
swingSign: 1 | -1;
|
||||
dirSign: 1 | -1;
|
||||
hingeAtStart: boolean;
|
||||
transomHeight: number;
|
||||
glazed: boolean;
|
||||
glazingRatio?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameter der Füllung einer Öffnung. `c` = Achs-Intervall und absolute Höhen der Öffnung, `host` =
|
||||
* Querausdehnung der ganzen Wand (wie im 2D/3D).
|
||||
*/
|
||||
export function fillParams(
|
||||
project: Project,
|
||||
wall: Wall,
|
||||
opening: Opening,
|
||||
c: { from: number; to: number; zBottom: number; zTop: number },
|
||||
host: { nLo: number; nHi: number },
|
||||
): FillParams {
|
||||
const isDoor = opening.kind === "door";
|
||||
const dt = isDoor ? getDoorType(project, opening) : undefined;
|
||||
const wt = isDoor ? undefined : getWindowType(project, opening);
|
||||
const t = dt ?? wt;
|
||||
const kind = dt?.kind ?? (opening.doorType === "wandoeffnung" ? "wandoeffnung" : "dreh");
|
||||
return {
|
||||
wallStart: wall.start,
|
||||
wallEnd: wall.end,
|
||||
from: c.from,
|
||||
to: c.to,
|
||||
zBottom: c.zBottom,
|
||||
zTop: c.zTop,
|
||||
nLo: host.nLo,
|
||||
nHi: host.nHi,
|
||||
frameDepth: t?.frameDepth,
|
||||
inset: t?.insetFromFace,
|
||||
insetOutside: (t?.insetFace ?? "aussen") === "aussen",
|
||||
frameWidth: t?.frameWidth,
|
||||
wingCount: opening.wingCount ?? wt?.wingCount ?? 1,
|
||||
panes: wt ? glazingPanesOf(wt) : 2,
|
||||
sashes: (wt?.sashes ?? []).map((s) => ({ post: s.kind === "pfosten", postWidth: s.postWidth, fixed: s.autoWidth === false, width: s.width })),
|
||||
doorKind: kind === "schiebe" ? 1 : kind === "wandoeffnung" ? 2 : 0,
|
||||
leafCount: dt?.leafCount ?? 1,
|
||||
swingSign: (opening.swing ?? "left") === "left" ? 1 : -1,
|
||||
dirSign: (opening.openingDir ?? "in") === "in" ? 1 : -1,
|
||||
hingeAtStart: (opening.hinge ?? "start") === "start",
|
||||
transomHeight: dt?.transomHeight ?? 0,
|
||||
glazed: dt?.leafStyle === "glas",
|
||||
glazingRatio: dt?.glazingRatio,
|
||||
};
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
// Basismengen für den IFC-Export ([B5], 28.10.): reine Rechnung aus der Geometrie, Werte nachrechenbar.
|
||||
import { describe, it, expect } from "vitest";
|
||||
import type { RWall } from "../plan/toWalls3d";
|
||||
import {
|
||||
columnQuantities,
|
||||
flightQuantities,
|
||||
meshVolume,
|
||||
openingQuantities,
|
||||
railingQuantities,
|
||||
ringArea,
|
||||
ringPerimeter,
|
||||
roofQuantities,
|
||||
slabQuantities,
|
||||
wallQuantities,
|
||||
} from "./ifcQuantities";
|
||||
|
||||
const byName = (q: { name: string; value: number }[]) => Object.fromEntries(q.map((x) => [x.name, x.value]));
|
||||
|
||||
/** Wandband: Quader `len` lang entlang x ab `x0`, Dicke, Höhe ab `base`. */
|
||||
function band(x0: number, len: number, thickness: number, height: number, base = 0, topDrop?: [number, number]): RWall {
|
||||
return { start: [x0, 0], end: [x0 + len, 0], thickness, height, baseElevation: base, color: [1, 1, 1], layers: [], wallId: "W", ...(topDrop ? { topDrop } : {}) };
|
||||
}
|
||||
|
||||
describe("Hilfen", () => {
|
||||
it("Ringfläche (unabhängig vom Umlaufsinn) und Umfang", () => {
|
||||
const sq = [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }, { x: 0, y: 3 }];
|
||||
expect(ringArea(sq)).toBe(12);
|
||||
expect(ringArea([...sq].reverse())).toBe(12);
|
||||
expect(ringPerimeter(sq)).toBe(14);
|
||||
expect(ringArea([])).toBe(0);
|
||||
});
|
||||
|
||||
it("Mesh-Volumen eines Würfels, unabhängig von der Wicklung", () => {
|
||||
const pos = [0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 2, 0, 0, 0, 2, 2, 0, 2, 2, 2, 2, 0, 2, 2];
|
||||
const idx = [0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4, 1, 2, 6, 1, 6, 5, 2, 3, 7, 2, 7, 6, 3, 0, 4, 3, 4, 7];
|
||||
expect(meshVolume(pos, idx)).toBeCloseTo(8, 12);
|
||||
const rev: number[] = [];
|
||||
for (let i = 0; i < idx.length; i += 3) rev.push(idx[i], idx[i + 2], idx[i + 1]);
|
||||
expect(meshVolume(pos, rev)).toBeCloseTo(8, 12);
|
||||
expect(meshVolume([], [])).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Wand", () => {
|
||||
const wall = { start: { x: 0, y: 0 }, end: { x: 5, y: 0 } };
|
||||
|
||||
it("eine Schicht: Länge, Dicke, Höhe, Seitenfläche, Volumen; Öffnung wird netto abgezogen", () => {
|
||||
const q = byName(
|
||||
wallQuantities(wall, [band(0, 5, 0.3, 2.6)], [{ from: 1, to: 2, zBottom: 0.9, zTop: 2.1 }]),
|
||||
);
|
||||
expect(q.Length).toBe(5);
|
||||
expect(q.Width).toBeCloseTo(0.3, 12);
|
||||
expect(q.Height).toBeCloseTo(2.6, 12);
|
||||
expect(q.GrossSideArea).toBeCloseTo(13, 12);
|
||||
expect(q.NetSideArea).toBeCloseTo(13 - 1.2, 12);
|
||||
expect(q.GrossVolume).toBeCloseTo(13 * 0.3, 12);
|
||||
expect(q.NetVolume).toBeCloseTo((13 - 1.2) * 0.3, 12);
|
||||
});
|
||||
|
||||
it("mehrere Schichten: Dicke und Volumen summieren, Öffnung schneidet jede Schicht", () => {
|
||||
// Aussenschicht 0.2 (Achse −0.15 … ), Dämmung 0.1: Mittellinien bei y = −0.05 und +0.1
|
||||
const a = { ...band(0, 5, 0.2, 2.6), start: [0, -0.05], end: [5, -0.05] } as RWall;
|
||||
const b = { ...band(0, 5, 0.1, 2.6), start: [0, 0.1], end: [5, 0.1] } as RWall;
|
||||
const q = byName(wallQuantities(wall, [a, b], [{ from: 2, to: 3, zBottom: 0, zTop: 2.1 }]));
|
||||
expect(q.Width).toBeCloseTo(0.3, 12);
|
||||
expect(q.GrossVolume).toBeCloseTo(5 * 0.3 * 2.6, 12);
|
||||
expect(q.NetVolume).toBeCloseTo((5 * 2.6 - 1 * 2.1) * 0.3, 12);
|
||||
});
|
||||
|
||||
it("innere Schicht endet unter der Decke: Seitenfläche mit voller Wandhöhe, Volumen je Schicht", () => {
|
||||
const outer = band(0, 5, 0.2, 2.6);
|
||||
const inner = band(0.1, 4.8, 0.1, 2.3);
|
||||
const q = byName(wallQuantities(wall, [outer, inner], []));
|
||||
expect(q.Height).toBeCloseTo(2.6, 12);
|
||||
expect(q.GrossSideArea).toBeCloseTo(13, 12);
|
||||
expect(q.GrossVolume).toBeCloseTo(5 * 0.2 * 2.6 + 4.8 * 0.1 * 2.3, 12);
|
||||
});
|
||||
|
||||
it("Gehrung/Anschluss: kürzeres Band ändert Volumen, nicht die Wandlänge", () => {
|
||||
const q = byName(wallQuantities(wall, [band(0.1, 4.8, 0.3, 2.6)], []));
|
||||
expect(q.Length).toBe(5);
|
||||
expect(q.GrossVolume).toBeCloseTo(4.8 * 0.3 * 2.6, 12);
|
||||
expect(q.NetVolume).toBeCloseTo(q.GrossVolume, 12);
|
||||
});
|
||||
|
||||
it("schräge Oberkante: Höhe fehlt (nicht konstant), Fläche und Volumen mit mittlerer Höhe", () => {
|
||||
const q = byName(wallQuantities(wall, [band(0, 5, 0.3, 3, 0, [0, 1])], []));
|
||||
expect(q.Height).toBeUndefined();
|
||||
expect(q.GrossSideArea).toBeCloseTo(5 * 2.5, 12);
|
||||
expect(q.GrossVolume).toBeCloseTo(5 * 0.3 * 2.5, 12);
|
||||
});
|
||||
|
||||
it("Mesh-Wand: Netto-Volumen aus dem Netz, Brutto bleibt der Quader", () => {
|
||||
const q = byName(wallQuantities(wall, [band(0, 5, 0.3, 2.6)], [{ from: 1, to: 2, zBottom: 0.9, zTop: 2.1 }], 3.5));
|
||||
expect(q.NetVolume).toBe(3.5);
|
||||
expect(q.GrossVolume).toBeCloseTo(13 * 0.3, 12);
|
||||
});
|
||||
|
||||
it("Öffnung grösser als die Wand: Netto nie negativ; Öffnung ausserhalb zieht nichts ab", () => {
|
||||
const q = byName(wallQuantities(wall, [band(0, 5, 0.3, 2.6)], [{ from: -1, to: 6, zBottom: -1, zTop: 5 }, { from: 8, to: 9, zBottom: 0, zTop: 2 }]));
|
||||
expect(q.NetSideArea).toBe(0);
|
||||
expect(q.NetVolume).toBeCloseTo(0, 12);
|
||||
});
|
||||
|
||||
it("keine Bänder: keine Mengen", () => {
|
||||
expect(wallQuantities(wall, [], [])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Decke, Dach, Stütze, Öffnung, Treppe", () => {
|
||||
it("Decke: Fläche, Umfang, Dicke; Aussparung nur netto", () => {
|
||||
const outline = [{ x: 0, y: 0 }, { x: 5, y: 0 }, { x: 5, y: 4 }, { x: 0, y: 4 }];
|
||||
const hole = [{ x: 1, y: 1 }, { x: 2, y: 1 }, { x: 2, y: 2 }, { x: 1, y: 2 }];
|
||||
const q = byName(slabQuantities(outline, [hole], 0.2));
|
||||
expect(q.Width).toBeCloseTo(0.2, 12);
|
||||
expect(q.Perimeter).toBe(18);
|
||||
expect(q.GrossArea).toBe(20);
|
||||
expect(q.NetArea).toBe(19);
|
||||
expect(q.GrossVolume).toBeCloseTo(4, 12);
|
||||
expect(q.NetVolume).toBeCloseTo(3.8, 12);
|
||||
});
|
||||
|
||||
it("Dach: geneigte Fläche > Grundrissfläche (Satteldach 30°)", () => {
|
||||
// Zwei Flächen 5 × 2 m Grundriss, 30° geneigt: je 5 × 2/cos(30°).
|
||||
const h = Math.tan(Math.PI / 6) * 2;
|
||||
const planes = [
|
||||
[[0, 0, 0], [5, 0, 0], [5, 2, h], [0, 2, h]],
|
||||
[[0, 4, 0], [0, 2, h], [5, 2, h], [5, 4, 0]],
|
||||
] as [number, number, number][][];
|
||||
const q = byName(roofQuantities(planes));
|
||||
expect(q.ProjectedArea).toBeCloseTo(20, 9);
|
||||
expect(q.GrossArea).toBeCloseTo(20 / Math.cos(Math.PI / 6), 9);
|
||||
expect(q.NetArea).toBe(q.GrossArea);
|
||||
});
|
||||
|
||||
it("Stütze 0.3 × 0.3 × 2.6", () => {
|
||||
const fp = [{ x: 0, y: 0 }, { x: 0.3, y: 0 }, { x: 0.3, y: 0.3 }, { x: 0, y: 0.3 }];
|
||||
const q = byName(columnQuantities(fp, 2.6));
|
||||
expect(q.Length).toBe(2.6);
|
||||
expect(q.CrossSectionArea).toBeCloseTo(0.09, 12);
|
||||
expect(q.OuterSurfaceArea).toBeCloseTo(1.2 * 2.6, 12);
|
||||
expect(q.NetSurfaceArea).toBeCloseTo(1.2 * 2.6 + 0.18, 12);
|
||||
expect(q.GrossVolume).toBeCloseTo(0.09 * 2.6, 12);
|
||||
expect(q.NetVolume).toBeCloseTo(q.GrossVolume, 12);
|
||||
});
|
||||
|
||||
it("Fenster/Tür: Breite, Höhe, Umfang, Fläche", () => {
|
||||
const q = byName(openingQuantities(1.2, 1.5));
|
||||
expect(q.Width).toBe(1.2);
|
||||
expect(q.Height).toBe(1.5);
|
||||
expect(q.Perimeter).toBeCloseTo(5.4, 12);
|
||||
expect(q.Area).toBeCloseTo(1.8, 12);
|
||||
});
|
||||
|
||||
it("Lauf und Geländer", () => {
|
||||
expect(byName(flightQuantities(3.4, 1.2))).toEqual({ Length: 3.4, GrossVolume: 1.2, NetVolume: 1.2 });
|
||||
expect(byName(railingQuantities(5))).toEqual({ Length: 5 });
|
||||
});
|
||||
|
||||
it("nie NaN/negativ: kaputte Eingaben ergeben 0", () => {
|
||||
const q = openingQuantities(Number.NaN, -1);
|
||||
for (const x of q) expect(Number.isFinite(x.value) && x.value >= 0).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,213 +0,0 @@
|
||||
// Basismengen (Qto_*BaseQuantities) für den IFC-Export ([B5], 28.10.): 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), kein Zugriff auf
|
||||
// das Projekt; `exportIfc.ts` sammelt und ruft sie auf, Rust schreibt die IfcElementQuantity.
|
||||
//
|
||||
// Netto = abzüglich Öffnungen (Wand, Decke). Fehlt einer Menge die Grundlage (z. B. Höhe bei schräger
|
||||
// Wandoberkante: „nur angeben, wenn konstant“), lassen wir sie weg statt zu raten.
|
||||
|
||||
import type { Vec2 } from "../model/types";
|
||||
import type { RWall } from "../plan/toWalls3d";
|
||||
|
||||
/** Eine Menge: Name nach IFC4-Vorlage, Art (Länge/Fläche/Volumen) und Wert (immer endlich und ≥ 0). */
|
||||
export interface Qty {
|
||||
name: string;
|
||||
kind: "length" | "area" | "volume";
|
||||
value: number;
|
||||
}
|
||||
|
||||
/** Rundungsfehler und kaputte Eingaben (NaN) auf 0, nie negativ. */
|
||||
const clean = (v: number): number => (Number.isFinite(v) && v > 0 ? v : 0);
|
||||
const q = (name: string, kind: Qty["kind"], value: number): Qty => ({ name, kind, value: clean(value) });
|
||||
const len = (name: string, v: number) => q(name, "length", v);
|
||||
const area = (name: string, v: number) => q(name, "area", v);
|
||||
const vol = (name: string, v: number) => q(name, "volume", v);
|
||||
|
||||
/** Fläche eines Rings (Shoelace, unabhängig vom Umlaufsinn); offener Ring, die Schlusskante gilt als gegeben. */
|
||||
export function ringArea(pts: readonly Vec2[]): number {
|
||||
let a = 0;
|
||||
for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) a += pts[j].x * pts[i].y - pts[i].x * pts[j].y;
|
||||
return Math.abs(a) / 2;
|
||||
}
|
||||
|
||||
/** Umfang eines geschlossenen Rings. */
|
||||
export function ringPerimeter(pts: readonly Vec2[]): number {
|
||||
let p = 0;
|
||||
for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) p += Math.hypot(pts[i].x - pts[j].x, pts[i].y - pts[j].y);
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Volumen eines geschlossenen Dreiecks-Netzes (Betrag der Summe der Tetraeder-Volumen zum Ursprung). */
|
||||
export function meshVolume(positions: readonly number[], indices: readonly number[]): number {
|
||||
let v = 0;
|
||||
for (let i = 0; i + 2 < indices.length; i += 3) {
|
||||
const a = indices[i] * 3;
|
||||
const b = indices[i + 1] * 3;
|
||||
const c = indices[i + 2] * 3;
|
||||
v +=
|
||||
positions[a] * (positions[b + 1] * positions[c + 2] - positions[b + 2] * positions[c + 1]) -
|
||||
positions[a + 1] * (positions[b] * positions[c + 2] - positions[b + 2] * positions[c]) +
|
||||
positions[a + 2] * (positions[b] * positions[c + 1] - positions[b + 1] * positions[c]);
|
||||
}
|
||||
return Math.abs(v) / 6;
|
||||
}
|
||||
|
||||
/** Öffnung einer Wand: Achs-Intervall (ab Wandanfang) und absolute Höhen. */
|
||||
export interface Cutout {
|
||||
from: number;
|
||||
to: number;
|
||||
zBottom: number;
|
||||
zTop: number;
|
||||
}
|
||||
|
||||
const overlap = (a0: number, a1: number, b0: number, b1: number): number => Math.max(0, Math.min(a1, b1) - Math.max(a0, b0));
|
||||
|
||||
/**
|
||||
* 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 (Gehrungen/Anschlüsse stecken in den Bandlängen);
|
||||
* NetVolume: abzüglich der Öffnungen je Band — oder `netVolume`, wenn die Wand als Netz mit schon
|
||||
* ausgestanzten Öffnungen (und Laibungen) geschrieben wird.
|
||||
*/
|
||||
export function wallQuantities(
|
||||
wall: { start: Vec2; end: Vec2 },
|
||||
bands: readonly RWall[],
|
||||
cutouts: readonly Cutout[],
|
||||
netVolume?: number,
|
||||
): Qty[] {
|
||||
if (bands.length === 0) return [];
|
||||
const axisLen = Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y);
|
||||
const ux = axisLen > 0 ? (wall.end.x - wall.start.x) / axisLen : 1;
|
||||
const uy = axisLen > 0 ? (wall.end.y - wall.start.y) / axisLen : 0;
|
||||
// Quer zur Achse: Ausdehnung aller Bänder entlang der linken Normalen (−uy, ux).
|
||||
let nLo = Infinity;
|
||||
let nHi = -Infinity;
|
||||
let zMin = Infinity;
|
||||
let zMax = -Infinity;
|
||||
let sloped = false;
|
||||
let gross = 0;
|
||||
let tallest = 0;
|
||||
for (const b of bands) {
|
||||
const l = Math.hypot(b.end[0] - b.start[0], b.end[1] - b.start[1]);
|
||||
const off = -(b.start[0] - wall.start.x) * uy + (b.start[1] - wall.start.y) * ux;
|
||||
nLo = Math.min(nLo, off - b.thickness / 2);
|
||||
nHi = Math.max(nHi, off + b.thickness / 2);
|
||||
zMin = Math.min(zMin, b.baseElevation);
|
||||
zMax = Math.max(zMax, b.baseElevation + b.height);
|
||||
const drop = b.topDrop ? (b.topDrop[0] + b.topDrop[1]) / 2 : 0;
|
||||
if (b.topDrop && (Math.abs(b.topDrop[0]) > 1e-9 || Math.abs(b.topDrop[1]) > 1e-9)) sloped = true;
|
||||
gross += l * b.thickness * (b.height - drop);
|
||||
tallest = Math.max(tallest, b.height - drop);
|
||||
}
|
||||
// Seitenfläche der Wandebene: innere Schichten enden oft unter der Decke (niedrigere Bänder), die Wand
|
||||
// selbst reicht über die volle Höhe — bei konstanter Oberkante zählt die Gesamthöhe, bei schräger die
|
||||
// höchste mittlere Bandhöhe.
|
||||
const grossSide = axisLen * (sloped ? tallest : zMax - zMin);
|
||||
let cutSide = 0;
|
||||
let cutVolume = 0;
|
||||
for (const c of cutouts) {
|
||||
cutSide += (c.to - c.from) * overlap(c.zBottom, c.zTop, zMin, zMax);
|
||||
for (const b of bands) {
|
||||
const a0 = (b.start[0] - wall.start.x) * ux + (b.start[1] - wall.start.y) * uy;
|
||||
const a1 = (b.end[0] - wall.start.x) * ux + (b.end[1] - wall.start.y) * uy;
|
||||
const ox = overlap(Math.min(a0, a1), Math.max(a0, a1), c.from, c.to);
|
||||
cutVolume += ox * overlap(c.zBottom, c.zTop, b.baseElevation, b.baseElevation + b.height) * b.thickness;
|
||||
}
|
||||
}
|
||||
// Netto aus dem Netz kann den Band-Quader um Rundung/Gehrungsdetails überschreiten: Brutto nie unter Netto.
|
||||
const net = netVolume ?? Math.max(0, gross - cutVolume);
|
||||
gross = Math.max(gross, net);
|
||||
const out: Qty[] = [len("Length", axisLen), len("Width", nHi - nLo)];
|
||||
if (!sloped && zMax - zMin > 0) out.push(len("Height", zMax - zMin));
|
||||
out.push(
|
||||
area("GrossSideArea", grossSide),
|
||||
area("NetSideArea", Math.max(0, grossSide - cutSide)),
|
||||
vol("GrossVolume", gross),
|
||||
vol("NetVolume", net),
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Brutto-Volumen der Löcher in einem Band (für Netz-Wände ohne Netz-Volumen, s. `wallQuantities`). */
|
||||
export function holeVolume(bands: readonly RWall[]): number {
|
||||
let v = 0;
|
||||
for (const b of bands) for (const h of b.holes ?? []) v += (h.to - h.from) * overlap(h.zBottom, h.zTop, b.baseElevation, b.baseElevation + b.height) * b.thickness;
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* Platten-Basismengen (Decke, Podest): Dicke, Umfang der Aussenkontur, Flächen und Volumen; Netto
|
||||
* zieht die Aussparungen ab.
|
||||
*/
|
||||
export function slabQuantities(outline: readonly Vec2[], openings: readonly (readonly Vec2[])[], thickness: number): Qty[] {
|
||||
const gross = ringArea(outline);
|
||||
const net = Math.max(0, gross - openings.reduce((s, r) => s + ringArea(r), 0));
|
||||
return [
|
||||
len("Width", thickness),
|
||||
len("Perimeter", ringPerimeter(outline)),
|
||||
area("GrossArea", gross),
|
||||
area("NetArea", net),
|
||||
vol("GrossVolume", gross * thickness),
|
||||
vol("NetVolume", net * thickness),
|
||||
];
|
||||
}
|
||||
|
||||
type Vec3 = readonly [number, number, number];
|
||||
|
||||
/**
|
||||
* Dach-Basismengen aus den geneigten Dachflächen (Aussenseite): geneigte Fläche (brutto = netto, das
|
||||
* Modell kennt keine Dachfenster/Aussparungen) und Grundrissprojektion.
|
||||
*/
|
||||
export function roofQuantities(planes: readonly (readonly Vec3[])[]): Qty[] {
|
||||
let sloped = 0;
|
||||
let projected = 0;
|
||||
for (const pts of planes) {
|
||||
// Newell: Vektorfläche des Polygons; Betrag = Fläche, z-Anteil = Projektion auf den Grundriss.
|
||||
let nx = 0;
|
||||
let ny = 0;
|
||||
let nz = 0;
|
||||
for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {
|
||||
const c = pts[j];
|
||||
const 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 += Math.hypot(nx, ny, nz) / 2;
|
||||
projected += Math.abs(nz) / 2;
|
||||
}
|
||||
return [area("GrossArea", sloped), area("NetArea", sloped), area("ProjectedArea", projected)];
|
||||
}
|
||||
|
||||
/** Stützen-Basismengen: Länge, Querschnitt, Mantel, Oberfläche und Volumen (keine Aussparungen). */
|
||||
export function columnQuantities(footprint: readonly Vec2[], length: number): Qty[] {
|
||||
const cross = ringArea(footprint);
|
||||
const outer = ringPerimeter(footprint) * length;
|
||||
return [
|
||||
len("Length", length),
|
||||
area("CrossSectionArea", cross),
|
||||
area("OuterSurfaceArea", outer),
|
||||
area("NetSurfaceArea", outer + 2 * cross),
|
||||
vol("GrossVolume", cross * length),
|
||||
vol("NetVolume", cross * length),
|
||||
];
|
||||
}
|
||||
|
||||
/** Tür-/Fenster-Basismengen (lichte Öffnung): Breite, Höhe, Umfang, Fläche. */
|
||||
export function openingQuantities(width: number, height: number): Qty[] {
|
||||
const w = clean(width);
|
||||
const h = clean(height);
|
||||
return [len("Width", w), len("Height", h), len("Perimeter", 2 * (w + h)), area("Area", w * h)];
|
||||
}
|
||||
|
||||
/** Treppenlauf: Lauflänge entlang der Lauflinie und Volumen (keine Aussparungen). */
|
||||
export function flightQuantities(length: number, volume: number): Qty[] {
|
||||
return [len("Length", length), vol("GrossVolume", volume), vol("NetVolume", volume)];
|
||||
}
|
||||
|
||||
/** Geländer: Länge. */
|
||||
export function railingQuantities(length: number): Qty[] {
|
||||
return [len("Length", length)];
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
// Treppen im IFC-Export ([B5], 28.10.): 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 (IfcRelAggregates). Quelle sind dieselben Ableitungen wie im 3D-Viewer
|
||||
// (`emitStairs` Tritt-Prismen und Podest, `emitStairMeshes` glatte Ortbeton-Laufplatte,
|
||||
// `emitStairRailings`), je Treppe mit einem Ein-Treppen-Projekt aufgerufen (die Ableitungen liefern keine
|
||||
// ids). Dieses Modul sammelt und rechnet die Basismengen; die Entitäten schreibt Rust (`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, wie im 3D).
|
||||
|
||||
import type { Project, Stair, Vec2 } from "../model/types";
|
||||
import { getStairType } from "../model/types";
|
||||
import { stairVerticalExtent } from "../model/wall";
|
||||
import { stairGeometry } from "../geometry/stair";
|
||||
import type { RSlab } from "../plan/toWalls3d";
|
||||
import { orientOutward } from "./meshOrient";
|
||||
import { flightQuantities, meshVolume, railingQuantities, ringArea, slabQuantities, type Qty } from "./ifcQuantities";
|
||||
import { emitStairMeshes, emitStairRailings, emitStairs } from "./model3dParts";
|
||||
|
||||
/** Ein Prisma (Profil in Welt-XY, Unterkante relativ zum Geschoss, Tiefe). */
|
||||
export interface StairSolid {
|
||||
pts: Vec2[];
|
||||
zRel: number;
|
||||
depth: number;
|
||||
}
|
||||
|
||||
export interface StairFlightParts {
|
||||
name: string;
|
||||
risers: number;
|
||||
treads: number;
|
||||
riserHeight: number;
|
||||
treadLength: number;
|
||||
/** IfcStairFlightTypeEnum. */
|
||||
predefined: "STRAIGHT" | "SPIRAL";
|
||||
quantities: Qty[];
|
||||
/** Entweder Prismen oder ein Dreiecks-Netz (IFC: x, y, z-hoch, Z relativ zum Geschoss). */
|
||||
solids?: StairSolid[];
|
||||
mesh?: { positions: number[]; indices: number[] };
|
||||
}
|
||||
|
||||
export interface StairParts {
|
||||
flights: StairFlightParts[];
|
||||
landing: { name: string; pts: Vec2[]; zRel: number; depth: number; quantities: Qty[] } | null;
|
||||
rail: { name: string; predefined: "HANDRAIL"; mesh: { positions: number[]; indices: number[] }; quantities: Qty[] } | null;
|
||||
}
|
||||
|
||||
const EPS = 1e-6;
|
||||
|
||||
/** Gleicher Umriss (gleiche Punktmenge, auch bei anderer Reihenfolge/Startpunkt). */
|
||||
function sameRing(a: readonly [number, number][], b: readonly Vec2[]): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
return a.every((p) => b.some((q) => Math.abs(p[0] - q.x) < EPS && Math.abs(p[1] - q.y) < EPS));
|
||||
}
|
||||
|
||||
const centroid = (pts: readonly Vec2[]): Vec2 => ({
|
||||
x: pts.reduce((s, p) => s + p.x, 0) / pts.length,
|
||||
y: pts.reduce((s, p) => s + p.y, 0) / pts.length,
|
||||
});
|
||||
|
||||
/** Netz (Modell x, y, z-hoch) nach IFC: Z relativ zum Geschoss, Wicklung nach aussen. */
|
||||
function ifcMesh(positions: readonly number[], indices: readonly number[], base: number): { positions: number[]; indices: number[] } {
|
||||
const pos = positions.slice();
|
||||
for (let i = 2; i < pos.length; i += 3) pos[i] -= base;
|
||||
return { positions: pos, indices: orientOutward(pos, indices) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Teile einer Treppe für den IFC-Export; `base` = Oberkante des Geschosses, dem die Treppe zugeordnet
|
||||
* ist (Z-Werte werden relativ dazu geschrieben). Leere Teile (keine Geometrie) ergeben `flights: []`,
|
||||
* `landing: null`, `rail: null` — der Aufrufer fällt dann auf den Fussabdruck zurück.
|
||||
*/
|
||||
export function stairParts(project: Project, stair: Stair, base: number): StairParts {
|
||||
const one: Project = { ...project, stairs: [stair] };
|
||||
const { zBottom, zTop } = stairVerticalExtent(project, stair);
|
||||
const rise = zTop - zBottom;
|
||||
const geo = stairGeometry(stair, rise);
|
||||
const slabs = emitStairs(one);
|
||||
const meshes = emitStairMeshes(one);
|
||||
const predefined = stair.shape === "spiral" ? "SPIRAL" : "STRAIGHT";
|
||||
|
||||
// Podest nur bei "L" (bei der Wendel ist das Polygon die Treppenmitte, Teil des Laufs).
|
||||
let landingSlab: RSlab | undefined;
|
||||
if (stair.shape === "L" && geo.landing) landingSlab = slabs.find((s) => sameRing(s.outline, geo.landing as Vec2[]));
|
||||
const treadSlabs = slabs.filter((s) => s !== landingSlab);
|
||||
|
||||
const solidOf = (s: RSlab): StairSolid => ({ pts: s.outline.map(([x, y]) => ({ x, y })), zRel: s.zBottom - base, depth: s.zTop - s.zBottom });
|
||||
const groups: RSlab[][] = [];
|
||||
if (landingSlab) {
|
||||
const top = landingSlab.zTop + EPS;
|
||||
const lower = treadSlabs.filter((s) => s.zTop <= top);
|
||||
const upper = treadSlabs.filter((s) => s.zTop > top);
|
||||
for (const g of [lower, upper]) if (g.length > 0) groups.push(g);
|
||||
} else if (treadSlabs.length > 0) {
|
||||
groups.push(treadSlabs);
|
||||
}
|
||||
|
||||
const flights: StairFlightParts[] = [];
|
||||
groups.forEach((g, k) => {
|
||||
// Tritte = verschiedene Oberkanten (Setzstufen-Platten und Nasen teilen die Höhe ihres Tritts).
|
||||
const tops = [...new Set(g.map((s) => Math.round(s.zTop / 1e-4)))];
|
||||
const treads = tops.length;
|
||||
// Lauflänge: Weg zwischen erstem und letztem Tritt (Schwerpunkte) plus eine Trittiefe, mit der Steigung.
|
||||
const lowest = g.reduce((m, s) => (s.zTop < m.zTop ? s : m), g[0]);
|
||||
const highest = g.reduce((m, s) => (s.zTop > m.zTop ? s : m), g[0]);
|
||||
const c0 = centroid(solidOf(lowest).pts);
|
||||
const c1 = centroid(solidOf(highest).pts);
|
||||
const run = Math.hypot(c1.x - c0.x, c1.y - c0.y) + geo.treadDepth;
|
||||
const lift = highest.zTop - lowest.zTop + geo.riserHeight;
|
||||
const solids = g.map(solidOf);
|
||||
const volume = g.reduce((s, x) => s + ringArea(x.outline.map(([px, py]) => ({ x: px, y: py }))) * (x.zTop - x.zBottom), 0);
|
||||
flights.push({
|
||||
name: groups.length > 1 ? `Lauf ${k + 1}` : "Lauf",
|
||||
risers: treads,
|
||||
treads,
|
||||
riserHeight: geo.riserHeight,
|
||||
treadLength: geo.treadDepth,
|
||||
predefined,
|
||||
quantities: flightQuantities(Math.hypot(run, lift), volume),
|
||||
solids,
|
||||
});
|
||||
});
|
||||
// Glatte Ortbeton-Laufplatte (gerade Betontreppe): ein Lauf als Netz.
|
||||
if (meshes.length > 0) {
|
||||
const positions: number[] = [];
|
||||
const indices: number[] = [];
|
||||
for (const m of meshes) {
|
||||
const at = positions.length / 3;
|
||||
for (const v of m.positions) positions.push(v);
|
||||
for (const i of m.indices) indices.push(at + i);
|
||||
}
|
||||
const mesh = ifcMesh(positions, indices, base);
|
||||
flights.push({
|
||||
name: flights.length > 0 ? `Lauf ${flights.length + 1}` : "Lauf",
|
||||
risers: geo.treads.length,
|
||||
treads: geo.treads.length,
|
||||
riserHeight: geo.riserHeight,
|
||||
treadLength: geo.treadDepth,
|
||||
predefined,
|
||||
quantities: flightQuantities(Math.hypot(stair.runLength, rise), meshVolume(mesh.positions, mesh.indices)),
|
||||
mesh,
|
||||
});
|
||||
}
|
||||
|
||||
let landing: StairParts["landing"] = null;
|
||||
if (landingSlab) {
|
||||
const s = solidOf(landingSlab);
|
||||
landing = { name: "Podest", pts: s.pts, zRel: s.zRel, depth: s.depth, quantities: slabQuantities(s.pts, [], s.depth) };
|
||||
}
|
||||
|
||||
let rail: StairParts["rail"] = null;
|
||||
const railMeshes = emitStairRailings(one);
|
||||
if (railMeshes.length > 0) {
|
||||
const positions: number[] = [];
|
||||
const indices: number[] = [];
|
||||
for (const m of railMeshes) {
|
||||
const at = positions.length / 3;
|
||||
for (const v of m.positions) positions.push(v);
|
||||
for (const i of m.indices) indices.push(at + i);
|
||||
}
|
||||
const sides = getStairType(project, stair)?.railing === "beide" ? 2 : 1;
|
||||
rail = {
|
||||
name: "Handlauf",
|
||||
predefined: "HANDRAIL",
|
||||
mesh: ifcMesh(positions, indices, base),
|
||||
quantities: railingQuantities(Math.hypot(stair.runLength, rise) * sides),
|
||||
};
|
||||
}
|
||||
return { flights, landing, rail };
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
// Wicklung von Dreiecks-Netzen nach aussen ausrichten — gemeinsam für Mesh-Export (OBJ/STL/glTF) und
|
||||
// IFC-Export. Die 3D-Ableitungen (`plan/toWalls3d/*`) liefern keine verlässliche Wicklung, weil render3d
|
||||
// doppelseitig zeichnet; Dateiformate verlangen sie.
|
||||
|
||||
/**
|
||||
* Richtet ein Dreiecks-Netz (Weltkoordinaten) so aus, dass die Flächennormalen nach AUSSEN zeigen:
|
||||
* 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. Offene
|
||||
* Komponenten haben kein sinnvolles Volumen und bleiben, wie sie sind (nach dem Konsistenz-Schritt).
|
||||
*/
|
||||
export function orientOutward(pos: readonly number[], idx: readonly number[]): number[] {
|
||||
const nTri = Math.floor(idx.length / 3);
|
||||
const nVert = pos.length / 3;
|
||||
const weld = new Map<string, number>();
|
||||
const canon = new Array<number>(nVert);
|
||||
const q = (v: number) => Math.round(v * 1e5);
|
||||
for (let i = 0; i < nVert; i++) {
|
||||
const key = `${q(pos[3 * i])},${q(pos[3 * i + 1])},${q(pos[3 * i + 2])}`;
|
||||
let c = weld.get(key);
|
||||
if (c === undefined) {
|
||||
c = weld.size;
|
||||
weld.set(key, c);
|
||||
}
|
||||
canon[i] = c;
|
||||
}
|
||||
const N = weld.size + 1;
|
||||
// Kante (min,max) → [(Dreieck, vorwärts?)…]
|
||||
const edges = new Map<number, number[]>();
|
||||
const corner = (t: number, k: number) => canon[idx[3 * t + k]];
|
||||
for (let t = 0; t < nTri; t++) {
|
||||
for (let k = 0; k < 3; k++) {
|
||||
const a = corner(t, k);
|
||||
const b = corner(t, (k + 1) % 3);
|
||||
if (a === b) continue;
|
||||
const key = Math.min(a, b) * N + Math.max(a, b);
|
||||
const list = edges.get(key);
|
||||
const entry = t * 2 + (a < b ? 1 : 0);
|
||||
if (list) list.push(entry);
|
||||
else edges.set(key, [entry]);
|
||||
}
|
||||
}
|
||||
// Nachbarschaft über Kanten mit genau zwei Dreiecken: Wicklungs-Paritaet (0 = gleich, 1 = gegenläufig noetig).
|
||||
const adj: number[][] = Array.from({ length: nTri }, () => []);
|
||||
for (const list of edges.values()) {
|
||||
if (list.length !== 2) continue;
|
||||
const [e1, e2] = list;
|
||||
const t1 = e1 >> 1;
|
||||
const t2 = e2 >> 1;
|
||||
if (t1 === t2) continue;
|
||||
// Gleiche Durchlaufrichtung = Widerspruch ⇒ eines muss gedreht werden.
|
||||
const parity = (e1 & 1) === (e2 & 1) ? 1 : 0;
|
||||
adj[t1].push(t2 * 2 + parity);
|
||||
adj[t2].push(t1 * 2 + parity);
|
||||
}
|
||||
const flip = new Array<number>(nTri).fill(-1);
|
||||
const out = idx.slice();
|
||||
for (let s = 0; s < nTri; s++) {
|
||||
if (flip[s] >= 0) continue;
|
||||
const comp: number[] = [s];
|
||||
flip[s] = 0;
|
||||
for (let h = 0; h < comp.length; h++) {
|
||||
const t = comp[h];
|
||||
for (const e of adj[t]) {
|
||||
const u = e >> 1;
|
||||
if (flip[u] < 0) {
|
||||
flip[u] = flip[t] ^ (e & 1);
|
||||
comp.push(u);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Volumen der Komponente mit den bisherigen Drehungen; Offenheit: Kante mit nur einem Dreieck.
|
||||
let vol = 0;
|
||||
for (const t of comp) {
|
||||
const [a, b, c] = flip[t] ? [idx[3 * t], idx[3 * t + 2], idx[3 * t + 1]] : [idx[3 * t], idx[3 * t + 1], idx[3 * t + 2]];
|
||||
const A = a * 3;
|
||||
const B = b * 3;
|
||||
const C = c * 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]);
|
||||
}
|
||||
const turn = vol < 0 ? 1 : 0;
|
||||
for (const t of comp) {
|
||||
if (flip[t] ^ turn) {
|
||||
out[3 * t + 1] = idx[3 * t + 2];
|
||||
out[3 * t + 2] = idx[3 * t + 1];
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// Testhilfe: liest die Mesh-Szene des Kerns (`meshExportData`, Kodierung `mesh_export.rs`) — z. B. das
|
||||
// öffnungsgenaue Wand-Volumen je Wand als Vergleichswert für IFC-Export und -Import.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { documentFor } from "../core/document";
|
||||
import { decodeExportFlat } from "./exportIfc";
|
||||
|
||||
export interface SceneGroup {
|
||||
name: string;
|
||||
kind: string;
|
||||
id: string;
|
||||
prims: { positions: Float64Array; indices: Float64Array }[];
|
||||
}
|
||||
|
||||
/** Knoten der Mesh-Szene (Welt x, Höhe, y; Wicklung nach aussen im Modell). */
|
||||
export function meshSceneGroups(project: Project): SceneGroup[] {
|
||||
const [b, text] = decodeExportFlat(documentFor(project).queryBin("meshExportData", [1, 1, 0]));
|
||||
const s = text.split("\0");
|
||||
let i = 2;
|
||||
i += 1 + b[i] * 7;
|
||||
i += 1 + b[i] * 2;
|
||||
const n = b[i++];
|
||||
const out: SceneGroup[] = [];
|
||||
for (let g = 0; g < n; g++) {
|
||||
const group: SceneGroup = { name: s[b[i]], kind: s[b[i + 1]], id: s[b[i + 2]], prims: [] };
|
||||
const np = b[i + 4];
|
||||
i += 5;
|
||||
for (let k = 0; k < np; k++) {
|
||||
const nv = b[i + 1];
|
||||
const positions = b.subarray(i + 2, i + 2 + nv * 3);
|
||||
i += 2 + nv * 3;
|
||||
const nt = b[i];
|
||||
const indices = b.subarray(i + 1, i + 1 + nt * 3);
|
||||
i += 1 + nt * 3;
|
||||
group.prims.push({ positions, indices });
|
||||
}
|
||||
out.push(group);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Volumen je Wand (Summe der Beträge je Schicht-Band, Öffnungen samt Laibungen ausgestanzt). */
|
||||
export function wallMeshVolumes(project: Project): Map<string, number> {
|
||||
const out = new Map<string, number>();
|
||||
for (const g of meshSceneGroups(project)) {
|
||||
if (g.kind !== "wall") continue;
|
||||
let sum = 0;
|
||||
for (const { positions: p, indices: x } of g.prims) {
|
||||
let v6 = 0;
|
||||
for (let t = 0; t + 2 < x.length; t += 3) {
|
||||
const [a, b, c] = [x[t] * 3, x[t + 1] * 3, x[t + 2] * 3];
|
||||
v6 += p[a] * (p[b + 1] * p[c + 2] - p[b + 2] * p[c + 1]) + p[a + 1] * (p[b + 2] * p[c] - p[b] * p[c + 2]) + p[a + 2] * (p[b] * p[c + 1] - p[b + 1] * p[c]);
|
||||
}
|
||||
sum += Math.abs(v6) / 6;
|
||||
}
|
||||
out.set(g.id, sum);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
// 3D-Teile einzelner Bauteile für die Exporte (OBJ/STL/glTF, IFC): dieselben Ableitungen wie das 3D,
|
||||
// gerechnet im Kern auf dem Projekt-Dokument (`queries.rs`, [K4]). Die Exporte rufen sie je Bauteil
|
||||
// mit einem Ein-Bauteil-Projekt auf (die Ableitungen liefern keine ids); damit das gemeinsame
|
||||
// Dokument der App nicht bei jedem Aufruf umgebaut wird, bekommt jeder Aufruf ein eigenes, kurzlebiges
|
||||
// Dokument.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import type { RMesh, RSlab } from "../plan/toWalls3d/shared";
|
||||
import { ProjectDocument, type QueryName } from "../core/document";
|
||||
|
||||
const DETAIL_CODE: Record<string, number> = { grob: 0, mittel: 1, fein: 2 };
|
||||
|
||||
function queryOnce<T>(project: Project, name: QueryName, args: number[] = [], text = ""): T {
|
||||
const doc = new ProjectDocument(project);
|
||||
try {
|
||||
return doc.query<T>(name, args, text);
|
||||
} finally {
|
||||
doc.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** Dach-Meshes (geschlossene Schicht-Körper je Dach). */
|
||||
export function emitRoofs(project: Project): RMesh[] {
|
||||
return queryOnce<RMesh[]>(project, "roofMeshes");
|
||||
}
|
||||
|
||||
/** Stützen als Profil-Extrusionen. */
|
||||
export function emitColumns(project: Project): RMesh[] {
|
||||
return queryOnce<RMesh[]>(project, "columnMeshes");
|
||||
}
|
||||
|
||||
/** Öffnungs-Einbauteile (Rahmen, Glas, Blatt) im Detailgrad `detail`. */
|
||||
export function emitOpeningMeshes(project: Project, detail: "grob" | "mittel" | "fein" = "fein"): RMesh[] {
|
||||
return queryOnce<RMesh[]>(project, "openingMeshes", [DETAIL_CODE[detail] ?? 2]);
|
||||
}
|
||||
|
||||
/** Treppentritte (und Podeste) als extrudierte Platten; `forSection` wie im Schnitt. */
|
||||
export function emitStairs(project: Project, forSection = false): RSlab[] {
|
||||
return queryOnce<RSlab[]>(project, "stairSlabs", [forSection ? 1 : 0]);
|
||||
}
|
||||
|
||||
/** Glatte Ortbeton-Laufplatten. */
|
||||
export function emitStairMeshes(project: Project): RMesh[] {
|
||||
return queryOnce<RMesh[]>(project, "stairMeshes");
|
||||
}
|
||||
|
||||
/** Handläufe und Pfosten. */
|
||||
export function emitStairRailings(project: Project): RMesh[] {
|
||||
return queryOnce<RMesh[]>(project, "stairRailings");
|
||||
}
|
||||
@@ -16,8 +16,7 @@ import { exportIfcSpf, ifcGuid } from "../export/exportIfc";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { ceilingVerticalExtent } from "../model/wall";
|
||||
import { polygonArea } from "../geometry/roomArea";
|
||||
import { pickGeometry } from "../plan/toWalls3d";
|
||||
import { wallCutMeshes } from "../plan/wallMeshCut";
|
||||
import { wallMeshVolumes } from "../export/meshScene.testutil";
|
||||
import { formatIfcReport, handleIfcWorkerRequest, ifcToImportedMeshes, readIfc, type IfcProduct, type IfcWorkerRequest } from "./ifcImport";
|
||||
|
||||
function volume(pos: ArrayLike<number>, idx: ArrayLike<number>): number {
|
||||
@@ -77,10 +76,7 @@ describe("IFC-Import: Rundreise mit dem eigenen Export", () => {
|
||||
// Wände: dieselben Ausschnitt-Netze wie der Export (Bänder je Wand). [B5] schreibt einfache Wände als
|
||||
// ungeschnittene Extrusion + IfcOpeningElement, der Import zieht die Öffnungen ab ([B3]) → bei allen
|
||||
// Wänden das ausgeschnittene Volumen.
|
||||
const bands = pickGeometry(sampleProject).walls;
|
||||
const cut = new Map<string, number>();
|
||||
const add = (m: Map<string, number>, id: string, v: number) => m.set(id, (m.get(id) ?? 0) + Math.abs(v));
|
||||
wallCutMeshes(bands).forEach((m, i) => add(cut, bands[i].wallId, volume(m.positions, m.indices)));
|
||||
const cut = wallMeshVolumes(sampleProject);
|
||||
const lines = new Map(ifc.split("\n").map((l) => [l.slice(0, l.indexOf("=")), l] as const));
|
||||
const wallsGot = products.filter((p) => p.ifcClass === "IfcWall");
|
||||
expect(wallsGot.length).toBe(sampleProject.walls.length);
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { roofMeshes } from "../toWalls3d";
|
||||
import { isWatertight } from "../wallMeshCut";
|
||||
import { sampleProject } from "../../model/sampleProject";
|
||||
import type { Project, Roof, RoofShape } from "../../model/types";
|
||||
|
||||
@@ -42,7 +41,8 @@ describe("Dach-Meshes geschlossen und nach aussen gewunden", () => {
|
||||
for (const m of meshes) {
|
||||
const c = closure(m);
|
||||
expect(c.vol6).toBeGreaterThan(0);
|
||||
if (exact.includes(shape)) expect(isWatertight(m, 1e-6)).toBe(true);
|
||||
// Dicht (Gauss: ∮ n dA = 0, wie `is_watertight` im Kern), sonst kleine Restlücke.
|
||||
if (exact.includes(shape)) expect(c.gap).toBeLessThan(1e-6);
|
||||
else expect(c.gap).toBeLessThan(0.01);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -245,10 +245,6 @@ export interface RModel3d {
|
||||
export const WALL_RGB: RRgb = [0.82, 0.8, 0.76];
|
||||
/** Etwas hellerer, kühlerer Ton für Deckenplatten (heben sich von Wänden ab). */
|
||||
export const SLAB_RGB: RRgb = [0.86, 0.86, 0.88];
|
||||
/** Gedämpftes Lehm-/Geländegrün-grau (three.js mats.terrain = 0xa9b0a2). */
|
||||
export const TERRAIN_RGB: RRgb = [169 / 255, 176 / 255, 162 / 255];
|
||||
/** Neutrales Hellgrau für importierte Meshes (three.js mats.mesh = 0x9fa6ae). */
|
||||
export const IMPORTED_RGB: RRgb = [159 / 255, 166 / 255, 174 / 255];
|
||||
/** Fallback-Farbe für 2D-Zeichnungen ohne color/lineStyle/Kategorie (wie drawing2DColor in Viewport3D.tsx, "#888888"). */
|
||||
export const DRAWING_LINE_FALLBACK_RGB: RRgb = [0x88 / 255, 0x88 / 255, 0x88 / 255];
|
||||
|
||||
|
||||
@@ -1,169 +0,0 @@
|
||||
// Unit-Tests für den gemeinsamen Wand-Loch-Ausschnitt-Generator (wallMeshCut.ts,
|
||||
// TS-Port von render3d/src/mesh.rs::extrude_layer_segment_with_holes). Prüft die
|
||||
// geometrische Zerlegung (gleiche Rechteck-Anzahl wie die Rust-Referenz), nicht
|
||||
// nur „läuft".
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { isWatertight, solidSubrects, wallCutMesh } from "./wallMeshCut";
|
||||
import type { CutMesh } from "./wallMeshCut";
|
||||
import type { RWall } from "./toWalls3d";
|
||||
|
||||
/**
|
||||
* Geschlossene-Fläche-Kennzahlen: Vektorfläche ∮ n dA (Σ (v1−v0)×(v2−v0)) und
|
||||
* 6× signiertes Volumen (Σ v0·(v1×v2)). Dienen den Watertight-Tests direkt (statt
|
||||
* eines naiven Kanten-Manifold-Zählers, der an den legitimen T-Stössen der vollen
|
||||
* Deckel/Boden-Streifen scheitern würde — siehe isWatertight-Doc in wallMeshCut.ts).
|
||||
*/
|
||||
function surfaceIntegrals(m: CutMesh): { areaLen: number; vol6: number } {
|
||||
const p = m.positions;
|
||||
let ax = 0;
|
||||
let ay = 0;
|
||||
let az = 0;
|
||||
let vol6 = 0;
|
||||
for (let t = 0; t < m.indices.length; t += 3) {
|
||||
const i0 = m.indices[t] * 3;
|
||||
const i1 = m.indices[t + 1] * 3;
|
||||
const i2 = m.indices[t + 2] * 3;
|
||||
const e1 = [p[i1] - p[i0], p[i1 + 1] - p[i0 + 1], p[i1 + 2] - p[i0 + 2]];
|
||||
const e2 = [p[i2] - p[i0], p[i2 + 1] - p[i0 + 1], p[i2 + 2] - p[i0 + 2]];
|
||||
const cx = e1[1] * e2[2] - e1[2] * e2[1];
|
||||
const cy = e1[2] * e2[0] - e1[0] * e2[2];
|
||||
const cz = e1[0] * e2[1] - e1[1] * e2[0];
|
||||
ax += cx;
|
||||
ay += cy;
|
||||
az += cz;
|
||||
vol6 += p[i0] * cx + p[i0 + 1] * cy + p[i0 + 2] * cz;
|
||||
}
|
||||
return { areaLen: Math.hypot(ax, ay, az), vol6 };
|
||||
}
|
||||
|
||||
/** Ein RWall-Band mit optionalen Löchern (frei stehend, Achse entlang +x). */
|
||||
function band(holes?: RWall["holes"]): RWall {
|
||||
return {
|
||||
start: [0, 0],
|
||||
end: [5, 0],
|
||||
thickness: 0.4,
|
||||
height: 2.6,
|
||||
baseElevation: 0,
|
||||
color: [0.8, 0.8, 0.8],
|
||||
layers: [],
|
||||
wallId: "W1",
|
||||
...(holes ? { holes } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
describe("solidSubrects — Koordinaten-Kompression (Rust-Parität)", () => {
|
||||
it("ohne Loch: genau ein Vollrechteck", () => {
|
||||
expect(solidSubrects(0, 5, 0, 2.6, [])).toEqual([[0, 5, 0, 2.6]]);
|
||||
});
|
||||
|
||||
it("ein voll im Inneren liegendes Loch → 3×3-Gitter minus 1 = 8 solide Teilrechtecke", () => {
|
||||
const rects = solidSubrects(0, 5, 0, 2.6, [[2, 3, 0.9, 2.4]]);
|
||||
expect(rects).toHaveLength(8);
|
||||
// Keiner der Teilrechteck-Mittelpunkte liegt im Loch.
|
||||
for (const [ua, ub, za, zb] of rects) {
|
||||
const cu = (ua + ub) / 2;
|
||||
const cz = (za + zb) / 2;
|
||||
expect(cu > 2 && cu < 3 && cz > 0.9 && cz < 2.4).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("randständiges Loch (Tür am Boden) → 3×2-Gitter minus 1 = 5 Teilrechtecke", () => {
|
||||
expect(solidSubrects(0, 5, 0, 2.6, [[2, 3, 0, 2.1]])).toHaveLength(5);
|
||||
});
|
||||
|
||||
it("zwei versetzt übereinanderliegende Löcher: keine überlappenden/entarteten Teilrechtecke", () => {
|
||||
const rects = solidSubrects(0, 5, 0, 2.8, [
|
||||
[1, 2, 0.9, 1.4],
|
||||
[3, 4, 1.6, 2.2],
|
||||
]);
|
||||
// Alle Teilrechtecke haben echte Ausdehnung und liegen ausserhalb beider Löcher.
|
||||
for (const [ua, ub, za, zb] of rects) {
|
||||
expect(ub - ua).toBeGreaterThan(0);
|
||||
expect(zb - za).toBeGreaterThan(0);
|
||||
}
|
||||
expect(rects.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("wallCutMesh — Loch-Ausschnitt-Mesh", () => {
|
||||
it("ohne Loch: 12 Dreiecke (volle Box-Äquivalenz)", () => {
|
||||
const m = wallCutMesh(band());
|
||||
expect(m.indices.length / 3).toBe(12);
|
||||
});
|
||||
|
||||
it("Fenster im Inneren: 48 Dreiecke, 4 Laibungen, Loch-Rand-Vertices vorhanden", () => {
|
||||
const m = wallCutMesh(band([{ from: 2, to: 3, zBottom: 0.9, zTop: 2.4 }]));
|
||||
expect(m.indices.length / 3).toBe(48);
|
||||
// Vertices an allen vier Loch-Rändern (Brüstung/Sturz/links/rechts).
|
||||
const has = (axis: number, val: number) => {
|
||||
for (let i = 0; i < m.positions.length; i += 3) {
|
||||
if (Math.abs(m.positions[i + axis] - val) < 1e-6) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
expect(has(1, 0.9)).toBe(true); // y = Brüstungs-OK
|
||||
expect(has(1, 2.4)).toBe(true); // y = Sturz-UK
|
||||
expect(has(0, 2)).toBe(true); // x = linke Kante
|
||||
expect(has(0, 3)).toBe(true); // x = rechte Kante
|
||||
// KEIN Vertex liegt strikt im offenen Loch-Rechteck (die Fläche ist wirklich weg).
|
||||
for (let i = 0; i < m.positions.length; i += 3) {
|
||||
const x = m.positions[i];
|
||||
const y = m.positions[i + 1];
|
||||
const strictlyInside = x > 2 + 1e-6 && x < 3 - 1e-6 && y > 0.9 + 1e-6 && y < 2.4 - 1e-6;
|
||||
expect(strictlyInside).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("Tür am Boden: 36 Dreiecke (untere Laibung entfällt, Boden bekommt die Lücke)", () => {
|
||||
const m = wallCutMesh(band([{ from: 2, to: 3, zBottom: 0, zTop: 2.1 }]));
|
||||
expect(m.indices.length / 3).toBe(36);
|
||||
});
|
||||
|
||||
it("alle Dreiecks-Indizes referenzieren existierende Vertices", () => {
|
||||
const m = wallCutMesh(band([{ from: 2, to: 3, zBottom: 0.9, zTop: 2.4 }]));
|
||||
const vcount = m.positions.length / 3;
|
||||
for (const idx of m.indices) {
|
||||
expect(idx).toBeGreaterThanOrEqual(0);
|
||||
expect(idx).toBeLessThan(vcount);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("wallCutMesh — Wasserdichtigkeit + Aussen-Orientierung (der hohl/offen-Bug)", () => {
|
||||
it("volle Wand OHNE Loch: geschlossen (∮ n dA = 0), Normalen aussen (Volumen = L·T·H)", () => {
|
||||
const m = wallCutMesh(band());
|
||||
const { areaLen, vol6 } = surfaceIntegrals(m);
|
||||
expect(areaLen).toBeLessThan(1e-6); // ∮ n dA = 0 ⇒ kein Loch, kein invertiertes Dreieck
|
||||
expect(vol6 / 6).toBeCloseTo(5 * 0.4 * 2.6, 6); // > 0 ⇒ aussen orientiert
|
||||
expect(isWatertight(m)).toBe(true);
|
||||
});
|
||||
|
||||
it("Wand mit Fenster: trotz T-Stösse geschlossen + aussen orientiert (Volumen = Wand − Fensterquader)", () => {
|
||||
const m = wallCutMesh(band([{ from: 2, to: 3, zBottom: 0.9, zTop: 2.4 }]));
|
||||
const { areaLen, vol6 } = surfaceIntegrals(m);
|
||||
expect(areaLen).toBeLessThan(1e-6);
|
||||
expect(vol6 / 6).toBeCloseTo(5 * 0.4 * 2.6 - 1 * 0.4 * (2.4 - 0.9), 6);
|
||||
expect(isWatertight(m)).toBe(true);
|
||||
});
|
||||
|
||||
it("eine EINZELNE invertierte Kappe würde erkannt (Regressionswächter gegen falsche Wicklung)", () => {
|
||||
// Bau die volle Wand, kehre die Wicklung EINES Dreiecks um → nicht mehr dicht.
|
||||
const m = wallCutMesh(band());
|
||||
const broken: CutMesh = { positions: m.positions.slice(), indices: m.indices.slice() };
|
||||
[broken.indices[1], broken.indices[2]] = [broken.indices[2], broken.indices[1]];
|
||||
expect(isWatertight(broken)).toBe(false);
|
||||
});
|
||||
|
||||
it("Türwand ist ein GESCHLOSSENER Prisma-Körper (Querschnitt = П-Polygon, Türkerbe umlaufend)", () => {
|
||||
// Die Türkerbe ist eine Einbuchtung der UNTEREN Umriss-Kante (kein Loch): der
|
||||
// Querschnitt bleibt EIN einfaches, geschlossenes Polygon (П-Form), das über
|
||||
// die Dicke extrudiert wieder einen geschlossenen Körper ergibt. Die fehlende
|
||||
// untere Laibung und die Boden-Lücke heben sich in ∮ n dA exakt auf.
|
||||
const m = wallCutMesh(band([{ from: 2, to: 3, zBottom: 0, zTop: 2.1 }]));
|
||||
const { areaLen, vol6 } = surfaceIntegrals(m);
|
||||
expect(areaLen).toBeLessThan(1e-6);
|
||||
expect(vol6 / 6).toBeCloseTo(5 * 0.4 * 2.6 - 1 * 0.4 * 2.1, 6);
|
||||
expect(isWatertight(m)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,98 +0,0 @@
|
||||
// Wand-Mesh MIT echtem Loch-Ausschnitt (Fenster/Türen) für die Datei-Exporte
|
||||
// (STL/OBJ/IFC): aus einem RWall-Band (Achse `start→end`, `thickness`,
|
||||
// `baseElevation`, `height` + rechteckige `holes`) entsteht das Dreiecks-Mesh mit
|
||||
// ausgestanzten Öffnungen inkl. Laibungen — so sehen die Exporte aus wie die
|
||||
// 3D-Ansicht. Gerechnet wird im Rust-Kern (`src-tauri/core/src/wall_mesh_cut.rs`,
|
||||
// dieselbe Zerlegung wie `render3d/src/mesh.rs::extrude_layer_segment_with_holes`,
|
||||
// ohne Gehrung: die Bänder sind an den Enden schon gekürzt). Hier bleibt die
|
||||
// flache Übergabe.
|
||||
//
|
||||
// ACHSEN: Modell (x, y) → Welt (x, Höhe, y), Y-UP — wie exportMesh.ts und der
|
||||
// 3D-Viewer.
|
||||
|
||||
import { core } from "../engine/coreWasm";
|
||||
import { FlatWriter } from "../geometry/coreFlat";
|
||||
import type { RWall } from "./toWalls3d";
|
||||
|
||||
/**
|
||||
* Ein Dreiecks-Mesh in LOKALEN (0-basierten) Indizes: `positions` flach
|
||||
* (x,y,z, …) in Weltmetern (Y-up), `indices` je 3 = ein Dreieck.
|
||||
*/
|
||||
export interface CutMesh {
|
||||
positions: number[];
|
||||
indices: number[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Zerlegt das Rechteck `[uLo,uHi]×[zLo,zHi]` MINUS `holes` (`[u0,u1,z0,z1]`) in
|
||||
* achsparallele, disjunkte solide Teilrechtecke (Koordinaten-Kompression wie
|
||||
* `mesh.rs::solid_subrects`).
|
||||
*/
|
||||
export function solidSubrects(
|
||||
uLo: number,
|
||||
uHi: number,
|
||||
zLo: number,
|
||||
zHi: number,
|
||||
holes: Array<[number, number, number, number]>,
|
||||
): Array<[number, number, number, number]> {
|
||||
const flat = new Float64Array(holes.length * 4);
|
||||
holes.forEach((h, i) => flat.set(h, i * 4));
|
||||
const r = core().solid_subrects_flat(uLo, uHi, zLo, zHi, flat);
|
||||
const out: Array<[number, number, number, number]> = [];
|
||||
for (let i = 0; i + 4 <= r.length; i += 4) out.push([r[i], r[i + 1], r[i + 2], r[i + 3]]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ob ein Mesh eine GESCHLOSSENE, nach aussen gewundene Fläche ist — Gauss-
|
||||
* Kriterium (∮ n dA = 0 und signiertes Volumen > 0) statt eines Kanten-Zählers,
|
||||
* damit die legitimen T-Stösse der vollen Deckel/Boden-Streifen nicht als
|
||||
* „offen" gelten. Rechnet im Kern; die Übergabe-Puffer werden wiederverwendet
|
||||
* (frische Typed Arrays je Aufruf kosteten mehr als die Rechnung selbst).
|
||||
*/
|
||||
export function isWatertight(mesh: CutMesh, eps = 1e-6): boolean {
|
||||
const p = mesh.positions;
|
||||
const x = mesh.indices;
|
||||
if (scratchPos.length < p.length) scratchPos = new Float64Array(p.length * 2);
|
||||
if (scratchIdx.length < x.length) scratchIdx = new Uint32Array(x.length * 2);
|
||||
for (let i = 0; i < p.length; i++) scratchPos[i] = p[i];
|
||||
// Ungültige Indizes (negativ, gebrochen, NaN) zeigen ins Leere ⇒ „nicht dicht".
|
||||
for (let i = 0; i < x.length; i++) scratchIdx[i] = Number.isInteger(x[i]) && x[i] >= 0 && x[i] < 0xffffffff ? x[i] : 0xffffffff;
|
||||
return core().is_watertight_flat(scratchPos.subarray(0, p.length), scratchIdx.subarray(0, x.length), eps);
|
||||
}
|
||||
|
||||
let scratchPos = new Float64Array(1024);
|
||||
let scratchIdx = new Uint32Array(1024);
|
||||
|
||||
/**
|
||||
* Loch-Ausschnitt-Meshes vieler Bänder in EINEM Kern-Aufruf (Reihenfolge wie
|
||||
* `walls`). Aufbau je Band: Langseiten (Gitter minus Löcher), Deckel/Boden und
|
||||
* Stirnkappen minus randständiger Löcher, Laibungen je Loch. Ohne Löcher die
|
||||
* volle Box; entartete Bänder liefern ein leeres Mesh.
|
||||
*/
|
||||
export function wallCutMeshes(walls: readonly RWall[]): CutMesh[] {
|
||||
const w = new FlatWriter().num(walls.length);
|
||||
for (const b of walls) {
|
||||
const holes = b.holes ?? [];
|
||||
w.num(b.start[0], b.start[1], b.end[0], b.end[1], b.thickness, b.baseElevation, b.height, holes.length);
|
||||
for (const h of holes) w.num(h.from, h.to, h.zBottom, h.zTop);
|
||||
}
|
||||
const buf = core().wall_cut_meshes_flat(w.done());
|
||||
const out: CutMesh[] = [];
|
||||
let i = 1;
|
||||
for (let k = 0; k < walls.length; k++) {
|
||||
const len = i < buf.length ? buf[i++] : 0;
|
||||
const positions = new Array<number>(len);
|
||||
for (let j = 0; j < len; j++) positions[j] = buf[i + j];
|
||||
i += len;
|
||||
const indices = new Array<number>(len / 3);
|
||||
for (let j = 0; j < len / 3; j++) indices[j] = j;
|
||||
out.push({ positions, indices });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Loch-Ausschnitt-Mesh EINES Bandes (s. {@link wallCutMeshes}). */
|
||||
export function wallCutMesh(w: RWall): CutMesh {
|
||||
return wallCutMeshes([w])[0];
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { t } from "../i18n";
|
||||
import { Dropdown } from "./Dropdown";
|
||||
import type { IfcExportOptions, IfcSchema } from "../export/ifcClassification";
|
||||
import type { IfcExportOptions, IfcSchema } from "../export/exportIfc";
|
||||
|
||||
/** Direkt-herunterladbare Exportformate (mit Datei-Endung). */
|
||||
export type ExportSaveFormat = "csv" | "ifc" | "obj" | "stl" | "glb" | "step";
|
||||
|
||||
Reference in new issue
Block a user