[K4] S2: OBJ/STL-Export in Rust (export_mesh.rs); exportMesh.ts nur noch Fassade

This commit is contained in:
karim committed 2026-10-28 02:24:13 +01:00
1 parent f16cf44b60
commit 96a5c219ec
5 files changed
+278 -346

No files matched your search

+256
View File
@@ -0,0 +1,256 @@
//! OBJ-/STL-Export des 3D-Gebäudemodells als reines Dreiecks-Netz ([K4] S2, vorher
//! `src/export/exportMesh.ts`). Wände: dieselben Schicht-Bänder wie der 3D-Viewer, gelochte Bänder
//! öffnungsgenau ausgeschnitten (`wall_mesh_cut`); Decken und Extrusionen als Umriss-Prismen
//! (Ear-Clipping-Kappen, Seitenmantel, optional verjüngt). Achsen: Modell (x, y) → Welt (x, Höhe, y),
//! Y-up, rechtshändig, Meter.
use crate::js_fmt::to_fixed;
use crate::model::*;
use crate::model3d;
use crate::wall_mesh_cut::{wall_cut_mesh, CutWall};
struct MeshGroup {
name: String,
positions: Vec<f64>,
indices: Vec<u32>,
}
/// OBJ-Gruppennamen dürfen keine Whitespaces/Sonderzeichen enthalten.
fn sanitize_name(id: &str) -> String {
let s: String = id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' }).collect();
if s.is_empty() {
"x".into()
} else {
s
}
}
/// Die 6 Quader-Seiten als Eckpunkt-Quadrupel, nach aussen gewunden.
const BOX_QUADS: [[u32; 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]];
fn push_wall_box(g: &mut MeshGroup, w: &model3d::RWall) {
let [sx, sy] = w.start;
let [ex, ey] = w.end;
let dx = ex - sx;
let dz = ey - sy;
let len = crate::jsmath::hypot2(dx, dz);
if len < 1e-9 || w.height <= 1e-9 || w.thickness <= 1e-9 {
return;
}
let (ax, az) = (dx / len, dz / len);
let (nx, nz) = (az, -ax);
let (half_len, half_height, half_thick) = (len / 2.0, w.height / 2.0, w.thickness / 2.0);
let (cx, cz) = ((sx + ex) / 2.0, (sy + ey) / 2.0);
let cy = w.base_elevation + w.height / 2.0;
let base = (g.positions.len() / 3) as u32;
for i in 0..8u32 {
let s_l = if i & 1 != 0 { 1.0 } else { -1.0 };
let s_h = if i & 2 != 0 { 1.0 } else { -1.0 };
let s_t = if i & 4 != 0 { 1.0 } else { -1.0 };
g.positions.extend([cx + s_l * half_len * ax + s_t * half_thick * nx, cy + s_h * half_height, cz + s_l * half_len * az + s_t * half_thick * nz]);
}
for [a, b, c, d] in BOX_QUADS {
g.indices.extend([base + a, base + b, base + c, base + a, base + c, base + d]);
}
}
fn signed_area_xy(pts: &[Vec2]) -> f64 {
let mut a = 0.0;
let mut j = pts.len().wrapping_sub(1);
for i in 0..pts.len() {
a += pts[j].x * pts[i].y - pts[i].x * pts[j].y;
j = i;
}
a / 2.0
}
fn push_prism(g: &mut MeshGroup, 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() as u32;
let (mut cx, mut cy_model) = (0.0, 0.0);
for p in &ccw {
cx += p.x;
cy_model += p.y;
}
cx /= n as f64;
cy_model /= n as f64;
let t = taper.clamp(0.0, 1.0);
let base = (g.positions.len() / 3) as u32;
for p in &ccw {
g.positions.extend([p.x, z_bottom, p.y]);
}
for p in &ccw {
let tx = cx + (p.x - cx) * (1.0 - t);
let ty = cy_model + (p.y - cy_model) * (1.0 - t);
g.positions.extend([tx, z_top, ty]);
}
let pts: Vec<crate::hatch::V2> = ccw.iter().map(|p| crate::hatch::V2 { x: p.x, y: p.y }).collect();
let cap = crate::gpu_compile::triangulate(&pts);
for tri in cap.chunks_exact(3) {
let (a, b, c) = (tri[0], tri[1], tri[2]);
g.indices.extend([base + a, base + b, base + c]);
g.indices.extend([base + n + a, base + n + c, base + n + b]);
}
for i in 0..n {
let j = (i + 1) % n;
let (bi, bj, ti, tj) = (base + i, base + j, base + n + i, base + n + j);
g.indices.extend([bi, ti, tj]);
g.indices.extend([bi, tj, bj]);
}
}
fn build_groups(p: &Project) -> Result<Vec<MeshGroup>, String> {
let mut groups: Vec<MeshGroup> = Vec::new();
let walls = model3d::emit_walls(p, true)?;
let mut by_id: Vec<(String, usize)> = Vec::new();
for w in &walls {
let gi = match by_id.iter().find(|(id, _)| *id == w.wall_id) {
Some((_, gi)) => *gi,
None => {
groups.push(MeshGroup { name: format!("Wand_{}", sanitize_name(&w.wall_id)), positions: vec![], indices: vec![] });
by_id.push((w.wall_id.clone(), groups.len() - 1));
groups.len() - 1
}
};
let g = &mut groups[gi];
if w.holes.as_ref().is_some_and(|h| !h.is_empty()) {
let cw = CutWall {
start: w.start,
end: w.end,
thickness: w.thickness,
base_elevation: w.base_elevation,
height: w.height,
holes: w.holes.as_ref().map_or(vec![], |hs| hs.iter().map(|h| [h.from, h.to, h.z_bottom, h.z_top]).collect()),
};
let finite = cw.start.iter().chain(&cw.end).all(|v| v.is_finite()) && [cw.thickness, cw.base_elevation, cw.height].iter().all(|v| v.is_finite()) && cw.holes.iter().flatten().all(|v| v.is_finite());
let cut = if finite { wall_cut_mesh(&cw) } else { Vec::new() };
let base = (g.positions.len() / 3) as u32;
g.positions.extend_from_slice(&cut);
g.indices.extend((0..(cut.len() / 3) as u32).map(|i| base + i));
} else {
push_wall_box(g, w);
}
}
for s in model3d::emit_slabs(p) {
let mut g = MeshGroup { name: format!("Decke_{}", sanitize_name(&s.ceiling_id)), positions: vec![], indices: vec![] };
let outline: Vec<Vec2> = s.outline.iter().map(|&[x, y]| Vec2 { x, y }).collect();
push_prism(&mut g, &outline, s.z_bottom, s.z_top, 0.0);
groups.push(g);
}
for solid in p.extruded_solids.as_deref().unwrap_or(&[]) {
if solid.points.len() < 3 || solid.height <= 0.0 {
continue;
}
let base_z = p.floor(&solid.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0));
let mut g = MeshGroup { name: format!("Extrusion_{}", sanitize_name(&solid.id)), positions: vec![], indices: vec![] };
push_prism(&mut g, &solid.points, base_z, base_z + solid.height, solid.taper.unwrap_or(0.0));
groups.push(g);
}
Ok(groups.into_iter().filter(|g| !g.indices.is_empty()).collect())
}
/// Kompakte Zahlformatierung (bis 6 Nachkommastellen, ohne Nullen, mindestens `.0`).
fn fmt(v: f64) -> String {
if !v.is_finite() {
return "0.0".into();
}
let mut s = to_fixed(v, 6);
let trimmed = s.trim_end_matches('0').len();
s.truncate(trimmed);
if s.ends_with('.') {
s.push('0');
}
s
}
/// Wavefront-OBJ des Gebäudemodells.
pub fn export_obj(p: &Project) -> Result<String, String> {
let groups = build_groups(p)?;
let mut lines: Vec<String> = vec![
"# DOSSIER OBJ-Export - Dreiecks-Mesh des 3D-Gebaeudemodells".into(),
"# Achsen: rechtshaendig, Y-up (Y = Hoehe ueber OKFF), wie der 3D-Viewer.".into(),
"# Waende: Schicht-Baender mit oeffnungsgenau ausgeschnittenen Loechern (inkl. Laibungen).".into(),
"# Decken/Extrusionen: Umriss-Prisma (Ear-Clipping-Triangulierung).".into(),
];
let mut offset = 0u32;
for g in &groups {
let vert_count = (g.positions.len() / 3) as u32;
if vert_count == 0 {
continue;
}
lines.push(format!("o {}", g.name));
for c in g.positions.chunks_exact(3) {
lines.push(format!("v {} {} {}", fmt(c[0]), fmt(c[1]), fmt(c[2])));
}
for t in g.indices.chunks_exact(3) {
lines.push(format!("f {} {} {}", t[0] + 1 + offset, t[1] + 1 + offset, t[2] + 1 + offset));
}
offset += vert_count;
}
Ok(lines.join("\n") + "\n")
}
/// ASCII-STL des Gebäudemodells.
pub fn export_stl(p: &Project) -> Result<String, String> {
let groups = build_groups(p)?;
let mut lines: Vec<String> = vec!["solid dossier".into()];
for g in &groups {
for t in g.indices.chunks_exact(3) {
let pt = |i: u32| -> [f64; 3] {
let k = i as usize * 3;
[g.positions[k], g.positions[k + 1], g.positions[k + 2]]
};
let (a, b, c) = (pt(t[0]), pt(t[1]), pt(t[2]));
let (ux, uy, uz) = (b[0] - a[0], b[1] - a[1], b[2] - a[2]);
let (vx, vy, vz) = (c[0] - a[0], c[1] - a[1], c[2] - a[2]);
let (mut nx, mut ny, mut nz) = (uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx);
let len = crate::jsmath::hypot(&[nx, ny, nz]);
if len > 1e-12 {
nx /= len;
ny /= len;
nz /= len;
} else {
nx = 0.0;
ny = 0.0;
nz = 0.0;
}
lines.push(format!("facet normal {} {} {}", fmt(nx), fmt(ny), fmt(nz)));
lines.push("outer loop".into());
for v in [a, b, c] {
lines.push(format!("vertex {} {} {}", fmt(v[0]), fmt(v[1]), fmt(v[2])));
}
lines.push("endloop".into());
lines.push("endfacet".into());
}
}
lines.push("endsolid dossier".into());
Ok(lines.join("\n") + "\n")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn zahlformat() {
assert_eq!(fmt(1.0), "1.0");
assert_eq!(fmt(1.5), "1.5");
assert_eq!(fmt(0.0), "0.0");
assert_eq!(fmt(10.0), "10.0");
assert_eq!(fmt(0.1234567), "0.123457");
assert_eq!(fmt(f64::NAN), "0.0");
}
#[test]
fn beispielprojekt() {
let p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap();
let obj = export_obj(&p).unwrap();
assert!(obj.contains("\no Wand_"));
let stl = export_stl(&p).unwrap();
assert!(stl.starts_with("solid dossier\n") && stl.ends_with("endsolid dossier\n"));
assert!(export_obj(&Project::default()).unwrap().lines().count() == 4);
}
}
+1
View File
@@ -5,6 +5,7 @@
//! Datenübergabe: flache `f64`-Puffer (s. [`flat`]), kein JSON — schnell und ohne Serde-Kosten.
pub mod export_ifc;
pub mod export_mesh;
pub mod export_schedule;
pub mod flat;
pub mod geo_rebase;
+3 -1
View File
@@ -2,7 +2,7 @@
//! antwortet. TS ruft sie über `ProjectDocument.query(name, args, text)`.
use crate::model::Project;
use crate::{export_schedule, kennzahlen, model3d, site_rules, sun};
use crate::{export_mesh, export_schedule, kennzahlen, model3d, site_rules, sun};
fn json<T: serde::Serialize>(v: &T) -> Result<String, String> {
serde_json::to_string(v).map_err(|e| e.to_string())
@@ -28,6 +28,8 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
("roofCutLayers", _) => json(&model3d::emit_roof_cut_layers(p)?),
("scheduleRows", _) => json(&export_schedule::schedule_rows(p)),
("scheduleCsv", 1) => Ok(export_schedule::export_schedule_csv(p, text, args[0] != 0.0)),
("objFile", _) => Ok(export_mesh::export_obj(p)?),
("stlFile", _) => Ok(export_mesh::export_stl(p)?),
("pickGeometry", _) => json(&model3d::pick_geometry(p)?),
("model3dParts", 3) => json(&model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?),
_ => Err(format!("Unbekannte Abfrage: {name}")),
+2
View File
@@ -27,6 +27,8 @@ export type QueryName =
| "roofCutLayers"
| "scheduleRows"
| "scheduleCsv"
| "objFile"
| "stlFile"
| "pickGeometry"
| "model3dParts";
+16 -345
View File
@@ -1,356 +1,27 @@
// OBJ-/STL-Export des 3D-Gebäudemodells als reines Dreiecks-Mesh. Pures Modul
// (kein Datei-IO, kein WASM) — Architektur wie exportDxf.ts/exportSchedule.ts:
// buildGroups() liest das Projekt und liefert reine Zahlen-Arrays, exportObj()/
// exportStl() serialisieren sie synchron zu Text.
//
// 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: identisch zur bestehenden 3D-Pick-/Highlight-Geometrie
// (siehe `selectionHighlightLines` in toWalls3d.ts): Modell (x, y) → Welt
// (x, Höhe, y), Y-UP, rechtshändig. Ein Weltvertex (vx,vy,vz) entspricht also
// (Modell-x, Meter-Höhe, Modell-y) — exakt wie im 3D-Viewer.
// OBJ-/STL-Export des 3D-Gebäudemodells als reines Dreiecks-Mesh. Gerechnet wird im Rust-Kern
// (`src-tauri/core/src/export_mesh.rs`, [K4] S2) auf dem Projekt-Dokument:
// • Wände: dieselben Schicht-Bänder wie der 3D-Viewer (Gehrungen, Decken-Dominanz); Bänder mit
// Öffnungs-Löchern öffnungsgenau ausgeschnitten (inkl. Laibungen), lochlose als Box.
// • Decken und extrudierte Profile (truck): Umriss-Prisma mit Ear-Clipping-Kappen, Seitenmantel,
// `taper` linear zum Schwerpunkt. (Bewusst nicht die asynchronen truck-Dreiecke: der Export
// bleibt synchron.)
// Achsen: Modell (x, y) → Welt (x, Höhe, y), Y-up, rechtshändig, Meter — wie der 3D-Viewer.
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 { Project } from "../model/types";
import { documentFor } from "../core/document";
/**
* Eine Mesh-Gruppe (ein Bauteil-Vorkommen: Wand/Decke/Extrusion) mit LOKALEN
* (0-basierten) Vertex-/Dreiecks-Indizes. `exportObj` verschiebt die Indizes
* beim Serialisieren auf die globale, 1-basierte OBJ-Nummerierung; `exportStl`
* braucht gar keine Indizes über Gruppen hinweg (STL ist unindiziert).
*/
interface MeshGroup {
name: string;
/** 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[];
}
function newGroup(name: string): MeshGroup {
return { name, positions: [], indices: [] };
}
/** 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: MeshGroup, 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: MeshGroup, 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: MeshGroup,
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);
}
}
/** Baut alle Mesh-Gruppen (Wände, Decken, Extrusionen) des Projekts. */
function buildGroups(project: Project): MeshGroup[] {
const groups: MeshGroup[] = [];
const { walls, slabs } = pickGeometry(project);
// 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>();
// 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)}`);
wallGroups.set(w.wallId, g);
groups.push(g);
}
pushWall(g, w, cuts.get(w));
}
// Decken: ein Prisma je Decke.
for (const s of slabs) {
const g = newGroup(`Decke_${sanitizeName(s.ceilingId)}`);
const outline: Vec2[] = s.outline.map(([x, y]) => ({ x, y }));
pushPrism(g, 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)}`);
pushPrism(g, solid.points, baseZ, baseZ + solid.height, solid.taper ?? 0);
groups.push(g);
}
return groups.filter((g) => g.indices.length > 0);
}
/** Kompakte, verlustarme Zahlformatierung (bis 6 Nachkommastellen, ohne Nullen). */
function fmt(v: number): string {
if (!Number.isFinite(v)) return "0.0";
const s = v.toFixed(6);
return s.replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, ".0");
}
/**
* Baut einen vollständigen Wavefront-OBJ-String des 3D-Gebäudemodells (Meter,
* rechtshändig, Y-up — siehe Moduldoc). Ein `o`-Objekt je Bauteil-Vorkommen
* (Wand/Decke/Extrusion). Leeres Projekt ⇒ gültige Datei nur mit Kopf-
* Kommentaren, kein `v`/`f` (kein Crash).
* Vollständiger Wavefront-OBJ-String (Meter, rechtshändig, Y-up). Ein `o`-Objekt je Bauteil-
* Vorkommen. Leeres Projekt ⇒ gültige Datei nur mit Kopf-Kommentaren.
*/
export function exportObj(project: Project): string {
const groups = buildGroups(project);
const lines: string[] = [
"# DOSSIER OBJ-Export - Dreiecks-Mesh des 3D-Gebaeudemodells",
"# Achsen: rechtshaendig, Y-up (Y = Hoehe ueber OKFF), wie der 3D-Viewer.",
"# Waende: Schicht-Baender mit oeffnungsgenau ausgeschnittenen Loechern (inkl. Laibungen).",
"# Decken/Extrusionen: Umriss-Prisma (Ear-Clipping-Triangulierung).",
];
let offset = 0;
for (const g of groups) {
const vertCount = g.positions.length / 3;
if (vertCount === 0) continue;
lines.push(`o ${g.name}`);
for (let i = 0; i < g.positions.length; i += 3) {
lines.push(`v ${fmt(g.positions[i])} ${fmt(g.positions[i + 1])} ${fmt(g.positions[i + 2])}`);
}
for (let i = 0; i < g.indices.length; i += 3) {
const a = g.indices[i] + 1 + offset;
const b = g.indices[i + 1] + 1 + offset;
const c = g.indices[i + 2] + 1 + offset;
lines.push(`f ${a} ${b} ${c}`);
}
offset += vertCount;
}
return lines.join("\n") + "\n";
return documentFor(project).queryJson("objFile");
}
/**
* Baut einen vollständigen ASCII-STL-String des 3D-Gebäudemodells (Meter,
* dieselbe Achsen-Konvention wie {@link exportObj}). Jedes Dreieck trägt eine
* aus dem Kreuzprodukt berechnete Facettennormale (konsistente Winding, siehe
* `pushWallBox`/`pushPrism`). Leeres Projekt ⇒ gültiges leeres `solid`-Gerüst.
* Vollständiger ASCII-STL-String (Meter, dieselbe Achsen-Konvention). Jedes Dreieck trägt eine aus
* dem Kreuzprodukt berechnete Facettennormale. Leeres Projekt ⇒ gültiges leeres `solid`-Gerüst.
*/
export function exportStl(project: Project): string {
const groups = buildGroups(project);
const lines: string[] = ["solid dossier"];
for (const g of groups) {
for (let i = 0; i < g.indices.length; i += 3) {
const ia = g.indices[i] * 3;
const ib = g.indices[i + 1] * 3;
const ic = g.indices[i + 2] * 3;
const ax = g.positions[ia];
const ay = g.positions[ia + 1];
const az = g.positions[ia + 2];
const bx = g.positions[ib];
const by = g.positions[ib + 1];
const bz = g.positions[ib + 2];
const cx = g.positions[ic];
const cy = g.positions[ic + 1];
const cz = g.positions[ic + 2];
const ux = bx - ax;
const uy = by - ay;
const uz = bz - az;
const vx = cx - ax;
const vy = cy - ay;
const vz = cz - az;
let nx = uy * vz - uz * vy;
let ny = uz * vx - ux * vz;
let nz = ux * vy - uy * vx;
const len = Math.hypot(nx, ny, nz);
if (len > 1e-12) {
nx /= len;
ny /= len;
nz /= len;
} else {
nx = 0;
ny = 0;
nz = 0;
}
lines.push(`facet normal ${fmt(nx)} ${fmt(ny)} ${fmt(nz)}`);
lines.push("outer loop");
lines.push(`vertex ${fmt(ax)} ${fmt(ay)} ${fmt(az)}`);
lines.push(`vertex ${fmt(bx)} ${fmt(by)} ${fmt(bz)}`);
lines.push(`vertex ${fmt(cx)} ${fmt(cy)} ${fmt(cz)}`);
lines.push("endloop");
lines.push("endfacet");
}
}
lines.push("endsolid dossier");
return lines.join("\n") + "\n";
return documentFor(project).queryJson("stlFile");
}