[B5] IFC-Export: Basismengen (Qto_*BaseQuantities), Treppen mit Läufen/Podest/Geländer, Deckenaussparungen

Qto_Wall/Slab/Roof/Column/Door/Window/StairFlight/Railing als IfcElementQuantity je Bauteil,
Werte aus der Geometrie (ifcQuantities.ts), Netto = abzüglich Öffnungen; mit ifcopenshell
nachgerechnet (± 1 %). IfcStair ohne Darstellung, aggregiert IfcStairFlight, IfcSlab(LANDING)
und IfcRailing wie im 3D. Deckenaussparungen als Löcher im Profil. orientOutward gemeinsam
mit dem Mesh-Export (meshOrient.ts). Rust: FLAT_VERSION 3, Pset-Arten 3-5.

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-28 15:01:32 +00:00
1 parent 7fb376a05e
commit f53c4ba760
12 files changed
+1477 -139

No files matched your search

+257
View File
@@ -0,0 +1,257 @@
// Basismengen im IFC-Export ([B5], 28.10.): Qto_Wall/Slab/Roof/Column/Door/Window/StairFlight/Railing
// werden gegen die Geometrie geprüft, die ifcopenshell aus derselben Datei liest (± 1 %), dazu Schema und
// Express-Regeln (`scripts/validate-ifc.py`, 0 Befunde). Ohne Python/ifcopenshell wird der zweite Teil übersprungen.
import { describe, expect, it } from "vitest";
import { spawnSync } from "node:child_process";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import "../engine/fileioWasm.setup";
import { exportIfcSpf } from "./exportIfc";
import { sampleProject } from "../model/sampleProject";
import type { Column, Project, Stair } from "../model/types";
const hasIfcOpenShell = spawnSync("python3", ["-c", "import ifcopenshell, ifcopenshell.validate, numpy"]).status === 0;
/** Das Demo-Haus plus Stütze, Deckenaussparung, L-Treppe (massiv) und gerade Treppe mit Geländer. */
function project(): Project {
const eg = "eg";
const column: Column = { id: "C1", type: "column", floorId: eg, categoryCode: "50", position: { x: 6.5, y: 1 }, profile: { kind: "rect", width: 0.3, depth: 0.2 }, rotation: 0.3, height: 2.5 };
const st0 = sampleProject.stairs![0];
const lStair: Stair = { ...st0, id: "ST-L", typeId: "stair-massiv", shape: "L", start: { x: 7.5, y: 0.4 }, run2Length: 1.5, turn: 1, stepCount: 14 };
const railed: Stair = { ...st0, id: "ST-R", typeId: "stair-rail", start: { x: 10, y: 0.4 } };
return {
...sampleProject,
ceilings: sampleProject.ceilings!.map((c) => ({ ...c, openings: [[{ x: 1, y: 1 }, { x: 2.5, y: 1 }, { x: 2.5, y: 2 }, { x: 1, y: 2 }]] })),
columns: [column],
stairTypes: [...sampleProject.stairTypes!, { id: "stair-rail", name: "Massiv mit Handlauf", structure: "massiv", closedRisers: true, treadThickness: 0.04, nosing: 0.03, railing: "beide", defaultWidth: 1 }],
stairs: [...sampleProject.stairs!, lStair, railed],
} as Project;
}
function writeIfc(name: string, ifc: string): string {
const dir = mkdtempSync(join(tmpdir(), "dossier-qto-"));
const file = join(dir, `${name}.ifc`);
writeFileSync(file, ifc);
return file;
}
/**
* Je Bauteil mit Basismengen: Klasse, Name, Mengen und unabhängig aus der Geometrie gelesene Werte
* (Volumen mit/ohne Öffnungsabzug, nach oben zeigende Fläche, Bounding-Box lokal).
*/
const QTO_INFO = `
import json, sys
import numpy as np
import ifcopenshell, ifcopenshell.geom, ifcopenshell.util.element as ue, ifcopenshell.util.shape as us
m = ifcopenshell.open(sys.argv[1])
net = ifcopenshell.geom.settings()
gross = ifcopenshell.geom.settings()
gross.set("disable-opening-subtractions", True)
local = ifcopenshell.geom.settings()
local.set("use-world-coords", False)
def up_areas(geom):
v = np.array(geom.verts).reshape(-1, 3)
f = np.array(geom.faces).reshape(-1, 3)
n = np.cross(v[f[:, 1]] - v[f[:, 0]], v[f[:, 2]] - v[f[:, 0]])
area = np.linalg.norm(n, axis=1) / 2
nz = n[:, 2] / np.maximum(np.linalg.norm(n, axis=1), 1e-12)
up = nz > 0.1
return float(area[up].sum()), float((area[up] * nz[up]).sum())
def opening_dims(wall):
out = []
for rel in wall.HasOpenings:
e = rel.RelatedOpeningElement
g = ifcopenshell.geom.create_shape(local, e).geometry
v = np.array(g.verts).reshape(-1, 3)
d = v.max(axis=0) - v.min(axis=0)
out.append([float(x) for x in d])
return out
out = []
for el in m.by_type("IfcElement"):
qtos = ue.get_psets(el, qtos_only=True)
if not qtos:
continue
item = {"cls": el.is_a(), "name": el.Name, "predefined": getattr(el, "PredefinedType", None), "qto": qtos}
if el.Representation is not None:
shape = ifcopenshell.geom.create_shape(net, el)
item["volume"] = us.get_volume(shape.geometry)
item["area"] = us.get_area(shape.geometry)
item["up"] = up_areas(shape.geometry)
item["rep"] = [r for r in el.Representation.Representations if r.RepresentationIdentifier == "Body"][0].RepresentationType
if el.is_a("IfcWall"):
item["grossVolume"] = us.get_volume(ifcopenshell.geom.create_shape(gross, el).geometry)
item["openings"] = opening_dims(el)
g = shape.geometry
v = np.array(g.verts).reshape(-1, 3)
item["zExtent"] = float(v[:, 2].max() - v[:, 2].min())
if el.is_a("IfcSlab"):
prof = [r for r in el.Representation.Representations if r.RepresentationIdentifier == "Body"][0].Items[0].SweptArea
holes = []
if prof.is_a("IfcArbitraryProfileDefWithVoids"):
for c in prof.InnerCurves:
p = np.array([q.Coordinates for q in c.Points])
holes.append(float(abs(0.5 * np.sum(p[:-1, 0] * p[1:, 1] - p[1:, 0] * p[:-1, 1]))))
item["holeAreas"] = holes
item["depth"] = float(el.Representation.Representations[0].Items[0].Depth)
if el.is_a("IfcDoor") or el.is_a("IfcWindow"):
host = [r.RelatingOpeningElement for r in el.FillsVoids]
g = ifcopenshell.geom.create_shape(local, host[0]).geometry
v = np.array(g.verts).reshape(-1, 3)
item["openingDims"] = [float(x) for x in (v.max(axis=0) - v.min(axis=0))]
out.append(item)
print(json.dumps(out))
`;
interface Item {
cls: string;
name: string;
predefined: string | null;
qto: Record<string, Record<string, number>>;
volume?: number;
area?: number;
up?: [number, number];
rep?: string;
grossVolume?: number;
openings?: number[][];
zExtent?: number;
holeAreas?: number[];
depth?: number;
openingDims?: number[];
}
function info(name: string, ifc: string): Item[] {
const r = spawnSync("python3", ["-c", QTO_INFO, writeIfc(name, ifc)], { encoding: "utf8", timeout: 120_000 });
expect(r.status, r.stderr).toBe(0);
return JSON.parse(r.stdout);
}
const rel = (a: number, b: number) => Math.abs(a - b) / Math.max(Math.abs(a), Math.abs(b), 1e-9);
const close = (a: number, b: number, tol = 0.01) => expect(rel(a, b), `${a} ≠ ${b}`).toBeLessThanOrEqual(tol);
const qof = (it: Item, set: string) => it.qto[set] ?? {};
describe("Basismengen im Export (ohne ifcopenshell)", () => {
it("jedes Bauteil trägt seine Mengen; Treppe mit Läufen, Podest und Geländer; Deckenaussparung", () => {
const ifc = exportIfcSpf(project());
const count = (cls: string) => (ifc.match(new RegExp(`^#\\d+=${cls}\\(`, "gm")) ?? []).length;
const sets = (name: string) => (ifc.match(new RegExp(`IFCELEMENTQUANTITY\\('[^']*',#\\d+,'${name}'`, "g")) ?? []).length;
expect(sets("Qto_WallBaseQuantities")).toBe(count("IFCWALL"));
expect(sets("Qto_SlabBaseQuantities")).toBe(count("IFCSLAB")); // Decke + Podest der L-Treppe
expect(sets("Qto_RoofBaseQuantities")).toBe(1);
expect(sets("Qto_ColumnBaseQuantities")).toBe(1);
expect(sets("Qto_DoorBaseQuantities")).toBe(count("IFCDOOR"));
expect(sets("Qto_WindowBaseQuantities")).toBe(count("IFCWINDOW"));
expect(sets("Qto_StairFlightBaseQuantities")).toBe(count("IFCSTAIRFLIGHT"));
expect(sets("Qto_RailingBaseQuantities")).toBe(count("IFCRAILING"));
expect(count("IFCSTAIR")).toBe(3);
expect(count("IFCSTAIRFLIGHT")).toBe(1 /* Beton: Netz */ + 2 /* L */ + 1);
expect(count("IFCRAILING")).toBe(1);
expect(count("IFCARBITRARYPROFILEDEFWITHVOIDS")).toBe(1);
expect(ifc).toContain(".LANDING.);");
});
it("Export ist deterministisch (GUIDs der Mengen stabil)", () => {
const strip = (s: string) => s.replace(/FILE_NAME\([^\n]*\n/, "").replace(/IFCOWNERHISTORY\([^\n]*\n/, "");
expect(strip(exportIfcSpf(project()))).toBe(strip(exportIfcSpf(project())));
});
});
describe.skipIf(!hasIfcOpenShell)("Basismengen gegen ifcopenshell", { timeout: 120_000 }, () => {
const ifc = exportIfcSpf(project());
const items = info("qto", ifc);
const of = (cls: string) => items.filter((i) => i.cls === cls);
it("schema- und regelkonform, alle Körper erzeugbar (0 Befunde)", () => {
const r = spawnSync("python3", ["scripts/validate-ifc.py", writeIfc("qto-validate", ifc)], { encoding: "utf8", timeout: 120_000 });
expect(`${r.stdout}\n${r.stderr}`).toContain("0 Befunde");
expect(r.status).toBe(0);
});
it("Wände: Netto-Volumen = Geometrie mit Öffnungsabzug, Brutto = ohne (Extrusions-Wände), Länge/Höhe/Seitenfläche", () => {
const walls = of("IfcWall");
expect(walls.length).toBe(9);
for (const w of walls) {
const q = qof(w, "Qto_WallBaseQuantities");
close(q.NetVolume, w.volume!);
if (w.rep === "SweptSolid") {
close(q.GrossVolume, w.grossVolume!);
// Seitenfläche brutto = Länge × Höhe; netto zieht die Öffnungen ab (Breite × Höhe der Öffnungskörper).
close(q.GrossSideArea, q.Length * q.Height);
const holes = (w.openings ?? []).reduce((s, d) => s + Math.max(...d.slice(0, 2)) * d[2], 0);
// Öffnungsquader sind quer 4 cm dicker als die Wand: die längere der zwei Grundrissmasse ist die Öffnungsbreite,
// sofern sie grösser als die Wanddicke ist.
if ((w.openings ?? []).every((d) => Math.max(d[0], d[1]) > q.Width + 0.05)) close(q.NetSideArea, q.GrossSideArea - holes);
close(q.Height, w.zExtent!);
} else {
// Netz-Wand: Brutto ≥ Netto, Seitenfläche netto ≤ brutto.
expect(q.GrossVolume).toBeGreaterThanOrEqual(q.NetVolume);
}
expect(q.NetSideArea).toBeLessThanOrEqual(q.GrossSideArea + 1e-9);
}
expect(walls.some((w) => w.rep === "SweptSolid")).toBe(true);
expect(walls.some((w) => w.rep === "Tessellation")).toBe(true);
// Mindestens eine Wand mit Öffnung: Netto < Brutto.
expect(walls.some((w) => qof(w, "Qto_WallBaseQuantities").NetVolume < qof(w, "Qto_WallBaseQuantities").GrossVolume - 1e-6)).toBe(true);
});
it("Decken und Podest: Volumen nach ifcopenshell, Aussparung = Brutto − Netto", () => {
const slabs = of("IfcSlab");
const floor = slabs.find((s) => s.predefined === "FLOOR")!;
const q = qof(floor, "Qto_SlabBaseQuantities");
close(q.NetVolume, floor.volume!);
const holes = floor.holeAreas!.reduce((a, b) => a + b, 0);
expect(holes).toBeCloseTo(1.5, 9);
close(q.GrossVolume - q.NetVolume, holes * floor.depth!);
close(q.GrossArea - q.NetArea, holes);
close(q.Width, floor.depth!);
const landing = slabs.find((s) => s.predefined === "LANDING")!;
const ql = qof(landing, "Qto_SlabBaseQuantities");
close(ql.NetVolume, landing.volume!);
close(ql.GrossArea * ql.Width, ql.GrossVolume);
});
it("Dach: Grundrissprojektion und geneigte Fläche = nach oben zeigende Netz-Dreiecke", () => {
const [roof] = of("IfcRoof");
const q = qof(roof, "Qto_RoofBaseQuantities");
close(q.GrossArea, roof.up![0]);
close(q.ProjectedArea, roof.up![1]);
expect(q.GrossArea).toBeGreaterThan(q.ProjectedArea);
});
it("Stütze: Volumen, Querschnitt × Länge", () => {
const [col] = of("IfcColumn");
const q = qof(col, "Qto_ColumnBaseQuantities");
close(q.GrossVolume, col.volume!);
close(q.CrossSectionArea * q.Length, q.GrossVolume);
close(q.CrossSectionArea, 0.3 * 0.2);
expect(q.Length).toBeCloseTo(2.5, 9);
});
it("Türen und Fenster: Breite/Höhe wie der Öffnungskörper, Fläche = Breite × Höhe", () => {
const fills = [...of("IfcDoor"), ...of("IfcWindow")];
expect(fills.length).toBe(3);
for (const f of fills) {
const q = qof(f, f.cls === "IfcDoor" ? "Qto_DoorBaseQuantities" : "Qto_WindowBaseQuantities");
close(q.Area, q.Width * q.Height);
close(q.Height, f.openingDims![2]);
expect([f.openingDims![0], f.openingDims![1]].some((d) => rel(d, q.Width) <= 0.01), `${f.name} Breite ${q.Width}`).toBe(true);
}
});
it("Treppenläufe: Brutto-Volumen = Geometrie; Geländer mit Länge", () => {
const flights = of("IfcStairFlight");
expect(flights.length).toBe(4);
for (const f of flights) {
const q = qof(f, "Qto_StairFlightBaseQuantities");
// Massive Treppen: Prismen können sich an den Nasen überlappen — ifcopenshell vereinigt nicht, Summe stimmt.
close(q.GrossVolume, f.volume!, 0.011);
expect(q.Length).toBeGreaterThan(1);
}
const [rail] = of("IfcRailing");
expect(qof(rail, "Qto_RailingBaseQuantities").Length).toBeGreaterThan(3);
});
});
+115 -22
View File
@@ -41,10 +41,11 @@
// • Dach → IfcRoof (Schicht-Meshes wie im 3D), Dachtyp → IfcRoofType mit Schichten.
// • Stütze → IfcColumn (Profil-Extrusion), Bauteil → IfcMaterial.
// • Raum → IfcSpace (im Geschoss aggregiert) mit Qto_SpaceBaseQuantities und SIA-416-Kategorie.
// • Treppe → IfcStair, GEOMETRISCH bewusst vereinfacht auf einen
// extrudierten Bounding-Footprint (Lauf-Rechteck bei "straight"; Achsen-
// ausgerichtete Bounding-Box der Kontrollpunkte bei "L"/"spiral") — die
// echte Stufengeometrie ist ausgelassen (siehe stairFootprint()).
// • Treppe → IfcStair ohne eigene Darstellung, zusammengefasst (IfcRelAggregates) aus Läufen
// (IfcStairFlight: Prismen der Tritte bzw. glatte Ortbeton-Laufplatte als Netz, Steigungs-/Auftrittsmasse),
// Podest (IfcSlab LANDING, nur "L") und Handlauf/Pfosten (IfcRailing HANDRAIL, wo das 3D sie zeigt) —
// dieselben Ableitungen wie das 3D (`ifcStairs.ts`). Ohne Teile bleibt der Fussabdruck-Quader
// (`stairFootprint()`).
//
// Material-Schichten: je Wand-/Deckentyp ein IfcWallType/IfcSlabType mit
// IfcMaterialLayerSet, die Exemplare erben ihn über IfcRelDefinesByType. Extrusions-Wände
@@ -54,6 +55,12 @@
// Wandanfang, X = Achse, Y = linke Normale (Rust rechnet die Welt-Profile ins Wandsystem). Mesh-
// Wände (schräge Oberkante, Laibungs-Rücksprung) haben weder Achse noch Usage.
//
// Basismengen ([B5], 28.10.): Qto_WallBaseQuantities (Length, Width, Height, GrossSideArea, NetSideArea,
// GrossVolume, NetVolume), Qto_SlabBaseQuantities, Qto_RoofBaseQuantities, Qto_ColumnBaseQuantities,
// Qto_DoorBaseQuantities/Qto_WindowBaseQuantities (Width, Height, Perimeter, Area), Qto_StairFlightBaseQuantities
// und Qto_RailingBaseQuantities — aus der Geometrie (`ifcQuantities.ts`), Netto = abzüglich Öffnungen;
// Rust schreibt je Bauteil einen IfcElementQuantity. Deckenaussparungen sind echte Löcher im Profil.
//
// Eigenschaften ([B5]): Pset_WallCommon/SlabCommon/RoofCommon/ColumnCommon/DoorCommon/
// WindowCommon/SpaceCommon nur mit Werten, die das Modell hergibt (Reference = Typname,
// IsExternal beim Dach und bei SIA-416-AGF-Räumen, Glasanteil der Glastür). Kein U-Wert,
@@ -68,6 +75,7 @@
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). Einheit: METER.
import type { Opening, Project, Stair, Vec2, Wall } from "../model/types";
import type { StairParts } from "./ifcStairs";
import {
columnLabel,
getCeilingType,
@@ -88,6 +96,18 @@ import { openingInterval, openingVerticalExtent } from "../geometry/opening";
import { emitRoofs } from "../plan/toWalls3d/roofs";
import { fileio } from "../engine/fileioWasm";
import { fillParams, type FillParams } from "./ifcOpenings";
import { stairParts } from "./ifcStairs";
import {
columnQuantities,
holeVolume,
meshVolume,
openingQuantities,
roofQuantities,
slabQuantities,
wallQuantities,
type Qty,
} from "./ifcQuantities";
import { roofBaseElevation, roofGeometry } from "../geometry/roof";
/** Deterministische 22-stellige IFC-GUID aus einem Namen (Rust, `ifc_export.rs::ifc_guid`). */
export function ifcGuid(name: string): string {
@@ -101,7 +121,7 @@ export function ifcString(s: string): string {
// ── Flacher Puffer (Gegenstück zu src-tauri/fileio/src/ifc_export.rs, dort die Kodierung) ─────
const FLAT_VERSION = 2;
const FLAT_VERSION = 3;
const REC_WALL_SOLIDS = 1;
const REC_WALL_MESH = 2;
const REC_CEILING = 3;
@@ -125,8 +145,17 @@ interface TypeRefIn {
layers: { componentId: string; componentName: string; thickness: number }[];
}
/** Pset-Eigenschaft: Kennung, Art (IfcIdentifier, IfcBoolean, IfcPositiveRatioMeasure) und Wert. */
type PropIn = { name: string; ident: string } | { name: string; bool: boolean } | { name: string; ratio: number };
/**
* Pset-Eigenschaft: Kennung, Art (IfcIdentifier, IfcBoolean, IfcPositiveRatioMeasure) und Wert; in einem Satz
* `Qto_…` Mengen (Länge, Fläche, Volumen) — Rust schreibt daraus je Bauteil einen IfcElementQuantity.
*/
type PropIn =
| { name: string; ident: string }
| { name: string; bool: boolean }
| { name: string; ratio: number }
| { name: string; length: number }
| { name: string; area: number }
| { name: string; volume: number };
interface PsetIn {
name: string;
props: PropIn[];
@@ -170,7 +199,10 @@ class FlatIfc {
for (const p of ps.props) {
if ("ident" in p) this.nums.push(this.str(p.name), 0, this.str(p.ident));
else if ("bool" in p) this.nums.push(this.str(p.name), 1, p.bool ? 1 : 0);
else this.nums.push(this.str(p.name), 2, p.ratio);
else if ("ratio" in p) this.nums.push(this.str(p.name), 2, p.ratio);
else if ("length" in p) this.nums.push(this.str(p.name), 3, p.length);
else if ("area" in p) this.nums.push(this.str(p.name), 4, p.area);
else this.nums.push(this.str(p.name), 5, p.volume);
}
}
}
@@ -228,11 +260,13 @@ class FlatIfc {
this.mesh(positions, indices, closed);
}
ceiling(structure: number, id: string, name: string, ty: TypeRefIn | null, psets: PsetIn[], outline: Vec2[], zRel: number, depth: number): void {
ceiling(structure: number, id: string, name: string, ty: TypeRefIn | null, psets: PsetIn[], outline: Vec2[], inner: readonly (readonly Vec2[])[], zRel: number, depth: number): void {
this.nums.push(REC_CEILING, structure, this.str(id), this.str(name));
this.typeRef(ty);
this.psets(psets);
this.pts(outline);
this.nums.push(inner.length);
for (const ring of inner) this.pts(ring);
this.nums.push(zRel, depth);
}
@@ -272,10 +306,44 @@ class FlatIfc {
this.psets(o.psets);
}
stair(structure: number, id: string, predefined: string, footprint: Vec2[], zRel: number, depth: number): void {
stair(structure: number, id: string, predefined: string, footprint: Vec2[], zRel: number, depth: number, parts: StairParts): void {
this.nums.push(REC_STAIR, structure, this.str(id), this.str(predefined));
this.pts(footprint);
this.nums.push(zRel, depth);
this.psets([]);
this.nums.push(parts.flights.length);
for (const f of parts.flights) {
this.nums.push(this.str(f.name), f.risers, f.treads, f.riserHeight, f.treadLength, this.str(f.predefined));
this.psets(qto("Qto_StairFlightBaseQuantities", f.quantities));
if (f.mesh) {
this.nums.push(1);
this.mesh(f.mesh.positions, f.mesh.indices, false);
} else {
const solids = f.solids ?? [];
this.nums.push(0, solids.length);
for (const s of solids) {
this.pts(s.pts);
this.nums.push(s.zRel, s.depth);
}
}
}
if (parts.landing) {
const l = parts.landing;
this.nums.push(1, this.str(l.name));
this.pts(l.pts);
this.nums.push(l.zRel, l.depth);
this.psets(qto("Qto_SlabBaseQuantities", l.quantities));
} else {
this.nums.push(0);
}
if (parts.rail) {
const r = parts.rail;
this.nums.push(1, this.str(r.name), this.str(r.predefined));
this.psets(qto("Qto_RailingBaseQuantities", r.quantities));
this.mesh(r.mesh.positions, r.mesh.indices, false);
} else {
this.nums.push(0);
}
}
extrusion(structure: number, id: string, pts: Vec2[], zRel: number, depth: number): void {
@@ -485,6 +553,17 @@ const ROOF_PREDEFINED: Record<string, string> = {
const identifier = (name: string, v: string): PropIn => ({ name, ident: v });
/** Basismengen als Pset `Qto_…` (nur wenn Mengen vorliegen). */
function qto(name: string, quantities: readonly Qty[]): PsetIn[] {
if (quantities.length === 0) return [];
return [
{
name,
props: quantities.map((x): PropIn => (x.kind === "length" ? { name: x.name, length: x.value } : x.kind === "area" ? { name: x.name, area: x.value } : { name: x.name, volume: x.value })),
},
];
}
/**
* Baut aus einem Projekt einen vollständigen IFC4-SPF-String (STEP Physical
* File). Kein Datei-IO. Leeres Projekt ⇒ valider Minimal-IFC (Project/Site/Building, kein Crash).
@@ -571,17 +650,18 @@ export function exportIfcSpf(projectIn: Project): string {
}
return out;
};
/** Name, Typ und Pset einer Wand (verwaister Wandtyp: Roh-ID als Name, kein Typ). */
const wallIdentity = (wall: Wall): { name: string; ty: TypeRefIn | null; psets: PsetIn[] } => {
/** Name, Typ und Pset einer Wand (verwaister Wandtyp: Roh-ID als Name, kein Typ); `quantities` = Basismengen. */
const wallIdentity = (wall: Wall, quantities: readonly Qty[]): { name: string; ty: TypeRefIn | null; psets: PsetIn[] } => {
const qtoSets = qto("Qto_WallBaseQuantities", quantities);
try {
const wt = getWallType(project, wall);
return {
name: wt.name,
ty: typeRef(0, "STANDARD", wt),
psets: [{ name: "Pset_WallCommon", props: [identifier("Reference", wt.name)] }],
psets: [{ name: "Pset_WallCommon", props: [identifier("Reference", wt.name)] }, ...qtoSets],
};
} catch {
return { name: wall.id, ty: null, psets: [] };
return { name: wall.id, ty: null, psets: qtoSets };
}
};
/** Ausdehnung aller Bänder quer zur Wandachse (entlang der linken Normalen ab `wall.start`). */
@@ -620,7 +700,7 @@ export function exportIfcSpf(projectIn: Project): string {
const rect = [addScaled(s, n, -h), addScaled(e, n, -h), addScaled(e, n, h), addScaled(s, n, h)];
return { pts: rect, zRel: b.baseElevation - baseOf(structure), depth: b.height };
});
const id = wallIdentity(wall);
const id = wallIdentity(wall, wallQuantities(wall, bands, cutouts));
// Wandsystem: Placement am Wandanfang, X = Achse, Y = linke Normale; die Schichten des Typs
// stehen ab der Aussenfläche (negative Normale) nebeneinander — IfcMaterialLayerSetUsage nur,
// wenn ihre Summe dem Querschnitt der Bänder entspricht (sonst wäre der Offset gelogen).
@@ -663,7 +743,15 @@ export function exportIfcSpf(projectIn: Project): string {
// (Wände sind extrudierte Querschnitts-Polygone → geschlossene Körper); der Guard fängt echte
// Defekte ab (invertierte Wicklung → Volumen < 0 → `$`).
const closed = isWatertight({ positions, indices });
const id = wallIdentity(wall);
// Netto: Volumen des Netzes (Öffnungen samt Laibungen schon ausgestanzt); ohne dichtes Netz Quader minus Löcher.
const meshBandsOfWall = bandsByWallId.get(wall.id)!;
const net = closed ? meshVolume(positions, indices) : undefined;
const quantities = wallQuantities(wall, meshBandsOfWall, cutoutsByWallId.get(wall.id) ?? [], net);
if (net === undefined) {
const gross = quantities.find((x) => x.name === "GrossVolume")!.value;
quantities.find((x) => x.name === "NetVolume")!.value = Math.max(0, gross - holeVolume(meshBandsOfWall));
}
const id = wallIdentity(wall, quantities);
flat.wallMesh(structure, wall.id, id.name, id.ty, id.psets, positions, indices, closed);
hostExtent.set(wall.id, crossExtent(wall, bandsByWallId.get(wall.id)!));
}
@@ -684,7 +772,10 @@ export function exportIfcSpf(projectIn: Project): string {
} catch {
/* verwaister Deckentyp — Roh-ID als Name, kein Typ */
}
flat.ceiling(structure, ceiling.id, name, ty, psets, ceiling.outline, zBottom - baseOf(structure), zTop - zBottom);
// Aussparungen (wie im 3D) als innere Ringe des Profils; Mengen: Netto zieht sie ab.
const inner = (ceiling.openings ?? []).filter((ring) => ring.length >= 3);
psets.push(...qto("Qto_SlabBaseQuantities", slabQuantities(ceiling.outline, inner, zTop - zBottom)));
flat.ceiling(structure, ceiling.id, name, ty, psets, ceiling.outline, inner, zBottom - baseOf(structure), zTop - zBottom);
}
// ── Öffnungen: IfcOpeningElement in der Wand, IfcDoor/IfcWindow darin ───
@@ -727,19 +818,19 @@ export function exportIfcSpf(projectIn: Project): string {
depth,
width: c.to - c.from,
fill: fillParams(project, wall, opening, c, host),
psets: [{ name: psetName, props }],
psets: [{ name: psetName, props }, ...qto(isDoor ? "Qto_DoorBaseQuantities" : "Qto_WindowBaseQuantities", openingQuantities(c.to - c.from, depth))],
});
}
}
// ── Treppen (vereinfachter Bounding-Footprint, siehe Dateikopf) ────────
// ── Treppen: Läufe, Podest, Geländer wie im 3D (`ifcStairs.ts`); ohne Teile der Fussabdruck-Quader ──
for (const stair of project.stairs ?? []) {
const footprint = stairFootprint(stair);
if (footprint.length < 3) continue;
const { zBottom, zTop } = stairVerticalExtent(project, stair);
const structure = structureOf(stair.floorId);
const predefined = stair.shape === "straight" ? "STRAIGHT_RUN_STAIR" : stair.shape === "spiral" ? "SPIRAL_STAIR" : "QUARTER_TURN_STAIR";
flat.stair(structure, stair.id, predefined, footprint, zBottom - baseOf(structure), zTop - zBottom);
flat.stair(structure, stair.id, predefined, footprint, zBottom - baseOf(structure), zTop - zBottom, stairParts(project, stair, baseOf(structure)));
}
// ── Extrudierte Körper (truck-Integration) → IfcBuildingElementProxy ───
@@ -815,13 +906,15 @@ export function exportIfcSpf(projectIn: Project): string {
const props: PropIn[] = [];
if (roofType) props.push(identifier("Reference", roofType.name));
props.push({ name: "IsExternal", bool: true });
// Mengen aus den geneigten Dachflächen (Aussenseite), wie sie auch das Netz erzeugen.
const planes = roofGeometry(roof, roofBaseElevation(project, roof)).planes.map((pl) => pl.pts);
flat.roof(
structure,
roof.id,
roofType?.name ?? "Dach",
predefined,
roofType ? typeRef(2, predefined, roofType) : null,
[{ name: "Pset_RoofCommon", props }],
[{ name: "Pset_RoofCommon", props }, ...qto("Qto_RoofBaseQuantities", roofQuantities(planes))],
positions,
indices,
closed,
@@ -844,7 +937,7 @@ export function exportIfcSpf(projectIn: Project): string {
zRel: zBottom - baseOf(structure),
depth: zTop - zBottom,
component: col.componentId ? { id: col.componentId, name: componentName(col.componentId) } : null,
psets: [{ name: "Pset_ColumnCommon", props: [identifier("Reference", label)] }],
psets: [{ name: "Pset_ColumnCommon", props: [identifier("Reference", label)] }, ...qto("Qto_ColumnBaseQuantities", columnQuantities(footprint, zTop - zBottom))],
});
}
flat.endColumns();
+2 -1
View File
@@ -3,7 +3,8 @@
import { describe, it, expect } from "vitest";
import "../engine/fileioWasm.setup";
import validator from "gltf-validator";
import { exportGlb, exportGltf, exportObj, exportStl, orientOutward } from "./exportMesh";
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 { emitOpeningMeshes } from "../plan/toWalls3d/openings";
+1 -91
View File
@@ -56,6 +56,7 @@ import { emitStairMeshes, emitStairRailings, emitStairs } from "../plan/toWalls3
import type { RMesh } from "../plan/toWalls3d/shared";
import { IMPORTED_RGB, TERRAIN_RGB, hexToRgb } from "../plan/toWalls3d/shared";
import { fileio } from "../engine/fileioWasm";
import { orientOutward } from "./meshOrient";
/**
* Ein Teil-Mesh mit EINEM Material und LOKALEN (0-basierten) Vertex-/Dreiecks-Indizes. Der Rust-Schreiber
@@ -244,97 +245,6 @@ function pushPrism(
}
}
/**
* 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;
}
/**
* 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
+164
View File
@@ -0,0 +1,164 @@
// 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);
});
});
+213
View File
@@ -0,0 +1,213 @@
// 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)];
}
+170
View File
@@ -0,0 +1,170 @@
// 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 { emitStairMeshes, emitStairRailings, emitStairs } from "../plan/toWalls3d/stairs";
import type { RSlab } from "../plan/toWalls3d";
import { orientOutward } from "./meshOrient";
import { flightQuantities, meshVolume, railingQuantities, ringArea, slabQuantities, type Qty } from "./ifcQuantities";
/** 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 };
}
+94
View File
@@ -0,0 +1,94 @@
// 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;
}
+2 -2
View File
@@ -33,8 +33,8 @@ describe("IFC-Import als Bauteile: Rundreise Demo-Haus", () => {
const { project: p, summary, report } = await importInto(emptyProject, sampleProject);
expect(report.parseErrors).toBe(0);
expect(summary).toMatchObject({ walls: 9, openings: 3, ceilings: 1, columns: 0, rooms: 1, floors: 0, wallTypes: 0, ceilingTypes: 0, components: 0, kept: 0 });
// Dach und Treppe bleiben Kontext-Mesh.
expect((p.context ?? []).map((c) => (c as { layer?: string }).layer).sort()).toEqual(["IfcRoof", "IfcStair"]);
// Dach und Treppenlauf (die IfcStair selbst hat keine Darstellung) bleiben Kontext-Mesh.
expect((p.context ?? []).map((c) => (c as { layer?: string }).layer).sort()).toEqual(["IfcRoof", "IfcStairFlight"]);
expect(validateProject(p)).toEqual([]);
const byOrig = new Map<string, Wall>();
+1 -1
View File
@@ -40,7 +40,7 @@ const bytesOf = (s: string) => new TextEncoder().encode(s);
/** Bauteile je IFC-Klasse aus dem Export-Text (Zeilen `#n=IFCWALL(`). */
function exportedCounts(ifc: string): Map<string, number> {
const m = new Map<string, number>();
for (const cls of ["IFCWALL", "IFCSLAB", "IFCROOF", "IFCDOOR", "IFCWINDOW", "IFCSTAIR", "IFCCOLUMN", "IFCBUILDINGELEMENTPROXY"]) {
for (const cls of ["IFCWALL", "IFCSLAB", "IFCROOF", "IFCDOOR", "IFCWINDOW", "IFCSTAIRFLIGHT", "IFCRAILING", "IFCCOLUMN", "IFCBUILDINGELEMENTPROXY"]) {
const n = (ifc.match(new RegExp(`^#\\d+=${cls}\\(`, "gm")) ?? []).length;
if (n) m.set(cls, n);
}