[K3c] Schnitt und Ansicht im Kern: Abfragen sectionPlan/elevationPlan liefern den Plan-Puffer v2

Neu: core/src/plan/section.rs (toSection.ts, generateSectionPlan, sectionOpenings.ts) und
core/src/plan/elevation.rs (toElevation.ts) rechnen auf dem Projekt-Dokument: Besitzer-Zuordnung,
Schicht-Bänder, Stil, Decken-Terminierung, Dominanz, Treppen, Monolith, Abzugskörper, Körper,
Gelände, Schnitt-Tiefe, geschnittene Fenster/Türen; Ansicht mit Eck-Verlängerung, Verdeckung,
Schatten und Painter-Reihenfolge. Der Prismen-Schnitt läuft über render3d::section::cut_section
(Kern hängt an render3d ohne Features); die frühere JSON-Reise der Zahlen wird bitgleich
nachgebildet. Aus TS kommen nur die truck-Körper (Float64Array). Die TS-Fassade
(plan/sectionCore.ts) liefert lazy Pläne wie generatePlan; Viewport, CLI und MCP laufen darüber.
CLI section/elevation kann --format json (render2d-Szene).

Gleichheit (vorübergehender Test sectionPort.parity.test.ts): Primitive (Object.is), Ausmass,
Szene und SVG gegen die TS-Fassung — Beispiel, 60 Zufallsprojekte, Kacheln 6x6; CLI-SVG
byte-gleich. Ausnahme: durchgesickerte render3d-Schraffur nicht zuordenbarer Bänder wird zur
vorgesehenen Rückfall-Schraffur (s. TODO). Die alte TS-Fassung bleibt bis nach den
Leistungs-Schritten für den Vergleich stehen. Nicht in der Tauri-App angesehen.
This commit is contained in:
Claude committed 2026-10-29 04:17:22 +00:00
1 parent c9a39b8c2f
commit c59619d1fc
15 files changed
+3094 -40

No files matched your search

