Files
DOSSIER/src/state/testHooks.ts
T

493 lines
31 KiB
TypeScript

// Test-Naht für die UI-Suite (`e2e/`), nur mit `?dossierTest` in der URL geladen (main.tsx): Dinge, die
// sich über die Oberfläche nicht auslösen lassen. Hier: ein absichtlicher Kern-Panic ([118],
// `__debug_panic` in `src-tauri/core/src/web/document.rs`), um den Wiederanlauf in echtem Chromium zu prüfen.
import { core, coreEpoch, coreReady } from "../engine/coreWasm";
import { getState } from "./appStore";
import { runSelectionAction, type SelectionActionId } from "./selectionActions";
import { storeDocument } from "./historySlice";
import { ceilingThickness } from "../model/types";
import { computeSection, generatePlan, generateVisibleLevelsPlan, materializeGreyed, materializeUnderlay, verticalExtents, generateSectionPlan, pickGeometry, projectToModel3d, projectWithTemplate } from "../core";
import { withDocument } from "../core/document";
import { collectVisibleCodes } from "../model/layers";
import { tracePlan } from "../core";
import { DESIGN_OPTION_GHOST_FILL, DESIGN_OPTION_GHOST_LINE, designOptionEditArg } from "../core";
import { getViewStateBridge } from "./viewTabs";
import { getView3dFilter, toFilter3d } from "./view3dFilter";
import { BUILTIN_PANEL_IDS } from "../panels/builtinPanels";
import { hiddenFloorIds, itemDisplay } from "../panels/displayMode";
import { renderJob } from "./renderJob";
import { CyclesCancelled } from "../core";
declare global {
interface Window {
__dossierTest?: {
/** Panic im Kern mitten im Zugriff auf das Store-Dokument; Ergebnis: Name des geworfenen Fehlers. */
corePanic: () => string;
/** Erfüllt, wenn der Kern wieder läuft. */
coreReady: () => Promise<void>;
coreEpoch: () => number;
/** Zahl der Elemente je Liste des Projekts (Wände, Öffnungen, Zeichnungsebenen) und das Projekt im Kern als JSON-Länge. */
counts: () => { walls: number; openings: number; drawingLevels: number; coreJson: number; /** [280] Träger. */ beams: number };
/** Endpunkte aller 2D-Linien des Projekts ([123] Transformations-Test). */
lines: () => { a: { x: number; y: number }; b: { x: number; y: number } }[];
/** [137] Polylinien-Punkte der 2D-Elemente mit Id-Präfix (Präsentations-Massstabsbalken). */
polylines: (prefix: string) => { id: string; pts: { x: number; y: number }[] }[];
/** [137] Gewählte 2D-Elemente und Gruppen. */
selected: () => { drawings: string[]; groups: string[]; all: string };
/** [144] Öffnungen (id, Wirtswand, Lage ab Wandanfang). */
openings: () => { id: string; hostWallId: string; position: number }[];
/** [187] Höhen von Decken (UK/OK/Dicke), Wänden (UK/OK) und Fenstern (Brüstung/Höhe) aus dem Kern, in Metern (absolutes Z). */
heights: () => {
ceilings: { id: string; zBottom: number; zTop: number; thickness: number }[];
walls: { id: string; zBottom: number; zTop: number }[];
openings: { id: string; sillHeight: number; height: number }[];
/** [187] Teil 2: Traufe (absolutes Z), Neigung, Attika-Höhe; Steighöhe der Treppen; Sohle der Baugruben. */
roofs: { id: string; eave: number; pitchDeg: number; parapetHeight: number }[];
stairs: { id: string; totalRise: number; baseOffset: number }[];
/** [187] Höhe je Höhenlinie der Höhenlinien-Sätze. */
contours: { id: string; zs: number[] }[];
excavations: { id: string; bottom: number }[];
};
/** [144] Auswahl setzen (wie ein Klick), z. B. `{ openings: ["D1"] }`. */
select: (patch: Record<string, string[]>) => void;
/** [144] Punkte einer Bemassung (Kette) — folgt sie der Öffnung? */
dimPts: (id: string) => { x: number; y: number }[];
/** [144] Texte der Hinweise (Benachrichtigungen). */
notices: () => string[];
/** [277] Rendering mit Ersatz-Cycles (acht Samples à 250 ms, Farbverlauf als Bild): macht den Dialog im Browser durchspielbar. */
fakeRender: () => void;
/** [173] Linien einer Klasse (z. B. "door-lintel") im Grundriss der aktiven Ebene (alle Kategorien, 1:50, Detailgrad der Anzeige). */
planLines: (cls: string) => number;
/** [281] Neigung je Decke (`id` → {rise, ramp}; waagrecht fehlt). */
ceilingSlopes: () => Record<string, { rise: number; ramp: boolean }>;
/** [281] Gefällelinie einer Decke (from/to in Metern; fehlt bei waagrechter Decke). */
ceilingSlopeLine: (id: string) => { from: { x: number; y: number }; to: { x: number; y: number } } | undefined;
/** [173] Modelldarstellung der aktiven Ebene (Feld `modelViewOptionId`). */
modelView: () => string | undefined;
/** [173] Schnitt der aktiven Ebene (1:50, Detailgrad der Anzeige): Zahl der Wand-Schnittflächen und ihre Fläche (m²). */
sectionWalls: () => Promise<{ n: number; area: number }>;
/** [193] Gelände-/Umgebungs-Elemente (Art, Id, bei der Baugrube die erste Umrissecke, bei Höhenlinien der erste Punkt). */
context: () => { id: string; type: string; first?: { x: number; y: number } }[];
/** [271] Füllfarben der Element-Flächen im Grundriss der aktiven Ebene (Farbe → Anzahl, alle Klassen, 1:100). */
planFillColors: () => Record<string, number>;
/** [272] Öffnungs-Ids im Grundriss der aktiven Ebene (alle Klassen, 1:100). */
planOpeningIds: () => string[];
/** [271] Umbau: Filter und Etappe der aktiven Ebene, Zeichen-Status, Status je Wand; [274] neuer Aufbau je Wand („type“ = Sanierungstyp, sonst Typ-Id, leer = keiner). */
renovation: () => { filter: string | null; phase: string | null; draw: string; walls: Record<string, string>; buildUp: Record<string, string> };
/** [272] Varianten: Kombination der aktiven Ebene, Zeichen-Variante, Variante je Element (`set/option`, leer = Hauptmodell), Sätze. */
designOptions: () => { level: Record<string, string>; combination: string | null; combinations: string[]; draw: string | null; elements: Record<string, string>; sets: string[] };
/** [272] Grundriss der aktiven Ebene wie auf dem Bildschirm (mit Bearbeitungsvariante): Wände und grau gezeichnete Wände (ids); dazu derselbe Grundriss für den Druck. */
designOptionPlan: () => { walls: string[]; grey: string[]; greyRooms: string[]; greyDrawings: string[]; printGrey: number };
/** [193] Gefüllte Flächen (Füllfarbe gesetzt) im Grundriss der aktiven Ebene (alle Kategorien, 1:100); bei 0 ist nichts Gefülltes mehr zu sehen. */
planFills: () => number;
/** [193] Höhe (z) des ersten Gelände-Netz-Punkts. */
terrainZ: () => number;
/** [207] Grundriss der aktiven Ebene mit der Ansichtsvorlage `templateId` (Klassen der Vorlage, Massstab 1:500): gefüllte Flächen mit Füllfarbe und Element-Ids. */
templateFills: (templateId: string) => { fill: string; ids: string[] }[];
/** [185] Darstellungszustand der Plan-Ansicht: aktive Ebene, Bildmitte (Modell-m), Zoom (px/m), Massstab. */
viewCamera: () => { levelId: string; center: { x: number; y: number } | null; pxPerMeter: number | null; scale: number };
/** [192] Sichtbare Ebenen-Codes und Zahl der Plan-Primitive (gesamt / mit Wand-Bezug) der aktiven Ebene. */
layerView: () => { wallId: string; visible: string[]; prims: number; wallPrims: number };
/** [195] Strichstärke-Override der Wände (id → mm), nur gesetzte. */
wallWeights: () => Record<string, number>;
/** [190] Auswahl-Aktion wie das native Menü (Bearbeiten > Verbinden usw.), ohne Tastendruck: `runSelectionAction`. */
selectionAction: (id: SelectionActionId) => void;
/** [190] Wände (id, Start, Ende) des Projekts. */
walls: () => { id: string; start: { x: number; y: number }; end: { x: number; y: number } }[];
/** [185] 3D-Element-Filter (Store) und die Wand-ids des 3D-Modells bzw. der Pick-Geometrie mit ihm. */
view3d: () => { only: string[] | null; hidden: string[]; walls: string[]; pickWalls: string[]; floors: string[]; pickOpenings: { id: string; host: string }[] };
/** [253] Objekte der Bibliothek im Projekt (Id, Lage, Drehung, Parameter, Seed, Klasse) mit Ausmass ihrer Plan-Linien (1:50) im aktiven Geschoss; dazu die Klassen-Codes des Projekts. */
libobjs: () => { items: { id: string; libId: string; at: { x: number; y: number }; rotation: number; params: Record<string, number | boolean | string>; seed: number | undefined; categoryCode: string; lines: number; w: number; h: number }[]; layers: string[] };
/** [202] Treppe (Antritt, Zentrum), erster Punkt des ersten Lochs der Decke `ceilingId` und Zahl der Plan-Linien der Treppe im aktiven Geschoss. */
stairHole: (stairId: string, ceilingId: string) => { start: { x: number; y: number }; center: { x: number; y: number } | null; hole0: { x: number; y: number } | null; lines: number };
/** [203] Grundriss der aktiven Ebene wie in der Ansicht (Geschoss-Überlagerung nach Zeichnungsebenen-Modus): Raumstempel je Geschoss (gesamt/gedimmt) und Zahl der Achs-Beschriftungen `axis`. */
planStamps: (axis: string) => { floors: Record<string, { n: number; greyed: number }>; axis: number };
/** [218] Stempel des Raums `roomId` im Grundriss der aktiven Ebene (wie angezeigt): Lage, Schrift der Namenszeile und Zusatzzeilen; `null` ohne Stempel. */
roomStamp: (roomId: string) => { at: { x: number; y: number }; basePt: number; name: { sizePt?: number; font?: string; bold?: boolean }; extra: { text: string; marks?: { sizePt?: number; font?: string; italic?: boolean } }[] } | null;
/** [218] Räume der aktiven Ebene mit Mittelpunkt des Umrisses (Modell-m). */
roomCenters: () => { id: string; name: string; x: number; y: number }[];
/** [205] Pausfolie des Reiters (Store) und ihr Plan für die aktive Ebene: Zahl der Primitive, Linienfarben, Zahl mit Auswahl-Ids, Ausmass. */
trace: () => { trace: unknown; n: number; colors: string[]; withIds: number; bounds: { minX: number; minY: number; maxX: number; maxY: number } | null; probe: { x: number; y: number } | null };
};
}
}
export function installTestHooks(): void {
window.__dossierTest = {
corePanic: () => {
try {
core().__debug_panic(storeDocument(getState().project).id);
} catch (e) {
return e instanceof Error ? e.name : String(e);
}
return "";
},
coreReady,
coreEpoch,
counts: () => {
const p = getState().project;
return { walls: p.walls.length, openings: p.openings?.length ?? 0, drawingLevels: p.drawingLevels.length, beams: p.beams?.length ?? 0, coreJson: storeDocument(p).json().length };
},
lines: () =>
getState().project.drawings2d.flatMap((d) => (d.geom.shape === "line" ? [{ a: d.geom.a, b: d.geom.b }] : [])),
polylines: (prefix) =>
getState().project.drawings2d.flatMap((d) => (d.id.startsWith(prefix) && d.geom.shape === "polyline" ? [{ id: d.id, pts: d.geom.pts }] : [])),
openings: () => (getState().project.openings ?? []).map((o) => ({ id: o.id, hostWallId: o.hostWallId, position: o.position })),
heights: () => {
const p = getState().project;
const ceilings = p.ceilings ?? [];
const ext = verticalExtents(p, p.walls, ceilings);
return {
ceilings: ceilings.map((c, i) => ({ id: c.id, zBottom: ext.ceilings[i].zBottom, zTop: ext.ceilings[i].zTop, thickness: ceilingThickness(p, c) })),
walls: p.walls.map((w, i) => ({ id: w.id, zBottom: ext.walls[i].zBottom, zTop: ext.walls[i].zTop })),
openings: (p.openings ?? []).map((o) => ({ id: o.id, sillHeight: o.sillHeight, height: o.height })),
roofs: (p.roofs ?? []).map((r) => {
const f = p.drawingLevels.find((l) => l.id === r.floorId);
return { id: r.id, eave: r.baseElevation ?? (f ? (f.baseElevation ?? 0) + (f.floorHeight ?? 0) : 0), pitchDeg: r.pitchDeg, parapetHeight: r.parapetHeight ?? 0 };
}),
stairs: (p.stairs ?? []).map((st) => ({ id: st.id, totalRise: st.totalRise ?? NaN, baseOffset: st.baseOffset ?? 0 })),
contours: (p.context ?? []).flatMap((c) => (c.type === "contourSet" ? [{ id: c.id, zs: c.contours.map((k) => k.z) }] : [])),
excavations: (p.context ?? []).flatMap((c) => (c.type === "excavation" ? [{ id: c.id, bottom: c.bottom }] : [])),
};
},
wallWeights: () => Object.fromEntries(getState().project.walls.flatMap((w) => (w.strokeWeight === undefined ? [] : [[w.id, w.strokeWeight]]))),
selectionAction: (id) => runSelectionAction(id),
walls: () => getState().project.walls.map((w) => ({ id: w.id, start: { ...w.start }, end: { ...w.end } })),
select: (patch) => getState().setSelection(patch),
dimPts: (id) => {
const g = getState().project.drawings2d.find((d) => d.id === id)?.geom;
return g?.shape === "dimension" ? g.pts.map((p) => ({ x: p.x, y: p.y })) : [];
},
notices: () => getState().notifications.map((n) => n.message),
fakeRender: () => fakeRender(),
ceilingSlopes: () =>
Object.fromEntries((getState().project.ceilings ?? []).flatMap((c) => (c.slope ? [[c.id, { rise: c.slope.rise, ramp: !!c.slope.ramp }]] : []))),
ceilingSlopeLine: (id) => {
const s = (getState().project.ceilings ?? []).find((c) => c.id === id)?.slope;
return s ? { from: { x: s.from.x, y: s.from.y }, to: { x: s.to.x, y: s.to.y } } : undefined;
},
planLines: (cls) => {
const s = getState();
const codes = new Set<string>();
const walk = (cs: { code: string; children?: unknown[] }[]): void => {
for (const c of cs) {
codes.add(c.code);
walk((c.children ?? []) as { code: string; children?: unknown[] }[]);
}
};
walk(s.project.layers);
return generatePlan(s.project, s.activeLevelId, codes, undefined, s.detail, false, false, true, 50).primitives.filter((q) => q.kind === "line" && q.cls === cls).length;
},
planOpeningIds: () => {
const s = getState();
const codes = new Set<string>();
const walk = (cs: { code: string; children?: unknown[] }[]): void => {
for (const c of cs) {
codes.add(c.code);
walk((c.children ?? []) as { code: string; children?: unknown[] }[]);
}
};
walk(s.project.layers);
const ids = new Set<string>();
for (const q of generatePlan(s.project, s.activeLevelId, codes, undefined, s.detail, false, false, true, 100).primitives) {
const o = (q as { openingId?: string }).openingId;
if (o) ids.add(o);
}
return [...ids].sort();
},
planFillColors: () => {
const s = getState();
const codes = new Set<string>();
const walk = (cs: { code: string; children?: unknown[] }[]): void => {
for (const c of cs) {
codes.add(c.code);
walk((c.children ?? []) as { code: string; children?: unknown[] }[]);
}
};
walk(s.project.layers);
const out: Record<string, number> = {};
for (const q of generatePlan(s.project, s.activeLevelId, codes, undefined, s.detail, false, false, true, 100).primitives) {
if (q.kind !== "polygon" || !q.fill || !Object.entries(q).some(([k, v]) => k.endsWith("Id") && !!v)) continue;
out[q.fill] = (out[q.fill] ?? 0) + 1;
}
return out;
},
designOptions: () => {
const s = getState();
const l = s.project.drawingLevels.find((x) => x.id === s.activeLevelId);
const elements: Record<string, string> = {};
for (const list of [s.project.walls, s.project.openings, s.project.roofs, s.project.ceilings, s.project.rooms]) {
for (const e of (list ?? []) as { id: string; designOption?: { set: string; option: string } }[]) elements[e.id] = e.designOption ? `${e.designOption.set}/${e.designOption.option}` : "";
}
return { level: l?.designOptions ?? {}, combination: l?.designOptionCombination ?? null, combinations: (s.project.designOptionCombinations ?? []).map((x) => x.name), draw: s.drawDesignOption ? `${s.drawDesignOption.set}/${s.drawDesignOption.option}` : null, elements, sets: (s.project.designOptionSets ?? []).map((x) => x.id) };
},
designOptionPlan: () => {
const s = getState();
const codes = collectVisibleCodes(s.project.layers);
const edit = designOptionEditArg(s.project, s.drawDesignOption, s.designOptionGrey);
const walls = new Set<string>();
const grey = new Set<string>();
const greyRooms = new Set<string>();
const greyDrawings = new Set<string>();
for (const q of generateVisibleLevelsPlan(s.project, s.activeLevelId, codes, undefined, s.detail, false, false, undefined, 100, false, edit).primitives) {
// [272] Räume (Rand) und 2D-Elemente (Linien-/Strichfarbe) ausserhalb der Bearbeitungsvariante in der Grau-Linienfarbe.
const r = q as { roomId?: string; drawingId?: string; stroke?: string; color?: string };
if (r.roomId && q.kind === "polygon" && r.stroke === DESIGN_OPTION_GHOST_LINE) greyRooms.add(r.roomId);
if (r.drawingId && (r.color === DESIGN_OPTION_GHOST_LINE || r.stroke === DESIGN_OPTION_GHOST_LINE)) greyDrawings.add(r.drawingId);
const w = (q as { wallId?: string; openingId?: string }).wallId;
if (q.kind !== "polygon" || !w || (q as { openingId?: string }).openingId) continue;
walls.add(w);
if (q.fill === DESIGN_OPTION_GHOST_FILL) grey.add(w);
}
const printGrey = generatePlan(s.project, s.activeLevelId, codes, undefined, s.detail, false, false, true, 100, true, false, null, null, edit).primitives.filter((q) => q.kind === "polygon" && q.fill === DESIGN_OPTION_GHOST_FILL).length;
return { walls: [...walls].sort(), grey: [...grey].sort(), greyRooms: [...greyRooms].sort(), greyDrawings: [...greyDrawings].sort(), printGrey };
},
renovation: () => {
const s = getState();
const l = s.project.drawingLevels.find((x) => x.id === s.activeLevelId);
return {
filter: l?.renovationFilter ?? null,
phase: l?.renovationPhase ?? null,
draw: s.drawRenovation.status,
walls: Object.fromEntries(s.project.walls.map((w) => [w.id, w.renovation?.status ?? "existing"])),
// [274] Wände, Decken und Dächer (Ids sind projektweit eindeutig).
buildUp: Object.fromEntries(
[...s.project.walls, ...(s.project.ceilings ?? []), ...(s.project.roofs ?? [])].map((w) => [w.id, w.renovation?.newTypeId ?? (w.renovation?.renovated ? "type" : "")]),
),
};
},
context: () =>
(getState().project.context ?? []).map((c) => ({ id: c.id, type: c.type, first: c.type === "excavation" ? c.outline[0] : c.type === "contourSet" ? c.contours[0]?.pts[0] : undefined })),
planFills: () => {
const s = getState();
const codes = new Set<string>();
const walk = (cs: { code: string; children?: unknown[] }[]): void => {
for (const c of cs) {
codes.add(c.code);
walk((c.children ?? []) as { code: string; children?: unknown[] }[]);
}
};
walk(s.project.layers);
// Ankommende Treppen anderer Geschosse ([202]: ohne Deckenloch unbeschnitten gezeichnet) gehören nicht zum Geschoss.
const ownStairs = new Set((s.project.stairs ?? []).filter((t) => t.floorId === s.activeLevelId).map((t) => t.id));
return generatePlan(s.project, s.activeLevelId, codes, undefined, s.detail, false, false, true, 100).primitives.filter(
(q) =>
q.kind === "polygon" &&
q.fill &&
q.fill !== "none" &&
(!q.stairId || ownStairs.has(q.stairId)) &&
// nur Füllungen von Elementen (Pfeilspitzen der Schnittmarken u. ä. tragen keine Element-Id)
Object.entries(q).some(([k, v]) => k.endsWith("Id") && !!v),
).length;
},
templateFills: (templateId) => {
const s = getState();
const tpl = (s.project.viewTemplates ?? []).find((x) => x.id === templateId);
if (!tpl) return [];
const codes = new Set<string>();
const walk = (cs: { code: string; children?: unknown[] }[]): void => {
for (const c of cs) {
if (tpl.layerVisibility?.[c.code] !== false) codes.add(c.code);
walk((c.children ?? []) as { code: string; children?: unknown[] }[]);
}
};
walk(s.project.layers);
const tp = projectWithTemplate(s.project, s.activeLevelId, tpl);
const prims = withDocument(tp, () => generatePlan(tp, s.activeLevelId, codes, undefined, "grob", false, true, true, 500).primitives);
return prims.flatMap((q) =>
q.kind === "polygon" && q.fill && q.fill !== "none"
? [{ fill: q.fill as string, ids: Object.entries(q).filter(([k, v]) => k.endsWith("Id") && !!v).map(([k, v]) => `${k}=${String(v)}`) }]
: [],
);
},
terrainZ: () => {
const t = (getState().project.context ?? []).find((c) => c.type === "terrainMesh");
return t && t.type === "terrainMesh" ? t.positions[2] : NaN;
},
modelView: () => getState().project.drawingLevels.find((l) => l.id === getState().activeLevelId)?.modelViewOptionId,
sectionWalls: async () => {
const s = getState();
const level = s.project.drawingLevels.find((l) => l.id === s.activeLevelId);
const out = level ? await computeSection(s.project, level) : null;
if (!out) return { n: 0, area: 0 };
const polys = generateSectionPlan(out, false, { scaleDenominator: 50, detail: s.detail }).primitives.filter((q) => q.kind === "polygon" && !!q.wallId);
const area = (pts: { x: number; y: number }[]) => Math.abs(pts.reduce((a, p, i) => a + p.x * pts[(i + 1) % pts.length].y - pts[(i + 1) % pts.length].x * p.y, 0)) / 2;
return { n: polys.length, area: polys.reduce((a, q) => a + (q.kind === "polygon" ? area(q.pts) : 0), 0) };
},
viewCamera: () => {
const st = getViewStateBridge()?.live();
return {
levelId: getState().activeLevelId,
center: st?.cameraCenter ?? null,
pxPerMeter: st?.cameraPxPerMeter ?? null,
scale: getState().scaleDenominator,
};
},
view3d: () => {
const f = getView3dFilter();
const s = getState();
const p = s.project;
const mode = s.displayModes[BUILTIN_PANEL_IDS.drawingLevels] ?? "all";
const hide = toFilter3d(f, [], hiddenFloorIds(p.drawingLevels, (id) => itemDisplay(mode, id === s.activeLevelId, p.drawingLevels.find((l) => l.id === id)?.visible ?? false)));
const uniq = (ids: string[]) => [...new Set(ids)].sort();
return {
only: f.only,
hidden: f.hidden,
// [216] Wände mit Formöffnung kommen als Körper-Netz (mit `wallId`) statt als Stücke.
walls: (() => {
const m = projectToModel3d(p, { hide });
return uniq([...m.walls.map((w) => w.wallId), ...m.meshes.flatMap((x) => (x.wallId ? [x.wallId] : []))]);
})(),
pickWalls: uniq(pickGeometry(p, 0, hide).walls.map((w) => w.wallId)),
pickOpenings: (() => {
const g = pickGeometry(p, 0, hide);
const ids = uniq([...g.openings.map((o) => o.openingId), ...g.openingMeshes.map((o) => o.openingId)]);
return ids.map((id) => ({ id, host: p.openings?.find((o) => o.id === id)?.hostWallId || p.openings?.find((o) => o.id === id)?.hostRoofId || p.openings?.find((o) => o.id === id)?.hostCeilingId || "" }));
})(),
floors: uniq(projectToModel3d(p, { hide }).walls.map((w) => p.walls.find((x) => x.id === w.wallId)?.floorId ?? "")),
};
},
planStamps: (axis) => {
const s = getState();
const p = s.project;
const mode = s.displayModes[BUILTIN_PANEL_IDS.drawingLevels] ?? "all";
const display = (id: string) => itemDisplay(mode, id === s.activeLevelId, p.drawingLevels.find((l) => l.id === id)?.visible ?? false);
const plan = materializeGreyed(materializeUnderlay(generateVisibleLevelsPlan(p, s.activeLevelId, collectVisibleCodes(p.layers), undefined, s.detail, false, false, display, s.scaleDenominator)), true);
const floorOf = new Map((p.rooms ?? []).map((r) => [r.id, r.floorId]));
const floors: Record<string, { n: number; greyed: number }> = {};
let n = 0;
for (const q of plan.primitives) {
if (q.kind === "text" && q.roomId) {
const f = (floors[floorOf.get(q.roomId) ?? "?"] ??= { n: 0, greyed: 0 });
f.n++;
if (q.greyed) f.greyed++;
} else if (q.kind === "drawingText" && q.text === axis && q.drawingId && p.drawings2d.some((d) => d.id === q.drawingId && d.geom.shape === "grid")) n++;
}
return { floors, axis: n };
},
roomStamp: (roomId) => {
const s = getState();
const p = s.project;
const mode = s.displayModes[BUILTIN_PANEL_IDS.drawingLevels] ?? "all";
const display = (id: string) => itemDisplay(mode, id === s.activeLevelId, p.drawingLevels.find((l) => l.id === id)?.visible ?? false);
const plan = materializeGreyed(materializeUnderlay(generateVisibleLevelsPlan(p, s.activeLevelId, collectVisibleCodes(p.layers), undefined, s.detail, false, false, display, s.scaleDenominator)), true);
for (const q of plan.primitives) {
if (q.kind !== "text" || q.roomId !== roomId) continue;
const m = q.doc.paragraphs[0]?.runs[0]?.marks ?? {};
return { at: q.at, basePt: q.basePt, name: { sizePt: m.sizePt, font: m.font, bold: m.bold }, extra: (q.extraLines ?? []).map((l) => ({ text: l.text, marks: l.marks })) };
}
return null;
},
roomCenters: () => {
const s = getState();
return (s.project.rooms ?? []).filter((r) => r.floorId === s.activeLevelId && r.boundary.length >= 3).map((r) => ({ id: r.id, name: r.name, x: r.boundary.reduce((a, v) => a + v.x, 0) / r.boundary.length, y: r.boundary.reduce((a, v) => a + v.y, 0) / r.boundary.length }));
},
trace: () => {
const s = getState();
const level = s.project.drawingLevels.find((l) => l.id === s.activeLevelId);
const plan = level ? tracePlan(s.project, level, s.trace, { visibleCodes: collectVisibleCodes(s.project.layers), detail: s.detail, scaleDenominator: s.scaleDenominator }) : null;
const prims = plan?.primitives ?? [];
const colors = [...new Set(prims.flatMap((q) => (q.kind === "line" && q.color ? [q.color] : [])))];
const withIds = prims.filter((q) => Object.entries(q).some(([k, v]) => k.endsWith("Id") && v !== undefined)).length;
// Mitte der längsten Pausen-Linie (Klickziel „nicht anwählbar").
let probe: { x: number; y: number } | null = null;
let best = 0;
for (const q of prims) {
if (q.kind !== "line") continue;
const len = Math.hypot(q.b.x - q.a.x, q.b.y - q.a.y);
if (len > best) [best, probe] = [len, { x: (q.a.x + q.b.x) / 2, y: (q.a.y + q.b.y) / 2 }];
}
return { trace: s.trace, n: prims.length, colors, withIds, bounds: plan?.bounds ?? null, probe };
},
libobjs: () => {
const s = getState();
const codes = new Set<string>();
const walk = (cs: { code: string; children?: unknown[] }[]): void => {
for (const c of cs) {
codes.add(c.code);
walk((c.children ?? []) as { code: string; children?: unknown[] }[]);
}
};
walk(s.project.layers);
const prims = generatePlan(s.project, s.activeLevelId, codes, undefined, s.detail, false, false, true, 50).primitives;
const items = s.project.drawings2d.flatMap((d) => {
if (d.geom.shape !== "libobj") return [];
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity, n = 0;
for (const q of prims) {
if (q.kind !== "line" || (q as { drawingId?: string }).drawingId !== d.id) continue;
n++;
for (const p of [q.a, q.b]) [x0, y0, x1, y1] = [Math.min(x0, p.x), Math.min(y0, p.y), Math.max(x1, p.x), Math.max(y1, p.y)];
}
return [{ id: d.id, libId: d.geom.libId, at: { ...d.geom.at }, rotation: d.geom.rotation, params: { ...(d.geom.params ?? {}) }, seed: d.geom.seed, categoryCode: d.categoryCode, lines: n, w: n ? x1 - x0 : 0, h: n ? y1 - y0 : 0 }];
});
return { items, layers: [...codes] };
},
layerView: () => {
const s = getState();
const vis: string[] = [];
const walk = (cs: { code: string; visible: boolean; children?: unknown[] }[]): void => {
for (const c of cs) {
if (c.visible) vis.push(c.code);
walk((c.children ?? []) as { code: string; visible: boolean; children?: unknown[] }[]);
}
};
walk(s.project.layers);
const prims = generatePlan(s.project, s.activeLevelId, new Set(vis), undefined, s.detail, false, false, true, 50).primitives;
return { wallId: s.project.walls.find((w) => w.floorId === s.activeLevelId)?.id ?? s.project.walls[0]?.id ?? "", visible: vis.sort(), prims: prims.length, wallPrims: prims.filter((q) => !!(q as { wallId?: string }).wallId).length };
},
selected: () => ({ drawings: [...getState().selection.drawings], groups: [...getState().selection.groups], all: JSON.stringify(getState().selection) }),
stairHole: (stairId, ceilingId) => {
const s = getState();
const st = (s.project.stairs ?? []).find((x) => x.id === stairId)!;
const hole = (s.project.ceilings ?? []).find((c) => c.id === ceilingId)?.openings?.[0]?.[0];
const codes = new Set<string>();
const walk = (cs: { code: string; children?: unknown[] }[]): void => {
for (const c of cs) {
codes.add(c.code);
walk((c.children ?? []) as { code: string; children?: unknown[] }[]);
}
};
walk(s.project.layers);
const lines = generatePlan(s.project, s.activeLevelId, codes, undefined, s.detail, false, false, true, 50).primitives.filter(
(q) => q.kind === "line" && (q as { stairId?: string }).stairId === stairId,
).length;
return { start: { ...st.start }, center: st.center ? { ...st.center } : null, hole0: hole ? { ...hole } : null, lines };
},
};
}
/** [277] Ersatz für das eingebaute Cycles: acht Samples, abbrechbar, am Ende ein kleines PNG (Farbverlauf). */
function fakeRender(): void {
const gradientPng = async (w: number, h: number): Promise<Uint8Array> => {
const c = document.createElement("canvas");
c.width = w;
c.height = h;
const g = c.getContext("2d")!;
const grad = g.createLinearGradient(0, 0, w, h);
grad.addColorStop(0, "#cfe3f5");
grad.addColorStop(1, "#e8d9c4");
g.fillStyle = grad;
g.fillRect(0, 0, w, h);
const blob = await new Promise<Blob>((res) => c.toBlob((b) => res(b!), "image/png"));
return new Uint8Array(await blob.arrayBuffer());
};
renderJob.overrideDeps({
cyclesAvailable: async () => true,
renderWithCycles: async (_project, req, hooks = {}) => {
const t0 = Date.now();
const status = (stage: "scene" | "start" | "render" | "tonemap" | "done", sample: number) =>
hooks.onStatus?.({ stage, fraction: sample / req.samples, sample, samples: req.samples, elapsedMs: Date.now() - t0, etaMs: stage === "render" && sample > 1 ? (req.samples - sample) * 250 : null });
status("scene", 0);
await new Promise((r) => setTimeout(r, 200));
for (let s = 1; s <= req.samples; s++) {
if (hooks.signal?.aborted) throw new CyclesCancelled();
status("render", s);
await new Promise((r) => setTimeout(r, 250));
}
if (hooks.signal?.aborted) throw new CyclesCancelled();
return { png: await gradientPng(Math.min(req.width, 640), Math.min(req.height, 360)), width: req.width, height: req.height, millis: Date.now() - t0 };
},
});
}