[K3c][14][12] Merge: Strichmuster auch auf dem Chunk-Weg (native Mac-Anzeige), kaputte Projekte lassen keine Abfrage mehr abbrechen, validate warnt

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-29 12:42:37 +00:00
commit 3ddb36c7f1
40 files changed
+2150 -324

No files matched your search

+14
View File
@@ -38,6 +38,20 @@ describe("dossier-cli", () => {
expect(JSON.parse(readFileSync(out, "utf8")).formatVersion).toBeGreaterThanOrEqual(1);
});
it("validate meldet hängende Verweise als Warnung, Plan rechnet trotzdem", async () => {
const broken = join(dir, "haengend.obp");
const p = { ...sampleProject, walls: sampleProject.walls.map((w, i) => (i === 0 ? { ...w, wallTypeId: "nope" } : w)) };
writeFileSync(broken, serializeProject(p));
const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
try {
expect(await run([broken, "validate"])).toBe(0);
expect(err.mock.calls.map((c) => String(c[0])).join("")).toContain(`Warnung: Wand „${sampleProject.walls[0].id}": Wandtyp „nope" fehlt.`);
} finally {
err.mockRestore();
}
expect(await run([broken, "plan", "--out", join(dir, "haengend.svg")])).toBe(0);
});
it("Plan als SVG", async () => {
const out = join(dir, "eg.svg");
expect(await call("plan", "--out", out)).toBe(0);
+5 -1
View File
@@ -110,6 +110,7 @@ import {
setWasmBytesProvider,
initCore,
validateProject,
projectWarnings,
sampleProject,
} from "../core";
import type { CoreOp, Project } from "../core";
@@ -556,11 +557,14 @@ async function execute(project: Project, file: string, command: string, rest: st
}
case "validate": {
const problems = validateProject(project);
// Hängende Verweise u. Ä.: das Projekt lässt sich rechnen (Vorgaben), aber es soll auffallen.
const warnings = projectWarnings(project);
if (warnings.length) process.stderr.write(warnings.map((w) => `Warnung: ${w}`).join("\n") + "\n");
if (problems.length) {
process.stderr.write(problems.join("\n") + "\n");
return 1;
}
process.stdout.write("ok\n");
process.stdout.write(warnings.length ? `ok (${warnings.length} Warnung${warnings.length === 1 ? "" : "en"})\n` : "ok\n");
return 0;
}
case "migrate":
+3 -1
View File
@@ -16,6 +16,7 @@ import {
serializeProject,
validateOps,
validateProject,
projectWarnings,
} from "../core";
import type { CoreOp, Project } from "../core";
@@ -124,7 +125,8 @@ export async function callTool(file: string, name: string, args: Record<string,
}
case "validate": {
const problems = validateProject(project);
return text(problems.length ? problems.join("\n") : "ok", problems.length > 0);
const warnings = projectWarnings(project).map((w) => `Warnung: ${w}`);
return text([...problems, ...warnings].join("\n") || "ok", problems.length > 0);
}
default:
return text(`unbekanntes Werkzeug: ${name}`, true);
+1
View File
@@ -20,6 +20,7 @@ export { planToSvgString } from "../export/planToSvgString";
export { setWasmBytesProvider } from "../engine/wasmSource";
export { initCore, coreReady } from "../engine/coreWasm";
export { applyOps, validateProject, validateOps } from "./ops";
export { projectWarnings } from "./ops";
export type { CoreOp } from "./ops";
export type { Project, DrawingLevel } from "../model/types";
export { computeKennzahlen, checkRoomProgram, solidVolume } from "../analysis/kennzahlen";
+10
View File
@@ -191,6 +191,16 @@ export function validateProject(p: Project): string[] {
return problemsOf(core().project_validate(JSON.stringify(p, markNonFinite)));
}
/**
* Warnungen zu einem Projekt, das trotzdem geladen und gerechnet wird (Kern `project_refs.rs`):
* hängende Verweise (Wandtyp, Bauteil, Geschoss, Schraffur, Linienstil, Stift, Gruppe, Layout …),
* Gruppen/Ordner, die sich selbst enthalten, und Werte, die nicht zum Modell passen. Die
* Ableitungen setzen dort Vorgaben ein; `dossier-cli validate` meldet die Liste.
*/
export function projectWarnings(p: Project): string[] {
return problemsOf(core().project_warnings(JSON.stringify(p)));
}
/**
* Prüft angewendete Ops (nur was sie anfassen, billig genug für jeden Drag-Schritt): nicht
* endliche Zahlen in neuen/ersetzten Elementen und `setField`-Zahlen, NEUE doppelte ids in den
+365
View File
@@ -0,0 +1,365 @@
// Robustheit des Kerns gegen kaputte Projekte: Dateien von der Platte und Importe können hängende
// Verweise (Wandtyp, Bauteil, Geschoss, Gruppe, Schraffur, Linienstil, Stift …), fehlende Felder,
// NaN, leere Polygone, doppelte ids und Zyklen (Gruppen/Ordner, die sich selbst enthalten) tragen.
// Keine Abfrage und keine Fassade darf daran werfen oder (in Rust) in Panik geraten — sie fallen auf
// Vorgaben zurück, wie der übrige tolerante Modell-Code. `validate` meldet die Verweise als Warnung.
import { beforeAll, describe, expect, it } from "vitest";
import type { Layout, Project } from "../model/types";
import { sampleProject } from "../model/sampleProject";
import { bigSampleProject } from "../plan/bigSampleProject.testing";
import { randomProject, richProject, rng } from "../model/richProject.testing";
import {
computeSection,
generateElevationPlan,
generatePlan,
generateSectionPlan,
generateVisibleLevelsPlan,
pickGeometry,
planSceneBin,
planToRenderScene,
projectToModel3d,
wallMaterialColorMaps,
} from "./index";
import {
buildPlanDxf,
checkRoomProgram,
checkSiteRules,
compareRoomProgram,
computeAreaTable,
computeIvhb,
computeKennzahlen,
exportGlb,
exportIfcSpf,
exportObj,
exportScheduleCsv,
exportStl,
layoutRoomProgram,
parseProjectFile,
planToSvgString,
projectLatLon,
serializeProject,
shadowPolygons,
sunPosition,
validateProject,
buildingFootprint,
modelTop,
projectWarnings,
} from "./extra";
import { loadFileioForTests } from "../engine/fileioWasm.testing";
import { buildLayoutTree, buildMasterTree, folderPdfPages, resolveTitleBlock, visibleCodesFromSnapshot } from "../model/layoutModel";
type Mut = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
const clone = (p: Project): Mut => JSON.parse(JSON.stringify(p)) as Mut;
const list = (p: Mut, k: string): Mut[] => (Array.isArray(p[k]) ? (p[k] as Mut[]) : []);
/** Alle Kategorie-Codes (verschachtelt), wie die CLI. */
function allCodes(p: Project): Set<string> {
const out = new Set<string>();
const walk = (ls: unknown): void => {
if (!Array.isArray(ls)) return;
for (const l of ls as Mut[]) {
if (l && typeof l.code === "string") out.add(l.code);
walk(l?.children);
}
};
walk(p.layers);
return out;
}
/** Verdorbene Fassungen eines Projekts: Name → Projekt. */
function corruptions(base: Project, seed: number): [string, Project][] {
const r = rng(seed);
const out: [string, Project][] = [];
const add = (name: string, f: (p: Mut) => void) => {
const p = clone(base);
f(p);
out.push([name, p as unknown as Project]);
};
const some = <T,>(a: T[]): T[] => a.filter((_, i) => i === 0 || r() < 0.5);
add("Wandtyp hängt", (p) => some(list(p, "walls")).forEach((w) => (w.wallTypeId = "nope")));
add("alle Wandtypen weg", (p) => (p.wallTypes = []));
add("Bauteil hängt", (p) => {
for (const k of ["wallTypes", "ceilingTypes", "roofTypes"]) for (const t of list(p, k)) for (const l of t.layers ?? []) l.componentId = "nope";
});
add("Bauteile weg", (p) => (p.components = []));
add("Schraffur/Linienstil hängt", (p) => {
for (const c of list(p, "components")) {
c.hatchId = "nope";
c.cutHatchId = "nope";
c.lineStyleId = "nope";
}
const walk = (ls: Mut[]) => {
for (const l of ls) {
l.hatchId = "nope";
l.lineStyleId = "nope";
l.penId = "nope";
walk(l.children ?? []);
}
};
walk(list(p, "layers"));
for (const d of list(p, "drawings2d")) {
d.hatchId = "nope";
d.lineStyleId = "nope";
d.penId = "nope";
d.fillPenId = "nope";
}
p.hatches = [];
p.lineStyles = [];
});
add("Stifte hängen", (p) => {
p.activePenSetId = "nope";
p.penSets = [{ id: "ps", name: "x", pens: { nope: { color: "not-a-color", weight: NaN } } }];
for (const w of list(p, "walls")) w.penId = "nope";
});
add("Geschoss hängt", (p) => {
for (const k of ["walls", "stairs", "columns", "ceilings", "rooms"]) for (const e of list(p, k)) e.floorId = "nope";
for (const k of ["drawings2d", "extrudedSolids"]) for (const e of list(p, k)) e.levelId = "nope";
for (const e of list(p, "roofs")) e.floorId = "nope";
for (const w of list(p, "walls")) {
w.bottom = { mode: "floor", floorId: "nope", offset: 0 };
w.top = { mode: "floor", floorId: "nope2" };
}
});
add("Öffnung ohne Wand", (p) => list(p, "openings").forEach((o) => (o.hostWallId = "nope")));
add("Typen hängen", (p) => {
for (const o of list(p, "openings")) o.typeId = "nope";
for (const s of list(p, "stairs")) s.typeId = "nope";
for (const c of list(p, "ceilings")) {
c.ceilingTypeId = "nope";
c.wallTypeId = "nope";
}
for (const rf of list(p, "roofs")) rf.roofTypeId = "nope";
for (const d of list(p, "drawings2d")) if (d.geom?.shape === "block") d.geom.blockDefId = "nope";
for (const pw of list(p, "parametricWalls")) pw.defaultWallTypeId = "nope";
});
add("Gruppen hängen und enthalten sich", (p) => {
p.groups = [
{ id: "g1", name: "A", wallIds: ["nope"], drawingIds: ["nope"], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: ["g1", "g2", "nope"] },
{ id: "g2", name: "B", wallIds: [list(p, "walls")[0]?.id ?? "x"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: ["g1"] },
];
});
add("Ordner zyklisch", (p) => {
p.viewSnapshotFolders = [
{ id: "f1", name: "A", parentId: "f2" },
{ id: "f2", name: "B", parentId: "f1" },
{ id: "f3", name: "C", parentId: "f3" },
];
p.layoutFolders = [
{ id: "lf1", name: "A", kind: "layout", parentId: "lf2" },
{ id: "lf2", name: "B", kind: "layout", parentId: "lf1" },
{ id: "lf3", name: "C", kind: "master", parentId: "lf3" },
];
for (const l of list(p, "layouts")) l.folderId = "lf1";
for (const m of list(p, "masterLayouts")) m.folderId = "lf3";
for (const s of list(p, "viewSnapshots")) s.folderId = "f1";
});
add("Layouts hängen", (p) => {
for (const l of list(p, "layouts")) {
l.masterId = "nope";
l.folderId = "nope";
for (const v of l.viewports ?? []) v.snapshotId = "nope";
}
for (const s of list(p, "viewSnapshots")) {
s.activeLevelId = "nope";
s.enabledOverrideRuleIds = ["nope"];
}
});
add("leere Polygone", (p) => {
for (const c of list(p, "ceilings")) c.outline = [];
for (const rm of list(p, "rooms")) rm.boundary = [];
for (const rf of list(p, "roofs")) rf.outline = [];
for (const x of list(p, "extrudedSolids")) x.points = [];
if (p.siteRules) p.siteRules.parcel = [];
for (const d of list(p, "drawings2d")) if (Array.isArray(d.geom?.pts)) d.geom.pts = [];
});
add("Ein-Punkt-Polygone", (p) => {
for (const c of list(p, "ceilings")) c.outline = c.outline?.slice(0, 1) ?? [];
for (const rm of list(p, "rooms")) rm.boundary = rm.boundary?.slice(0, 2) ?? [];
for (const rf of list(p, "roofs")) rf.outline = rf.outline?.slice(0, 2) ?? [];
for (const w of list(p, "walls")) w.end = { ...w.start };
});
add("NaN", (p) => {
const ws = list(p, "walls");
if (ws[0]) ws[0].start = { x: NaN, y: 0 };
if (ws[1]) ws[1].height = NaN;
for (const c of list(p, "ceilings").slice(0, 1)) c.outline = [{ x: NaN, y: NaN }, { x: 1, y: 0 }, { x: 1, y: 1 }];
for (const t of list(p, "wallTypes").slice(0, 1)) for (const l of t.layers ?? []) l.thickness = NaN;
for (const lv of list(p, "drawingLevels")) lv.baseElevation = NaN;
for (const o of list(p, "openings").slice(0, 2)) o.width = NaN;
for (const s of list(p, "stairs").slice(0, 1)) s.width = NaN;
});
add("Unendlich und negativ", (p) => {
for (const w of list(p, "walls").slice(0, 2)) w.height = -3;
for (const t of list(p, "wallTypes")) for (const l of t.layers ?? []) l.thickness = -0.1;
for (const o of list(p, "openings").slice(0, 2)) {
o.width = 1e300;
o.offset = -1e300;
}
for (const s of list(p, "stairs")) {
s.steps = 1e9;
s.width = 0;
}
for (const c of list(p, "columns")) c.height = -1;
});
add("fehlende Felder", (p) => {
for (const k of ["walls", "openings", "ceilings", "roofs", "stairs", "rooms", "columns", "drawings2d", "extrudedSolids", "wallTypes", "components", "drawingLevels", "hatches", "lineStyles", "layouts", "viewSnapshots"]) {
for (const e of some(list(p, k))) {
const keys = Object.keys(e).filter((x) => x !== "id");
for (const x of keys) if (r() < 0.4) delete e[x];
}
}
});
add("doppelte ids", (p) => {
for (const k of ["walls", "openings", "ceilings", "roofs", "stairs", "rooms", "drawings2d", "wallTypes", "components", "drawingLevels", "hatches", "lineStyles", "layers"]) {
const a = list(p, k);
if (a.length) p[k] = [...a, ...a.map((e) => ({ ...e }))];
}
});
add("falsche Typen", (p) => {
for (const w of list(p, "walls").slice(0, 1)) {
w.height = "hoch";
w.start = null;
}
for (const c of list(p, "ceilings").slice(0, 1)) c.outline = "keine Liste";
for (const d of list(p, "drawings2d").slice(0, 2)) d.geom = { shape: "unbekannt" };
for (const lv of list(p, "drawingLevels").slice(0, 1)) lv.kind = "unbekannt";
});
add("Schnitt-/Ansichtslinien kaputt", (p) => {
for (const lv of list(p, "drawingLevels")) {
if (lv.kind === "section" || lv.kind === "elevation") {
lv.line = { a: { x: 0, y: 0 }, b: { x: 0, y: 0 } };
lv.depth = NaN;
}
}
});
add("Baurecht/Sonne kaputt", (p) => {
p.siteRules = { parcel: [{ x: 0, y: 0 }, { x: NaN, y: 1 }, { x: 1, y: 1 }], setbacks: [NaN, -1], defaultSetback: NaN, buildingLines: [{ a: { x: 0, y: 0 }, b: { x: 0, y: 0 } }], maxHeight: NaN, show: true };
p.sunStudy = { when: "kein Datum", show: true };
p.geoAnchor = { lv95: { e: NaN, n: 1e12 }, height: NaN, model: { x: 0, y: 0 } };
});
return out;
}
/** Ruft alle Kern-Abfragen/Fassaden auf ein Projekt auf; liefert die Fehler (Name: Meldung). */
async function runAll(project: Project): Promise<string[]> {
const errors: string[] = [];
const run = async (name: string, f: () => unknown): Promise<unknown> => {
try {
return await f();
} catch (e) {
errors.push(`${name}: ${e instanceof Error ? e.message : String(e)}`);
return undefined;
}
};
const codes = allCodes(project);
const levels = Array.isArray(project.drawingLevels) ? project.drawingLevels.filter((l) => l && typeof l === "object") : [];
const plans: unknown[] = [];
for (const l of levels) {
if (l.kind === "section") {
const o = (await run(`computeSection ${l.id}`, () => computeSection(project, l))) as Awaited<ReturnType<typeof computeSection>> | undefined;
if (o) plans.push(await run(`generateSectionPlan ${l.id}`, () => generateSectionPlan(o, false, { visibleCodes: codes, hiddenLines: true, openings: true })));
} else if (l.kind === "elevation") {
plans.push(await run(`generateElevationPlan ${l.id}`, () => generateElevationPlan(project, l)));
} else {
plans.push(await run(`generatePlan ${l.id}`, () => generatePlan(project, l.id, codes, undefined, "fein", true, false, true, 50)));
await run(`generateVisibleLevelsPlan ${l.id}`, () => generateVisibleLevelsPlan(project, l.id, codes));
}
}
await run("generatePlan unbekanntes Geschoss", () => generatePlan(project, "nope", codes));
for (const [i, plan] of plans.entries()) {
if (!plan) continue;
const pl = plan as Parameters<typeof planToRenderScene>[0];
await run(`planToRenderScene #${i}`, () => planToRenderScene(pl, 100));
await run(`planSceneBin #${i}`, () => planSceneBin(pl, 100));
await run(`planToSvgString #${i}`, () => planToSvgString(pl, { scaleDenominator: 100 }));
await run(`buildPlanDxf #${i}`, () => buildPlanDxf(pl, project));
}
await run("projectToModel3d", () => projectToModel3d(project));
await run("pickGeometry", () => pickGeometry(project));
await run("wallMaterialColorMaps", () => wallMaterialColorMaps(project));
await run("exportIfcSpf", () => exportIfcSpf(project));
await run("exportObj", () => exportObj(project));
await run("exportStl", () => exportStl(project));
await run("exportGlb", () => exportGlb(project));
await run("exportScheduleCsv", () => exportScheduleCsv(project));
await run("computeKennzahlen", () => computeKennzahlen(project));
await run("checkRoomProgram", () => checkRoomProgram(project));
await run("compareRoomProgram", () => compareRoomProgram(project));
await run("layoutRoomProgram", () => layoutRoomProgram(project));
await run("computeAreaTable", () => computeAreaTable(project));
await run("computeIvhb", () => computeIvhb(project));
await run("checkSiteRules", () => checkSiteRules(project));
await run("buildingFootprint", () => buildingFootprint(project));
await run("modelTop", () => modelTop(project));
await run("sun", () => {
const { lat, lon } = projectLatLon(project);
return shadowPolygons(project, sunPosition(lat, lon, new Date(Date.UTC(2026, 5, 21, 10))));
});
await run("Layouts", () => {
const layouts = Array.isArray(project.layouts) ? project.layouts : [];
const masters = Array.isArray(project.masterLayouts) ? project.masterLayouts : [];
const folders = Array.isArray(project.layoutFolders) ? project.layoutFolders : [];
buildLayoutTree(folders, layouts);
buildMasterTree(folders, masters);
for (const f of folders) folderPdfPages(project, f.id);
for (const l of layouts as Layout[]) {
resolveTitleBlock(project, l, masters.find((m) => m.id === l.masterId), "2026-10-29");
for (const v of l.viewports ?? []) {
const snap = (project.viewSnapshots ?? []).find((s) => s.id === v.snapshotId);
if (snap) generatePlan(project, snap.activeLevelId ?? "", visibleCodesFromSnapshot(snap));
}
}
});
await run("validateProject", () => validateProject(project));
await run("projectWarnings", () => projectWarnings(project));
await run("serialize/parse", () => {
const r = parseProjectFile(serializeProject(project));
if (!r.ok) throw new Error(r.error);
});
return errors;
}
describe("Kern robust gegen kaputte Projekte", () => {
beforeAll(async () => {
await loadFileioForTests();
});
const bases: [string, () => Project][] = [
["Beispiel", () => sampleProject],
["alle Element-Arten", () => richProject()],
...[1, 3, 5, 8, 11, 13, 21].map((seed): [string, () => Project] => [`Zufall ${seed}`, () => randomProject(seed)]),
["Kacheln 2×2", () => bigSampleProject(2)],
];
for (const [baseName, make] of bases) {
it(`${baseName}: keine Abfrage wirft`, async () => {
const base = make();
const failures: string[] = [];
for (const [i, [name, p]] of corruptions(base, 7 + baseName.length).entries()) {
for (const e of await runAll(p)) failures.push(`[${name} #${i}] ${e}`);
}
expect(failures).toEqual([]);
}, 240_000);
}
it("hängender Wandtyp: Plan wie mit dem Rückfall-Typ (kein Werfen, Wand bleibt sichtbar)", () => {
const p = clone(sampleProject);
p.walls[0].wallTypeId = "nope";
const floor = sampleProject.drawingLevels.find((l) => l.kind === "floor")!;
const plan = generatePlan(p as Project, floor.id, allCodes(sampleProject));
expect(plan.primitives.some((x) => x.kind === "polygon" && (x as { wallId?: string }).wallId === p.walls[0].id)).toBe(true);
});
it("validate meldet hängende Verweise als Warnung", () => {
const p = clone(sampleProject);
p.walls[0].wallTypeId = "nope";
p.openings[0].hostWallId = "wand-fehlt";
const w = projectWarnings(p as Project);
expect(w.some((x) => x.includes("nope"))).toBe(true);
expect(w.some((x) => x.includes("wand-fehlt"))).toBe(true);
expect(projectWarnings(sampleProject)).toEqual([]);
});
});
+4 -2
View File
@@ -703,10 +703,12 @@ describe("[B5] Pset_*Common mit den Werten aus dem Modell", () => {
});
describe("Sammler im Kern ([K4], 29.10.)", () => {
it("Fehler des Kerns kommen mit dessen Meldung (unbekannter Wandtyp)", () => {
it("hängender Wandtyp (Datei/Import): Export mit dem Rückfall-Typ statt Abbruch", () => {
const p = fixtureProject();
const broken: Project = { ...p, walls: p.walls.map((w, i) => (i === 0 ? { ...w, wallTypeId: "fehlt" } : w)) };
expect(() => exportIfcSpf(broken)).toThrow("Unbekannter Wandtyp: fehlt");
const spf = exportIfcSpf(broken);
expect(spf).toContain("IFCWALL");
expect(spf).toContain(p.walls[0].id);
});
it("zweimal exportieren gibt dieselbe Datei (bis auf den Zeitstempel)", () => {
+3 -2
View File
@@ -568,7 +568,7 @@ export function resolveTitleBlock(
today: string = new Date().toISOString().slice(0, 10),
): ResolvedTitleBlock {
const arg = {
layout: { id: layout.id, name: layout.name, planNumber: layout.planNumber, viewports: layout.viewports.slice(0, 1) },
layout: { id: layout.id, name: layout.name, planNumber: layout.planNumber, viewports: (layout.viewports ?? []).slice(0, 1) },
master: master ? { titleBlock: master.titleBlock } : null,
today,
};
@@ -581,7 +581,8 @@ export function resolveTitleBlock(
*/
export function visibleCodesFromSnapshot(snap: ViewSnapshot): Set<string> {
const out = new Set<string>();
for (const [code, visible] of Object.entries(snap.layerVisibility)) {
// Fehlt die Map (Datei/Import), ist nichts sichtbar — kein Absturz.
for (const [code, visible] of Object.entries(snap.layerVisibility ?? {})) {
if (visible) out.add(code);
}
return out;
+154
View File
@@ -0,0 +1,154 @@
// Testhilfe: Beispielprojekt mit allen Element-Arten (`richProject`) und daraus abgeleitete
// Zufallsprojekte (`randomProject`, Listen gemischt/gekürzt, Zahlen verrauscht, optionale Felder weg).
// Genutzt von der Modell-Rundreise und dem Robustheitstest des Kerns.
import { sampleProject } from "./sampleProject";
import type { Drawing2DGeom, LayoutAnnotation, ParametricRule, Project, RichTextDoc } from "./types";
export const plain = (p: unknown): unknown => JSON.parse(JSON.stringify(p));
const doc: RichTextDoc = {
version: 1,
paragraphs: [{ runs: [{ text: "Hallo", marks: { bold: true, sizePt: 9, color: "#112233", super: true } }], align: "center", lineHeight: 1.2 }],
};
const geoms: Drawing2DGeom[] = [
{ shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } },
{ shape: "xline", a: { x: 0, y: 0 }, b: { x: 1, y: 1 } },
{ shape: "ray", a: { x: 0, y: 0 }, b: { x: 0, y: 1 } },
{ shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], closed: true, bulge: [0, 0.5, 0] },
{ shape: "rect", min: { x: 0, y: 0 }, max: { x: 2, y: 1 } },
{ shape: "circle", center: { x: 1, y: 1 }, r: 0.5 },
{ shape: "arc", center: { x: 1, y: 1 }, r: 0.5, a0: 0, a1: 1.5 },
{ shape: "ellipse", center: { x: 1, y: 1 }, rx: 2, ry: 1, rotation: 0.3 },
{ shape: "bezier", pts: [{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 1 }, { x: 3, y: 0 }] },
{ shape: "spline", pts: [{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 0 }], closed: false, mode: "control" },
{
shape: "dimension", pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }], offset: 0.5, gapMm: 1, overshootMm: 2, tickLenMm: 3,
textHeightMm: 2.5, lineWeightMm: 0.18, extWeightMm: 0.13, tickWeightMm: 0.35, textOffsetsMm: [{ along: 1, perp: -1 }],
},
{ shape: "kote", at: { x: 1, y: 2 }, value: 3.05, kind: "ukRoh", rotation: 0 },
{ shape: "detailref", at: { x: 1, y: 2 }, label: "3", sheetLayoutId: "lay1", sheetLabel: "A-12" },
{ shape: "scalebar", at: { x: 0, y: -2 }, segmentLength: 1, segments: 5 },
{ shape: "pointmarker", at: { x: 2, y: 2 } },
{
shape: "text", at: { x: 0, y: 3 }, text: "Notiz", height: 0.25, angle: 0.1, width: 2, marks: { italic: true }, doc,
leaderTarget: { x: 1, y: 1 }, leaderBendPoints: [{ x: 0.5, y: 2 }], pathPts: [{ x: 0, y: 3 }, { x: 2, y: 3 }],
},
{ shape: "block", blockDefId: "blk1", at: { x: 5, y: 5 }, rotation: 1.57, scale: 2 },
{ shape: "image", min: { x: 0, y: 0 }, max: { x: 1, y: 1 }, src: "data:image/png;base64,AAAA", opacity: 0.5 },
];
const rules: ParametricRule[] = [
{ type: "grid", spacing: 3, directions: "both", wallTypeId: "wt1", referenceLine: "center", height: 2.8 },
{ type: "module", moduleSize: 1.2, direction: "x", referenceWallId: "w1" },
{ type: "conditional-thickness", condition: "exterior", wallTypeId: "wt1", logic: "or" },
{ type: "reference-line", referenceLine: "left", target: "all" },
{ type: "sequence", rules: [{ type: "reference-line", referenceLine: "right", target: "exterior" }], stopOnMatch: true },
];
const annotations: LayoutAnnotation[] = [
{ kind: "line", id: "a1", x1Mm: 0, y1Mm: 0, x2Mm: 10, y2Mm: 10, color: "#000000", weightMm: 0.25 },
{ kind: "rect", id: "a2", xMm: 1, yMm: 2, widthMm: 30, heightMm: 20 },
{ kind: "text", id: "a3", xMm: 1, yMm: 2, text: "Titel", heightMm: 5, doc, widthMm: 40 },
{ kind: "image", id: "a4", xMm: 1, yMm: 2, widthMm: 30, heightMm: 20, src: "data:image/png;base64,AAAA", opacity: 1 },
];
/** Beispielprojekt, ergänzt um alle Element-Arten, die es selbst nicht enthält. */
export function richProject(): Project {
const lvl = sampleProject.drawingLevels[0].id;
return {
...sampleProject,
formatVersion: 2,
textStyles: [{ id: "ts1", label: "Titel", marks: { bold: true, font: "Helvetica", sizePt: 14 } }],
blockDefs: [{ id: "blk1", name: "Nordpfeil", geom2d: geoms.slice(0, 4) }],
pens: [{ id: "pen1", name: "Kontur" }],
penSets: [{ id: "ps1", name: "Standard", pens: { pen1: { color: "#000000", weight: 0.35 } } }],
activePenSetId: "ps1",
customPalettes: [{ id: "pal1", name: "Projekt", colors: ["#ff0000", "#00ff00"], visible: true }],
builtinPaletteBanks: { ral: false, tango: true },
roomProgram: [{ name: "Wohnen", siaCategory: "HNF", area: 30, count: 2, group: "Wohnung", note: "Süd" }],
roomProgramTolerance: 0.1,
parcelArea: 812,
sunStudy: { when: "2026-06-21T12:00", show: true },
siteRules: {
parcel: [{ x: -5, y: -5 }, { x: 30, y: -5 }, { x: 30, y: 30 }],
setbacks: [3, 4, 5], defaultSetback: 4, buildingLines: [{ a: { x: 0, y: 0 }, b: { x: 10, y: 0 } }], maxHeight: 15, show: true,
},
scaleLineWeights: true,
drawings2d: geoms.map((geom, i) => ({
id: `d${i}`, type: "drawing2d" as const, levelId: lvl, categoryCode: "90", geom,
...(i % 2 ? { noPrint: true, endMarks: { start: "arrow" as const, end: "dot" as const, sizeMm: 2 }, opacity: 0.8 } : {}),
...(i % 3 === 0 ? { hatchOrigin: { x: 1, y: 1 }, hatchSource: "layer" as const, weightMm: 0.5, fillColor: "#eeeeee" } : {}),
})),
context: [
{ type: "importedMesh", id: "c1", name: "Nachbar", layer: "L", categoryCode: "95", color: "#aabbcc", ifcGlobalId: "2O2Fr$t4X7Zf8NOew3FLOH", positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [0, 1, 2] },
{
type: "contourSet", id: "c2", name: "Höhenlinien", contours: [
{ z: 400, pts: [{ x: 0, y: 0 }, { x: 5, y: 1 }], closed: false, layer: "HL", filled: true },
{ z: 401, pts: [], closed: false, curve: { kind: "arc", cx: 0, cy: 0, r: 2, a0: 0, a1: 1 } },
],
},
{ type: "terrainMesh", id: "c3", name: "Gelände", positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [0, 1, 2], vertexColors: [1, 0, 0, 0, 1, 0, 0, 0, 1] },
{ type: "image", id: "c4", name: "Luftbild", src: "data:image/png;base64,AAAA", min: { x: 0, y: 0 }, max: { x: 10, y: 10 }, opacity: 0.7, drape: true, filters: { saturation: 0.5, grayscale: 1 } },
],
extrudedSolids: [
{ id: "x1", type: "extrudedSolid", levelId: lvl, points: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], height: 2, baseOffset: 0.1, operation: "subtract", taper: 0.1, cornerRadius: 0.05, chamfer: 0.02 },
{ id: "x2", type: "extrudedSolid", levelId: lvl, points: [], height: 1, circle: { center: { x: 3, y: 3 }, r: 0.4 }, brep: { spec: { kind: "box", w: 1, nested: { a: [1, 2] } }, origin: { x: 0, y: 0 }, label: "Quader" } },
],
columns: [
{
id: "col1", type: "column", floorId: lvl, categoryCode: "50", position: { x: 2, y: 2 }, profile: { kind: "round", radius: 0.15 },
rotation: 0, height: 2.6, bottom: { mode: "floor", floorId: lvl, offset: -0.1 }, top: { mode: "custom", z: 3 }, strokeWeightSource: "object",
},
{ id: "col2", type: "column", floorId: lvl, categoryCode: "50", position: { x: 4, y: 2 }, profile: { kind: "rect", width: 0.3, depth: 0.2 }, rotation: 0.5, height: 2.6 },
],
groups: [{ id: "g1", name: "Gruppe", wallIds: [sampleProject.walls[0].id], drawingIds: ["d1"], ceilingIds: [], roomIds: [], stairIds: [], columnIds: ["col1"], roofIds: [], openingIds: [], groupIds: [] }],
parametricWalls: [{ id: "pw1", name: "Raster", description: "Test", rules, defaultWallTypeId: sampleProject.wallTypes[0].id }],
overrideRules: [{ id: "or1", name: "Rot", enabled: true, condition: { type: "layer_name", operator: "contains", value: "Wand" }, actions: { color: "#ff0000", lineweight: 0.5 } }],
viewSnapshots: [{
id: "vs1", name: "EG", folderId: "vf1", viewType: "grundriss", view3d: "isoBackLeft", fov: 50, scaleDenominator: 100, detail: "fein", activeLevelId: lvl,
layerVisibility: { "10": true, "20": false }, drawingVisibility: { [lvl]: true }, enabledOverrideRuleIds: ["or1"], cameraCenter: { x: 1, y: 2 }, cameraPxPerMeter: 40,
}],
viewSnapshotFolders: [{ id: "vf1", name: "Pläne" }, { id: "vf2", name: "Unter", parentId: "vf1" }],
layouts: [{ id: "lay1", name: "Blatt 1", paper: "a3", orientation: "landscape", planNumber: "A-12", masterId: "m1", folderId: "lf1", viewports: [{ id: "vp1", snapshotId: "vs1", xMm: 10, yMm: 10, widthMm: 200, heightMm: 150, scaleDenominator: 50 }], annotations }],
masterLayouts: [{ id: "m1", name: "Master", paper: "a3", orientation: "landscape", titleBlock: { projectName: "P", sheetName: "S", scale: "1:100", date: "28.10.", author: "K" }, border: true }],
layoutFolders: [{ id: "lf1", name: "Pläne", kind: "layout" }],
referenceElevationMasl: 432.1,
geoAnchor: { lv95: { e: 2600000, n: 1200000 }, height: 432, model: { x: 0, y: 0 }, label: "Bern" },
};
}
/** Zufallsgenerator mit Saat (LCG, reproduzierbar). */
export function rng(seed: number): () => number {
let x = seed >>> 0;
return () => (x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296;
}
// Optionale Projekt-Felder (laut Typ) — dürfen in Zufallsprojekten fehlen.
const OPTIONAL_KEYS = [
"formatVersion", "textStyles", "ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens", "penSets",
"activePenSetId", "customPalettes", "builtinPaletteBanks", "roomProgram", "roomProgramTolerance", "parcelArea", "sunStudy", "siteRules",
"scaleLineWeights", "ceilings", "roofs", "openings", "stairs", "rooms", "context", "extrudedSolids", "columns", "groups",
"parametricWalls", "overrideRules", "viewSnapshots", "viewSnapshotFolders", "layouts", "masterLayouts", "layoutFolders",
"referenceElevationMasl", "geoAnchor",
] as const satisfies readonly (keyof Project)[];
/** Zufallsprojekt: Listen gemischt/gekürzt/verdoppelt, Zahlen verrauscht, optionale Felder weggelassen. */
export function randomProject(seed: number): Project {
const r = rng(seed);
const jitter = (v: unknown, depth = 0): unknown => {
if (typeof v === "number") return r() < 0.5 ? v : Math.round((v + (r() - 0.5) * 10) * 1e6) / 1e6;
if (Array.isArray(v)) {
let a = v.map((x) => jitter(x, depth + 1));
if (depth === 1 && a.length > 1 && r() < 0.3) a = a.filter(() => r() < 0.7);
if (depth === 1 && r() < 0.2) a = [...a].reverse();
return a;
}
if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, jitter(x, depth + 1)]));
return v;
};
const p = jitter(plain(richProject()), 0) as Record<string, unknown>;
for (const k of OPTIONAL_KEYS) if (r() < 0.25) delete p[k];
return p as unknown as Project;
}
+2 -149
View File
@@ -6,9 +6,8 @@
import { describe, expect, it } from "vitest";
import { ProjectDocument } from "../core/document";
import { sampleProject } from "./sampleProject";
import type { Drawing2DGeom, LayoutAnnotation, ParametricRule, Project, RichTextDoc } from "./types";
const plain = (p: unknown): unknown => JSON.parse(JSON.stringify(p));
import type { Project } from "./types";
import { plain, randomProject, richProject } from "./richProject.testing";
function viaRust(p: Project): unknown {
const d = new ProjectDocument(p);
@@ -35,152 +34,6 @@ function diffPaths(a: unknown, b: unknown, path = "", out: string[] = []): strin
return out;
}
const doc: RichTextDoc = {
version: 1,
paragraphs: [{ runs: [{ text: "Hallo", marks: { bold: true, sizePt: 9, color: "#112233", super: true } }], align: "center", lineHeight: 1.2 }],
};
const geoms: Drawing2DGeom[] = [
{ shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } },
{ shape: "xline", a: { x: 0, y: 0 }, b: { x: 1, y: 1 } },
{ shape: "ray", a: { x: 0, y: 0 }, b: { x: 0, y: 1 } },
{ shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], closed: true, bulge: [0, 0.5, 0] },
{ shape: "rect", min: { x: 0, y: 0 }, max: { x: 2, y: 1 } },
{ shape: "circle", center: { x: 1, y: 1 }, r: 0.5 },
{ shape: "arc", center: { x: 1, y: 1 }, r: 0.5, a0: 0, a1: 1.5 },
{ shape: "ellipse", center: { x: 1, y: 1 }, rx: 2, ry: 1, rotation: 0.3 },
{ shape: "bezier", pts: [{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 1 }, { x: 3, y: 0 }] },
{ shape: "spline", pts: [{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 0 }], closed: false, mode: "control" },
{
shape: "dimension", pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }], offset: 0.5, gapMm: 1, overshootMm: 2, tickLenMm: 3,
textHeightMm: 2.5, lineWeightMm: 0.18, extWeightMm: 0.13, tickWeightMm: 0.35, textOffsetsMm: [{ along: 1, perp: -1 }],
},
{ shape: "kote", at: { x: 1, y: 2 }, value: 3.05, kind: "ukRoh", rotation: 0 },
{ shape: "detailref", at: { x: 1, y: 2 }, label: "3", sheetLayoutId: "lay1", sheetLabel: "A-12" },
{ shape: "scalebar", at: { x: 0, y: -2 }, segmentLength: 1, segments: 5 },
{ shape: "pointmarker", at: { x: 2, y: 2 } },
{
shape: "text", at: { x: 0, y: 3 }, text: "Notiz", height: 0.25, angle: 0.1, width: 2, marks: { italic: true }, doc,
leaderTarget: { x: 1, y: 1 }, leaderBendPoints: [{ x: 0.5, y: 2 }], pathPts: [{ x: 0, y: 3 }, { x: 2, y: 3 }],
},
{ shape: "block", blockDefId: "blk1", at: { x: 5, y: 5 }, rotation: 1.57, scale: 2 },
{ shape: "image", min: { x: 0, y: 0 }, max: { x: 1, y: 1 }, src: "data:image/png;base64,AAAA", opacity: 0.5 },
];
const rules: ParametricRule[] = [
{ type: "grid", spacing: 3, directions: "both", wallTypeId: "wt1", referenceLine: "center", height: 2.8 },
{ type: "module", moduleSize: 1.2, direction: "x", referenceWallId: "w1" },
{ type: "conditional-thickness", condition: "exterior", wallTypeId: "wt1", logic: "or" },
{ type: "reference-line", referenceLine: "left", target: "all" },
{ type: "sequence", rules: [{ type: "reference-line", referenceLine: "right", target: "exterior" }], stopOnMatch: true },
];
const annotations: LayoutAnnotation[] = [
{ kind: "line", id: "a1", x1Mm: 0, y1Mm: 0, x2Mm: 10, y2Mm: 10, color: "#000000", weightMm: 0.25 },
{ kind: "rect", id: "a2", xMm: 1, yMm: 2, widthMm: 30, heightMm: 20 },
{ kind: "text", id: "a3", xMm: 1, yMm: 2, text: "Titel", heightMm: 5, doc, widthMm: 40 },
{ kind: "image", id: "a4", xMm: 1, yMm: 2, widthMm: 30, heightMm: 20, src: "data:image/png;base64,AAAA", opacity: 1 },
];
/** Beispielprojekt, ergänzt um alle Element-Arten, die es selbst nicht enthält. */
function richProject(): Project {
const lvl = sampleProject.drawingLevels[0].id;
return {
...sampleProject,
formatVersion: 2,
textStyles: [{ id: "ts1", label: "Titel", marks: { bold: true, font: "Helvetica", sizePt: 14 } }],
blockDefs: [{ id: "blk1", name: "Nordpfeil", geom2d: geoms.slice(0, 4) }],
pens: [{ id: "pen1", name: "Kontur" }],
penSets: [{ id: "ps1", name: "Standard", pens: { pen1: { color: "#000000", weight: 0.35 } } }],
activePenSetId: "ps1",
customPalettes: [{ id: "pal1", name: "Projekt", colors: ["#ff0000", "#00ff00"], visible: true }],
builtinPaletteBanks: { ral: false, tango: true },
roomProgram: [{ name: "Wohnen", siaCategory: "HNF", area: 30, count: 2, group: "Wohnung", note: "Süd" }],
roomProgramTolerance: 0.1,
parcelArea: 812,
sunStudy: { when: "2026-06-21T12:00", show: true },
siteRules: {
parcel: [{ x: -5, y: -5 }, { x: 30, y: -5 }, { x: 30, y: 30 }],
setbacks: [3, 4, 5], defaultSetback: 4, buildingLines: [{ a: { x: 0, y: 0 }, b: { x: 10, y: 0 } }], maxHeight: 15, show: true,
},
scaleLineWeights: true,
drawings2d: geoms.map((geom, i) => ({
id: `d${i}`, type: "drawing2d" as const, levelId: lvl, categoryCode: "90", geom,
...(i % 2 ? { noPrint: true, endMarks: { start: "arrow" as const, end: "dot" as const, sizeMm: 2 }, opacity: 0.8 } : {}),
...(i % 3 === 0 ? { hatchOrigin: { x: 1, y: 1 }, hatchSource: "layer" as const, weightMm: 0.5, fillColor: "#eeeeee" } : {}),
})),
context: [
{ type: "importedMesh", id: "c1", name: "Nachbar", layer: "L", categoryCode: "95", color: "#aabbcc", ifcGlobalId: "2O2Fr$t4X7Zf8NOew3FLOH", positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [0, 1, 2] },
{
type: "contourSet", id: "c2", name: "Höhenlinien", contours: [
{ z: 400, pts: [{ x: 0, y: 0 }, { x: 5, y: 1 }], closed: false, layer: "HL", filled: true },
{ z: 401, pts: [], closed: false, curve: { kind: "arc", cx: 0, cy: 0, r: 2, a0: 0, a1: 1 } },
],
},
{ type: "terrainMesh", id: "c3", name: "Gelände", positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [0, 1, 2], vertexColors: [1, 0, 0, 0, 1, 0, 0, 0, 1] },
{ type: "image", id: "c4", name: "Luftbild", src: "data:image/png;base64,AAAA", min: { x: 0, y: 0 }, max: { x: 10, y: 10 }, opacity: 0.7, drape: true, filters: { saturation: 0.5, grayscale: 1 } },
],
extrudedSolids: [
{ id: "x1", type: "extrudedSolid", levelId: lvl, points: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], height: 2, baseOffset: 0.1, operation: "subtract", taper: 0.1, cornerRadius: 0.05, chamfer: 0.02 },
{ id: "x2", type: "extrudedSolid", levelId: lvl, points: [], height: 1, circle: { center: { x: 3, y: 3 }, r: 0.4 }, brep: { spec: { kind: "box", w: 1, nested: { a: [1, 2] } }, origin: { x: 0, y: 0 }, label: "Quader" } },
],
columns: [
{
id: "col1", type: "column", floorId: lvl, categoryCode: "50", position: { x: 2, y: 2 }, profile: { kind: "round", radius: 0.15 },
rotation: 0, height: 2.6, bottom: { mode: "floor", floorId: lvl, offset: -0.1 }, top: { mode: "custom", z: 3 }, strokeWeightSource: "object",
},
{ id: "col2", type: "column", floorId: lvl, categoryCode: "50", position: { x: 4, y: 2 }, profile: { kind: "rect", width: 0.3, depth: 0.2 }, rotation: 0.5, height: 2.6 },
],
groups: [{ id: "g1", name: "Gruppe", wallIds: [sampleProject.walls[0].id], drawingIds: ["d1"], ceilingIds: [], roomIds: [], stairIds: [], columnIds: ["col1"], roofIds: [], openingIds: [], groupIds: [] }],
parametricWalls: [{ id: "pw1", name: "Raster", description: "Test", rules, defaultWallTypeId: sampleProject.wallTypes[0].id }],
overrideRules: [{ id: "or1", name: "Rot", enabled: true, condition: { type: "layer_name", operator: "contains", value: "Wand" }, actions: { color: "#ff0000", lineweight: 0.5 } }],
viewSnapshots: [{
id: "vs1", name: "EG", folderId: "vf1", viewType: "grundriss", view3d: "isoBackLeft", fov: 50, scaleDenominator: 100, detail: "fein", activeLevelId: lvl,
layerVisibility: { "10": true, "20": false }, drawingVisibility: { [lvl]: true }, enabledOverrideRuleIds: ["or1"], cameraCenter: { x: 1, y: 2 }, cameraPxPerMeter: 40,
}],
viewSnapshotFolders: [{ id: "vf1", name: "Pläne" }, { id: "vf2", name: "Unter", parentId: "vf1" }],
layouts: [{ id: "lay1", name: "Blatt 1", paper: "a3", orientation: "landscape", planNumber: "A-12", masterId: "m1", folderId: "lf1", viewports: [{ id: "vp1", snapshotId: "vs1", xMm: 10, yMm: 10, widthMm: 200, heightMm: 150, scaleDenominator: 50 }], annotations }],
masterLayouts: [{ id: "m1", name: "Master", paper: "a3", orientation: "landscape", titleBlock: { projectName: "P", sheetName: "S", scale: "1:100", date: "28.10.", author: "K" }, border: true }],
layoutFolders: [{ id: "lf1", name: "Pläne", kind: "layout" }],
referenceElevationMasl: 432.1,
geoAnchor: { lv95: { e: 2600000, n: 1200000 }, height: 432, model: { x: 0, y: 0 }, label: "Bern" },
};
}
/** Zufallsgenerator mit Saat (LCG, reproduzierbar). */
function rng(seed: number): () => number {
let x = seed >>> 0;
return () => (x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296;
}
// Optionale Projekt-Felder (laut Typ) — dürfen in Zufallsprojekten fehlen.
const OPTIONAL_KEYS = [
"formatVersion", "textStyles", "ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens", "penSets",
"activePenSetId", "customPalettes", "builtinPaletteBanks", "roomProgram", "roomProgramTolerance", "parcelArea", "sunStudy", "siteRules",
"scaleLineWeights", "ceilings", "roofs", "openings", "stairs", "rooms", "context", "extrudedSolids", "columns", "groups",
"parametricWalls", "overrideRules", "viewSnapshots", "viewSnapshotFolders", "layouts", "masterLayouts", "layoutFolders",
"referenceElevationMasl", "geoAnchor",
] as const satisfies readonly (keyof Project)[];
/** Zufallsprojekt: Listen gemischt/gekürzt/verdoppelt, Zahlen verrauscht, optionale Felder weggelassen. */
function randomProject(seed: number): Project {
const r = rng(seed);
const jitter = (v: unknown, depth = 0): unknown => {
if (typeof v === "number") return r() < 0.5 ? v : Math.round((v + (r() - 0.5) * 10) * 1e6) / 1e6;
if (Array.isArray(v)) {
let a = v.map((x) => jitter(x, depth + 1));
if (depth === 1 && a.length > 1 && r() < 0.3) a = a.filter(() => r() < 0.7);
if (depth === 1 && r() < 0.2) a = [...a].reverse();
return a;
}
if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, jitter(x, depth + 1)]));
return v;
};
const p = jitter(plain(richProject()), 0) as Record<string, unknown>;
for (const k of OPTIONAL_KEYS) if (r() < 0.25) delete p[k];
return p as unknown as Project;
}
describe("Modell-Rundreise TS → Rust → TS ([K4] S4)", () => {
it("Beispielprojekt bleibt gleich", () => {
const back = viaRust(sampleProject);
+1
View File
@@ -165,6 +165,7 @@ function disposeGeometry(gl: BufferGl, g: GpuGeometry): void {
gl.deleteBuffer(g.fill.indexBuffer);
gl.deleteBuffer(g.line.vertexBuffer);
gl.deleteBuffer(g.line.indexBuffer);
if (g.dash) gl.deleteBuffer(g.dash.instanceBuffer);
}
export interface ChunkStats {
+19
View File
@@ -57,6 +57,25 @@ describe('compilePrimitivesToGpu: zusammenhängende Linien-Segmente', () => {
});
});
describe('compilePrimitivesToGpu: Strichmuster (Shader-Instanzen wie der Szenen-Pfad)', () => {
it('gestrichelte Linie wird EINE Strich-Instanz statt durchgezogener Striche', () => {
const uploads: ArrayBufferView[] = [];
const gl = { ...glStub, bufferData: (_t: number, d: ArrayBufferView) => uploads.push(d) } as unknown as WebGL2RenderingContext;
const dashed = { ...seg(0, 0, 2, 0, 'a'), dash: [3, 1] } as Primitive;
const g = compilePrimitivesToGpu(gl, [seg(0, 1, 1, 1, 'b'), dashed], 90);
expect(g.dash?.batches).toEqual([{ startInstance: 0, instanceCount: 1, color: [0, 0, 0, 1], strokeMm: 0.18, lineAt: g.line.batches[0].indexCount }]);
const inst = uploads[uploads.length - 1] as Float32Array;
expect(inst.length).toBe(16);
// Lauflänge des Zugs (Bildschirm-Einheiten) und Muster 3/1 mm × 0.1 m/mm × 90.
expect(inst[5]).toBeCloseTo(180, 4);
expect(Array.from(inst.slice(7, 10)).map((v) => +v.toFixed(4))).toEqual([2, 27, 9]);
});
it('ohne Strichmuster keine Strich-Geometrie', () => {
expect(compilePrimitivesToGpu(glStub, [seg(0, 0, 1, 0, 'a')], 90).dash).toBeUndefined();
});
});
/** Summierte Dreiecksfläche (Betrag) aus Indizes über pts. */
function triArea(pts: Vec2[], idx: number[]): number {
let area = 0;
+18 -1
View File
@@ -12,7 +12,7 @@
import type { Primitive } from '../generatePlan';
import type { Vec2 } from '../../model/types';
import type { BufferGl, GpuGeometry, Rgba } from './glPlanTypes';
import type { BufferGl, DashBatch, GpuGeometry, Rgba } from './glPlanTypes';
import { encodePlanBuf, type DecodedPlanBuf } from '../planBuf';
import { core } from '../../engine/coreWasm';
@@ -94,6 +94,20 @@ function uploadCompiled(gl: BufferGl, out: Uint32Array): GpuGeometry {
screenPx: meta[k + 7] === 1,
});
}
// Strich-Instanzen (hinter den Linien-Batches; ältere Ausgaben ohne diesen Teil → keine).
const nDash = k < m ? meta[k] : 0;
const nDashBatches = k + 1 < m ? meta[k + 1] : 0;
k += 2;
const dashBatches: DashBatch[] = [];
for (let i = 0; i < nDashBatches; i++, k += 8) {
dashBatches.push({
startInstance: meta[k],
instanceCount: meta[k + 1],
color: [meta[k + 2], meta[k + 3], meta[k + 4], meta[k + 5]] as Rgba,
strokeMm: meta[k + 6],
lineAt: meta[k + 7],
});
}
let off = out.byteOffset + 8 + m * 8;
const fillPos = new Float32Array(out.buffer, off, nFillPos);
off += nFillPos * 4;
@@ -103,6 +117,8 @@ function uploadCompiled(gl: BufferGl, out: Uint32Array): GpuGeometry {
const lineVerts = new Uint32Array(out.buffer, off, nLineVerts);
off += nLineVerts * 4;
const lineIdx = new Uint32Array(out.buffer, off, nLineIdx);
off += nLineIdx * 4;
const dashInst = new Float32Array(out.buffer, off, nDash * 16);
const upload = (target: number, data: ArrayBufferView & { length: number }): WebGLBuffer | null => {
if (!data.length) return null;
@@ -123,6 +139,7 @@ function uploadCompiled(gl: BufferGl, out: Uint32Array): GpuGeometry {
indexBuffer: upload(gl.ELEMENT_ARRAY_BUFFER, lineIdx),
batches: lineBatches,
},
...(nDash > 0 ? { dash: { instanceBuffer: upload(gl.ARRAY_BUFFER, dashInst), batches: dashBatches } } : {}),
origin: { x: originX, y: originY },
bounds: {
minX: isFinite(minX) ? minX : 0,
+22
View File
@@ -99,10 +99,32 @@ export interface GpuGeometry {
indexBuffer: WebGLBuffer | null;
batches: LineBatch[];
};
/**
* Gestrichelte Striche: je Segment EINE Instanz (16 × f32: ax, ay, bx, by, s0, runLen, total,
* count, dash0..7 in Bildschirm-Einheiten relativ zu `origin`); Striche/Lücken setzt der
* Fragment-Shader (`DASH_LINE_WGSL` in render2d). Fehlt bei Geometrie ohne Strichmuster.
*/
dash?: {
instanceBuffer: WebGLBuffer | null;
batches: DashBatch[];
};
/** Modell-Bounds (Meter) für Debug/Einpassen; nicht render-kritisch. */
bounds: { minX: number; minY: number; maxX: number; maxY: number };
}
/** Ein Strich-Batch: Instanz-Bereich mit Farbe + Papier-Strichbreite (mm). */
export interface DashBatch {
startInstance: number;
instanceCount: number;
color: Rgba;
strokeMm: number;
/**
* Maler-Reihenfolge: Anzahl Linien-Indizes vor diesem Batch — gezeichnet vor dem ersten
* Linien-Batch mit `startIndex >= lineAt` (kein Linien-Batch überspannt diese Stelle).
*/
lineAt: number;
}
/** Rechteckiger Ausschnitt in Bildschirm-Einheiten (viewBox). */
export interface ViewBox {
x: number;
+11
View File
@@ -24,6 +24,9 @@ export interface NativeChunkLayout {
line_vtx: number | null;
line_idx: number | null;
line_batches: { start: number; count: number; color: number[]; stroke_mm: number; screen_px: boolean; device_px?: boolean }[];
/** Strich-Instanzen (gestrichelte Segmente, `DASH_LINE_WGSL`), s. `GpuGeometry.dash`. */
dash_inst?: number | null;
dash_batches?: { start: number; count: number; color: number[]; stroke_mm: number; line_at: number }[];
origin: [number, number];
greyed: boolean;
}
@@ -193,6 +196,14 @@ export class NativeGl implements BufferGl {
stroke_mm: b.strokeMm,
screen_px: !!b.screenPx,
})),
dash_inst: id(g.dash?.instanceBuffer ?? null),
dash_batches: (g.dash?.batches ?? []).map((b) => ({
start: b.startInstance,
count: b.instanceCount,
color: b.color,
stroke_mm: b.strokeMm,
line_at: b.lineAt,
})),
origin: [g.origin?.x ?? 0, g.origin?.y ?? 0] as [number, number],
greyed: !!g.greyed,
};
+1
View File
@@ -237,6 +237,7 @@ export function useNativePlanRenderer(
gl.deleteBuffer(old.fill.indexBuffer);
gl.deleteBuffer(old.line.vertexBuffer);
gl.deleteBuffer(old.line.indexBuffer);
if (old.dash) gl.deleteBuffer(old.dash.instanceBuffer);
highlightGeom.current = null;
}
if (prims.length) {