+4
View File
@@ -596,6 +596,10 @@ async function execute(project: Project, file: string, command: string, rest: st
plan = generateElevationPlan(project, lvl);
if (!plan) fail("keine gültige Ansichtslinie");
}
if (args.flags.get("format") === "json") {
out(args, JSON.stringify(planToRenderScene(plan, scale)), `${lvl.name}.scene.json`);
return 0;
}
out(args, planToSvgString(plan, { scaleDenominator: scale }), `${lvl.name}.svg`);
return 0;
}
+4 -2
View File
@@ -36,6 +36,8 @@ export type QueryName =
| "pickGeometry"
| "model3dParts"
| "planDomains"
| "sectionPlan"
| "elevationPlan"
| "modelJson";
export class ProjectDocument {
@@ -99,9 +101,9 @@ export class ProjectDocument {
* Abfrage mit binärer Antwort (`queries.rs::run_bin`, z. B. `planDomains` als Plan-Puffer v2,
* s. `plan/planBuf.ts`). Fehler kommen als Fehlerpuffer (`decodePlanBuf` wirft die Meldung).
*/
queryBin(name: QueryName, args: number[] = [], text = ""): Uint8Array {
queryBin(name: QueryName, args: number[] | Float64Array = [], text = ""): Uint8Array {
if (!this.handle) throw new Error(`Kern-Abfrage „${name}": Dokument nicht offen`);
return core().doc_query_bin(this.handle, name, Float64Array.from(args), text);
return core().doc_query_bin(this.handle, name, args instanceof Float64Array ? args : Float64Array.from(args), text);
}
/** Datei-Text des Projekts (Formatversion vorn, Einrückung 2). */
+5 -8
View File
@@ -172,7 +172,6 @@ export {
type PlanImage,
type UnderlayGroup,
generatePlan,
generateSectionPlan,
generateVisibleLevelsPlan,
materializeGreyed,
materializeUnderlay,
@@ -294,12 +293,12 @@ export {
} from "../plan/planView/underlayAccess";
export {
sectionOpeningPrimitives,
} from "../plan/sectionOpenings";
export {
type ElevationOptions,
type SectionOutput,
computeSection,
generateElevationPlan,
} from "../plan/toElevation";
generateSectionPlan,
} from "../plan/sectionCore";
export {
planSceneBin,
@@ -307,8 +306,6 @@ export {
} from "../plan/toRenderScene";
export {
type SectionOutput,
computeSection,
sameSectionInputs,
sameSectionLine,
sectionPlaneFromLevel,
+66
View File
@@ -0,0 +1,66 @@
// VORÜBERGEHEND ([K3c]): Messung alt (TS) gegen neu (Kern) für Schnitt und Ansicht (nur mit BENCH=1).
import { it } from "vitest";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { setWasmBytesProvider } from "../engine/wasmSource";
import { computeSection as oldCompute } from "./toSection";
import { generateSectionPlan as oldGen } from "./generatePlan";
import { sectionOpeningPrimitives } from "./sectionOpenings";
import { generateElevationPlan as oldElev } from "./toElevation";
import { computeSection as newCompute, generateSectionPlan as newGen, generateElevationPlan as newElev } from "./sectionCore";
import { planToRenderScene } from "./toRenderScene";
import { sampleProject } from "../model/sampleProject";
import { flattenCategories } from "../model/types";
import type { DrawingLevel, Project } from "../model/types";
import { bigSectionProject } from "./sectionParity.testing";
async function time(f: () => Promise<unknown> | unknown, runs: number): Promise<[number, number]> {
await f();
const t: number[] = [];
for (let i = 0; i < runs; i++) {
const t0 = performance.now();
await f();
t.push(performance.now() - t0);
}
t.sort((a, b) => a - b);
return [t[0], t[Math.floor(t.length / 2)]];
}
const fmt = ([a, b]: [number, number]) => `${a.toFixed(1)}/${b.toFixed(1)}`;
it.skipIf(!process.env.BENCH)("Messung Schnitt/Ansicht alt gegen neu", async () => {
setWasmBytesProvider(async (name) => readFileSync(join(process.cwd(), "src", "engine", name === "trucksolid" ? "pkgTruck/trucksolid_bg.wasm" : "pkg3d/render3d_bg.wasm")));
const only = process.env.BENCH_ONLY;
const all: Array<[string, Project]> = [["Beispiel", sampleProject], ["big6", bigSectionProject(6)], ["big8", bigSectionProject(8)], ["big16", bigSectionProject(16)]];
const cases = all.filter(([n]) => !only || only.split(",").includes(n));
const rows: string[] = ["Projekt | Ebene | alt Plan | neu Plan | alt +Szene | neu +Szene (ms min/median)"];
for (const [name, p] of cases) {
const codes = new Set(flattenCategories(p.layers).map((c) => c.code));
const levels = p.drawingLevels.filter((l) => (l.kind === "section" || l.kind === "elevation") && l.linePoints) as DrawingLevel[];
const runs = name === "big16" ? 1 : name === "Beispiel" ? 20 : 5;
for (const l of levels) {
if (l.kind === "section") {
const oldP = async () => {
const o = (await oldCompute(p, l))!;
const pl = oldGen(o, false, { hiddenLines: l.hiddenLines, visibleCodes: codes });
return { ...pl, primitives: [...pl.primitives, ...sectionOpeningPrimitives(p, l, codes)] };
};
const newP = async () => newGen((await newCompute(p, l))!, false, { hiddenLines: l.hiddenLines, visibleCodes: codes, openings: true });
const a = await time(oldP, runs);
const b = await time(newP, runs);
const c = await time(async () => planToRenderScene(await oldP(), 100), runs);
const d = await time(async () => planToRenderScene(await newP(), 100), runs);
rows.push(`${name} | ${l.id} Schnitt | ${fmt(a)} | ${fmt(b)} | ${fmt(c)} | ${fmt(d)}`);
process.stderr.write(rows[rows.length - 1] + "\n");
} else {
const a = await time(() => oldElev(p, l), runs);
const b = await time(() => newElev(p, l), runs);
const c = await time(() => planToRenderScene(oldElev(p, l)!, 100), runs);
const d = await time(() => planToRenderScene(newElev(p, l)!, 100), runs);
rows.push(`${name} | ${l.id} Ansicht | ${fmt(a)} | ${fmt(b)} | ${fmt(c)} | ${fmt(d)}`);
process.stderr.write(rows[rows.length - 1] + "\n");
}
}
}
console.log(rows.join("\n"));
}, 3_600_000);
+164
View File
@@ -0,0 +1,164 @@
// Schnitt und Ansicht aus dem Kern ([K3c]): die Abfragen `sectionPlan`/`elevationPlan`
// (`src-tauri/core/src/plan/{section,elevation}.rs`) liefern den Plan-Puffer v2 samt Pick-Ids;
// TS reicht nur die Ebene, die Sichtbarkeit (UI-Zustand) und — für den Schnitt — die
// asynchron gebauten truck-Körper hinein.
import type { DrawingLevel, Project } from "../model/types";
import { flattenCategories, getFloor } from "../model/types";
import { documentFor } from "../core/document";
import { buildSolidMesh } from "../engine/truckSolid";
import { extrudedSolidSpec } from "./extrudedSolidSpec";
import { decodePlanBuf } from "./planBuf";
import { lazyPlan } from "./planLazy";
import type { CategoryDisplayResolver, Plan } from "./generatePlan";
/** Vorbereitete Eingabe eines Schnitts: Projekt, Ebene und die truck-Körper (flach). */
export interface SectionOutput {
project: Project;
level: DrawingLevel;
/** `[mono, openings, n, (index, nPos, pos…, nIdx, idx…) × n]`: Platz für die zwei Schalter, dann die
* geschnittenen freien Körper. */
bodies: Float64Array;
}
/** Ob die Ebene eine gültige Schnittlinie trägt (wie `sectionPlaneFromLevel`). */
function hasLine(level: DrawingLevel): boolean {
const line = level.linePoints;
if (!line) return false;
return Math.hypot(line[1].x - line[0].x, line[1].y - line[0].y) >= 1e-9;
}
/** Ob ein Körper als Abzugskörper wirkt (s. `voids.ts`). */
function isVoid(s: NonNullable<Project["extrudedSolids"]>[number]): boolean {
return s.operation === "subtract" && !s.brep && (s.taper ?? 0) < 1e-6 && s.points.length >= 3 && s.height > 0;
}
/**
* Bereitet den Schnitt der Ebene vor: baut die Netze der freien Körper (truck, asynchron, mit
* Cache). `null`, wenn die Ebene keine gültige Schnittlinie trägt.
*/
export async function computeSection(project: Project, level: DrawingLevel): Promise<SectionOutput | null> {
if (!hasLine(level)) return null;
const bodies: number[] = [0, 0, 0];
const solids = project.extrudedSolids ?? [];
for (let index = 0; index < solids.length; index++) {
const solid = solids[index];
if (solid.operation === "subtract" || isVoid(solid)) continue;
let baseZ = 0;
try {
baseZ = solid.levelId ? (getFloor(project, solid.levelId).baseElevation ?? 0) : 0;
} catch {
baseZ = 0;
}
const spec = extrudedSolidSpec(solid, baseZ);
if (!spec) continue;
let mesh: { positions: ArrayLike<number>; indices: ArrayLike<number> };
try {
mesh = await buildSolidMesh(spec, 0.01);
} catch {
continue; // Körper nicht baubar → im Schnitt weglassen, wie im 3D
}
bodies.push(index, mesh.positions.length);
for (let i = 0; i < mesh.positions.length; i++) bodies.push(mesh.positions[i]);
bodies.push(mesh.indices.length);
for (let i = 0; i < mesh.indices.length; i++) bodies.push(mesh.indices[i]);
bodies[2]++;
}
return { project, level, bodies: Float64Array.from(bodies) };
}
/** Kategorie-Codes, die Schnitt/Ansicht prüfen. */
function candidateCodes(project: Project): Set<string> {
const codes = new Set<string>();
for (const c of flattenCategories(project.layers)) codes.add(c.code);
for (const list of [project.walls, project.ceilings, project.roofs, project.stairs, project.openings]) {
for (const e of list ?? []) codes.add(e.categoryCode);
}
for (const c of project.context ?? []) if (c.type === "terrainMesh" && c.categoryCode !== undefined) codes.add(c.categoryCode);
return codes;
}
/** Sichtbarkeit (UI-Zustand) als Code-Listen für den Kern. */
function visibilityArgs(project: Project, visibleCodes?: Set<string>, categoryDisplay?: CategoryDisplayResolver) {
const invisible: string[] = [];
const norender: string[] = [];
const grey: string[] = [];
for (const c of candidateCodes(project)) {
if (visibleCodes && !visibleCodes.has(c)) invisible.push(c);
if (categoryDisplay) {
const d = categoryDisplay(c);
if (!d.render) norender.push(c);
if (d.greyed) grey.push(c);
}
}
return { hasVis: !!visibleCodes, invisible, hasDisplay: !!categoryDisplay, norender, grey };
}
/** Ebene ohne fremde Felder für den Kern. */
function levelArg(level: DrawingLevel) {
return {
kind: level.kind,
linePoints: level.linePoints,
directionSign: level.directionSign,
depth: level.depth,
shadows: level.shadows,
};
}
/**
* Plan eines Schnitts (Cut-Flächen mit Stil und Pick-Ids, Gelände, sichtbare/verdeckte Kanten,
* Bodenlinie). `openings`: geschnittene Fenster/Türen anhängen (nicht im Ausmass).
*/
export function generateSectionPlan(
output: SectionOutput,
mono = false,
opts: { hiddenLines?: boolean; visibleCodes?: Set<string>; categoryDisplay?: CategoryDisplayResolver; openings?: boolean } = {},
): Plan {
const { project, level } = output;
const text = JSON.stringify({
level: levelArg(level),
hiddenLines: !!opts.hiddenLines,
...visibilityArgs(project, opts.visibleCodes, opts.categoryDisplay),
});
const args = output.bodies.slice();
args[0] = mono ? 1 : 0;
args[1] = opts.openings ? 1 : 0;
const buf = decodePlanBuf(documentFor(project).queryBin("sectionPlan", args, text));
if (buf.groups.length === 0) return { primitives: [], bounds: { minX: 0, minY: 0, maxX: 1, maxY: 1 } };
const b = buf.bounds ?? [0, 0, 1, 1];
return lazyPlan(
{ bounds: { minX: b[0], minY: b[1], maxX: b[2], maxY: b[3] } },
buf.groups.map(([from, to]) => ({ buf, from, to })),
);
}
/** Optionen des Ansichts-Generators. */
export interface ElevationOptions {
/** Schlagschatten zeichnen (Default aus `level.shadows`). */
shadows?: boolean;
/** Schwarz-Weiss-Modus (neutralisierte Füllungen). */
mono?: boolean;
/**
* Ebenen-Panel-Sichtbarkeit: mit beiden Angaben werden Flächen ausgeblendeter Kategorien vor der
* Verdeckung entfernt (sie verdecken dann auch nichts); ohne bleibt jede Fläche sichtbar.
*/
visibleCodes?: Set<string>;
categoryDisplay?: CategoryDisplayResolver;
}
/**
* Ansichts-Plan einer Ebene (gefüllte Fassadenansicht, Painter fern → nah, Öffnungen, Schatten,
* Bodenlinie). `null` ohne Ansichtslinie.
*/
export function generateElevationPlan(project: Project, level: DrawingLevel, opts: ElevationOptions = {}): Plan | null {
if (!hasLine(level)) return null;
const shadows = opts.shadows ?? level.shadows ?? false;
const text = JSON.stringify({ level: levelArg(level), ...visibilityArgs(project, opts.visibleCodes, opts.categoryDisplay) });
const buf = decodePlanBuf(documentFor(project).queryBin("elevationPlan", [opts.mono ? 1 : 0, shadows ? 1 : 0], text));
if (buf.groups.length === 0) return null;
const b = buf.bounds ?? [0, 0, 1, 1];
return lazyPlan(
{ bounds: { minX: b[0], minY: b[1], maxX: b[2], maxY: b[3] } },
buf.groups.map(([from, to]) => ({ buf, from, to })),
);
}
+173
View File
@@ -0,0 +1,173 @@
// VORÜBERGEHEND ([K3c]): Zufallsprojekte und Schnitt-/Ansichtsebenen für den Gleichheitstest
// alt (TS) gegen neu (Kern). Wird mit dem Test gelöscht.
import type { DrawingLevel, ExtrudedSolid, Project, TerrainMesh, Wall } from "../model/types";
import { sampleProject } from "../model/sampleProject";
import { bigSampleProject } from "./bigSampleProject.testing";
export function rng(seed: number): () => number {
let x = (seed * 2654435761) >>> 0;
return () => (x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296;
}
const pick = <T>(r: () => number, a: readonly T[]): T => a[Math.floor(r() * a.length)];
const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v)) as T;
const round = (v: number) => Math.round(v * 1e4) / 1e4;
const HATCHES = ["none", "insulation", "diagonal", "crosshatch", "solid-concrete", "sia-concrete", "sia-brick", "sia-insulation", "missing-hatch"];
const COLORS = ["#ff0000", "#00aa33", " #123456 ", "#abc", "#000000"];
function terrain(r: () => number): TerrainMesh {
const n = 12;
const positions: number[] = [];
const tilt = (r() - 0.5) * 0.3;
for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) positions.push(i * 2 - 8, j * 2 - 8, tilt * (i - 5) + (r() - 0.5) * 0.4 - 0.2);
const indices: number[] = [];
for (let j = 0; j + 1 < n; j++)
for (let i = 0; i + 1 < n; i++) {
const a = j * n + i;
indices.push(a, a + 1, a + n, a + 1, a + n + 1, a + n);
}
return { id: "terrain" + Math.floor(r() * 100), type: "terrainMesh", name: "Gelände", positions, indices, categoryCode: r() < 0.5 ? "99" : undefined } as TerrainMesh;
}
/** Zufallsprojekt auf Basis des Beispielhauses (Wände, Öffnungen, Dächer, Treppen, Abzugskörper, Overrides …). */
export function randomSectionProject(seed: number): Project {
const r = rng(seed);
const p = clone(sampleProject) as Project;
const jit = (v: number, a: number) => round(v + (r() - 0.5) * a);
// Wände: verschieben, Typen, Overrides, Terminierung, zusätzliche Wände
const extra: Wall[] = [];
for (let k = 0; k < Math.floor(r() * 4); k++) {
const x0 = jit(2.5, 6), y0 = jit(2, 5);
const ang = r() < 0.6 ? (r() < 0.5 ? 0 : Math.PI / 2) : r() * Math.PI;
const len = 1 + r() * 4;
extra.push({
id: `WX${k}`, type: "wall", floorId: r() < 0.7 ? "eg" : "og", categoryCode: r() < 0.8 ? "20" : "22",
start: { x: x0, y: y0 }, end: { x: round(x0 + Math.cos(ang) * len), y: round(y0 + Math.sin(ang) * len) },
wallTypeId: pick(r, ["aw", "iw", "iw", "aw", "nope"]), height: round(2 + r()),
} as Wall);
}
p.walls = [...p.walls, ...extra].map((w) => {
const o: Wall = { ...w };
if (r() < 0.2) o.start = { x: jit(o.start.x, 0.4), y: jit(o.start.y, 0.4) };
if (r() < 0.2) o.end = { x: jit(o.end.x, 0.4), y: jit(o.end.y, 0.4) };
if (r() < 0.15) o.wallTypeId = pick(r, ["aw", "iw"]);
if (r() < 0.2) {
o.hatchSource = pick(r, ["layer", "object"] as const);
if (r() < 0.6) o.hatchId = pick(r, HATCHES);
}
if (r() < 0.15) { o.foreground = pick(r, COLORS); o.foregroundSource = pick(r, ["layer", "object"] as const); }
if (r() < 0.15) { o.background = pick(r, COLORS); o.backgroundSource = pick(r, ["layer", "object"] as const); }
if (r() < 0.3) o.sliceTermination = pick(r, ["below", "above", "both"] as const);
if (r() < 0.1) o.height = round(1 + r() * 3);
return o;
});
// Öffnungen
const ops = [...(p.openings ?? [])];
for (let k = 0; k < Math.floor(r() * 5); k++) {
const host = pick(r, p.walls);
const door = r() < 0.4;
ops.push({
id: `OX${k}`, type: "opening", hostWallId: host.id, categoryCode: r() < 0.9 ? "21" : "22",
kind: door ? "door" : "window",
typeId: door ? pick(r, ["door-standard", "door-entry", "nope", undefined]) : pick(r, ["window-standard", "window-double", "nope", undefined]),
position: round(r() * 3), width: round(0.5 + r() * 1.5), height: round(0.8 + r() * 1.6), sillHeight: door ? 0 : round(r() * 1.2),
...(door && r() < 0.2 ? { doorType: "wandoeffnung" } : {}),
...(r() < 0.2 ? { wingCount: 1 + Math.floor(r() * 3) } : {}),
} as never);
}
p.openings = ops.map((o) => (r() < 0.2 ? { ...o, position: jit(o.position, 1), width: Math.max(0.2, jit(o.width, 0.6)) } : o));
// Decken
p.ceilings = (p.ceilings ?? []).map((c) => ({
...c,
...(r() < 0.3 ? { thickness: round(0.1 + r() * 0.3) } : {}),
...(r() < 0.2 ? { ceilingTypeId: undefined, wallTypeId: pick(r, ["aw", "iw", "nope"]) } : {}),
...(r() < 0.2 ? { hatchSource: pick(r, ["layer", "object"] as const), hatchId: pick(r, HATCHES) } : {}),
}));
if (r() < 0.4) {
p.ceilings!.push({ ...p.ceilings![0], id: "CX", floorId: "og", outline: [{ x: -1, y: -1 }, { x: 3, y: -1 }, { x: 3, y: 2 }, { x: -1, y: 2 }] });
}
// Dächer
p.roofs = (p.roofs ?? []).map((rf) => ({
...rf,
shape: pick(r, ["sattel", "walm", "pult", "flach", "mansarde", "zelt", "sattel"] as const),
pitchDeg: round(10 + r() * 40),
overhang: round(r() * 0.8),
ridgeAxis: pick(r, ["x", "y"] as const),
...(r() < 0.5 ? { roofTypeId: "roof-warm" } : {}),
...(r() < 0.2 ? { color: pick(r, COLORS) } : {}),
...(r() < 0.3 ? { thickness: round(r() * 0.4) } : {}),
}));
if (r() < 0.3) p.roofs!.push({ ...p.roofs![0], id: "RX", outline: [{ x: 5, y: 0 }, { x: 8, y: 0 }, { x: 8, y: 3 }, { x: 5, y: 3 }], shape: "pult", roofTypeId: undefined });
// Treppen
p.stairs = (p.stairs ?? []).map((st) => ({
...st,
typeId: pick(r, ["stair-standard", "stair-massiv", "stair-wange-holz", "stair-aufgesattelt", undefined]),
shape: pick(r, ["straight", "straight", "L", "spiral"] as const),
...(r() < 0.3 ? { start: { x: jit(st.start.x, 2), y: jit(st.start.y, 2) } } : {}),
}));
// Abzugskörper und freie Körper
const solids: ExtrudedSolid[] = [];
for (let k = 0; k < Math.floor(r() * 4); k++) {
const cx = jit(2.5, 6), cy = jit(2, 5), w = 0.3 + r() * 1.5, d = 0.3 + r() * 1.5;
solids.push({
id: `X${k}`, type: "extrudedSolid", levelId: r() < 0.7 ? "eg" : "og",
points: [{ x: cx, y: cy }, { x: round(cx + w), y: cy }, { x: round(cx + w), y: round(cy + d) }, { x: cx, y: round(cy + d) }],
height: round(0.3 + r() * 2.5), baseOffset: round(r() * 1.5),
...(r() < 0.7 ? { operation: "subtract" } : {}),
} as ExtrudedSolid);
}
p.extrudedSolids = solids;
if (r() < 0.3) p.context = [terrain(r)];
return p;
}
/** Schnitt-/Ansichtsebenen quer durch das Projekt (verschiedene Lagen, Richtungen, Tiefen). */
export function sectionLevels(p: Project, seed: number, count: number): DrawingLevel[] {
const r = rng(seed * 7 + 1);
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (const w of p.walls) for (const q of [w.start, w.end]) {
minX = Math.min(minX, q.x); maxX = Math.max(maxX, q.x); minY = Math.min(minY, q.y); maxY = Math.max(maxY, q.y);
}
if (!isFinite(minX)) { minX = 0; minY = 0; maxX = 5; maxY = 4; }
const out: DrawingLevel[] = [];
for (let k = 0; k < count; k++) {
const kind = k % 2 === 0 ? "section" : "elevation";
const mode = Math.floor(r() * 3);
let a, b;
if (mode === 0) {
const y = round(minY - 1 + r() * (maxY - minY + 2));
a = { x: minX - 1, y }; b = { x: maxX + 1, y };
} else if (mode === 1) {
const x = round(minX - 1 + r() * (maxX - minX + 2));
a = { x, y: minY - 1 }; b = { x, y: maxY + 1 };
} else {
a = { x: round(minX - 1 + r() * 2), y: round(minY - 1 + r() * (maxY - minY)) };
b = { x: round(maxX + 1 - r() * 2), y: round(minY + r() * (maxY - minY + 1)) };
}
if (r() < 0.5) [a, b] = [b, a];
out.push({
id: `lvl${k}`, name: `L${k}`, kind, visible: true, locked: false,
linePoints: [a, b],
directionSign: r() < 0.5 ? 1 : -1,
...(r() < 0.25 ? { depth: round(r() * 6) } : {}),
...(r() < 0.4 ? { shadows: true } : {}),
...(r() < 0.3 ? { hiddenLines: true } : {}),
} as DrawingLevel);
}
return out;
}
/** Grosses Projekt mit Schnitt-/Ansichtslinien quer über alle Kacheln. */
export function bigSectionProject(n: number): Project {
const p = bigSampleProject(n);
const span = n * 8;
const levels: DrawingLevel[] = [
{ id: "bs1", name: "S1", kind: "section", visible: true, locked: false, linePoints: [{ x: -2, y: 2 }, { x: span, y: 2 }], directionSign: 1 } as DrawingLevel,
{ id: "bs2", name: "S2", kind: "section", visible: true, locked: false, linePoints: [{ x: 3.5, y: -2 }, { x: 3.5, y: span }], directionSign: -1, hiddenLines: true } as DrawingLevel,
{ id: "be1", name: "E1", kind: "elevation", visible: true, locked: false, linePoints: [{ x: -2, y: -3 }, { x: span, y: -3 }], directionSign: 1, shadows: true } as DrawingLevel,
{ id: "be2", name: "E2", kind: "elevation", visible: true, locked: false, linePoints: [{ x: -3, y: span }, { x: -3, y: -2 }], directionSign: 1 } as DrawingLevel,
];
return { ...p, drawingLevels: [...p.drawingLevels, ...levels] };
}
+197
View File
@@ -0,0 +1,197 @@
// VORÜBERGEHEND ([K3c]): Gleichheit alte TS-Fassung gegen den Kern (Schnitt/Ansicht). Wird mit
// der TS-Fassung gelöscht.
import { beforeAll, describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { setWasmBytesProvider } from "../engine/wasmSource";
import { computeSection as oldCompute } from "./toSection";
import { generateSectionPlan as oldGen } from "./generatePlan";
import { sectionOpeningPrimitives } from "./sectionOpenings";
import { computeSection as newCompute, generateSectionPlan as newGen, generateElevationPlan as newElev } from "./sectionCore";
import { generateElevationPlan as oldElev, type ElevationOptions } from "./toElevation";
import { sampleProject } from "../model/sampleProject";
import { flattenCategories } from "../model/types";
import type { DrawingLevel, Project } from "../model/types";
import type { CategoryDisplayResolver, Plan, Primitive } from "./generatePlan";
import { planToRenderScene } from "./toRenderScene";
import { planToSvgString } from "../export/planToSvgString";
import { bigSectionProject, randomSectionProject, rng, sectionLevels } from "./sectionParity.testing";
beforeAll(() => {
setWasmBytesProvider(async (name) =>
readFileSync(join(process.cwd(), "src", "engine", name === "trucksolid" ? "pkgTruck/trucksolid_bg.wasm" : "pkg3d/render3d_bg.wasm")),
);
});
/** Erster Unterschied (Pfad) zweier Werte; Zahlen per Object.is, fehlend = undefined. */
function diff(a: unknown, b: unknown, path = ""): string | null {
if (typeof a === "number" && typeof b === "number") return Object.is(a, b) ? null : `${path}: ${a} != ${b}`;
if (a === b) return null;
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) return `${path}: Länge ${a.length} != ${b.length}`;
for (let i = 0; i < a.length; i++) {
const d = diff(a[i], b[i], `${path}[${i}]`);
if (d) return d;
}
return null;
}
if (a && b && typeof a === "object" && typeof b === "object") {
const ra = a as Record<string, unknown>;
const rb = b as Record<string, unknown>;
for (const k of new Set([...Object.keys(ra), ...Object.keys(rb)])) {
const d = diff(ra[k], rb[k], `${path}.${k}`);
if (d) return d;
}
return null;
}
return `${path}: ${JSON.stringify(a)} != ${JSON.stringify(b)}`;
}
const FALLBACK_HATCH = { pattern: "diagonal", scale: 1, angle: 45, color: "#0f0f0f", lineWeight: 0.13, dash: null };
/** Alte Ausgabe: render3d-interne Schraffur (Muster als Zahl), die als Plan-Schraffur durchsickerte, wird
* zur vorgesehenen Rückfall-Schraffur (Fehler der alten Fassung, s. TODO [K3c]). */
function fixOld(p: Primitive, mono: boolean): Primitive {
if (p.kind !== "polygon" || typeof (p.hatch as { pattern: unknown }).pattern !== "number") return p;
stats.foreignHatch++;
return { ...p, hatch: mono ? { ...FALLBACK_HATCH, color: "#1f242c" } : FALLBACK_HATCH, fill: mono ? "#f0f0f0" : p.fill } as Primitive;
}
interface Opts { mono: boolean; hiddenLines?: boolean; visibleCodes?: Set<string>; categoryDisplay?: CategoryDisplayResolver; openings: boolean }
function optionSets(project: Project, seed: number): Opts[] {
const r = rng(seed * 13 + 5);
const codes = [...flattenCategories(project.layers).map((c) => c.code), "22", "99"];
const vis = new Set(codes.filter(() => r() < 0.75));
const grey = new Set(codes.filter(() => r() < 0.3));
const hide = new Set(codes.filter(() => r() < 0.15));
const disp: CategoryDisplayResolver = (c) => ({ render: !hide.has(c), greyed: grey.has(c), locked: false });
return [
{ mono: false, openings: false, visibleCodes: new Set(codes) },
{ mono: true, openings: true, hiddenLines: true, visibleCodes: vis, categoryDisplay: disp },
{ mono: false, openings: true, categoryDisplay: disp },
];
}
async function oldPlan(project: Project, level: DrawingLevel, o: Opts): Promise<{ prims: Primitive[]; raw: Primitive[]; bounds: Plan["bounds"] } | null> {
const out = await oldCompute(project, level);
if (!out) return null;
const plan = oldGen(out, o.mono, { hiddenLines: o.hiddenLines, visibleCodes: o.visibleCodes, categoryDisplay: o.categoryDisplay });
const ops = o.openings ? sectionOpeningPrimitives(project, level, o.visibleCodes, o.categoryDisplay) : [];
return { prims: [...plan.primitives.map((p) => fixOld(p, o.mono)), ...ops], raw: [...plan.primitives, ...ops], bounds: plan.bounds };
}
async function newPlan(project: Project, level: DrawingLevel, o: Opts): Promise<{ prims: Primitive[]; bounds: Plan["bounds"]; plan: Plan } | null> {
const out = await newCompute(project, level);
if (!out) return null;
const plan = newGen(out, o.mono, o);
return { prims: plan.primitives, bounds: plan.bounds, plan };
}
/** Szene (render2d) und SVG wie die Verbraucher: alt als gewöhnlicher Plan, neu aus dem Puffer. */
function outputsDiffer(a: { prims: Primitive[]; raw: Primitive[]; bounds: Plan["bounds"] }, b: Plan): string | null {
const sa = JSON.stringify(planToRenderScene({ primitives: a.prims, bounds: a.bounds }, 100));
const sb = JSON.stringify(planToRenderScene(b, 100));
if (sa !== sb) return "Szene verschieden";
const va = planToSvgString({ primitives: a.raw, bounds: a.bounds }, { scaleDenominator: 100 });
const vb = planToSvgString(b, { scaleDenominator: 100 });
return va === vb ? null : "SVG verschieden";
}
async function settle<T>(f: () => Promise<T>): Promise<{ ok: T } | { err: string }> {
try {
return { ok: await f() };
} catch (e) {
return { err: String(e) };
}
}
/** Vergleicht alt/neu für eine Ebene; liefert Fehlertext oder null. */
async function compareSection(project: Project, level: DrawingLevel, o: Opts): Promise<string | null> {
const a = await settle(() => oldPlan(project, level, o));
const b = await settle(() => newPlan(project, level, o));
if ("err" in a || "err" in b) {
if ("err" in a && "err" in b) {
stats.errors++;
return null;
}
return `Fehler nur auf einer Seite: alt ${"err" in a ? a.err : "ok"}, neu ${"err" in b ? b.err : "ok"}`;
}
stats.prims += a.ok?.prims.length ?? 0;
if (!a.ok || !b.ok) return a.ok === b.ok ? null : "null nur auf einer Seite";
return diff({ prims: a.ok.prims, bounds: a.ok.bounds }, { prims: b.ok.prims, bounds: b.ok.bounds }) ?? (FULL ? outputsDiffer(a.ok, b.ok.plan) : null);
}
/** Szene und SVG mitvergleichen (langsamer). */
const FULL = process.env.PARITY_FULL !== "0";
let stats = { levels: 0, prims: 0, errors: 0, foreignHatch: 0, elevations: 0, elevPrims: 0, elevErrors: 0 };
function elevOptions(project: Project, seed: number): ElevationOptions[] {
const [, b, c] = optionSets(project, seed);
return [{}, { mono: true, visibleCodes: b.visibleCodes, categoryDisplay: b.categoryDisplay }, { shadows: true, categoryDisplay: c.categoryDisplay }, { shadows: false, visibleCodes: b.visibleCodes }];
}
function compareElevation(project: Project, level: DrawingLevel, o: ElevationOptions): string | null {
const run = (f: typeof oldElev) => {
try {
const pl = f(project, level, o);
return { ok: pl ? { prims: pl.primitives, bounds: pl.bounds, plan: pl } : null };
} catch (e) {
return { err: String(e) };
}
};
const a = run(oldElev);
const b = run(newElev);
if ("err" in a || "err" in b) {
if ("err" in a && "err" in b) {
stats.elevErrors++;
return null;
}
return `Fehler nur auf einer Seite: alt ${"err" in a ? a.err : "ok"}, neu ${"err" in b ? b.err : "ok"}`;
}
stats.elevPrims += a.ok?.prims.length ?? 0;
if (!a.ok || !b.ok) return a.ok === b.ok ? null : "null nur auf einer Seite";
return diff({ prims: a.ok.prims, bounds: a.ok.bounds }, { prims: b.ok.prims, bounds: b.ok.bounds }) ??
(FULL ? outputsDiffer({ prims: a.ok.prims, raw: a.ok.prims, bounds: a.ok.bounds }, b.ok.plan) : null);
}
async function check(project: Project, levels: DrawingLevel[], label: string, seed = 1) {
const sets = optionSets(project, seed);
for (const level of levels.filter((l) => l.kind === "section")) {
for (const [k, o] of sets.entries()) {
const d = await compareSection(project, level, o);
expect(d, `${label} ${level.id} Optionen ${k}`).toBeNull();
stats.levels++;
}
}
for (const level of levels.filter((l) => l.kind === "elevation")) {
for (const [k, o] of elevOptions(project, seed).entries()) {
const d = compareElevation(project, level, o);
expect(d, `${label} ${level.id} Ansicht-Optionen ${k}`).toBeNull();
stats.elevations++;
}
}
}
describe("Schnitt und Ansicht: Kern gleich alter TS-Fassung", () => {
it("Beispielprojekt, viele Schnittlinien", async () => {
const own = sampleProject.drawingLevels;
await check(sampleProject, [...own, ...sectionLevels(sampleProject, 1, 40)], "Beispiel");
}, 600_000);
it("Zufallsprojekte", async () => {
const n = Number(process.env.PARITY_N ?? 60);
for (let seed = 1; seed <= n; seed++) {
const p = randomSectionProject(seed);
await check(p, sectionLevels(p, seed, 12), `Saat ${seed}`, seed);
}
console.log("Gleichheit:", stats);
}, 3_600_000);
it("Grosses Projekt (6×6)", async () => {
const p = bigSectionProject(6);
await check(p, p.drawingLevels, "big6");
console.log("Gleichheit (gesamt):", stats);
}, 600_000);
});
+14 -30
View File
@@ -23,13 +23,12 @@ import { categoryNameForPick } from "../core";
import type { PickKind } from "../core";
import { generatePlan, generateSectionPlan, generateVisibleLevelsPlan } from "../core";
import { planWithExtra } from "../core";
import type { CategoryDisplayResolver, Plan, Primitive } from "../core";
import type { CategoryDisplayResolver, Primitive } from "../core";
import type { RichTextDoc } from "../text/richText";
import { computeSection, sameSectionInputs, sameSectionLine } from "../core";
import type { SectionOutput } from "../core";
import { generateElevationPlan } from "../core";
import { crossKindOverlayAllowed, planUnderlayPrimitives } from "../core";
import { sectionOpeningPrimitives } from "../core";
import { levelMarkerPrimitives, levelMarksEnabled } from "../core";
import { setSheetOwnerOutlines, setSheetSnapSegments, snapSegmentsFromPrimitives } from "../tools/sheetSnapGeometry";
import { pushNativeScene, pushNativeWalls } from "./plan/nativeSync";
@@ -923,24 +922,12 @@ function LevelPlanView({
}
/**
* Geschnittene Fenster/Türen in den Schnitt-Plan einsetzen: nach den Cut-
* Polygonen (liegen in deren Aussparung), vor den Ansichtskanten — die Reihen-
* folge spielt kaum eine Rolle, da sie sich nicht überdecken.
*/
function withSectionOpenings(plan: Plan, openings: Primitive[]): Plan {
if (openings.length === 0) return plan;
return { ...plan, primitives: [...plan.primitives, ...openings] };
}
/**
* Schnitt-/Ansichts-Ebene: der render3d-Schnitt-Extraktor (WASM, plan/toSection)
* durchschneidet das Modell entlang der Schnittlinie der Ebene und übersetzt das
* Ergebnis (Cut-Polygone + sichtbare/verdeckte Kanten) über generateSectionPlan
* in Plan-Primitive, die dieselbe PlanView wie ein Grundriss zeichnet.
* Schnitt-/Ansichts-Ebene: der Kern rechnet Schnitt bzw. Ansicht entlang der Schnittlinie der
* Ebene (`generateSectionPlan`/`generateElevationPlan`, Plan-Puffer v2 mit Pick-Ids, samt den
* geschnittenen Fenstern/Türen), die dieselbe PlanView wie ein Grundriss zeichnet.
*
* Die Berechnung ist asynchron (WASM lazy geladen); bis das Ergebnis da ist,
* bzw. wenn die Ebene keine Schnittlinie trägt oder das WASM-Modul den Export
* (noch) nicht kennt, wird ein Hinweis eingeblendet.
* Der Schnitt ist asynchron (die freien Körper baut truck); bis das Ergebnis da ist bzw. wenn
* die Ebene keine Schnittlinie trägt, wird ein Hinweis eingeblendet.
*/
function SectionPlanView({
project,
@@ -1052,9 +1039,8 @@ function SectionPlanView({
selectedDrawingIds?: string[];
gripHandlers: GripHandlers;
}) {
// Die Ansicht (kind "elevation") läuft NICHT über den WASM-Schnitt, sondern
// über den rein TS-seitigen Flächen-Generator (Painter, toElevation.ts) —
// synchron, kein Lazy-Load. Nur der echte Schnitt braucht die WASM-Pipeline.
// Die Ansicht (kind "elevation") ist synchron (Kern, Painter); nur der Schnitt wartet auf die
// truck-Körper.
const isElevation = level.kind === "elevation";
const [output, setOutput] = useState<SectionOutput | null>(null);
const [status, setStatus] = useState<"loading" | "ready" | "empty" | "error">(
@@ -1122,14 +1108,12 @@ function SectionPlanView({
const sectionPlan = useMemo(
() =>
!isElevation && output
? withSectionOpenings(
generateSectionPlan(output, mono, {
hiddenLines: level.hiddenLines,
visibleCodes,
categoryDisplay,
}),
sectionOpeningPrimitives(inputs.project, inputs.level, visibleCodes, categoryDisplay),
)
? generateSectionPlan(output, mono, {
hiddenLines: level.hiddenLines,
visibleCodes,
categoryDisplay,
openings: true,
})
: null,
[isElevation, output, mono, level.hiddenLines, visibleCodes, categoryDisplay, inputs],
);