Merge claude/practical-noether-1hb2s1 in [216]
This commit is contained in:
231 files changed
+11368
-1152
No files matched your search
+14
-13
@@ -60,6 +60,7 @@ import { useCommandEngineHost } from "./state/useCommandEngineHost";
|
||||
import { TRANSFORM_COMMANDS, useToolInput } from "./state/useToolInput";
|
||||
import { useSelectionCommands } from "./state/useSelectionCommands";
|
||||
import { openObjectSettings } from "./state/objectSettings";
|
||||
import type { InfoGroupId } from "./panels/objectInfo/groups";
|
||||
import { openObjectSettingsWindowNative, useObjectSettingsWindowHost } from "./native/objectSettingsWindow";
|
||||
import { isTauriRuntime } from "./native/projectFile";
|
||||
import {
|
||||
@@ -183,7 +184,7 @@ export default function App() {
|
||||
// ── Kontextmenüs (transienter UI-State, bleibt lokal) ─────────────────────
|
||||
const {
|
||||
layerClipboard, setLayerClipboard, drawingStyleClipboard, setDrawingStyleClipboard, menu, setMenu, editor,
|
||||
setEditor, nativeLayerSettingsCode, setNativeLayerSettingsCode, stampEditorRoomId, setStampEditorRoomId,
|
||||
setEditor, nativeLayerSettingsCode, setNativeLayerSettingsCode,
|
||||
editTextId, setEditTextId, editTextMinHeightM, setEditTextMinHeightM,
|
||||
} = useContextMenuState();
|
||||
|
||||
@@ -504,14 +505,16 @@ export default function App() {
|
||||
|
||||
// [195] Taste T / Menü „Objekteinstellungen…" (state/objectSettings.ts): unter Tauri natives Nebenfenster ([195b]),
|
||||
// sonst schwebendes Panel.
|
||||
const openSettingsOfObject = () =>
|
||||
openObjectSettings({
|
||||
activeTool,
|
||||
revealObjectSettings: (group) =>
|
||||
isTauriRuntime()
|
||||
? void openObjectSettingsWindowNative(group)
|
||||
: setLayout((l) => revealPanel(l, "object-settings", { x: 96, y: 96, w: 360, h: 560 })),
|
||||
});
|
||||
const settingsDeps = () => ({
|
||||
activeTool,
|
||||
revealObjectSettings: (group: InfoGroupId | null) =>
|
||||
isTauriRuntime()
|
||||
? void openObjectSettingsWindowNative(group)
|
||||
: setLayout((l) => revealPanel(l, "object-settings", { x: 96, y: 96, w: 360, h: 560 })),
|
||||
});
|
||||
const openSettingsOfObject = () => openObjectSettings(settingsDeps());
|
||||
// [218] Doppelklick auf einen Raumstempel: dieselben Objekteinstellungen, Abschnitt „Raumstempel" fokussiert.
|
||||
const openRoomStampSettings = () => openObjectSettings(settingsDeps(), "roomStamp");
|
||||
useObjectSettingsShortcut(shortcutOverrides, engineRef, openSettingsOfObject);
|
||||
useCloseObjectSettingsOnEscape(activeTool !== "select" || commandActive);
|
||||
|
||||
@@ -606,7 +609,8 @@ export default function App() {
|
||||
categoryDisplay,
|
||||
floorDisplay,
|
||||
selectionState: { selection, setSelection, groupPath },
|
||||
contextMenuState: { setMenu, setStampEditorRoomId, editTextId, setEditTextId, setEditTextMinHeightM },
|
||||
contextMenuState: { setMenu, editTextId, setEditTextId, setEditTextMinHeightM },
|
||||
openRoomStampSettings,
|
||||
});
|
||||
|
||||
// „Bild einfügen" (Werkzeug „image") — siehe state/useImportHandling.ts.
|
||||
@@ -655,7 +659,6 @@ export default function App() {
|
||||
onToggleSection3dCut,
|
||||
openLayerSettings,
|
||||
openSettings,
|
||||
onOpenStampEditor,
|
||||
openResources,
|
||||
dxfInputRef,
|
||||
planViewRef,
|
||||
@@ -1034,8 +1037,6 @@ export default function App() {
|
||||
pendingCopyMode={pendingCopyMode}
|
||||
setPendingCopyMode={setPendingCopyMode}
|
||||
commitCopyCount={commitCopyCount}
|
||||
stampEditorRoomId={stampEditorRoomId}
|
||||
setStampEditorRoomId={setStampEditorRoomId}
|
||||
/>
|
||||
|
||||
{/* Aktives Kontextmenü (genau eines), verdrahtet in menus/AppContextMenu.tsx. */}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Project } from "../model/types";
|
||||
import { computeKennzahlen, checkRoomProgram, solidVolume } from "./kennzahlen";
|
||||
import { computeAreaTable } from "./areaTable";
|
||||
|
||||
const sq = (x: number, y: number, s: number) => [
|
||||
{ x, y }, { x: x + s, y }, { x: x + s, y: y + s }, { x, y: y + s },
|
||||
@@ -41,6 +42,11 @@ describe("computeKennzahlen", () => {
|
||||
const k = computeKennzahlen(p);
|
||||
expect(k.gv).toBeCloseTo(300 - 3, 6);
|
||||
});
|
||||
it("[206] ohne freie Körper: GV wie die Flächentabelle (GF × Geschosshöhe), nicht 0", () => {
|
||||
const k = computeKennzahlen(sampleProject);
|
||||
expect(k.gv).toBeGreaterThan(0);
|
||||
expect(k.gv).toBeCloseTo(computeAreaTable(sampleProject).gv, 6);
|
||||
});
|
||||
});
|
||||
|
||||
function areaOf(pts: { x: number; y: number }[]) {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// • Flächen je Geschoss aus den Räumen (SIA 416: GF, NGF/aGF), Summe über das Gebäude.
|
||||
// • Gebäudevolumen (GV) aus den freien Körpern (Massenmodell); Abzugskörper zählen nicht mit,
|
||||
// ihr Volumen wird abgezogen.
|
||||
// ihr Volumen wird abgezogen. Ohne freie Körper GF × Geschosshöhe wie die Flächentabelle ([206]).
|
||||
// • Ausnützungs-/Überbauungsziffer nur mit `project.parcelArea` oder der Parzellengrenze (`siteRules`).
|
||||
// • Raumprogramm (`project.roomProgram`, Soll) gegen die gezeichneten Räume.
|
||||
// Exakt für Prismen/Kegelstümpfe/Kreise, Näherung sonst (Fasen/Rundungen). Raumflächen je
|
||||
@@ -30,7 +30,7 @@ export interface Kennzahlen {
|
||||
levels: LevelKennzahlen[];
|
||||
gf: number;
|
||||
agf: number;
|
||||
/** Gebäudevolumen aus den freien Körpern (m³), Abzugskörper abgezogen. */
|
||||
/** Gebäudevolumen aus den freien Körpern (m³), Abzugskörper abgezogen; ohne Körper GF × Geschosshöhe. */
|
||||
gv: number;
|
||||
/** Bebaute Fläche ≈ GF des untersten Geschosses (m²). */
|
||||
footprint: number;
|
||||
|
||||
+163
-3
@@ -20,6 +20,7 @@
|
||||
// das Massstab-Kriterium einer Regel (ab/bis 1:n) gilt nach --scale;
|
||||
// --model-view <Name> wählt eine Modelldarstellung (eigene Stufe oder grob/mittel/fein) [173]
|
||||
// --hide <Code|Name,…> blendet Klassen aus (z. B. --hide "Schatten,Auto-Bemassung") [180]
|
||||
// --snapshot <Name|id> übernimmt Geschoss, Massstab, Vorlage und Sichtbarkeit eines Ausschnitts [207]
|
||||
// dossier-cli <projekt.obp> ifc [--ebkph] [--ebenen] (IFC mit eBKP-H-Hauptgruppen bzw. Modell-Ebenen als Klassifikation)
|
||||
// --schema 4|2x3: IFC4 (Standard) oder IFC2x3 (Coordination View 2.0)
|
||||
// dossier-cli <projekt.obp> dxf [--binary] [--scale 100] [--dim-unit cm] [--layout]|dwg|ifc|step|obj [--no-mtl]|stl|glb|gltf|schedule [--openings|--elements|--rooms] [--format json|csv|svg|pdf]|kennzahlen [--sia416] [--ivhb] [--format json|csv|svg|pdf] [--agsf m2] [--gruenflaeche m2] [--agf-basis gf|ngf|nf] [--untergeschosse]|raumprogramm [--import tabelle] [--sheet name|nr] [--mode replace|append] [--tolerance %] [--generate] [--format json|csv|svg|pdf] [--save projekt.obp]|sun [--level EG] [--out datei]
|
||||
@@ -35,6 +36,8 @@
|
||||
// dossier-cli <projekt.obp> erkennen [--level EG] [--source ebene] [--out neu.obp]
|
||||
// [154] Bauteile aus 2D-Zeichnung erkennen (Wände, Öffnungen, Räume
|
||||
// ins Geschoss); Bericht als JSON. Z. B. convert plan.dxf p.obp --cmd "erkennen --out e.obp"
|
||||
// dossier-cli <projekt.obp> render --out bild.png [--view iso|perspective|front|back|left|right|top] [--when 2026-06-21T10:00Z]
|
||||
// [--camera Name|id] [--samples 128] [--size 1920x1080] [--cpu] [--blender pfad] [--keep] [211] Rendering mit Blender/Cycles
|
||||
// dossier-cli <projekt.obp> model3d [--explode 3] [--hide …] [--grey …] [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png)
|
||||
// dossier-cli pointcloud-info <datei.las|laz|e57|ply|xyz|pts> [--voxel 0.05] [--max 2000000]
|
||||
// Punktwolke lesen ([B9]) und Bericht als JSON (ohne Projekt)
|
||||
@@ -51,7 +54,9 @@
|
||||
//
|
||||
// WASM-Pakete (src/engine/pkg*) werden aus DOSSIER_WASM_DIR bzw. `<repo>/src/engine` gelesen.
|
||||
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { spawn } from "node:child_process";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import {
|
||||
@@ -141,8 +146,17 @@ import {
|
||||
recognizeMutation,
|
||||
recognizeReport,
|
||||
recognizeSourceLevels,
|
||||
buildRenderPackage,
|
||||
runBlenderRender,
|
||||
defaultRenderTime,
|
||||
BlenderMissingError,
|
||||
BLENDER_CANDIDATES,
|
||||
BLENDER_DOWNLOAD_URL,
|
||||
RENDER_VIEW_PRESETS,
|
||||
findRenderCamera,
|
||||
projectRenderCameras,
|
||||
} from "../core";
|
||||
import type { Filter3d, Project, ViewTemplate } from "../core";
|
||||
import type { BlenderHost, Filter3d, Project, RenderViewPreset, TextureLoader, ViewTemplate } from "../core";
|
||||
import { serveStdio } from "./mcp";
|
||||
import { startBridge } from "./mcpBridge";
|
||||
|
||||
@@ -444,7 +458,7 @@ export async function run(argv: string[]): Promise<number> {
|
||||
if (file === "mcp" && args.flags.has("app")) return runAppBridge(args);
|
||||
if (!file || (!command && args.cmds.length === 0)) {
|
||||
process.stderr.write(
|
||||
"Aufruf: dossier-cli <projekt.obp> <info|validate|migrate|plan|section|elevation|dxf|dwg|ifc|import-ifc|import-mesh|erkennen|step|obj [--no-mtl]|stl|glb|gltf|schedule|kennzahlen|raumprogramm|sun|model3d> [Optionen]\n" +
|
||||
"Aufruf: dossier-cli <projekt.obp> <info|validate|migrate|plan|section|elevation|dxf|dwg|ifc|import-ifc|import-mesh|erkennen|step|obj [--no-mtl]|stl|glb|gltf|schedule|kennzahlen|raumprogramm|sun|model3d|render> [Optionen]\n" +
|
||||
" dossier-cli convert <eingabe.dxf|dwg|ifc|pdf|obj|stl|gltf|glb|ply|obp> <ausgabe.obp|dxf|dwg|ifc|obj|stl|glb|gltf|step> [--cmd \"befehl …\"]…\n" +
|
||||
" dossier-cli <projekt.obp> --cmd \"befehl …\" [--cmd …] ({last} = zuletzt geschriebene Datei)\n" +
|
||||
" dossier-cli pointcloud-info <datei> [--voxel 0.05] [--max 2000000]\n" +
|
||||
@@ -672,6 +686,131 @@ async function meshInto(project: Project, bytes: Uint8Array, path: string, args:
|
||||
return { next: r.project, report: { ...read.report, contextObjects: r.contextObjects } };
|
||||
}
|
||||
|
||||
/** [211] Das Blender-Skript: neben `dist-cli/` (`<repo>/scripts/blender`) bzw. aus `src/cli/` (Vitest); `--script` übersteuert. */
|
||||
function renderScript(args: Args): string {
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const own = args.flags.get("script");
|
||||
const candidates = own ? [own] : [resolve(here, "..", "scripts", "blender", "render_dossier.py"), resolve(here, "..", "..", "scripts", "blender", "render_dossier.py")];
|
||||
const found = candidates.find((c) => existsSync(c));
|
||||
if (!found) return fail(`render: Blender-Skript nicht gefunden (${candidates.join(", ")})`);
|
||||
return readFileSync(found, "utf8");
|
||||
}
|
||||
|
||||
/** [211] Bildkarten der mitgelieferten Materialien (`/assets/materials/…` unter `<repo>/public`); Web-Adressen lädt die CLI nicht. */
|
||||
function localTextureLoader(): TextureLoader {
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const roots = [resolve(here, "..", "public"), resolve(here, "..", "..", "public")];
|
||||
return async (url) => {
|
||||
if (/^[a-z]+:/i.test(url)) return null;
|
||||
for (const r of roots) {
|
||||
const p = join(r, url);
|
||||
if (existsSync(p)) return new Uint8Array(readFileSync(p));
|
||||
}
|
||||
return null;
|
||||
};
|
||||
}
|
||||
|
||||
/** [211] Blender als Kindprozess (Node): Programmdatei suchen, Arbeitsordner im Temp-Ordner, Ausgabe zeilenweise. */
|
||||
function nodeBlenderHost(keep: boolean): BlenderHost {
|
||||
let dir = "";
|
||||
return {
|
||||
async find(custom) {
|
||||
const c = custom?.trim();
|
||||
if (c) {
|
||||
if (existsSync(c)) return c;
|
||||
const inner = join(c, "Contents", "MacOS", "Blender");
|
||||
return existsSync(inner) ? inner : null;
|
||||
}
|
||||
for (const d of (process.env.PATH ?? "").split(process.platform === "win32" ? ";" : ":")) {
|
||||
if (d && existsSync(join(d, "blender"))) return join(d, "blender");
|
||||
}
|
||||
return BLENDER_CANDIDATES.find((p) => existsSync(p)) ?? null;
|
||||
},
|
||||
async prepare(files) {
|
||||
dir = mkdtempSync(join(tmpdir(), "dossier-render-"));
|
||||
for (const f of files) {
|
||||
const target = join(dir, f.path);
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
writeFileSync(target, f.bytes);
|
||||
}
|
||||
if (keep) process.stderr.write(`Arbeitsordner: ${dir}\n`);
|
||||
return dir;
|
||||
},
|
||||
spawn(exe, argv, onLine) {
|
||||
const child = spawn(exe, argv, { stdio: ["ignore", "pipe", "pipe"] });
|
||||
const feed = (): ((d: Buffer) => void) => {
|
||||
let rest = "";
|
||||
return (d) => {
|
||||
const parts = (rest + d.toString("utf8")).split(/[\r\n]+/);
|
||||
rest = parts.pop() ?? "";
|
||||
for (const p of parts) if (p) onLine(p);
|
||||
};
|
||||
};
|
||||
child.stdout.on("data", feed());
|
||||
child.stderr.on("data", feed());
|
||||
const done = new Promise<number>((res) => {
|
||||
child.on("error", (e) => {
|
||||
onLine(`DOSSIER_ERROR ${e.message}`);
|
||||
res(1);
|
||||
});
|
||||
child.on("close", (code) => res(code ?? -1));
|
||||
});
|
||||
return { done, cancel: () => void child.kill() };
|
||||
},
|
||||
async readFile(path) {
|
||||
return new Uint8Array(readFileSync(path));
|
||||
},
|
||||
join: (d, r) => join(d, r),
|
||||
};
|
||||
}
|
||||
|
||||
/** `dossier-cli … render`: Paket bauen, Blender starten, Bild nach `--out`. Rückgabe = Exit-Code. */
|
||||
async function runRender(project: Project, args: Args): Promise<number> {
|
||||
const view = (args.flags.get("view") ?? "iso") as RenderViewPreset;
|
||||
if (!(RENDER_VIEW_PRESETS as readonly string[]).includes(view)) return fail(`--view: ${RENDER_VIEW_PRESETS.join("|")}`);
|
||||
// [213] `--camera <Name|id>`: gespeicherte Kamera (Standpunkt, Ziel, Bildwinkel; Sonnenzeit der Kamera, falls `--when` fehlt).
|
||||
const camKey = args.flags.get("camera");
|
||||
const choice = camKey ? findRenderCamera(project, camKey) : null;
|
||||
if (camKey && !choice) return fail(`--camera: "${camKey}" nicht gefunden (vorhanden: ${projectRenderCameras(project).map((c) => c.name).join(", ") || "keine"})`);
|
||||
const whenText = args.flags.get("when");
|
||||
const when = whenText ? new Date(whenText) : (choice?.sunWhen ?? defaultRenderTime(project));
|
||||
if (Number.isNaN(when.getTime())) return fail("--when: ungültiges Datum");
|
||||
const samples = Number(args.flags.get("samples") ?? 128);
|
||||
if (!Number.isFinite(samples) || samples < 1) return fail("--samples: Zahl ≥ 1");
|
||||
const sizeText = args.flags.get("size") ?? "1920x1080";
|
||||
const m = /^(\d+)x(\d+)$/i.exec(sizeText);
|
||||
if (!m) return fail("--size: BreitexHöhe in Pixeln, z. B. 1920x1080");
|
||||
await loadFileio();
|
||||
const pkg = await buildRenderPackage(
|
||||
project,
|
||||
{ width: Number(m[1]), height: Number(m[2]), samples, when, camera: choice ? choice.camera : { preset: view }, device: args.flags.has("cpu") ? "cpu" : "auto" },
|
||||
localTextureLoader(),
|
||||
);
|
||||
if (pkg.missingTextures.length > 0) process.stderr.write(`Hinweis: ${pkg.missingTextures.length} Bildkarten nicht lesbar (Material erscheint einfarbig)\n`);
|
||||
const target = args.flags.get("out") ?? `${project.name || "projekt"}.png`;
|
||||
try {
|
||||
const res = await runBlenderRender(nodeBlenderHost(args.flags.has("keep")), pkg, {
|
||||
script: renderScript(args),
|
||||
blenderPath: args.flags.get("blender"),
|
||||
onLine: args.flags.has("verbose") ? (l) => process.stderr.write(` ${l}\n`) : undefined,
|
||||
onProgress: (e) => {
|
||||
if (e.stage === "render" && e.done > 0 && e.total > 0 && (e.done === e.total || e.done % Math.max(1, Math.floor(e.total / 8)) === 0)) process.stderr.write(`Sample ${e.done}/${e.total}\n`);
|
||||
},
|
||||
});
|
||||
writeFileSync(target, res.png);
|
||||
lastOutput = target;
|
||||
process.stderr.write(`geschrieben: ${target} (${res.png.length} Bytes)\n`);
|
||||
return 0;
|
||||
} catch (e) {
|
||||
if (e instanceof BlenderMissingError) {
|
||||
process.stderr.write(`Blender nicht gefunden. Installieren (${BLENDER_DOWNLOAD_URL}) oder --blender <pfad> angeben.\n`);
|
||||
return 3;
|
||||
}
|
||||
process.stderr.write(`dossier-cli: ${e instanceof Error ? e.message : String(e)}\n`);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/** Führt EINEN Befehl gegen ein geladenes Projekt aus (Rückgabe = Exit-Code). */
|
||||
async function execute(project: Project, file: string, command: string, rest: string[], args: Args): Promise<number> {
|
||||
const scale = Number(args.flags.get("scale") ?? 100);
|
||||
@@ -685,6 +824,24 @@ async function execute(project: Project, file: string, command: string, rest: st
|
||||
};
|
||||
collectCodes(project.layers);
|
||||
|
||||
// [207] `--snapshot <Name|id>` (plan/section/elevation): Geschoss, Massstab, verknüpfte Ansichtsvorlage und Sichtbarkeit eines
|
||||
// Ausschnitts (`viewSnapshots`) übernehmen, z. B. `plan --snapshot "Situation 1:500" --hatch`. Ausdrückliche Flags gehen vor.
|
||||
const snapName = args.flags.get("snapshot");
|
||||
if (snapName && (command === "plan" || command === "section" || command === "elevation")) {
|
||||
const n = snapName.toLowerCase();
|
||||
const snap = (project.viewSnapshots ?? []).find((s) => s.id.toLowerCase() === n || s.name.toLowerCase() === n);
|
||||
if (!snap) fail(`Ausschnitt nicht gefunden: ${snapName}`);
|
||||
const level = project.drawingLevels.find((l) => l.id === snap.activeLevelId);
|
||||
if (!level) fail(`Ausschnitt ${snap.name}: Ebene ${snap.activeLevelId} fehlt`);
|
||||
const f = args.flags;
|
||||
if (!f.has("level")) f.set("level", level.id);
|
||||
if (!f.has("scale")) f.set("scale", String(snap.scaleDenominator));
|
||||
if (!f.has("template") && snap.templateId && snap.templateLinked) f.set("template", snap.templateId);
|
||||
const hidden = [...allCodes].filter((c) => snap.layerVisibility[c] === false || !(c in snap.layerVisibility));
|
||||
if (!f.has("hide") && hidden.length) f.set("hide", hidden.join(","));
|
||||
if (command !== "plan") rest = [rest[0] ?? level.id];
|
||||
}
|
||||
|
||||
switch (command) {
|
||||
case "info": {
|
||||
const levels = project.drawingLevels.map((l) => `${l.kind}:${l.name}`);
|
||||
@@ -1023,6 +1180,9 @@ async function execute(project: Project, file: string, command: string, rest: st
|
||||
case "mcp":
|
||||
await serveStdio(file);
|
||||
return 0;
|
||||
case "render":
|
||||
// [211] Rendering mit Blender/Cycles (Paket + Blender-Prozess, `export/blenderRender.ts`)
|
||||
return runRender(project, args);
|
||||
case "model3d":
|
||||
{
|
||||
// `--explode <m>`: Explosionsaxonometrie ([65]), Geschosse um Index × Abstand angehoben. `--hide`: Klassen aus ([180]).
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
// [211] dossier-cli render: Paket, Aufruf von Blender und Bild — mit einem Blender-Ersatz (Shell-Skript), das die
|
||||
// Kommandozeile prüft, Cycles-Zeilen ausgibt und ein PNG neben scene.json schreibt. Ein echter Blender-Lauf
|
||||
// steht nicht in der Testsuite (Beschreibung in TODO.md [211]).
|
||||
import { describe, expect, it, beforeAll, vi } from "vitest";
|
||||
import { chmodSync, existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { run } from "./main";
|
||||
import { serializeProject } from "../core";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "dossier-cli-render-"));
|
||||
const file = join(dir, "demo.obp");
|
||||
const fake = join(dir, "blender-fake");
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.DOSSIER_WASM_DIR = join(process.cwd(), "src", "engine");
|
||||
writeFileSync(file, serializeProject(sampleProject));
|
||||
// Ersatz-Blender: sucht scene.json hinter `--`, prüft das Skript, schreibt das Bild (PNG-Kopf) daneben.
|
||||
writeFileSync(
|
||||
fake,
|
||||
`#!/bin/sh
|
||||
echo "args: $@" > "${dir}/fake-args.txt"
|
||||
scene=""
|
||||
script=""
|
||||
prev=""
|
||||
for a in "$@"; do
|
||||
if [ "$prev" = "--python" ]; then script="$a"; fi
|
||||
prev="$a"
|
||||
scene="$a"
|
||||
done
|
||||
[ -f "$script" ] || { echo "DOSSIER_ERROR Skript fehlt"; exit 1; }
|
||||
[ -f "$scene" ] || { echo "DOSSIER_ERROR scene.json fehlt"; exit 1; }
|
||||
cp "$scene" "${dir}/fake-scene.json"
|
||||
echo "DOSSIER_STAGE render"
|
||||
echo "Fra:1 Mem:1M | Sample 8/16"
|
||||
echo "Fra:1 Mem:1M | Sample 16/16"
|
||||
printf '\\211PNG\\r\\n\\032\\n' > "$(dirname "$scene")/render.png"
|
||||
echo "DOSSIER_DONE x"
|
||||
`,
|
||||
);
|
||||
chmodSync(fake, 0o755);
|
||||
});
|
||||
|
||||
describe("dossier-cli render", () => {
|
||||
it("baut das Paket, ruft Blender mit dem Skript auf und schreibt das Bild", async () => {
|
||||
const png = join(dir, "bild.png");
|
||||
const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
|
||||
try {
|
||||
expect(await run([file, "render", "--out", png, "--view", "front", "--when", "2026-06-21T10:00Z", "--samples", "16", "--size", "640x360", "--cpu", "--blender", fake])).toBe(0);
|
||||
} finally {
|
||||
err.mockRestore();
|
||||
}
|
||||
expect(existsSync(png)).toBe(true);
|
||||
expect(Array.from(readFileSync(png).subarray(1, 4))).toEqual([80, 78, 71]);
|
||||
const args = readFileSync(join(dir, "fake-args.txt"), "utf8");
|
||||
expect(args).toMatch(/-b --python-exit-code 1 --python .*render_dossier\.py -- .*scene\.json/);
|
||||
const scene = JSON.parse(readFileSync(join(dir, "fake-scene.json"), "utf8"));
|
||||
expect(scene.camera).toEqual({ preset: "front" });
|
||||
expect(scene.resolution).toEqual({ width: 640, height: 360 });
|
||||
expect(scene.samples).toBe(16);
|
||||
expect(scene.device).toBe("cpu");
|
||||
expect(scene.sun.when).toBe("2026-06-21T10:00:00.000Z");
|
||||
expect(scene.sun.elevation).toBeGreaterThan(40);
|
||||
}, 60_000);
|
||||
|
||||
it("--camera: gespeicherte Kamera und deren Sonnenzeit (--when übersteuert)", async () => {
|
||||
const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
|
||||
try {
|
||||
expect(await run([":musterhaus-komplex", "render", "--out", join(dir, "k.png"), "--camera", "Südost", "--samples", "8", "--size", "320x180", "--cpu", "--blender", fake])).toBe(0);
|
||||
const scene = JSON.parse(readFileSync(join(dir, "fake-scene.json"), "utf8"));
|
||||
expect(scene.camera.kind).toBe("perspective");
|
||||
expect(scene.camera.position[0]).toBeCloseTo(17, 6);
|
||||
expect(scene.camera.position[1]).toBeCloseTo(-3, 6);
|
||||
expect(scene.camera.fovDeg).toBe(50);
|
||||
expect(scene.sun.when).toBe("2026-06-21T16:00:00.000Z");
|
||||
expect(await run([":musterhaus-komplex", "render", "--out", join(dir, "k2.png"), "--camera", "kamera-suedost", "--when", "2026-06-21T08:00Z", "--samples", "8", "--size", "320x180", "--cpu", "--blender", fake])).toBe(0);
|
||||
expect(JSON.parse(readFileSync(join(dir, "fake-scene.json"), "utf8")).sun.when).toBe("2026-06-21T08:00:00.000Z");
|
||||
// `fail()` beendet den Prozess: hier als Ausnahme abfangen.
|
||||
const exit = vi.spyOn(process, "exit").mockImplementation((() => {
|
||||
throw new Error("exit");
|
||||
}) as never);
|
||||
await expect(run([":musterhaus-komplex", "render", "--out", join(dir, "k3.png"), "--camera", "gibt-es-nicht", "--blender", fake])).rejects.toThrow("exit");
|
||||
exit.mockRestore();
|
||||
expect(err.mock.calls.map((c) => String(c[0])).join("")).toContain("--camera");
|
||||
} finally {
|
||||
err.mockRestore();
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
it("ohne Blender: Hinweis und Exit-Code 3", async () => {
|
||||
const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
|
||||
try {
|
||||
expect(await run([file, "render", "--out", join(dir, "x.png"), "--blender", join(dir, "gibt-es-nicht")])).toBe(3);
|
||||
expect(err.mock.calls.map((c) => String(c[0])).join("")).toContain("Blender nicht gefunden");
|
||||
} finally {
|
||||
err.mockRestore();
|
||||
}
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -10,8 +10,8 @@
|
||||
// bestehende Decken-Darstellung (generatePlan / 3D); der Draft zeigt den Umriss.
|
||||
//
|
||||
// Herkunft der Decken-Felder (CommandContext):
|
||||
// • wallTypeId ← ctx.activeWallTypeId (Fallback: erster Projekt-Wandtyp) — der
|
||||
// Schichtaufbau (Bauteil/Schraffur/Material) wird identisch zur Wand aufgelöst.
|
||||
// • ceilingTypeId ← erster Deckentyp des Projekts (`ceilingTypes`, [206]); ohne Deckentypen gilt
|
||||
// das Pflichtfeld wallTypeId ← ctx.activeWallTypeId (Fallback: erster Projekt-Wandtyp).
|
||||
// • floorId ← ctx.level.id (aktives Geschoss)
|
||||
// • categoryCode← "30" (Ebene „Decken"; Fallback ctx.defaultCategoryCode)
|
||||
|
||||
|
||||
@@ -38,5 +38,5 @@ describe("[66] Befehl praesentation", () => {
|
||||
expect(q.layouts?.some((l) => l.id === id)).toBe(false);
|
||||
expect(q.drawingLevels.some((l) => l.sketch)).toBe(false);
|
||||
expect(q.drawingLevels.length).toBe(before.drawingLevels.length);
|
||||
});
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
// [211] Rendering mit Blender — öffnet den Dialog (in App montiert) und endet sofort; Muster `presentation`.
|
||||
|
||||
import { openRenderDialog } from "../../state/renderDialogHook";
|
||||
import type { Command, CommandResult, CommandState } from "../types";
|
||||
|
||||
const IDLE: CommandState = { phase: "idle", lastPoint: null };
|
||||
|
||||
function open(): [CommandState, CommandResult] {
|
||||
openRenderDialog();
|
||||
return [{ ...IDLE }, { draft: null, done: true }];
|
||||
}
|
||||
|
||||
export const renderingCommand: Command = {
|
||||
name: "rendering",
|
||||
labelKey: "cmd.rendering.label",
|
||||
prompt: () => "cmd.rendering.prompt",
|
||||
accepts: () => [],
|
||||
options: () => [],
|
||||
init: () => ({ ...IDLE }),
|
||||
autoRun: (): CommandResult => {
|
||||
openRenderDialog();
|
||||
return { draft: null, done: true };
|
||||
},
|
||||
onInput: () => open(),
|
||||
onMove: (state): [CommandState, CommandResult] => [state, { draft: null }],
|
||||
onConfirm: () => open(),
|
||||
onCancel: (): [CommandState, CommandResult] => [{ ...IDLE }, { draft: null, done: true }],
|
||||
};
|
||||
@@ -76,6 +76,7 @@ import { blockCommand } from "./cmds/block";
|
||||
import { defblockCommand } from "./cmds/defblock";
|
||||
import { presentationCommand } from "./cmds/presentation";
|
||||
import { traceMoveCommand, traceRotateCommand } from "./cmds/tracemove";
|
||||
import { renderingCommand } from "./cmds/rendering";
|
||||
|
||||
/** Alle bekannten Befehle, Schlüssel = Befehlsname (lowercase). */
|
||||
export const COMMANDS: Record<string, Command> = {
|
||||
@@ -149,6 +150,7 @@ export const COMMANDS: Record<string, Command> = {
|
||||
multiline: multilineCommand,
|
||||
import: importCommand,
|
||||
praesentation: presentationCommand,
|
||||
rendering: renderingCommand,
|
||||
terrain: terrainCommand,
|
||||
excavation: excavationCommand,
|
||||
meshcrop: meshCropCommand,
|
||||
@@ -201,6 +203,9 @@ export const ALIASES: Record<string, string> = {
|
||||
praesentationsplan: "praesentation",
|
||||
präsentation: "praesentation",
|
||||
presentation: "praesentation",
|
||||
render: "rendering",
|
||||
blender: "rendering",
|
||||
rendern: "rendering",
|
||||
lukarne: "dormer",
|
||||
dachhof: "roofhole",
|
||||
lichthof: "roofhole",
|
||||
|
||||
@@ -72,6 +72,7 @@ export { EMPTY_MEMBERSHIP, containingGroupId, expandToGroups, isInsideActiveGrou
|
||||
export type { GroupMembership, MemberKind } from "../model/groups";
|
||||
export { arcApex, drawingVertices, gripPt, openEdges, polylineEdgeGrips, ringEdges } from "../geometry/grips";
|
||||
export { verticalExtents } from "../geometry/grips";
|
||||
export { cameraGripPoints } from "../geometry/grips";
|
||||
export type { VerticalExtent } from "../geometry/grips";
|
||||
export type { GripRequest, RingKind } from "../geometry/grips";
|
||||
export { edgeArcToggle, type ArcRingKind } from "../geometry/grips";
|
||||
@@ -96,3 +97,10 @@ export { recognizeMutation, recognizeReport, recognizeSourceLevels } from "../io
|
||||
export type { RecognizeOptions, RecognizeReport, RecognizeUnclear } from "../io/recognizeDrawing";
|
||||
export { meshGripIndices, growRect, nearestMeshVertex, meshTolerance } from "../geometry/meshPick";
|
||||
export type { MeshRect } from "../geometry/meshPick";
|
||||
// [211] Rendering mit Blender/Cycles: Export-Paket, Prozess-Ablauf (Gastgeber: Tauri/Electron/Node)
|
||||
export {
|
||||
buildRenderPackage, runBlenderRender, parseBlenderLine, blenderArgs, glbMaterials, renderSun, defaultRenderTime, paperPixels,
|
||||
projectRenderCameras, findRenderCamera,
|
||||
BlenderMissingError, RenderCancelled, RENDER_SIZE_PRESETS, RENDER_QUALITY_PRESETS, RENDER_VIEW_PRESETS, BLENDER_CANDIDATES, BLENDER_DOWNLOAD_URL,
|
||||
} from "../export/blenderRender";
|
||||
export type { BlenderHost, RenderPackage, RenderOptions, RenderScene, RenderCamera, RenderCameraSpec, RenderViewPreset, RenderMaterial, RenderRole, RenderCameraChoice, TextureLoader, BlenderEvent, RenderResult, RenderRunOptions } from "../export/blenderRender";
|
||||
@@ -362,6 +362,16 @@ describe("Kern robust gegen kaputte Projekte", () => {
|
||||
}, 240_000);
|
||||
}
|
||||
|
||||
it("[217] Wände mit negativer/NaN-Höhe unter dem Dach: 3D und Exporte ohne Kern-Panic", async () => {
|
||||
for (const h of [-3, NaN, 0, -1e300]) {
|
||||
const p = clone(richProject());
|
||||
for (const w of list(p, "walls")) w.height = h;
|
||||
for (const r of list(p, "roofs")) r.floorId = list(p, "walls")[0]?.floorId ?? r.floorId;
|
||||
const errors = await runAll(p as unknown as Project);
|
||||
expect(errors, `Höhe ${h}`).toEqual([]);
|
||||
}
|
||||
}, 120_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";
|
||||
|
||||
@@ -39,7 +39,7 @@ export interface RichTextEditorProps {
|
||||
autoFocus?: boolean;
|
||||
/**
|
||||
* "pt" (Default) — absolute Schriftgrösse, passend für ein schwebendes
|
||||
* Dialogfenster ohne Zoom-Bezug (TextEditorDialog). "em" — Grösse relativ
|
||||
* Dialogfenster ohne Zoom-Bezug. "em" — Grösse relativ
|
||||
* zur geerbten Schriftgrösse des `.rt-surface`-Containers: für die beiden
|
||||
* Inline-Editoren AUF der Zeichenfläche/dem Blatt (PlanView/LayoutSheet),
|
||||
* die die Basisgrösse selbst per CSS-Variable aus dem echten Zoom setzen —
|
||||
|
||||
@@ -16,6 +16,7 @@ Abschnitt 3.4).
|
||||
| `exportPdf.ts` | Vektor-PDF eines Plans (Massstab, Papier, Ausrichtung) mit jsPDF und svg2pdf |
|
||||
| `layoutPdf.ts` | alle Layouts eines Ordners als Mehrseiten-PDF |
|
||||
| `pdfLayers.ts` | PDF-Ebenen (Optional Content Groups, `[80]`) |
|
||||
| `pdfInfo.ts` | PDF-Info-Wörterbuch; bei anonymer Wettbewerbs-Abgabe nur das Kennwort, Producer/Datum längengleich neutralisiert (`[208]`) |
|
||||
| `exportDxf.ts` | DXF/DWG des Grundrisses in Modellmetern; Schreiben in `src-tauri/fileio/src/export.rs` |
|
||||
| `legendSvg.ts` | Legende als Plan-/Druck-SVG (`[82]`) |
|
||||
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
// [211] Rendering mit Blender: Szenen-JSON (Kamera, Sonne aus dem Sonnenstand, Materialzuordnung), Paket und
|
||||
// Prozess-Ablauf gegen einen gemockten Gastgeber. Blender selbst läuft hier nicht.
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import "../engine/fileioWasm.setup";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { buildComplexSampleProject } from "../model/sampleProjectComplex";
|
||||
import type { Project } from "../model/types";
|
||||
import { projectLatLon, sunPosition } from "../analysis/sun";
|
||||
import {
|
||||
BlenderMissingError,
|
||||
RenderCancelled,
|
||||
blenderArgs,
|
||||
buildRenderPackage,
|
||||
defaultRenderTime,
|
||||
glbMaterials,
|
||||
paperPixels,
|
||||
parseBlenderLine,
|
||||
renderSun,
|
||||
runBlenderRender,
|
||||
findRenderCamera,
|
||||
projectRenderCameras,
|
||||
renderCameraOf,
|
||||
splitRoofMaterials,
|
||||
TERRAIN_MATERIAL,
|
||||
type BlenderHost,
|
||||
type RenderOptions,
|
||||
} from "./blenderRender";
|
||||
import { exportGlb } from "./exportMesh";
|
||||
import { cameraToView } from "../viewport/cameraView";
|
||||
|
||||
const when = new Date(Date.UTC(2026, 5, 21, 10, 0, 0));
|
||||
const opts = (over: Partial<RenderOptions> = {}): RenderOptions => ({ width: 640, height: 360, samples: 16, when, camera: { preset: "iso" }, ...over });
|
||||
|
||||
describe("Sonne und Kamera in scene.json", () => {
|
||||
it("Sonne = Sonnenstand des Projekts am gewählten Zeitpunkt", () => {
|
||||
const { lat, lon } = projectLatLon(sampleProject);
|
||||
const s = sunPosition(lat, lon, when);
|
||||
const r = renderSun(sampleProject, when);
|
||||
expect(r.azimuth).toBeCloseTo(s.azimuth, 9);
|
||||
expect(r.elevation).toBeCloseTo(s.elevation, 9);
|
||||
expect(r.when).toBe("2026-06-21T10:00:00.000Z");
|
||||
// Mittsommer, Vormittag in Zürich: Sonne im Südosten und hoch.
|
||||
expect(r.azimuth).toBeGreaterThan(90);
|
||||
expect(r.azimuth).toBeLessThan(180);
|
||||
expect(r.elevation).toBeGreaterThan(40);
|
||||
});
|
||||
|
||||
it("Vorbelegung der Zeit aus der Sonnenstudie, sonst Mittsommer", () => {
|
||||
const p: Project = { ...sampleProject, sunStudy: { when: "2026-12-21T11:00:00Z", show: true } };
|
||||
expect(defaultRenderTime(p).toISOString()).toBe("2026-12-21T11:00:00.000Z");
|
||||
expect(defaultRenderTime({ ...sampleProject, sunStudy: undefined }).getUTCMonth()).toBe(5);
|
||||
expect(defaultRenderTime({ ...sampleProject, sunStudy: { when: "kaputt", show: true } }).getUTCMonth()).toBe(5);
|
||||
});
|
||||
|
||||
it("A-Formate bei 300 dpi", () => {
|
||||
expect(paperPixels("a4", "landscape", 300)).toEqual({ width: 3508, height: 2480 });
|
||||
expect(paperPixels("a3", "portrait", 300)).toEqual({ width: 3508, height: 4961 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Materialien aus dem GLB", () => {
|
||||
it("Farbe sRGB, Rauheit, Glas = Alpha-Blend mit Deckkraft < 1", () => {
|
||||
const mats = glbMaterials(exportGlb(buildComplexSampleProject()));
|
||||
expect(mats.length).toBeGreaterThan(2);
|
||||
const glass = mats.filter((m) => m.glass);
|
||||
expect(glass.length).toBeGreaterThan(0);
|
||||
for (const g of glass) expect(g.opacity).toBeLessThan(1);
|
||||
for (const m of mats.filter((m) => !m.glass)) {
|
||||
expect(m.opacity).toBe(1);
|
||||
expect(m.color.every((c) => c >= 0 && c <= 1)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Paket", () => {
|
||||
it("GLB, scene.json und Materialtabelle; Kamera der Ansicht wird übernommen", async () => {
|
||||
const camera = { kind: "perspective" as const, position: [10, -12, 8] as [number, number, number], direction: [-0.5, 0.7, -0.5] as [number, number, number], up: [0, 0, 1] as [number, number, number], fovDeg: 50, orthoHeight: 0 };
|
||||
const pkg = await buildRenderPackage(sampleProject, opts({ camera, samples: 64 }));
|
||||
expect(pkg.files.map((f) => f.path)).toEqual(["model.glb", "scene.json"]);
|
||||
const json = JSON.parse(new TextDecoder().decode(pkg.files[1].bytes));
|
||||
expect(json.camera).toEqual(camera);
|
||||
expect(json.resolution).toEqual({ width: 640, height: 360 });
|
||||
expect(json.samples).toBe(64);
|
||||
expect(json.denoise).toBe(true);
|
||||
expect(json.model).toBe("model.glb");
|
||||
expect(json.sun.azimuth).toBeCloseTo(renderSun(sampleProject, when).azimuth, 9);
|
||||
expect(json.materials.length).toBeGreaterThan(0);
|
||||
const glb = pkg.files[0].bytes;
|
||||
expect(new DataView(glb.buffer, glb.byteOffset).getUint32(0, true)).toBe(0x46546c67);
|
||||
});
|
||||
|
||||
it("Texturen aus dem Material-System: nach Bauteilname zugeordnet, einmal gespeichert, fehlende gemeldet", async () => {
|
||||
// Bauteil, das im GLB vorkommt: dessen Name steht in der Materialtabelle.
|
||||
const names = new Set(glbMaterials(exportGlb(sampleProject)).map((m) => m.name));
|
||||
const comp = sampleProject.components.find((c) => names.has(c.name));
|
||||
expect(comp).toBeDefined();
|
||||
const withMat: Project = {
|
||||
...sampleProject,
|
||||
components: sampleProject.components.map((c) =>
|
||||
c.id === comp!.id ? { ...c, material: { color: "/assets/materials/Concrete048/color.jpg", normal: "/assets/materials/Concrete048/normal.jpg", roughness: "https://example.test/gibt-es-nicht.png", sizeM: 2 } } : c,
|
||||
),
|
||||
};
|
||||
const loaded: string[] = [];
|
||||
const pkg = await buildRenderPackage(withMat, opts(), async (url) => {
|
||||
loaded.push(url);
|
||||
return url.includes("example.test") ? null : new Uint8Array([1, 2, 3]);
|
||||
});
|
||||
const used = pkg.scene.materials.filter((m) => m.name === comp!.name && m.textures);
|
||||
expect(used.length).toBeGreaterThan(0);
|
||||
expect(used[0].textures).toEqual({ color: "textures/0_color.jpg", normal: "textures/1_normal.jpg" });
|
||||
expect(used[0].sizeM).toBe(2);
|
||||
expect(pkg.files.map((f) => f.path)).toContain("textures/0_color.jpg");
|
||||
expect(pkg.missingTextures).toEqual(["https://example.test/gibt-es-nicht.png"]);
|
||||
});
|
||||
|
||||
it("Glas bekommt keine Textur", async () => {
|
||||
const pkg = await buildRenderPackage(buildComplexSampleProject(), opts(), async () => new Uint8Array([1]));
|
||||
for (const m of pkg.scene.materials.filter((m) => m.glass)) expect(m.textures).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Blender-Ausgabe", () => {
|
||||
it("liest Cycles-Fortschritt und die Marken des Skripts", () => {
|
||||
expect(parseBlenderLine("Fra:1 Mem:34.12M (Peak 40M) | Time:00:02.10 | Remaining:00:10.5 | Mem:2M | Scene, ViewLayer | Sample 16/128")).toEqual({ kind: "sample", done: 16, total: 128 });
|
||||
expect(parseBlenderLine("DOSSIER_STAGE render")).toEqual({ kind: "stage", stage: "render" });
|
||||
expect(parseBlenderLine("DOSSIER_DONE /tmp/x/render.png")).toEqual({ kind: "done", path: "/tmp/x/render.png" });
|
||||
expect(parseBlenderLine("DOSSIER_ERROR kaputt")).toEqual({ kind: "error", message: "kaputt" });
|
||||
expect(parseBlenderLine("Blender 4.2.0")).toBeNull();
|
||||
});
|
||||
|
||||
it("Kommandozeile", () => {
|
||||
expect(blenderArgs("/a/s.py", "/a/scene.json")).toEqual(["-b", "--python-exit-code", "1", "--python", "/a/s.py", "--", "/a/scene.json"]);
|
||||
});
|
||||
});
|
||||
|
||||
/** Gemockter Gastgeber: Blender gibt eine feste Ausgabe und schreibt (oder nicht) das Bild. */
|
||||
function fakeHost(lines: string[], o: { code?: number; png?: boolean; exe?: string | null; hang?: boolean } = {}) {
|
||||
const written: { path: string; bytes: Uint8Array }[] = [];
|
||||
const calls: { exe: string; args: string[] }[] = [];
|
||||
let cancelled = false;
|
||||
const host: BlenderHost = {
|
||||
find: async (custom) => (o.exe === undefined ? (custom ?? "/usr/bin/blender") : o.exe),
|
||||
prepare: async (files) => {
|
||||
written.push(...files);
|
||||
return "/tmp/job";
|
||||
},
|
||||
spawn: (exe, args, onLine) => {
|
||||
calls.push({ exe, args });
|
||||
let end!: (c: number) => void;
|
||||
const done = new Promise<number>((r) => (end = r));
|
||||
const cancel = () => {
|
||||
cancelled = true;
|
||||
end(-1);
|
||||
};
|
||||
if (!o.hang) {
|
||||
queueMicrotask(() => {
|
||||
for (const l of lines) onLine(l);
|
||||
end(o.code ?? 0);
|
||||
});
|
||||
}
|
||||
return { done, cancel };
|
||||
},
|
||||
readFile: async () => {
|
||||
if (o.png === false) throw new Error("fehlt");
|
||||
return new Uint8Array([137, 80, 78, 71]);
|
||||
},
|
||||
join: (d, r) => `${d}/${r}`,
|
||||
};
|
||||
return { host, written, calls, wasCancelled: () => cancelled };
|
||||
}
|
||||
|
||||
describe("Prozess-Fassade (gemockt)", () => {
|
||||
it("startet Blender mit dem Skript, meldet Fortschritt und liefert das Bild", async () => {
|
||||
const pkg = await buildRenderPackage(sampleProject, opts());
|
||||
const f = fakeHost(["DOSSIER_STAGE import", "DOSSIER_STAGE render", "Fra:1 | Sample 8/16", "Fra:1 | Sample 16/16", "DOSSIER_DONE /tmp/job/render.png"]);
|
||||
const seen: string[] = [];
|
||||
const res = await runBlenderRender(f.host, pkg, {
|
||||
script: "print('x')",
|
||||
blenderPath: "/opt/Blender",
|
||||
onProgress: (e) => seen.push(`${e.stage}:${Math.round(e.fraction * 100)}`),
|
||||
});
|
||||
expect(f.calls[0].exe).toBe("/opt/Blender");
|
||||
expect(f.calls[0].args).toEqual(blenderArgs("/tmp/job/render_dossier.py", "/tmp/job/scene.json"));
|
||||
expect(new TextDecoder().decode(f.written.find((w) => w.path === "render_dossier.py")!.bytes)).toBe("print('x')");
|
||||
expect(seen).toContain("render:50");
|
||||
expect(seen.at(-1)).toBe("done:100");
|
||||
expect(Array.from(res.png)).toEqual([137, 80, 78, 71]);
|
||||
expect(res.path).toBe("/tmp/job/render.png");
|
||||
});
|
||||
|
||||
it("ohne Blender: BlenderMissingError, nichts wird geschrieben", async () => {
|
||||
const pkg = await buildRenderPackage(sampleProject, opts());
|
||||
const f = fakeHost([], { exe: null });
|
||||
await expect(runBlenderRender(f.host, pkg, { script: "" })).rejects.toBeInstanceOf(BlenderMissingError);
|
||||
expect(f.written).toEqual([]);
|
||||
});
|
||||
|
||||
it("Fehler des Skripts kommt mit seinem Text", async () => {
|
||||
const pkg = await buildRenderPackage(sampleProject, opts());
|
||||
const f = fakeHost(["DOSSIER_ERROR Das Modell enthaelt keine Koerper"], { code: 1 });
|
||||
await expect(runBlenderRender(f.host, pkg, { script: "" })).rejects.toThrow("Das Modell enthaelt keine Koerper");
|
||||
});
|
||||
|
||||
it("Abbrechen beendet den Prozess", async () => {
|
||||
const pkg = await buildRenderPackage(sampleProject, opts());
|
||||
const f = fakeHost([], { hang: true });
|
||||
const ac = new AbortController();
|
||||
const p = runBlenderRender(f.host, pkg, { script: "", signal: ac.signal });
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
ac.abort();
|
||||
await expect(p).rejects.toBeInstanceOf(RenderCancelled);
|
||||
expect(f.wasCancelled()).toBe(true);
|
||||
});
|
||||
|
||||
it("Exit 0 ohne Bild ist ein Fehler", async () => {
|
||||
const pkg = await buildRenderPackage(sampleProject, opts());
|
||||
const f = fakeHost([], { png: false });
|
||||
await expect(runBlenderRender(f.host, pkg, { script: "" })).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Blender-Skript", () => {
|
||||
const path = join(process.cwd(), "scripts", "blender", "render_dossier.py");
|
||||
const script = readFileSync(path, "utf8");
|
||||
|
||||
it("enthält die Schritte: glTF-Import, Himmel mit Sonne, Cycles mit Entrauscher, PNG", () => {
|
||||
for (const marker of ["import_scene.gltf", "ShaderNodeTexSky", "sun_rotation", "OPENIMAGEDENOISE", "METAL", "render.render(write_still=True)", "DOSSIER_DONE"]) {
|
||||
expect(script).toContain(marker);
|
||||
}
|
||||
});
|
||||
|
||||
it("ist gültiges Python", () => {
|
||||
const r = spawnSync("python3", ["-c", "import ast,sys; ast.parse(open(sys.argv[1]).read())", path]);
|
||||
if (r.error) return; // kein Python: übersprungen
|
||||
expect(r.status, String(r.stderr)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Materialzuordnung Gelände und Dach ([211])", () => {
|
||||
const mk = buildComplexSampleProject();
|
||||
|
||||
it("Dachschichten bekommen eigene Materialien nach Baustoff (Ziegel, Kies, Blech), nicht mehr alle „Dach“", async () => {
|
||||
const pkg = await buildRenderPackage(mk, opts(), async () => new Uint8Array([1]));
|
||||
const roofs = pkg.scene.materials.filter((m) => m.role === "roof");
|
||||
const names = roofs.map((m) => m.name);
|
||||
expect(names).toContain("Dach: Tonziegel");
|
||||
expect(names).toContain("Dach: Kies / Sauberkeitsschicht");
|
||||
expect(names).toContain("Dach: Trapezblech");
|
||||
expect(names).not.toContain("Dach");
|
||||
const tile = roofs.find((m) => m.name === "Dach: Tonziegel")!;
|
||||
expect(tile.component).toBe("Tonziegel");
|
||||
// Bildkarten des Baustoffs „Tonziegel“ (RoofingTiles013A), nicht des Namens „Dach“.
|
||||
expect(tile.textures?.color).toBeDefined();
|
||||
expect(tile.sizeM).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("das neue GLB bleibt gültig und die Dachknoten zeigen auf die neuen Materialien", () => {
|
||||
const glb = splitRoofMaterials(exportGlb(mk), mk);
|
||||
const dv = new DataView(glb.buffer, glb.byteOffset, glb.byteLength);
|
||||
expect(dv.getUint32(0, true)).toBe(0x46546c67);
|
||||
expect(dv.getUint32(8, true)).toBe(glb.byteLength);
|
||||
expect(dv.getUint32(12, true) % 4).toBe(0);
|
||||
const json = JSON.parse(new TextDecoder().decode(glb.subarray(20, 20 + dv.getUint32(12, true))));
|
||||
// BIN-Chunk dahinter unverändert vorhanden.
|
||||
const binLen = dv.getUint32(20 + dv.getUint32(12, true), true);
|
||||
expect(20 + dv.getUint32(12, true) + 8 + binLen).toBe(glb.byteLength);
|
||||
const roofNode = json.nodes.find((n: { name?: string }) => n.name === "Dach_dach-haupt");
|
||||
const used = json.meshes[roofNode.mesh].primitives.map((p: { material: number }) => json.materials[p.material].name);
|
||||
expect(used).toEqual(["Dach: Tonziegel"]);
|
||||
});
|
||||
|
||||
it("Gelände: Rolle terrain mit Wiese aus der Bibliothek; ohne Bildkarten bleibt die Rolle für den Leser", async () => {
|
||||
const pkg = await buildRenderPackage(mk, opts(), async () => new Uint8Array([1]));
|
||||
const terrain = pkg.scene.materials.find((m) => m.name === "Gelaende")!;
|
||||
expect(terrain.role).toBe("terrain");
|
||||
expect(terrain.textures?.color).toMatch(/^textures\/\d+_color\.jpg$/);
|
||||
expect(terrain.sizeM).toBe(TERRAIN_MATERIAL.sizeM);
|
||||
expect(TERRAIN_MATERIAL.libraryId).toBe("Grass005");
|
||||
const bare = await buildRenderPackage(mk, opts());
|
||||
const t2 = bare.scene.materials.find((m) => m.name === "Gelaende")!;
|
||||
expect(t2.role).toBe("terrain");
|
||||
expect(t2.textures).toBeUndefined();
|
||||
});
|
||||
|
||||
it("Glas und Öffnungsteile haben ihre Rolle, Wände „building“", async () => {
|
||||
const pkg = await buildRenderPackage(mk, opts());
|
||||
expect(pkg.scene.materials.find((m) => m.glass)?.role).toBe("opening");
|
||||
expect(pkg.scene.materials.find((m) => m.name === "Aussenputz")?.role).toBe("building");
|
||||
});
|
||||
|
||||
it("jedes Material des GLB hat eine Rolle und kommt in der Tabelle vor, nicht benutzte (altes „Dach“) fehlen", () => {
|
||||
const mats = glbMaterials(splitRoofMaterials(exportGlb(mk), mk));
|
||||
expect(mats.every((m) => m.role)).toBe(true);
|
||||
expect(mats.some((m) => m.name === "Dach")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Kamera wählen ([213])", () => {
|
||||
const mk = buildComplexSampleProject();
|
||||
|
||||
it("Südost: gleiche Sicht wie cameraToView, Sonnenzeit der Kamera", () => {
|
||||
const choice = findRenderCamera(mk, "Südost")!;
|
||||
expect(choice).toBeTruthy();
|
||||
expect(choice.id).toBe("kamera-suedost");
|
||||
const cam = mk.cameras![0];
|
||||
const view = cameraToView(mk, cam)!;
|
||||
expect(choice.camera.position).toEqual(view.position);
|
||||
expect(choice.camera.direction).toEqual(view.direction);
|
||||
expect(choice.camera.up).toEqual(view.up);
|
||||
expect(choice.camera.fovDeg).toBe(view.fovDeg);
|
||||
expect(choice.camera.kind).toBe(view.kind);
|
||||
expect(choice.camera.orthoHeight).toBe(view.orthoHeight);
|
||||
expect(choice.sunWhen?.toISOString()).toBe("2026-06-21T16:00:00.000Z");
|
||||
// Augenhöhe 1.6 m über OK EG.
|
||||
expect(choice.camera.position[2]).toBeCloseTo(1.6 + (mk.drawingLevels.find((l) => l.id === "eg")?.baseElevation ?? 0), 9);
|
||||
});
|
||||
|
||||
it("Suche nach Id oder Name (Schreibweise egal), unbekannt = null", () => {
|
||||
expect(findRenderCamera(mk, "kamera-suedost")?.name).toBe("Südost");
|
||||
expect(findRenderCamera(mk, "südost")?.id).toBe("kamera-suedost");
|
||||
expect(findRenderCamera(mk, "gibt es nicht")).toBeNull();
|
||||
expect(projectRenderCameras(sampleProject)).toEqual([]);
|
||||
});
|
||||
|
||||
it("entartete Kamera (Standpunkt = Ziel) fällt aus der Liste", () => {
|
||||
const cam = { ...mk.cameras![0], target: { ...mk.cameras![0].position } };
|
||||
expect(renderCameraOf(mk, { ...cam, targetHeight: 1.6 })).toBeNull();
|
||||
expect(projectRenderCameras({ ...mk, cameras: [{ ...cam, targetHeight: 1.6 }] })).toEqual([]);
|
||||
});
|
||||
|
||||
it("das Paket trägt die Kamera und die Sonne der Kamera", async () => {
|
||||
const choice = findRenderCamera(mk, "Südost")!;
|
||||
const pkg = await buildRenderPackage(mk, opts({ camera: choice.camera, when: choice.sunWhen! }));
|
||||
expect(pkg.scene.camera).toEqual(choice.camera);
|
||||
expect(pkg.scene.sun.when).toBe("2026-06-21T16:00:00.000Z");
|
||||
// Abendsonne: tiefer als zur Vormittagszeit des Projekts.
|
||||
expect(pkg.scene.sun.elevation).toBeLessThan(renderSun(mk, defaultRenderTime(mk)).elevation);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,581 @@
|
||||
// Rendering mit Blender/Cycles ([211]): Export-Paket für ein installiertes Blender (eigener Prozess, GPL —
|
||||
// nichts davon ist in Dossier eingebunden).
|
||||
//
|
||||
// Paket (ein Ordner): `model.glb` (Export [201]: Normalen, PBR-Materialien, Glas als Alpha-Blend), `scene.json`
|
||||
// (Kamera, Sonne, Bildgrösse, Samples, Materialtabelle) und `textures/…` (Bildkarten aus dem Material-System).
|
||||
// Das Python-Skript `scripts/blender/render_dossier.py` liest `scene.json`. Dieses Modul baut nur das Paket;
|
||||
// den Prozess starten die Gastgeber (`src/native/blender.ts`: Tauri/Electron, `src/cli/main.ts`: Node).
|
||||
//
|
||||
// UV-Koordinaten: das GLB hat keine. Texturen legt das Skript per Box-Projektion über Objektkoordinaten
|
||||
// (Kachelgrösse `sizeM` des Materials in Metern), das ersetzt UVs ohne den Rust-Exporter anzufassen.
|
||||
// Materialzuordnung: der glTF-Materialname ist der Bauteilname (`Component.name`); dessen `material` (ambientCG-
|
||||
// Karten) kommt als Textur-Eintrag in die Materialtabelle. Verglasung (Deckkraft < 1) bekommt `glass: true`. Dachschichten
|
||||
// bekommen je Baustoff ein eigenes Material (`splitRoofMaterials`), das Gelände die Wiese `Grass005`, jedes Material seine
|
||||
// Verwendung (`role`, aus dem Knoten des GLB) — der Leser wählt danach Ersatzlooks ohne Bildkarte.
|
||||
//
|
||||
// Das Format ist renderer-neutral und in `doc/RENDER-SZENE.md` beschrieben (Blender-Skript = ein Leser davon;
|
||||
// später auch Cycles-Standalone, [215]).
|
||||
//
|
||||
// Achsen in `scene.json`: Modell-Koordinaten (x Ost, y Nord, z oben, Meter) — Blenders glTF-Import dreht das
|
||||
// Y-oben-GLB genau dorthin zurück, Kamera und Sonne brauchen im Skript keine Umrechnung.
|
||||
|
||||
import type { Camera, ComponentMaterial, LayoutOrientation, LayoutPaperFormat, Project } from "../model/types";
|
||||
import { projectLatLon, sunPosition } from "../analysis/sun";
|
||||
import { sheetSizeMm } from "../model/layoutModel";
|
||||
import { exportGlb } from "./exportMesh";
|
||||
|
||||
/** Kamera in Modell-Koordinaten (gleiche Form wie `ViewCamera` der 3D-Ansicht, `viewport/cameraBridge.ts`). */
|
||||
export interface RenderCamera {
|
||||
kind: "perspective" | "orthogonal";
|
||||
position: [number, number, number];
|
||||
/** Blickrichtung, normiert. */
|
||||
direction: [number, number, number];
|
||||
up: [number, number, number];
|
||||
/** Vertikaler Öffnungswinkel in Grad (perspektivisch). */
|
||||
fovDeg: number;
|
||||
/** Sichthöhe in Metern (orthografisch). */
|
||||
orthoHeight: number;
|
||||
}
|
||||
|
||||
/** Voreingestellte Blickrichtungen; das Skript rahmt das Modell selbst ein (Ortho ausser `perspective`). */
|
||||
export const RENDER_VIEW_PRESETS = ["iso", "perspective", "front", "back", "left", "right", "side", "top"] as const;
|
||||
export type RenderViewPreset = (typeof RENDER_VIEW_PRESETS)[number];
|
||||
|
||||
export type RenderCameraSpec = { preset: RenderViewPreset } | RenderCamera;
|
||||
|
||||
/** Vorgaben für Bildgrössen im Dialog. */
|
||||
export interface RenderSizePreset {
|
||||
id: string;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export const RENDER_SIZE_PRESETS: RenderSizePreset[] = [
|
||||
{ id: "hd", width: 1920, height: 1080 },
|
||||
{ id: "uhd", width: 3840, height: 2160 },
|
||||
{ id: "square", width: 2400, height: 2400 },
|
||||
];
|
||||
|
||||
/** Qualitätsstufen = Samples je Pixel (Cycles, mit Denoiser). */
|
||||
export const RENDER_QUALITY_PRESETS = [
|
||||
{ id: "draft", samples: 32 },
|
||||
{ id: "normal", samples: 128 },
|
||||
{ id: "high", samples: 512 },
|
||||
{ id: "final", samples: 1536 },
|
||||
] as const;
|
||||
|
||||
/** Grösse eines Papierformats in Pixeln bei `dpi` (z. B. A3 quer bei 300 dpi = 4961 × 3508). */
|
||||
export function paperPixels(paper: LayoutPaperFormat, orientation: LayoutOrientation, dpi: number): { width: number; height: number } {
|
||||
const { w, h } = sheetSizeMm(paper, orientation);
|
||||
return { width: Math.max(1, Math.round((w / 25.4) * dpi)), height: Math.max(1, Math.round((h / 25.4) * dpi)) };
|
||||
}
|
||||
|
||||
export interface RenderOptions {
|
||||
width: number;
|
||||
height: number;
|
||||
samples: number;
|
||||
/** Zeitpunkt der Sonne (Datum, UTC-basiert wie `SunStudy.when`). */
|
||||
when: Date;
|
||||
/** Kamera der aktiven 3D-Ansicht oder eine Voreinstellung. */
|
||||
camera: RenderCameraSpec;
|
||||
/** Entrauschen (Standard: an). */
|
||||
denoise?: boolean;
|
||||
/** `cpu` erzwingt die CPU, sonst GPU wenn vorhanden. */
|
||||
device?: "auto" | "cpu";
|
||||
}
|
||||
|
||||
/** Eintrag der Materialtabelle in `scene.json`. */
|
||||
export interface RenderMaterial {
|
||||
/** glTF-Materialname (= Bauteilname). */
|
||||
name: string;
|
||||
/** Basisfarbe sRGB 0..1. */
|
||||
color: [number, number, number];
|
||||
opacity: number;
|
||||
roughness: number;
|
||||
metallic: number;
|
||||
/** Verglasung: der Leser ersetzt Alpha durch Transmission. */
|
||||
glass: boolean;
|
||||
/** Transmission 0..1 (Glas 1, sonst 0), Brechungsindex. Renderer-neutral: jeder Leser setzt sie in sein PBR-Material. */
|
||||
transmission: number;
|
||||
ior: number;
|
||||
/** Dateien relativ zu `scene.json`, nach Karte. */
|
||||
textures?: Partial<Record<TextureKind, string>>;
|
||||
/** Kantenlänge einer Texturkachel in Metern. */
|
||||
sizeM?: number;
|
||||
/** Wofür das Material gebraucht wird (aus dem Bauteil-Knoten des GLB); der Leser wählt danach Ersatzlooks (Wiese, Ziegel, Kontext). */
|
||||
role?: RenderRole;
|
||||
/** Name des Bauteils (Baustoff), dessen Aussehen gilt, wenn er vom Materialnamen abweicht (Dachschicht: `Dach: Tonziegel`). */
|
||||
component?: string;
|
||||
}
|
||||
|
||||
/** Verwendung eines Materials: Gelände, Dach, Kontext-Körper (Nachbarn), Öffnungsteile, sonst Gebäude. */
|
||||
export type RenderRole = "terrain" | "roof" | "context" | "opening" | "building";
|
||||
|
||||
export type TextureKind = "color" | "normal" | "roughness" | "metalness";
|
||||
const TEXTURE_KINDS: TextureKind[] = ["color", "normal", "roughness", "metalness"];
|
||||
|
||||
export interface RenderScene {
|
||||
version: 1;
|
||||
/** Name des Projekts (für Dateinamen und Metadaten). */
|
||||
project: string;
|
||||
model: string;
|
||||
output: string;
|
||||
resolution: { width: number; height: number };
|
||||
samples: number;
|
||||
denoise: boolean;
|
||||
device: "auto" | "cpu";
|
||||
camera: RenderCameraSpec;
|
||||
sun: { azimuth: number; elevation: number; when: string; lat: number; lon: number };
|
||||
materials: RenderMaterial[];
|
||||
}
|
||||
|
||||
/** Sonnenstand aus Ort (`geoAnchor`) und Zeit — dieselbe Rechnung wie Lageplan und 3D-Schatten. */
|
||||
export function renderSun(project: Project, when: Date): RenderScene["sun"] {
|
||||
const { lat, lon } = projectLatLon(project);
|
||||
const s = sunPosition(lat, lon, when);
|
||||
return { azimuth: s.azimuth, elevation: s.elevation, when: when.toISOString(), lat, lon };
|
||||
}
|
||||
|
||||
/** Vorbelegung des Dialogs: Zeit der Sonnenstudie, sonst Mittsommer 14 Uhr (UTC+2 ≈ 12:00 UTC). */
|
||||
export function defaultRenderTime(project: Project): Date {
|
||||
const w = project.sunStudy ? new Date(project.sunStudy.when) : null;
|
||||
return w && Number.isFinite(w.getTime()) ? w : new Date(Date.UTC(2026, 5, 21, 12, 0, 0));
|
||||
}
|
||||
|
||||
/** JSON-Chunk eines GLB. */
|
||||
function glbJson(glb: Uint8Array): GltfJson {
|
||||
const dv = new DataView(glb.buffer, glb.byteOffset, glb.byteLength);
|
||||
if (glb.byteLength < 20 || dv.getUint32(0, true) !== 0x46546c67) throw new Error("Kein GLB");
|
||||
const len = dv.getUint32(12, true);
|
||||
return JSON.parse(new TextDecoder().decode(glb.subarray(20, 20 + len)));
|
||||
}
|
||||
|
||||
interface GltfMaterial {
|
||||
name?: string;
|
||||
alphaMode?: string;
|
||||
extras?: { component?: string };
|
||||
pbrMetallicRoughness?: { baseColorFactor?: number[]; metallicFactor?: number; roughnessFactor?: number };
|
||||
}
|
||||
|
||||
interface GltfJson {
|
||||
materials?: GltfMaterial[];
|
||||
meshes?: { name?: string; primitives: { material?: number }[] }[];
|
||||
nodes?: { name?: string; mesh?: number; extras?: { type?: string; id?: string } }[];
|
||||
}
|
||||
|
||||
/** GLB mit geändertem JSON-Chunk (BIN-Chunk unverändert; Länge auf 4 Byte aufgefüllt). */
|
||||
function glbWithJson(glb: Uint8Array, json: GltfJson): Uint8Array {
|
||||
const dv = new DataView(glb.buffer, glb.byteOffset, glb.byteLength);
|
||||
const oldLen = dv.getUint32(12, true);
|
||||
const rest = glb.subarray(20 + oldLen);
|
||||
const bytes = new TextEncoder().encode(JSON.stringify(json));
|
||||
const padded = new Uint8Array(Math.ceil(bytes.length / 4) * 4).fill(0x20);
|
||||
padded.set(bytes);
|
||||
const out = new Uint8Array(20 + padded.length + rest.length);
|
||||
const odv = new DataView(out.buffer);
|
||||
out.set(glb.subarray(0, 4), 0);
|
||||
odv.setUint32(4, dv.getUint32(4, true), true);
|
||||
odv.setUint32(8, out.length, true);
|
||||
odv.setUint32(12, padded.length, true);
|
||||
out.set(glb.subarray(16, 20), 16);
|
||||
out.set(padded, 20);
|
||||
out.set(rest, 20 + padded.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
const linearToSrgb = (c: number): number => {
|
||||
const x = Math.min(1, Math.max(0, c));
|
||||
return x <= 0.0031308 ? x * 12.92 : 1.055 * Math.pow(x, 1 / 2.4) - 0.055;
|
||||
};
|
||||
|
||||
const hexToLinear = (hex: string): [number, number, number] | null => {
|
||||
const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
|
||||
if (!m) return null;
|
||||
const c = (i: number) => {
|
||||
const v = parseInt(m[1].slice(i, i + 2), 16) / 255;
|
||||
return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
|
||||
};
|
||||
return [c(0), c(2), c(4)];
|
||||
};
|
||||
|
||||
/**
|
||||
* Dachschichten als eigene Materialien. Der Kern legt alle Dachteile unter den Namen „Dach" ab (gleiche Farbe =
|
||||
* ein Material), darum hängt „Ziegel" am selben Material wie „Kies", und Texturen lassen sich nicht zuordnen.
|
||||
* Hier bekommt jedes Dach-Teilnetz ein Material `Dach: <Baustoff>`: die Schicht des Dachtyps (aussen → innen),
|
||||
* deren Baustoff-Farbe die des Teilnetzes ist (sichtbar ist die äusserste), Rückfall die äusserste Schicht.
|
||||
* Hat das Dach eine eigene Farbe (`Roof.color`), bleibt es bei dieser (ohne Baustoff-Textur).
|
||||
*/
|
||||
export function splitRoofMaterials(glb: Uint8Array, project: Project): Uint8Array {
|
||||
const json = glbJson(glb);
|
||||
const mats = json.materials ?? [];
|
||||
const roofById = new Map((project.roofs ?? []).map((r) => [r.id, r]));
|
||||
const made = new Map<string, number>();
|
||||
let changed = false;
|
||||
for (const node of json.nodes ?? []) {
|
||||
if (node.extras?.type !== "roof" || node.mesh === undefined) continue;
|
||||
const roof = roofById.get(node.extras.id ?? "");
|
||||
const type = roof?.roofTypeId ? project.roofTypes?.find((t) => t.id === roof.roofTypeId) : undefined;
|
||||
if (!roof || roof.color || !type || type.layers.length === 0) continue;
|
||||
const layers = type.layers.map((l) => project.components.find((c) => c.id === l.componentId)).filter((c): c is NonNullable<typeof c> => !!c);
|
||||
if (layers.length === 0) continue;
|
||||
for (const prim of json.meshes?.[node.mesh]?.primitives ?? []) {
|
||||
const src = prim.material === undefined ? undefined : mats[prim.material];
|
||||
if (!src || src.name !== "Dach") continue;
|
||||
const f = src.pbrMetallicRoughness?.baseColorFactor ?? [1, 1, 1, 1];
|
||||
const close = (a: [number, number, number] | null) => a !== null && Math.abs(a[0] - f[0]) + Math.abs(a[1] - f[1]) + Math.abs(a[2] - f[2]) < 0.02;
|
||||
const comp = layers.find((c) => close(hexToLinear(c.color))) ?? layers[0];
|
||||
const key = `${comp.name}|${prim.material}`;
|
||||
let idx = made.get(key);
|
||||
if (idx === undefined) {
|
||||
idx = mats.length;
|
||||
mats.push({ ...src, name: `Dach: ${comp.name}`, extras: { component: comp.name } });
|
||||
made.set(key, idx);
|
||||
}
|
||||
prim.material = idx;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed ? glbWithJson(glb, { ...json, materials: mats }) : glb;
|
||||
}
|
||||
|
||||
/** Verwendung je Material aus den Knoten (`extras.type`); bei mehreren gewinnt Gelände vor Kontext, Dach, Öffnung, Gebäude. */
|
||||
const ROLE_PRIORITY: RenderRole[] = ["terrain", "context", "roof", "opening", "building"];
|
||||
function roleOfNode(type: string | undefined): RenderRole {
|
||||
switch (type) {
|
||||
case "terrain":
|
||||
return "terrain";
|
||||
case "context":
|
||||
return "context";
|
||||
case "roof":
|
||||
return "roof";
|
||||
case "window":
|
||||
case "door":
|
||||
case "opening":
|
||||
return "opening";
|
||||
default:
|
||||
return "building";
|
||||
}
|
||||
}
|
||||
|
||||
/** Materialien eines GLB (glTF speichert die Farbe linear, hier sRGB), mit Verwendung; nicht benutzte entfallen. */
|
||||
export function glbMaterials(glb: Uint8Array): RenderMaterial[] {
|
||||
const json = glbJson(glb);
|
||||
const roles = new Map<number, RenderRole>();
|
||||
for (const node of json.nodes ?? []) {
|
||||
if (node.mesh === undefined) continue;
|
||||
const role = roleOfNode(node.extras?.type);
|
||||
for (const prim of json.meshes?.[node.mesh]?.primitives ?? []) {
|
||||
if (prim.material === undefined) continue;
|
||||
const prev = roles.get(prim.material);
|
||||
if (!prev || ROLE_PRIORITY.indexOf(role) < ROLE_PRIORITY.indexOf(prev)) roles.set(prim.material, role);
|
||||
}
|
||||
}
|
||||
const out: RenderMaterial[] = [];
|
||||
(json.materials ?? []).forEach((m, i) => {
|
||||
const p = m.pbrMetallicRoughness ?? {};
|
||||
const f = p.baseColorFactor ?? [1, 1, 1, 1];
|
||||
const opacity = f[3] ?? 1;
|
||||
const glass = m.alphaMode === "BLEND" && opacity < 1;
|
||||
const used = roles.get(i);
|
||||
// Materialien ohne Knoten (Altlasten nach `splitRoofMaterials`) lässt der Leser weg; ohne Knotenangaben (GLB fremder Herkunft) bleiben alle.
|
||||
if (!used && roles.size > 0) return;
|
||||
out.push({
|
||||
name: m.name ?? "",
|
||||
color: [linearToSrgb(f[0] ?? 1), linearToSrgb(f[1] ?? 1), linearToSrgb(f[2] ?? 1)],
|
||||
opacity,
|
||||
roughness: p.roughnessFactor ?? 0.9,
|
||||
metallic: p.metallicFactor ?? 0,
|
||||
glass,
|
||||
transmission: glass ? 1 : 0,
|
||||
ior: 1.5,
|
||||
...(used ? { role: used } : {}),
|
||||
...(m.extras?.component ? { component: m.extras.component } : {}),
|
||||
});
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Liest Bilddateien (URL aus dem Material-System → Bytes) oder liefert null, wenn nicht erreichbar. */
|
||||
export type TextureLoader = (url: string) => Promise<Uint8Array | null>;
|
||||
|
||||
export interface RenderPackage {
|
||||
scene: RenderScene;
|
||||
/** Dateien des Pakets (relative Pfade), `scene.json` und `model.glb` eingeschlossen. */
|
||||
files: { path: string; bytes: Uint8Array }[];
|
||||
/** URLs, die sich nicht laden liessen (Hinweis an den Nutzer; Rendering läuft mit Grundfarbe). */
|
||||
missingTextures: string[];
|
||||
}
|
||||
|
||||
function extensionOf(url: string): string {
|
||||
const m = /\.([a-z0-9]{2,4})(?:[?#].*)?$/i.exec(url);
|
||||
return m ? m[1].toLowerCase() : "jpg";
|
||||
}
|
||||
|
||||
/** Wiese für das Gelände (ambientCG Grass005, im Material-Katalog `public/assets/materials`); Kachel 4 m. */
|
||||
export const TERRAIN_MATERIAL: ComponentMaterial = {
|
||||
libraryId: "Grass005",
|
||||
color: "/assets/materials/Grass005/color.jpg",
|
||||
normal: "/assets/materials/Grass005/normal.jpg",
|
||||
roughness: "/assets/materials/Grass005/roughness.jpg",
|
||||
sizeM: 4,
|
||||
};
|
||||
|
||||
/** Bauteil-Materialkarten nach glTF-Materialname (erste Komponente gleichen Namens mit Farbkarte gewinnt). */
|
||||
function componentMaterials(project: Project): Map<string, ComponentMaterial> {
|
||||
const byName = new Map<string, ComponentMaterial>();
|
||||
for (const c of project.components ?? []) {
|
||||
if (c.material?.color && !byName.has(c.name)) byName.set(c.name, c.material);
|
||||
}
|
||||
return byName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut das Export-Paket für Blender: GLB, Materialtabelle (mit Texturen, soweit `loadTexture` sie liefert),
|
||||
* Kamera, Sonne. Verlangt das geladene Format-Modul (`await loadFileio()`) und den Kern.
|
||||
*/
|
||||
export async function buildRenderPackage(project: Project, opts: RenderOptions, loadTexture?: TextureLoader): Promise<RenderPackage> {
|
||||
const glb = splitRoofMaterials(exportGlb(project), project);
|
||||
const files: RenderPackage["files"] = [{ path: "model.glb", bytes: glb }];
|
||||
const materials = glbMaterials(glb);
|
||||
const comp = componentMaterials(project);
|
||||
const missing: string[] = [];
|
||||
const stored = new Map<string, string>();
|
||||
|
||||
for (const mat of materials) {
|
||||
// Gelände hat im Modell kein Material: Wiese aus der mitgelieferten Bibliothek (ohne Bildkarten übernimmt der Leser eine Wiesenfarbe).
|
||||
const cm = mat.role === "terrain" ? TERRAIN_MATERIAL : comp.get(mat.component ?? mat.name);
|
||||
if (!cm || mat.glass || !loadTexture) continue;
|
||||
const textures: Partial<Record<TextureKind, string>> = {};
|
||||
for (const kind of TEXTURE_KINDS) {
|
||||
const url = cm[kind];
|
||||
if (!url) continue;
|
||||
let path = stored.get(url);
|
||||
if (!path) {
|
||||
const bytes = await loadTexture(url).catch(() => null);
|
||||
if (!bytes || bytes.length === 0) {
|
||||
if (!missing.includes(url)) missing.push(url);
|
||||
continue;
|
||||
}
|
||||
path = `textures/${stored.size}_${kind}.${extensionOf(url)}`;
|
||||
stored.set(url, path);
|
||||
files.push({ path, bytes });
|
||||
}
|
||||
textures[kind] = path;
|
||||
}
|
||||
if (textures.color) {
|
||||
mat.textures = textures;
|
||||
mat.sizeM = cm.sizeM && cm.sizeM > 0 ? cm.sizeM : 1;
|
||||
}
|
||||
}
|
||||
|
||||
const scene: RenderScene = {
|
||||
version: 1,
|
||||
project: project.name || "projekt",
|
||||
model: "model.glb",
|
||||
output: "render.png",
|
||||
resolution: { width: Math.round(opts.width), height: Math.round(opts.height) },
|
||||
samples: Math.max(1, Math.round(opts.samples)),
|
||||
denoise: opts.denoise ?? true,
|
||||
device: opts.device ?? "auto",
|
||||
camera: opts.camera,
|
||||
sun: renderSun(project, opts.when),
|
||||
materials,
|
||||
};
|
||||
files.push({ path: "scene.json", bytes: new TextEncoder().encode(JSON.stringify(scene, null, 2)) });
|
||||
return { scene, files, missingTextures: missing };
|
||||
}
|
||||
|
||||
// ── Kameras ([213]) ─────────────────────────────────────────────────────────
|
||||
|
||||
/** Eine gespeicherte Kamera (`Project.cameras`) als Rendering-Kamera, mit ihrer Sonnenzeit. */
|
||||
export interface RenderCameraChoice {
|
||||
id: string;
|
||||
name: string;
|
||||
camera: RenderCamera;
|
||||
/** `Camera.sunWhen`, falls gesetzt und gültig. */
|
||||
sunWhen?: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sicht einer Kamera in Modell-Koordinaten: Standpunkt = Fussboden des Geschosses + Augenhöhe, Blick zum Ziel,
|
||||
* Up aus der Senkrechten (bei senkrechtem Blick Norden). Gleiche Rechnung wie `viewport/cameraView.ts::cameraToView`
|
||||
* (der Kern darf den Viewport nicht importieren; der Test vergleicht beide). Null bei Standpunkt = Ziel.
|
||||
*/
|
||||
export function renderCameraOf(project: Project, cam: Camera): RenderCamera | null {
|
||||
const base = project.drawingLevels.find((l) => l.id === cam.floorId)?.baseElevation;
|
||||
const eye: [number, number, number] = [cam.position.x, cam.position.y, (typeof base === "number" && Number.isFinite(base) ? base : 0) + (Number.isFinite(cam.eyeHeight) ? cam.eyeHeight : 1.6)];
|
||||
const tgt: [number, number, number] = [cam.target.x, cam.target.y, cam.targetHeight];
|
||||
if (![...eye, ...tgt].every(Number.isFinite)) return null;
|
||||
const d = [tgt[0] - eye[0], tgt[1] - eye[1], tgt[2] - eye[2]];
|
||||
const len = Math.hypot(d[0], d[1], d[2]);
|
||||
if (!(len > 1e-9)) return null;
|
||||
const dir: [number, number, number] = [d[0] / len, d[1] / len, d[2] / len];
|
||||
const ref = Math.abs(dir[2]) > 0.9999 ? [0, 1, 0] : [0, 0, 1];
|
||||
const k = ref[0] * dir[0] + ref[1] * dir[1] + ref[2] * dir[2];
|
||||
const u = [ref[0] - dir[0] * k, ref[1] - dir[1] * k, ref[2] - dir[2] * k];
|
||||
const ul = Math.hypot(u[0], u[1], u[2]);
|
||||
const fov = Number.isFinite(cam.fovDeg) && cam.fovDeg > 0 ? Math.min(120, Math.max(5, cam.fovDeg)) : 50;
|
||||
return {
|
||||
kind: cam.projection === "perspective" ? "perspective" : "orthogonal",
|
||||
position: eye,
|
||||
direction: dir,
|
||||
up: [u[0] / ul, u[1] / ul, u[2] / ul],
|
||||
fovDeg: fov,
|
||||
orthoHeight: cam.orthoHeight && cam.orthoHeight > 0 ? cam.orthoHeight : 10,
|
||||
};
|
||||
}
|
||||
|
||||
/** Alle brauchbaren Kameras des Projekts in Listenreihenfolge. */
|
||||
export function projectRenderCameras(project: Project): RenderCameraChoice[] {
|
||||
const out: RenderCameraChoice[] = [];
|
||||
for (const c of project.cameras ?? []) {
|
||||
const camera = renderCameraOf(project, c);
|
||||
if (!camera) continue;
|
||||
const w = c.sunWhen ? new Date(c.sunWhen) : null;
|
||||
out.push({ id: c.id, name: c.name, camera, ...(w && Number.isFinite(w.getTime()) ? { sunWhen: w } : {}) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Kamera nach Id oder Name (Gross-/Kleinschreibung egal; bei gleichem Namen die erste). */
|
||||
export function findRenderCamera(project: Project, key: string): RenderCameraChoice | null {
|
||||
const all = projectRenderCameras(project);
|
||||
const k = key.trim().toLowerCase();
|
||||
return all.find((c) => c.id === key) ?? all.find((c) => c.name.toLowerCase() === k) ?? null;
|
||||
}
|
||||
|
||||
// ── Blender-Ausgabe lesen ───────────────────────────────────────────────────
|
||||
|
||||
export type BlenderEvent =
|
||||
| { kind: "sample"; done: number; total: number }
|
||||
| { kind: "stage"; stage: string }
|
||||
| { kind: "done"; path: string }
|
||||
| { kind: "error"; message: string }
|
||||
| { kind: "note"; message: string };
|
||||
|
||||
/** Eine Ausgabezeile von Blender: Cycles meldet `… | Sample 16/128`, das Skript die `DOSSIER_*`-Marken. */
|
||||
export function parseBlenderLine(line: string): BlenderEvent | null {
|
||||
const s = /\bSample\s+(\d+)\s*\/\s*(\d+)/.exec(line);
|
||||
if (s) return { kind: "sample", done: Number(s[1]), total: Number(s[2]) };
|
||||
const m = /^DOSSIER_(STAGE|DONE|ERROR|NOTE)\s+(.*)$/.exec(line.trim());
|
||||
if (!m) return null;
|
||||
const text = m[2].trim();
|
||||
switch (m[1]) {
|
||||
case "STAGE":
|
||||
return { kind: "stage", stage: text };
|
||||
case "DONE":
|
||||
return { kind: "done", path: text };
|
||||
case "ERROR":
|
||||
return { kind: "error", message: text };
|
||||
default:
|
||||
return { kind: "note", message: text };
|
||||
}
|
||||
}
|
||||
|
||||
/** Kommandozeile von Blender für das Skript (Hintergrund, Fehler im Skript = Exit-Code 1). */
|
||||
export function blenderArgs(scriptPath: string, scenePath: string): string[] {
|
||||
return ["-b", "--python-exit-code", "1", "--python", scriptPath, "--", scenePath];
|
||||
}
|
||||
|
||||
/** Aufruf-Gastgeber (Tauri, Electron, Node): alles, was nur ein Prozess/Dateisystem kann. */
|
||||
export interface BlenderHost {
|
||||
/** Pfad der Blender-Programmdatei (eigene Angabe zuerst, dann übliche Orte), oder null. */
|
||||
find(custom?: string): Promise<string | null>;
|
||||
/** Legt einen neuen Arbeitsordner an, schreibt die Dateien hinein, gibt den Ordner zurück. */
|
||||
prepare(files: { path: string; bytes: Uint8Array }[]): Promise<string>;
|
||||
/** Startet Blender; `onLine` für jede Ausgabezeile (stdout und stderr). */
|
||||
spawn(exe: string, args: string[], onLine: (line: string) => void): { done: Promise<number>; cancel(): void };
|
||||
readFile(path: string): Promise<Uint8Array>;
|
||||
/** Pfad zu `dir/rel`. */
|
||||
join(dir: string, rel: string): string;
|
||||
}
|
||||
|
||||
export class BlenderMissingError extends Error {
|
||||
constructor() {
|
||||
super("Blender nicht gefunden");
|
||||
this.name = "BlenderMissingError";
|
||||
}
|
||||
}
|
||||
|
||||
export class RenderCancelled extends Error {
|
||||
constructor() {
|
||||
super("Rendering abgebrochen");
|
||||
this.name = "RenderCancelled";
|
||||
}
|
||||
}
|
||||
|
||||
export interface RenderRunOptions {
|
||||
/** Eigener Blender-Pfad (Einstellungen). */
|
||||
blenderPath?: string;
|
||||
/** Text des Python-Skripts (`scripts/blender/render_dossier.py`). */
|
||||
script: string;
|
||||
/** Fortschritt 0..1 (Samples) und Phase. */
|
||||
onProgress?: (e: { fraction: number; stage: string; done: number; total: number }) => void;
|
||||
/** Rohausgabe von Blender (für Fehlermeldungen/Protokoll). */
|
||||
onLine?: (line: string) => void;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface RenderResult {
|
||||
png: Uint8Array;
|
||||
dir: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Packt das Paket aus, startet Blender, meldet den Fortschritt und liest das Bild. Wirft
|
||||
* {@link BlenderMissingError}, {@link RenderCancelled} oder einen Fehler mit der Meldung des Skripts.
|
||||
*/
|
||||
export async function runBlenderRender(host: BlenderHost, pkg: RenderPackage, opts: RenderRunOptions): Promise<RenderResult> {
|
||||
const exe = await host.find(opts.blenderPath);
|
||||
if (!exe) throw new BlenderMissingError();
|
||||
const dir = await host.prepare([...pkg.files, { path: "render_dossier.py", bytes: new TextEncoder().encode(opts.script) }]);
|
||||
const scenePath = host.join(dir, "scene.json");
|
||||
let stage = "import";
|
||||
let error = "";
|
||||
let lastLines: string[] = [];
|
||||
const total = pkg.scene.samples;
|
||||
const job = host.spawn(exe, blenderArgs(host.join(dir, "render_dossier.py"), scenePath), (line) => {
|
||||
opts.onLine?.(line);
|
||||
lastLines.push(line);
|
||||
if (lastLines.length > 12) lastLines = lastLines.slice(-12);
|
||||
const ev = parseBlenderLine(line);
|
||||
if (!ev) return;
|
||||
if (ev.kind === "stage") {
|
||||
stage = ev.stage;
|
||||
opts.onProgress?.({ fraction: 0, stage, done: 0, total });
|
||||
} else if (ev.kind === "sample") {
|
||||
opts.onProgress?.({ fraction: ev.total > 0 ? Math.min(1, ev.done / ev.total) : 0, stage: "render", done: ev.done, total: ev.total });
|
||||
} else if (ev.kind === "error") {
|
||||
error = ev.message;
|
||||
}
|
||||
});
|
||||
const onAbort = () => job.cancel();
|
||||
opts.signal?.addEventListener("abort", onAbort);
|
||||
if (opts.signal?.aborted) job.cancel();
|
||||
let code: number;
|
||||
try {
|
||||
code = await job.done;
|
||||
} finally {
|
||||
opts.signal?.removeEventListener("abort", onAbort);
|
||||
}
|
||||
if (opts.signal?.aborted) throw new RenderCancelled();
|
||||
if (code !== 0) throw new Error(error || `Blender beendet mit Code ${code}: ${lastLines.slice(-3).join(" | ")}`);
|
||||
const path = host.join(dir, pkg.scene.output);
|
||||
const png = await host.readFile(path).catch(() => null);
|
||||
if (!png || png.length === 0) throw new Error(error || "Blender hat kein Bild geschrieben");
|
||||
opts.onProgress?.({ fraction: 1, stage: "done", done: total, total });
|
||||
return { png, dir, path };
|
||||
}
|
||||
|
||||
/** Übliche Blender-Orte, in Suchreihenfolge (macOS-App, Linux-Pakete). `blender` im PATH prüft der Gastgeber zuerst. */
|
||||
export const BLENDER_CANDIDATES = [
|
||||
"/Applications/Blender.app/Contents/MacOS/Blender",
|
||||
"/usr/bin/blender",
|
||||
"/usr/local/bin/blender",
|
||||
"/snap/bin/blender",
|
||||
"/var/lib/flatpak/exports/bin/org.blender.Blender",
|
||||
];
|
||||
|
||||
/** Download-Seite für den Hinweis ohne Blender. */
|
||||
export const BLENDER_DOWNLOAD_URL = "https://www.blender.org/download/";
|
||||
@@ -16,6 +16,8 @@ import "svg2pdf.js";
|
||||
import type { Plan } from "../plan/generatePlan";
|
||||
import { planToRenderScene } from "../plan/toRenderScene";
|
||||
import { sceneToPrintSvg } from "./sceneToPrintSvg";
|
||||
import type { Project } from "../model/types";
|
||||
import { finishPdfBytes, pdfInfoFields } from "./pdfInfo";
|
||||
|
||||
/** Unterstützte Papierformate (Blattmasse in mm, Hochformat-Basis). */
|
||||
export type PaperFormat = "a4" | "a3";
|
||||
@@ -42,6 +44,8 @@ export interface ExportPdfOptions {
|
||||
titleBlock?: boolean;
|
||||
/** Dateiname des Downloads (ohne/inkl. .pdf). */
|
||||
fileName?: string;
|
||||
/** Wettbewerb ([208]): bei anonymer Abgabe nur das Kennwort als Titel, keine Erzeuger-/Datumsangaben im PDF. */
|
||||
competition?: Project["competition"];
|
||||
}
|
||||
|
||||
/** Blattmasse (mm) nach Format + Ausrichtung. */
|
||||
@@ -90,6 +94,8 @@ export async function buildPlanPdf(
|
||||
// und deckungsgleich mit der Blattgröße; svg2pdf bildet sie 1:1 auf das mm-Ziel
|
||||
// (Blattbreite/-höhe) ab.
|
||||
await doc.svg(print.svg, { x: 0, y: 0, width: pageW, height: pageH });
|
||||
// Info-Wörterbuch ([208]): anonym nur das Kennwort.
|
||||
doc.setProperties(pdfInfoFields({ name: opts.subtitle ?? opts.title, competition: opts.competition }));
|
||||
|
||||
if (opts.titleBlock ?? true) {
|
||||
drawTitleBlock(doc, pageW, pageH, opts);
|
||||
@@ -149,5 +155,16 @@ export async function savePlanPdf(
|
||||
): Promise<void> {
|
||||
const doc = await buildPlanPdf(plan, opts);
|
||||
const name = (opts.fileName ?? "grundriss").replace(/\.pdf$/i, "");
|
||||
if (opts.competition?.anonymous) {
|
||||
// doc.save() schreibt Producer/Datum selbst; anonym darum über die nachbearbeiteten Bytes.
|
||||
const bytes = finishPdfBytes({ competition: opts.competition }, new Uint8Array(doc.output("arraybuffer")));
|
||||
const url = URL.createObjectURL(new Blob([bytes as BlobPart], { type: "application/pdf" }));
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `${name}.pdf`;
|
||||
a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
return;
|
||||
}
|
||||
doc.save(`${name}.pdf`);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// [208] Blatt-PDF: Bild eingebettet (JPEG ohne Neukompression), Plakat-Kopfzeile, anonyme Abgabe ohne Metadaten.
|
||||
import { inflateSync } from "node:zlib";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Layout, Project } from "../model/types";
|
||||
import { createPosterMaster, posterTemplate } from "../model/posterTemplates";
|
||||
import { addImage, createLayoutImage } from "../model/layoutImages";
|
||||
import { JPEG_64X48, PNG_40X30, PNG_40X30_ALPHA } from "../model/layoutImages.testing";
|
||||
import { buildPagesPdf, layoutPages, pdfBytes } from "./layoutPdf";
|
||||
import { pdfInfoText } from "./pdfInfo";
|
||||
|
||||
const latin1 = (b: Uint8Array): string => {
|
||||
let s = "";
|
||||
for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]);
|
||||
return s;
|
||||
};
|
||||
|
||||
/** Alle Flate-Streams des PDF entpackt, hintereinander (Seiteninhalt ist komprimiert). */
|
||||
function streamsText(bytes: Uint8Array): string {
|
||||
const all = Buffer.from(bytes);
|
||||
const text = all.toString("latin1");
|
||||
let out = "";
|
||||
for (const m of text.matchAll(/stream\r?\n/g)) {
|
||||
const from = m.index! + m[0].length;
|
||||
const to = text.indexOf("endstream", from);
|
||||
try {
|
||||
out += inflateSync(all.subarray(from, to)).toString("latin1") + "\n";
|
||||
} catch {
|
||||
// kein Flate-Stream (z. B. JPEG)
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function indexOfBytes(hay: Uint8Array, needle: Uint8Array): number {
|
||||
outer: for (let i = 0; i + needle.length <= hay.length; i++) {
|
||||
for (let j = 0; j < needle.length; j++) if (hay[i + j] !== needle[j]) continue outer;
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function poster(extra?: Partial<Project>): Project {
|
||||
const master = createPosterMaster("m1", posterTemplate("poster-a1-landscape")!);
|
||||
master.titleBlock = { projectName: "Büro Muster AG", author: "Maria Muster" };
|
||||
const base: Layout = { id: "l1", name: "Grundriss", paper: "a1", orientation: "landscape", masterId: "m1", viewports: [] };
|
||||
const img = createLayoutImage("i1", "foto.jpg", JPEG_64X48, { w: 841, h: 594 })!;
|
||||
return { ...sampleProject, name: "Haus Muster", masterLayouts: [master], layouts: [addImage(base, img)], ...extra };
|
||||
}
|
||||
|
||||
describe("Blatt-PDF mit Bild", () => {
|
||||
it("bettet das JPEG unverändert ein (DCTDecode, keine Neukompression)", async () => {
|
||||
const p = poster();
|
||||
const doc = await buildPagesPdf(p, layoutPages(p, ["l1"]));
|
||||
const bytes = pdfBytes(p, doc!);
|
||||
expect(latin1(bytes)).toContain("/DCTDecode");
|
||||
expect(indexOfBytes(bytes, JPEG_64X48)).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("PNG mit und ohne Alpha lässt sich einbetten", async () => {
|
||||
for (const png of [PNG_40X30, PNG_40X30_ALPHA]) {
|
||||
const p = poster();
|
||||
const img = createLayoutImage("i2", "r.png", png, { w: 841, h: 594 })!;
|
||||
p.layouts = [addImage({ ...p.layouts![0], images: [] }, img)];
|
||||
const doc = await buildPagesPdf(p, layoutPages(p, ["l1"]));
|
||||
expect(latin1(pdfBytes(p, doc!))).toContain("/Subtype /Image");
|
||||
}
|
||||
});
|
||||
|
||||
it("Blattgrösse A1 quer, Plakat-Kopfzeile mit Kennwort und Plan x/n", async () => {
|
||||
const p = poster({ competition: { anonymous: false, keyword: "FALKE 7" } });
|
||||
const doc = await buildPagesPdf(p, layoutPages(p, ["l1"]));
|
||||
const bytes = pdfBytes(p, doc!);
|
||||
expect(latin1(bytes)).toMatch(/\/MediaBox \[0 0 2383\.93\d* 1683\.7\d*/); // 841 × 594 mm in pt
|
||||
const content = streamsText(bytes);
|
||||
expect(content).toContain("(Kennwort)");
|
||||
expect(content).toContain("(FALKE 7)");
|
||||
expect(content).toContain("(Plan 1/1)");
|
||||
});
|
||||
|
||||
it("anonyme Abgabe: keine Büro-/Autor-Angaben, Info nur mit Kennwort, kein jsPDF-Producer", async () => {
|
||||
const p = poster({ competition: { anonymous: true, keyword: "FALKE 7" } });
|
||||
const doc = await buildPagesPdf(p, layoutPages(p, ["l1"]));
|
||||
const bytes = pdfBytes(p, doc!);
|
||||
const info = pdfInfoText(bytes);
|
||||
expect(info).toContain("/Title (FALKE 7)");
|
||||
expect(info).not.toMatch(/jsPDF/);
|
||||
expect(info).not.toContain("/Author");
|
||||
expect(info).not.toContain("/Creator");
|
||||
expect(info).toContain("D:20000101000000");
|
||||
const all = latin1(bytes) + streamsText(bytes);
|
||||
expect(all).not.toContain("Büro Muster");
|
||||
expect(all).not.toContain("Maria Muster");
|
||||
expect(all).not.toContain("Haus Muster");
|
||||
expect(all).toContain("(FALKE 7)");
|
||||
});
|
||||
|
||||
it("nicht anonym: Projektname im Titel, Bearbeiter im Info-Wörterbuch", async () => {
|
||||
const p = poster();
|
||||
const doc = await buildPagesPdf(p, layoutPages(p, ["l1"]));
|
||||
const info = pdfInfoText(pdfBytes(p, doc!));
|
||||
expect(info).toContain("/Title (Haus Muster)");
|
||||
expect(info).toContain("Maria Muster");
|
||||
});
|
||||
});
|
||||
+77
-1
@@ -20,6 +20,9 @@ import { generatePlan, type Plan } from "../plan/generatePlan";
|
||||
import { snapshotMono, snapshotOverrideRuleIds, snapshotTemplate, viewportLevelPlan } from "../plan/viewportPlan";
|
||||
import { planToPrintSvg } from "./planToPrintSvg";
|
||||
import { drawTablesPdf, sheetTables } from "./sheetTable";
|
||||
import { applyPdfInfo, finishPdfBytes } from "./pdfInfo";
|
||||
import { imageGeometry } from "../model/layoutImages";
|
||||
import { posterHeaderItems, viewportScaleLabel } from "../model/posterTemplates";
|
||||
import { collectVisibleCodes } from "../model/types";
|
||||
import {
|
||||
effectiveSheetSizeMm,
|
||||
@@ -90,6 +93,9 @@ function drawTitleBlock(
|
||||
doc.text(`${tb.date} · ${fmt}`, x + boxW - 3, y + boxH - 2.4, { align: "right" });
|
||||
}
|
||||
|
||||
/** Schrifthöhe in mm → pt (jsPDF misst Schriftgrössen in pt). */
|
||||
const MM_TO_PT = 72 / 25.4;
|
||||
|
||||
function clip(s: string, max: number): string {
|
||||
return s.length > max ? s.slice(0, max - 1) + "…" : s;
|
||||
}
|
||||
@@ -149,6 +155,55 @@ function inLayer(ctx: PageCtx, name: string, fn: () => void | Promise<void>): Pr
|
||||
return ctx.layers ? ctx.layers.run(name, fn) : fn();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bilder des Blatts ([208]): das Original unverändert eingebettet (JPEG ohne Neukompression), auf den Rahmen
|
||||
* geklippt; mit Zuschnitt liegt das ganze Bild verschoben/vergrössert dahinter, sichtbar ist nur der Rahmen.
|
||||
*/
|
||||
function drawImagesPdf(doc: jsPDF, layout: Layout): void {
|
||||
for (const img of layout.images ?? []) {
|
||||
const m = /^data:image\/(png|jpeg);base64,/.exec(img.src);
|
||||
if (!m || img.widthMm <= 0 || img.heightMm <= 0) continue;
|
||||
const g = imageGeometry(img);
|
||||
doc.saveGraphicsState();
|
||||
doc.rect(g.clip.x, g.clip.y, g.clip.w, g.clip.h, null);
|
||||
doc.clip();
|
||||
doc.discardPath();
|
||||
try {
|
||||
doc.addImage(img.src, m[1] === "png" ? "PNG" : "JPEG", g.draw.x, g.draw.y, g.draw.w, g.draw.h, img.id, "NONE");
|
||||
} finally {
|
||||
doc.restoreGraphicsState();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Massstabsangabe unter jedem Viewport ([208], Master `viewportScaleLabels`). */
|
||||
function drawScaleLabelsPdf(doc: jsPDF, project: Project, layout: Layout, sheet: { w: number; h: number }, scaleOverride?: number): void {
|
||||
doc.setTextColor(17, 17, 17);
|
||||
doc.setFont("helvetica", "normal");
|
||||
for (const vp of layout.viewports) {
|
||||
const l = viewportScaleLabel(project, vp, sheet, scaleOverride);
|
||||
if (!l) continue;
|
||||
doc.setFontSize(l.sizeMm * MM_TO_PT);
|
||||
doc.text(l.text, l.x, l.y);
|
||||
}
|
||||
}
|
||||
|
||||
/** Plakat-Kopfzeile ([208]): Band, Kennwort-Feld, Titel, „Plan x/n". */
|
||||
function drawPosterHeaderPdf(doc: jsPDF, project: Project, layout: Layout, master: MasterLayout, sheet: { w: number; h: number }): void {
|
||||
doc.setDrawColor(17, 17, 17);
|
||||
doc.setTextColor(17, 17, 17);
|
||||
for (const it of posterHeaderItems(project, layout, master, sheet)) {
|
||||
if (it.kind === "rect") {
|
||||
doc.setLineWidth(it.stroke);
|
||||
doc.rect(it.x, it.y, it.w, it.h);
|
||||
} else {
|
||||
doc.setFont("helvetica", it.bold ? "bold" : "normal");
|
||||
doc.setFontSize(it.sizeMm * MM_TO_PT);
|
||||
doc.text(it.text, it.x, it.y, { align: it.align });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Zeichnet die Viewports + Master-Elemente EINER Seite in das jsPDF-Dokument. */
|
||||
async function renderPage(
|
||||
doc: jsPDF,
|
||||
@@ -196,6 +251,18 @@ async function renderPage(
|
||||
}
|
||||
}
|
||||
|
||||
// Bilder ([208]): Renderings, Fotos — über den Viewports, unter Legenden und Schriftfeld.
|
||||
try {
|
||||
await inLayer(ctx, t("pdfLayers.images"), () => drawImagesPdf(doc, layout));
|
||||
} catch {
|
||||
// Ein Bild, das nicht einbettet, darf die Seite nicht killen.
|
||||
}
|
||||
|
||||
// Massstab je Viewport ([208]).
|
||||
if (master?.viewportScaleLabels) {
|
||||
await inLayer(ctx, t("pdfLayers.frame"), () => drawScaleLabelsPdf(doc, project, layout, { w: widthMm, h: heightMm }, ctx.scaleOverride));
|
||||
}
|
||||
|
||||
// Legenden ([82]): live aus den Viewports (oder Handauswahl), Muster vom Kern-Schraffurgenerator.
|
||||
for (const lg of layout.legends ?? []) {
|
||||
try {
|
||||
@@ -219,6 +286,7 @@ async function renderPage(
|
||||
}
|
||||
const tb = resolveTitleBlock(project, layout, master);
|
||||
drawTitleBlock(doc, widthMm, heightMm, tb, layout.paper, layout.orientation, ctx.includeRevision);
|
||||
if (master.posterHeader) drawPosterHeaderPdf(doc, project, layout, master, { w: widthMm, h: heightMm });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -259,6 +327,9 @@ export async function buildPagesPdf(project: Project, pages: FolderPdfPage[], op
|
||||
|
||||
const first = sizeOf(pages[0]);
|
||||
const doc = new jsPDF({ unit: "mm", format: [first.w, first.h], orientation: orientOf(first), compress: true });
|
||||
// Info-Wörterbuch: anonym nur das Kennwort ([208]); sonst Projektname und Bearbeiter des ersten Blatts.
|
||||
const firstMaster = findMaster(project, pages[0].layout);
|
||||
applyPdfInfo(doc, project, firstMaster ? resolveTitleBlock(project, pages[0].layout, firstMaster).author : undefined);
|
||||
const ctx: PageCtx = {
|
||||
layers: opts.layers ? enablePdfLayers(doc) : undefined,
|
||||
scaleOverride: opts.scaleOverride && opts.scaleOverride > 0 ? opts.scaleOverride : undefined,
|
||||
@@ -301,5 +372,10 @@ export async function buildFolderPdf(project: Project, folderId: string): Promis
|
||||
export async function folderPdfBytes(project: Project, folderId: string): Promise<Uint8Array | null> {
|
||||
const doc = await buildFolderPdf(project, folderId);
|
||||
if (!doc) return null;
|
||||
return new Uint8Array(doc.output("arraybuffer"));
|
||||
return pdfBytes(project, doc);
|
||||
}
|
||||
|
||||
/** Fertige PDF-Bytes eines Dokuments; bei anonymer Abgabe ohne Erzeuger-/Datumsangaben ([208]). */
|
||||
export function pdfBytes(project: Project, doc: jsPDF): Uint8Array {
|
||||
return finishPdfBytes(project, new Uint8Array(doc.output("arraybuffer")));
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// PDF-Metadaten ([208]): Titel/Autor/Ersteller des Info-Wörterbuchs. Bei anonymer Wettbewerbs-Abgabe
|
||||
// (`Project.competition`) enthält das PDF nur das Kennwort als Titel — keine Büro-, Autor- oder Programmangaben:
|
||||
// jsPDF schreibt `/Producer (jsPDF x.y.z)` und `/CreationDate` immer selbst, darum wird die fertige Datei
|
||||
// längengleich nachbearbeitet (Xref-Offsets bleiben gültig).
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch.
|
||||
|
||||
import type { jsPDF } from "jspdf";
|
||||
import type { Project } from "../model/types";
|
||||
|
||||
/** Ist die Abgabe anonym? */
|
||||
export function isAnonymous(project: Pick<Project, "competition">): boolean {
|
||||
return project.competition?.anonymous === true;
|
||||
}
|
||||
|
||||
/** Kennwort der Abgabe (getrimmt, leer ohne Wettbewerb). */
|
||||
export function competitionKeyword(project: Pick<Project, "competition">): string {
|
||||
return (project.competition?.keyword ?? "").trim();
|
||||
}
|
||||
|
||||
/** Projektname für Schriftfelder und Dateinamen der Exporte: bei anonymer Abgabe das Kennwort. */
|
||||
export function exportProjectName(project: Pick<Project, "name" | "competition">): string {
|
||||
return isAnonymous(project) ? competitionKeyword(project) : (project.name ?? "");
|
||||
}
|
||||
|
||||
/** Info-Felder, die ins PDF gehören: anonym nur das Kennwort als Titel, sonst Projektname und Autor des Titelblocks. */
|
||||
export function pdfInfoFields(project: Pick<Project, "name" | "competition">, author?: string): { title: string; author: string; subject: string; keywords: string; creator: string } {
|
||||
if (isAnonymous(project)) return { title: competitionKeyword(project), author: "", subject: "", keywords: "", creator: "" };
|
||||
return { title: project.name ?? "", author: author ?? "", subject: "", keywords: "", creator: "Dossier" };
|
||||
}
|
||||
|
||||
/** Setzt die Info-Felder auf dem jsPDF-Dokument. */
|
||||
export function applyPdfInfo(doc: jsPDF, project: Pick<Project, "name" | "competition">, author?: string): void {
|
||||
doc.setProperties(pdfInfoFields(project, author));
|
||||
}
|
||||
|
||||
/**
|
||||
* Anonymisiert die fertigen PDF-Bytes: `/Producer (…)` wird durch Leerzeichen gleicher Länge ersetzt und das
|
||||
* Datum in `/CreationDate` auf einen festen Wert gesetzt. Gilt nur für anonyme Abgaben; sonst unverändert.
|
||||
*/
|
||||
export function finishPdfBytes(project: Pick<Project, "competition">, bytes: Uint8Array): Uint8Array {
|
||||
return isAnonymous(project) ? neutralizePdfInfo(bytes) : bytes;
|
||||
}
|
||||
|
||||
/** Letzte Fundstelle des ASCII-Musters in den Bytes (-1: keine). */
|
||||
function lastIndexOfAscii(bytes: Uint8Array, pattern: string): number {
|
||||
const n = pattern.length;
|
||||
outer: for (let i = bytes.length - n; i >= 0; i--) {
|
||||
for (let j = 0; j < n; j++) if (bytes[i + j] !== pattern.charCodeAt(j)) continue outer;
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Längengleiche Ersetzung der Erzeuger- und Datumsangabe im Info-Wörterbuch (das letzte im Text, nahe dem Ende). */
|
||||
export function neutralizePdfInfo(bytes: Uint8Array): Uint8Array {
|
||||
// Byteweise, nicht über TextDecoder: "latin1" ist dort windows-1252 und verfälschte Binärdaten.
|
||||
const out = new Uint8Array(bytes);
|
||||
const blank = (key: string, fn: (v: string) => string) => {
|
||||
const at = lastIndexOfAscii(out, `${key} (`);
|
||||
if (at < 0) return;
|
||||
const from = at + key.length + 2;
|
||||
let to = from;
|
||||
while (to < out.length && out[to] !== 0x29 /* ) */) to++;
|
||||
if (to >= out.length) return;
|
||||
let v = "";
|
||||
for (let i = from; i < to; i++) v += String.fromCharCode(out[i]);
|
||||
const next = fn(v);
|
||||
if (next.length !== v.length) return;
|
||||
for (let i = 0; i < next.length; i++) out[from + i] = next.charCodeAt(i);
|
||||
};
|
||||
blank("/Producer", (v) => " ".repeat(v.length));
|
||||
blank("/CreationDate", (v) => v.replace(/^D:\d{14}/, "D:20000101000000"));
|
||||
blank("/ModDate", (v) => v.replace(/^D:\d{14}/, "D:20000101000000"));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Hilfsfunktion für Tests: das Info-Wörterbuch als Text. */
|
||||
export function pdfInfoText(bytes: Uint8Array): string {
|
||||
const at = lastIndexOfAscii(bytes, "/Producer");
|
||||
if (at < 0) return "";
|
||||
const start = Math.max(0, at - 4);
|
||||
let s = "";
|
||||
for (let i = start; i < Math.min(bytes.length, at + 400); i++) s += String.fromCharCode(bytes[i]);
|
||||
const end = s.indexOf(">>");
|
||||
return end < 0 ? s : s.slice(0, end + 2);
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import { collectVisibleCodes } from "../model/types";
|
||||
import { generatePlan } from "../plan/generatePlan";
|
||||
import { sheetLevelOf } from "../model/layoutModel";
|
||||
import { legendDrawings, legendEntries } from "../analysis/legend";
|
||||
import { buildPagesPdf, layoutPages } from "./layoutPdf";
|
||||
import { buildPagesPdf, layoutPages, pdfBytes } from "./layoutPdf";
|
||||
import { buildPlanDwg, buildPlanDxfBinary } from "./exportDxf";
|
||||
import { loadFileio } from "../engine/fileioWasm";
|
||||
import { withDocument } from "../core/document";
|
||||
@@ -97,7 +97,7 @@ async function publishFiles(shown: Project, set: PublishSet, plan: PublishPlan):
|
||||
paperOverride: plan.paperOverride,
|
||||
includeRevision: plan.includeRevision,
|
||||
});
|
||||
if (doc) out.push({ fileName: f.fileName, bytes: new Uint8Array(doc.output("arraybuffer")), mime: "application/pdf" });
|
||||
if (doc) out.push({ fileName: f.fileName, bytes: pdfBytes(shown, doc), mime: "application/pdf" });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -85,9 +85,11 @@ export function planPublish(project: Project, set: PublishSet, today: string): P
|
||||
const revision = includeRevision ? (bump ? nextRevision(l.revision) : (l.revision ?? "")) : "";
|
||||
return { layoutId: l.id, number: tb.planNumber, name: l.name, revision };
|
||||
});
|
||||
// Anonyme Abgabe ([208]): Dateinamen tragen das Kennwort statt Projektnummer und Projektname.
|
||||
const anon = project.competition?.anonymous === true;
|
||||
const base = {
|
||||
Projektnummer: project.projectNumber ?? "",
|
||||
Projekt: project.name ?? "",
|
||||
Projektnummer: anon ? "" : (project.projectNumber ?? ""),
|
||||
Projekt: anon ? (project.competition?.keyword ?? "").trim() : (project.name ?? ""),
|
||||
Datum: today,
|
||||
Satz: set.name,
|
||||
};
|
||||
|
||||
+12
-1
@@ -7,7 +7,7 @@
|
||||
// Bewusst TS: die Rahmen-Ecken einer Textspalte (`textFrameCorners` braucht die Schrift-Metrik der
|
||||
// Hülle) — der Kern meldet dafür nur „Textspalte".
|
||||
|
||||
import type { Ceiling, Drawing2D, Drawing2DGeom, EdgeGrip, Project, Vec2, Wall } from "../model/types";
|
||||
import type { Camera, Ceiling, Drawing2D, Drawing2DGeom, EdgeGrip, Project, Vec2, Wall } from "../model/types";
|
||||
import { documentFor } from "../core/document";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import { toMarkedJson } from "../core/ops";
|
||||
@@ -46,6 +46,9 @@ export type GripRequest =
|
||||
// [176] Schnittlinie: 0 = Anfang, dann `bendPoints`, zuletzt das Ende.
|
||||
| { op: "sectionLineGrip"; id: string; index: number; pt: P }
|
||||
| { op: "sectionBendInsert"; id: string; seg: number; pt: P }
|
||||
// [213] Kamera: 0 = Standpunkt, 1 = Ziel, 2 = Bildwinkel bzw. Sichtbreite (Kern `camera::grip_edit`); `cameraBy` verschiebt Standpunkt und Ziel.
|
||||
| { op: "cameraGrip"; id: string; index: number; pt: P }
|
||||
| { op: "cameraBy"; id: string; delta: P }
|
||||
| { op: "sectionBendDelete"; id: string; index: number }
|
||||
| { op: "sectionLineTidy"; id: string; tol?: number }
|
||||
// [26] Ecke an Umriss-Ringen einfügen (hinter Kante `seg`), löschen, aufräumen (Kern `ring_edit`); Dach: flacher Index.
|
||||
@@ -100,6 +103,14 @@ export function drawingVertices(d: Drawing2D, scaleDenominator: number = DEFAULT
|
||||
return out;
|
||||
}
|
||||
|
||||
/** [213] Griffe einer Kamera im Grundriss beim Massstab 1:`scaleDenominator`: Standpunkt, Ziel, Bildwinkel/Sichtbreite (Kern `camera::grip_points`). */
|
||||
export function cameraGripPoints(c: Camera, scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR): Vec2[] {
|
||||
const f = core().camera_grip_points(JSON.stringify(c), scaleDenominator);
|
||||
const out: Vec2[] = [];
|
||||
for (let i = 0; i + 1 < f.length; i += 2) out.push({ x: f[i], y: f[i + 1] });
|
||||
return out;
|
||||
}
|
||||
|
||||
type Owner = { drawingId?: string; wallId?: string };
|
||||
|
||||
function flat(verts: readonly Vec2[]): Float64Array {
|
||||
|
||||
+154
-11
@@ -961,7 +961,6 @@ export const de = {
|
||||
"objinfo.room.buildUp": "Aufbau",
|
||||
"objinfo.room.finishes": "Oberflächen (Raumbuch)",
|
||||
"objinfo.room.finishHint": "Material wählen oder Freitext eingeben",
|
||||
"objinfo.room.editStamp": "Stempel bearbeiten …",
|
||||
// ── Extrusions-Attribute (truck-Integration, Object-Info-Panel) ─────────
|
||||
"objinfo.sectionLine.section": "Schnittlinie",
|
||||
"objinfo.dimText.section": "Masszahl",
|
||||
@@ -1049,6 +1048,7 @@ export const de = {
|
||||
"nav.categoryDerived.81": "Abgeleitete Darstellung: automatische Aussenbemassung (je Kette änderbar)",
|
||||
"nav.categoryDerived.82": "Abgeleitete Darstellung: automatische Höhenkoten in Schnitt und Ansicht",
|
||||
"nav.categoryDerived.91": "Abgeleitete Darstellung: Schnitt- und Ansichtsmarken im Grundriss",
|
||||
"nav.categoryDerived.92": "Kameras: Symbol mit Sichtkegel im Grundriss (Element Kamera, je Kamera änderbar)",
|
||||
"nav.categorySettings": "Ebeneneinstellungen für {name}",
|
||||
"nav.drawingLevelsWindow": "Zeichnungsebenen als eigenes Fenster öffnen",
|
||||
|
||||
@@ -1356,6 +1356,12 @@ export const de = {
|
||||
"resources.modelViews.opt.roomStamps.divider": "Trennlinie",
|
||||
"resources.modelViews.opt.dimensions.chains": "Ketten der Aussenbemassung",
|
||||
"resources.modelViews.opt.dimensions.levelMarks": "Höhenkoten",
|
||||
"resources.modelViews.section.situation": "Situationsplan / Schwarzplan",
|
||||
"resources.modelViews.opt.situation.own": "Eigenes Gebäude (Umriss über alle Geschosse)",
|
||||
"resources.modelViews.opt.situation.context": "Kontextgebäude (Grundfläche)",
|
||||
"resources.modelViews.opt.situation.symbols": "Nordpfeil und Massstabsbalken",
|
||||
"resources.modelViews.val.black": "schwarz",
|
||||
"resources.modelViews.val.grey": "grau",
|
||||
"resources.modelViews.opt.stairs.stepNumbers": "Stufennummern",
|
||||
"resources.modelViews.val.outer": "ohne Öffnungen",
|
||||
"resources.modelViews.val.total": "nur Gesamtmass",
|
||||
@@ -2055,6 +2061,44 @@ export const de = {
|
||||
"cmd.circlestotrees.label": "Kreise in Bäume umwandeln",
|
||||
"objinfo.kind.tree": "Baum",
|
||||
"objinfo.tree.many": "{n} Bäume",
|
||||
"camera.title": "Kameras",
|
||||
"camera.defaultName": "Kamera",
|
||||
"camera.empty": "Keine Kameras. Mit „+“ aus der aktuellen 3D-Ansicht anlegen.",
|
||||
"camera.createFromView": "Kamera aus aktueller Ansicht anlegen",
|
||||
"camera.created": "Kamera „{name}“ angelegt",
|
||||
"camera.open": "Kamera öffnen",
|
||||
"camera.rowHint": "Klick wählt die Kamera, Doppelklick öffnet sie im 3D",
|
||||
"camera.delete": "Kamera löschen",
|
||||
"camera.update": "Aus aktueller Ansicht",
|
||||
"camera.updateHint": "Standpunkt, Ziel, Bildwinkel und Projektion mit der aktuellen 3D-Ansicht überschreiben",
|
||||
"camera.updated": "Kamera „{name}“ aus der aktuellen Ansicht aktualisiert",
|
||||
"camera.iso": "Isometrisch",
|
||||
"camera.isoHint": "Standpunkt so legen, dass die Kamera das Ziel isometrisch (45°, 35,3° Neigung) ansieht",
|
||||
"camera.noViewport": "Die 3D-Ansicht ist nicht geöffnet.",
|
||||
"camera.invalid": "Kamera „{name}“ hat keinen gültigen Blick (Standpunkt gleich Ziel?).",
|
||||
"objinfo.kind.camera": "Kamera",
|
||||
"objinfo.camera.many": "{n} Kameras",
|
||||
"objinfo.camera.section": "Kamera",
|
||||
"objinfo.camera.name": "Name",
|
||||
"objinfo.camera.projection": "Projektion",
|
||||
"objinfo.camera.projection.perspective": "Perspektive",
|
||||
"objinfo.camera.projection.axonometric": "Axonometrie",
|
||||
"objinfo.camera.projection.parallel": "Parallelprojektion",
|
||||
"objinfo.camera.stand": "Standpunkt",
|
||||
"objinfo.camera.eyeHeight": "Augenhöhe über Geschoss",
|
||||
"objinfo.camera.target": "Ziel",
|
||||
"objinfo.camera.targetHeight": "Höhe Ziel",
|
||||
"objinfo.camera.fov": "Bildwinkel (vertikal)",
|
||||
"objinfo.camera.focal": "Brennweite (Kleinbild)",
|
||||
"objinfo.camera.orthoHeight": "Sichthöhe",
|
||||
"objinfo.camera.sun": "Sonnenstand",
|
||||
"objinfo.camera.sunHint": "Datum und Uhrzeit (UTC); „Kamera öffnen“ stellt die Sonnenstudie darauf. Leer = Sonne bleibt.",
|
||||
"objinfo.camera.locked": "Gesperrt: Die Kamera lässt sich nicht ändern.",
|
||||
"pick.kind.camera": "Kamera",
|
||||
"shortcut.walkMode": "Begehen im 3D ein/aus",
|
||||
"walk.toggle": "Begehen",
|
||||
"walk.hint": "Begehen (Umschalt+F): W/A/S/D oder Pfeile gehen, Q/E runter und hoch, Umschalt schneller, Alt langsamer, mit gedrückter Maustaste umschauen",
|
||||
"viewport3d.camera.create": "Kamera aus aktueller Ansicht anlegen",
|
||||
"objinfo.tree.section": "Baum",
|
||||
"objinfo.tree.species": "Art",
|
||||
"objinfo.tree.speciesHint": "z. B. Quercus robur",
|
||||
@@ -2909,7 +2953,7 @@ export const de = {
|
||||
"kennzahlen.programIssue": "{name}: {status}",
|
||||
"kennzahlen.gf": "Geschossfläche (SIA 416) aus den Räumen",
|
||||
"kennzahlen.agf": "Anrechenbare Geschossfläche ≈ NGF",
|
||||
"kennzahlen.gv": "Gebäudevolumen aus den freien Körpern",
|
||||
"kennzahlen.gv": "Gebäudevolumen aus den freien Körpern, ohne solche GF × Geschosshöhe",
|
||||
"kennzahlen.az": "Ausnützungsziffer aGF / Parzelle",
|
||||
"kennzahlen.uez": "Überbauungsziffer bebaute Fläche / Parzelle",
|
||||
"kennzahlen.parcelArea": "Parzellenfläche",
|
||||
@@ -3288,21 +3332,33 @@ export const de = {
|
||||
"text.editTitle": "Text bearbeiten",
|
||||
"text.apply": "Übernehmen",
|
||||
"text.cancel": "Abbrechen",
|
||||
"roomStamp.title": "Raumstempel bearbeiten",
|
||||
"roomStamp.title": "Raumstempel",
|
||||
"roomStamp.number": "Raumnummer",
|
||||
"roomStamp.name": "Raumname",
|
||||
"roomStamp.nameLine2": "Raumname Zeile 2",
|
||||
"roomStamp.showFloorArea": "Bodenfläche anzeigen",
|
||||
"roomStamp.floorAreaPrefix": "Präfix Bodenfläche",
|
||||
"roomStamp.name": "Name",
|
||||
"roomStamp.nameLine2": "Name Zeile 2",
|
||||
"roomStamp.showFloorArea": "Bodenfläche",
|
||||
"roomStamp.floorAreaPrefix": "Präfix",
|
||||
"roomStamp.asModelView": "Wie Modelldarstellung",
|
||||
"roomStamp.on": "An",
|
||||
"roomStamp.off": "Aus",
|
||||
"roomStamp.showUsage": "SIA-Kategorie anzeigen",
|
||||
"roomStamp.showDivider": "Trennlinie unter dem Namen",
|
||||
"roomStamp.showFinish": "Bodenbelag anzeigen",
|
||||
"roomStamp.roundingStep": "Flächen-Rundung",
|
||||
"roomStamp.showUsage": "SIA-Kategorie",
|
||||
"roomStamp.showDivider": "Trennlinie",
|
||||
"roomStamp.showFinish": "Bodenbelag",
|
||||
"roomStamp.roundingStep": "Rundung",
|
||||
"roomStamp.roundingStepDefault": "Standard (2 Nachkommastellen)",
|
||||
"roomStamp.occupancy": "Personenzahl",
|
||||
"roomStamp.font.section": "Schrift",
|
||||
"roomStamp.font.all": "Ganzer Stempel",
|
||||
"roomStamp.font.name": "Name",
|
||||
"roomStamp.font.line2": "Zeile 2",
|
||||
"roomStamp.font.number": "Nummer",
|
||||
"roomStamp.font.area": "Fläche",
|
||||
"roomStamp.font.usage": "Kategorie",
|
||||
"roomStamp.font.default": "Standard",
|
||||
"roomStamp.font.family": "Schriftart",
|
||||
"roomStamp.font.size": "Schriftgrösse (pt)",
|
||||
"roomStamp.font.color": "Schriftfarbe",
|
||||
"roomStamp.font.reset": "Auf Standard zurücksetzen",
|
||||
"text.selectedHint": "Formatierung wirkt auf den ausgewählten Text",
|
||||
|
||||
// ── Rich-Text-Editor ────────────────────────────────────────────────────────
|
||||
@@ -3861,6 +3917,93 @@ export const de = {
|
||||
"presentation.tooBig": "Präsentationsplan: passt auch 1:{scale} nicht ganz aufs Blatt – grösseres Format wählen",
|
||||
"presentation.empty": "Präsentationsplan: keine Ansicht mit Inhalt gewählt",
|
||||
"presentation.failed": "Präsentationsplan konnte nicht erstellt werden",
|
||||
// [211] Rendering mit Blender/Cycles
|
||||
"cmd.rendering.label": "Rendering…",
|
||||
"cmd.rendering.prompt": "Rendering mit Blender einrichten …",
|
||||
"menu.view.rendering": "Rendering mit Blender …",
|
||||
"render.title": "Rendering mit Blender",
|
||||
"render.intro": "Fotorealistisches Bild der aktiven 3D-Ansicht mit Blender/Cycles (installiertes Blender, läuft als eigener Prozess).",
|
||||
"render.camera.title": "Kamera",
|
||||
"render.camera.live": "Aktuelle 3D-Ansicht",
|
||||
"render.camera.saved": "Kamera: «{name}» (gespeichert)",
|
||||
"render.camera.view": "Kamera: aktuelle 3D-Ansicht",
|
||||
"render.camera.preset": "Kamera: Voreinstellung «{name}» (3D-Ansicht nicht offen)",
|
||||
"render.size": "Bildgrösse",
|
||||
"render.size.hd": "Full HD, 1920 × 1080",
|
||||
"render.size.uhd": "4K, 3840 × 2160",
|
||||
"render.size.a4": "A4 quer, 300 dpi",
|
||||
"render.size.a3": "A3 quer, 300 dpi",
|
||||
"render.size.a2": "A2 quer, 300 dpi",
|
||||
"render.size.custom": "Eigene Grösse",
|
||||
"render.width": "Breite (Pixel)",
|
||||
"render.height": "Höhe (Pixel)",
|
||||
"render.quality": "Qualität",
|
||||
"render.quality.draft": "Entwurf (32 Samples)",
|
||||
"render.quality.normal": "Normal (128 Samples)",
|
||||
"render.quality.high": "Hoch (512 Samples)",
|
||||
"render.quality.final": "Final (1536 Samples)",
|
||||
"render.time": "Datum und Uhrzeit der Sonne",
|
||||
"render.sun": "Sonne: Azimut {az}°, Höhe {el}°",
|
||||
"render.sun.night": "Die Sonne steht dann unter dem Horizont; gerendert wird bei Dämmerung (Sonnenhöhe 1°).",
|
||||
"render.blenderPath": "Blender-Programmdatei",
|
||||
"render.blenderPath.placeholder": "automatisch suchen",
|
||||
"render.start": "Rendern",
|
||||
"render.abort": "Rendering abbrechen",
|
||||
"render.working": "Paket wird vorbereitet …",
|
||||
"render.stage.import": "Modell wird in Blender geladen …",
|
||||
"render.stage.materials": "Materialien werden gesetzt …",
|
||||
"render.stage.camera": "Kamera wird eingerichtet …",
|
||||
"render.stage.sky": "Himmel und Sonne werden eingerichtet …",
|
||||
"render.stage.render": "Rendern: Sample {done} von {total}",
|
||||
"render.stage.done": "Fertig",
|
||||
"render.done": "Rendering fertig ({width} × {height})",
|
||||
"render.save": "Bild speichern …",
|
||||
"render.again": "Neu rendern",
|
||||
"render.saved": "Rendering gespeichert",
|
||||
"render.cancelled": "Rendering abgebrochen",
|
||||
"render.error": "Rendering fehlgeschlagen: {message}",
|
||||
"render.missingTextures": "{n} Bildkarten waren nicht erreichbar; diese Materialien erscheinen einfarbig.",
|
||||
"render.missing.title": "Blender nicht gefunden",
|
||||
"render.missing.text": "Für das Rendering braucht Dossier ein installiertes Blender (kostenlos, ab Version 3.6). Es wird nur als eigenes Programm aufgerufen. Nach der Installation hier erneut «Rendern» wählen oder oben den Pfad der Programmdatei eintragen.",
|
||||
"render.missing.download": "Blender herunterladen",
|
||||
"render.browser.text": "Im Browser kann Dossier Blender nicht starten. Das Paket enthält Modell (GLB), Szenenbeschreibung, Texturen und das Blender-Skript samt Anleitung.",
|
||||
"render.zip.save": "Paket als ZIP speichern",
|
||||
"render.zip.saved": "Rendering-Paket gespeichert",
|
||||
"render.zip.readme.title": "Dossier: Rendering-Paket für Blender/Cycles",
|
||||
"render.zip.readme.steps": "Blender (ab 3.6) installieren, diesen Ordner entpacken und im Ordner ausführen:",
|
||||
"render.zip.readme.result": "Das Bild entsteht als render.png neben scene.json. Bildgrösse, Samples, Kamera und Sonne stehen in scene.json.",
|
||||
"settings.section.rendering": "Rendering",
|
||||
"settings.blenderPath": "Blender-Programmdatei",
|
||||
"settings.blenderPath.hint": "Leer: Blender wird im PATH und an den üblichen Orten gesucht (macOS: /Applications/Blender.app).",
|
||||
// [208] Wettbewerbs-Abgabe: Bilder auf Blättern, Plakat-Vorlagen, Anonymität
|
||||
"sheetImage.title": "Bild",
|
||||
"sheetImage.add": "Bild",
|
||||
"sheetImage.width": "Breite mm",
|
||||
"sheetImage.dpi": "{dpi} dpi auf dem Blatt",
|
||||
"sheetImage.lowDpi": "niedrige Auflösung",
|
||||
"sheetImage.crop": "Zuschnitt",
|
||||
"sheetImage.crop.left": "Links",
|
||||
"sheetImage.crop.right": "Rechts",
|
||||
"sheetImage.crop.top": "Oben",
|
||||
"sheetImage.crop.bottom": "Unten",
|
||||
"sheetImage.cropReset": "Zuschnitt aufheben",
|
||||
"sheetImage.remove": "Bild entfernen",
|
||||
"sheetImage.invalid": "Nur PNG- und JPEG-Bilder bis 40 MB lassen sich einsetzen.",
|
||||
"pdfLayers.images": "Bilder",
|
||||
"poster.template.name": "Plakat {format} {orientation}",
|
||||
"poster.header.keyword": "Kennwort",
|
||||
"poster.header.plan": "Plan {x}/{n}",
|
||||
"layouts.newLayout.poster": "Plakat-Vorlage (Wettbewerb)",
|
||||
"layouts.newLayout.posterHint": "Gestaltungsraster als Hilfslinien, Kopfzeile mit Kennwort und „Plan x/n“, Massstab unter jedem Viewport.",
|
||||
"publish.competition.anonymous": "Wettbewerb (anonym)",
|
||||
"publish.competition.keyword": "Kennwort",
|
||||
"publish.competition.hint": "Plankopf, PDF-Titel und Dateinamen zeigen nur das Kennwort; kein Büro- oder Autorname, keine Programm- und Datumsangaben im PDF.",
|
||||
"publish.wbw.add": "WBW-Abgabe anlegen",
|
||||
"publish.wbw.name": "WBW-Abgabe",
|
||||
"render.toLayout": "Ins Layout einsetzen",
|
||||
"render.toLayout.target": "Blatt",
|
||||
"render.toLayout.none": "Noch kein Layout-Blatt vorhanden: zuerst ein Blatt anlegen.",
|
||||
"render.toLayout.done": "Rendering ins Blatt „{name}“ eingesetzt.",
|
||||
} as const;
|
||||
|
||||
export type TranslationKey = keyof typeof de;
|
||||
+154
-11
@@ -957,7 +957,6 @@ export const en: Record<TranslationKey, string> = {
|
||||
"objinfo.room.buildUp": "Build-up",
|
||||
"objinfo.room.finishes": "Finishes (room book)",
|
||||
"objinfo.room.finishHint": "Choose a material or type free text",
|
||||
"objinfo.room.editStamp": "Edit stamp …",
|
||||
// ── Extruded solid attributes (truck integration, object info panel) ────
|
||||
"objinfo.sectionLine.section": "Section line",
|
||||
"objinfo.dimText.section": "Dimension text",
|
||||
@@ -1044,6 +1043,7 @@ export const en: Record<TranslationKey, string> = {
|
||||
"nav.categoryDerived.81": "Derived display: automatic exterior dimensions (each chain can be reassigned)",
|
||||
"nav.categoryDerived.82": "Derived display: automatic level marks in sections and elevations",
|
||||
"nav.categoryDerived.91": "Derived display: section and elevation marks in plans",
|
||||
"nav.categoryDerived.92": "Cameras: symbol with view cone in plans (camera element, each camera can be reassigned)",
|
||||
"nav.categorySettings": "Layer settings for {name}",
|
||||
"nav.drawingLevelsWindow": "Open drawing levels as its own window",
|
||||
|
||||
@@ -1350,6 +1350,12 @@ export const en: Record<TranslationKey, string> = {
|
||||
"resources.modelViews.opt.roomStamps.divider": "Divider line",
|
||||
"resources.modelViews.opt.dimensions.chains": "Exterior dimension chains",
|
||||
"resources.modelViews.opt.dimensions.levelMarks": "Level marks",
|
||||
"resources.modelViews.section.situation": "Site plan / figure-ground plan",
|
||||
"resources.modelViews.opt.situation.own": "Own building (outline over all floors)",
|
||||
"resources.modelViews.opt.situation.context": "Context buildings (footprint)",
|
||||
"resources.modelViews.opt.situation.symbols": "North arrow and scale bar",
|
||||
"resources.modelViews.val.black": "black",
|
||||
"resources.modelViews.val.grey": "grey",
|
||||
"resources.modelViews.opt.stairs.stepNumbers": "Step numbers",
|
||||
"resources.modelViews.val.outer": "without openings",
|
||||
"resources.modelViews.val.total": "overall only",
|
||||
@@ -2044,6 +2050,44 @@ export const en: Record<TranslationKey, string> = {
|
||||
"cmd.circlestotrees.label": "Convert circles to trees",
|
||||
"objinfo.kind.tree": "Tree",
|
||||
"objinfo.tree.many": "{n} trees",
|
||||
"camera.title": "Cameras",
|
||||
"camera.defaultName": "Camera",
|
||||
"camera.empty": "No cameras. Use “+” to create one from the current 3D view.",
|
||||
"camera.createFromView": "Create camera from current view",
|
||||
"camera.created": "Camera “{name}” created",
|
||||
"camera.open": "Open camera",
|
||||
"camera.rowHint": "Click selects the camera, double-click opens it in 3D",
|
||||
"camera.delete": "Delete camera",
|
||||
"camera.update": "From current view",
|
||||
"camera.updateHint": "Overwrite position, target, field of view and projection with the current 3D view",
|
||||
"camera.updated": "Camera “{name}” updated from the current view",
|
||||
"camera.iso": "Isometric",
|
||||
"camera.isoHint": "Move the camera so it looks at the target isometrically (45°, 35.3° pitch)",
|
||||
"camera.noViewport": "The 3D view is not open.",
|
||||
"camera.invalid": "Camera “{name}” has no valid view (position equals target?).",
|
||||
"objinfo.kind.camera": "Camera",
|
||||
"objinfo.camera.many": "{n} cameras",
|
||||
"objinfo.camera.section": "Camera",
|
||||
"objinfo.camera.name": "Name",
|
||||
"objinfo.camera.projection": "Projection",
|
||||
"objinfo.camera.projection.perspective": "Perspective",
|
||||
"objinfo.camera.projection.axonometric": "Axonometric",
|
||||
"objinfo.camera.projection.parallel": "Parallel projection",
|
||||
"objinfo.camera.stand": "Position",
|
||||
"objinfo.camera.eyeHeight": "Eye height above floor",
|
||||
"objinfo.camera.target": "Target",
|
||||
"objinfo.camera.targetHeight": "Target height",
|
||||
"objinfo.camera.fov": "Field of view (vertical)",
|
||||
"objinfo.camera.focal": "Focal length (35 mm)",
|
||||
"objinfo.camera.orthoHeight": "View height",
|
||||
"objinfo.camera.sun": "Sun position",
|
||||
"objinfo.camera.sunHint": "Date and time (UTC); “Open camera” sets the sun study to it. Empty = sun stays.",
|
||||
"objinfo.camera.locked": "Locked: the camera cannot be changed.",
|
||||
"pick.kind.camera": "Camera",
|
||||
"shortcut.walkMode": "Walk through 3D on/off",
|
||||
"walk.toggle": "Walk",
|
||||
"walk.hint": "Walk (Shift+F): W/A/S/D or arrow keys move, Q/E down and up, Shift faster, Alt slower, hold a mouse button to look around",
|
||||
"viewport3d.camera.create": "Create camera from current view",
|
||||
"objinfo.tree.section": "Tree",
|
||||
"objinfo.tree.species": "Species",
|
||||
"objinfo.tree.speciesHint": "e.g. Quercus robur",
|
||||
@@ -2859,7 +2903,7 @@ export const en: Record<TranslationKey, string> = {
|
||||
"kennzahlen.programIssue": "{name}: {status}",
|
||||
"kennzahlen.gf": "Gross floor area (SIA 416) from rooms",
|
||||
"kennzahlen.agf": "Chargeable floor area ≈ net floor area",
|
||||
"kennzahlen.gv": "Building volume from the free solids",
|
||||
"kennzahlen.gv": "Building volume from the free solids, without them GFA × storey height",
|
||||
"kennzahlen.az": "Floor area ratio (usable area / site)",
|
||||
"kennzahlen.uez": "Site coverage (built area / site)",
|
||||
"kennzahlen.parcelArea": "Site area",
|
||||
@@ -3276,21 +3320,33 @@ export const en: Record<TranslationKey, string> = {
|
||||
"text.editTitle": "Edit text",
|
||||
"text.apply": "Apply",
|
||||
"text.cancel": "Cancel",
|
||||
"roomStamp.title": "Edit room stamp",
|
||||
"roomStamp.title": "Room stamp",
|
||||
"roomStamp.number": "Room number",
|
||||
"roomStamp.name": "Room name",
|
||||
"roomStamp.nameLine2": "Room name line 2",
|
||||
"roomStamp.showFloorArea": "Show floor area",
|
||||
"roomStamp.floorAreaPrefix": "Floor area prefix",
|
||||
"roomStamp.name": "Name",
|
||||
"roomStamp.nameLine2": "Name line 2",
|
||||
"roomStamp.showFloorArea": "Floor area",
|
||||
"roomStamp.floorAreaPrefix": "Prefix",
|
||||
"roomStamp.asModelView": "As model view",
|
||||
"roomStamp.on": "On",
|
||||
"roomStamp.off": "Off",
|
||||
"roomStamp.showUsage": "Show SIA category",
|
||||
"roomStamp.showDivider": "Divider line below the name",
|
||||
"roomStamp.showFinish": "Show floor finish",
|
||||
"roomStamp.roundingStep": "Area rounding",
|
||||
"roomStamp.showUsage": "SIA category",
|
||||
"roomStamp.showDivider": "Divider",
|
||||
"roomStamp.showFinish": "Floor finish",
|
||||
"roomStamp.roundingStep": "Rounding",
|
||||
"roomStamp.roundingStepDefault": "Default (2 decimal places)",
|
||||
"roomStamp.occupancy": "Occupancy",
|
||||
"roomStamp.font.section": "Font",
|
||||
"roomStamp.font.all": "Whole stamp",
|
||||
"roomStamp.font.name": "Name",
|
||||
"roomStamp.font.line2": "Line 2",
|
||||
"roomStamp.font.number": "Number",
|
||||
"roomStamp.font.area": "Area",
|
||||
"roomStamp.font.usage": "Category",
|
||||
"roomStamp.font.default": "Default",
|
||||
"roomStamp.font.family": "Font family",
|
||||
"roomStamp.font.size": "Font size (pt)",
|
||||
"roomStamp.font.color": "Font color",
|
||||
"roomStamp.font.reset": "Reset to default",
|
||||
"text.selectedHint": "Formatting applies to the selected text",
|
||||
|
||||
"rt.bold": "Bold",
|
||||
@@ -3847,4 +3903,91 @@ export const en: Record<TranslationKey, string> = {
|
||||
"presentation.tooBig": "Presentation sheet: does not fully fit even at 1:{scale} – choose a larger format",
|
||||
"presentation.empty": "Presentation sheet: no view with content chosen",
|
||||
"presentation.failed": "Could not create the presentation sheet",
|
||||
// [211] Rendering mit Blender/Cycles
|
||||
"cmd.rendering.label": "Rendering…",
|
||||
"cmd.rendering.prompt": "Set up rendering with Blender …",
|
||||
"menu.view.rendering": "Render with Blender …",
|
||||
"render.title": "Render with Blender",
|
||||
"render.intro": "Photorealistic image of the active 3D view with Blender/Cycles (installed Blender, runs as a separate process).",
|
||||
"render.camera.title": "Camera",
|
||||
"render.camera.live": "Current 3D view",
|
||||
"render.camera.saved": "Camera: «{name}» (saved)",
|
||||
"render.camera.view": "Camera: current 3D view",
|
||||
"render.camera.preset": "Camera: preset «{name}» (3D view not open)",
|
||||
"render.size": "Image size",
|
||||
"render.size.hd": "Full HD, 1920 × 1080",
|
||||
"render.size.uhd": "4K, 3840 × 2160",
|
||||
"render.size.a4": "A4 landscape, 300 dpi",
|
||||
"render.size.a3": "A3 landscape, 300 dpi",
|
||||
"render.size.a2": "A2 landscape, 300 dpi",
|
||||
"render.size.custom": "Custom size",
|
||||
"render.width": "Width (pixels)",
|
||||
"render.height": "Height (pixels)",
|
||||
"render.quality": "Quality",
|
||||
"render.quality.draft": "Draft (32 samples)",
|
||||
"render.quality.normal": "Normal (128 samples)",
|
||||
"render.quality.high": "High (512 samples)",
|
||||
"render.quality.final": "Final (1536 samples)",
|
||||
"render.time": "Date and time of the sun",
|
||||
"render.sun": "Sun: azimuth {az}°, elevation {el}°",
|
||||
"render.sun.night": "The sun is below the horizon then; the image is rendered at twilight (sun elevation 1°).",
|
||||
"render.blenderPath": "Blender executable",
|
||||
"render.blenderPath.placeholder": "search automatically",
|
||||
"render.start": "Render",
|
||||
"render.abort": "Cancel rendering",
|
||||
"render.working": "Preparing package …",
|
||||
"render.stage.import": "Loading model into Blender …",
|
||||
"render.stage.materials": "Setting materials …",
|
||||
"render.stage.camera": "Setting up camera …",
|
||||
"render.stage.sky": "Setting up sky and sun …",
|
||||
"render.stage.render": "Rendering: sample {done} of {total}",
|
||||
"render.stage.done": "Done",
|
||||
"render.done": "Rendering done ({width} × {height})",
|
||||
"render.save": "Save image …",
|
||||
"render.again": "Render again",
|
||||
"render.saved": "Rendering saved",
|
||||
"render.cancelled": "Rendering cancelled",
|
||||
"render.error": "Rendering failed: {message}",
|
||||
"render.missingTextures": "{n} texture maps were not reachable; these materials appear in a single colour.",
|
||||
"render.missing.title": "Blender not found",
|
||||
"render.missing.text": "Rendering needs an installed Blender (free, version 3.6 or later). Dossier only calls it as a separate program. After installing it, choose «Render» again or enter the executable path above.",
|
||||
"render.missing.download": "Download Blender",
|
||||
"render.browser.text": "In the browser Dossier cannot start Blender. The package contains the model (GLB), scene description, textures and the Blender script with instructions.",
|
||||
"render.zip.save": "Save package as ZIP",
|
||||
"render.zip.saved": "Rendering package saved",
|
||||
"render.zip.readme.title": "Dossier: rendering package for Blender/Cycles",
|
||||
"render.zip.readme.steps": "Install Blender (3.6 or later), unzip this folder and run inside it:",
|
||||
"render.zip.readme.result": "The image is written as render.png next to scene.json. Image size, samples, camera and sun are in scene.json.",
|
||||
"settings.section.rendering": "Rendering",
|
||||
"settings.blenderPath": "Blender executable",
|
||||
"settings.blenderPath.hint": "Empty: Blender is searched in PATH and the usual places (macOS: /Applications/Blender.app).",
|
||||
// [208] Competition submission: images on sheets, poster templates, anonymity
|
||||
"sheetImage.title": "Image",
|
||||
"sheetImage.add": "Image",
|
||||
"sheetImage.width": "Width mm",
|
||||
"sheetImage.dpi": "{dpi} dpi on the sheet",
|
||||
"sheetImage.lowDpi": "low resolution",
|
||||
"sheetImage.crop": "Crop",
|
||||
"sheetImage.crop.left": "Left",
|
||||
"sheetImage.crop.right": "Right",
|
||||
"sheetImage.crop.top": "Top",
|
||||
"sheetImage.crop.bottom": "Bottom",
|
||||
"sheetImage.cropReset": "Reset crop",
|
||||
"sheetImage.remove": "Remove image",
|
||||
"sheetImage.invalid": "Only PNG and JPEG images up to 40 MB can be placed.",
|
||||
"pdfLayers.images": "Images",
|
||||
"poster.template.name": "Poster {format} {orientation}",
|
||||
"poster.header.keyword": "Keyword",
|
||||
"poster.header.plan": "Plan {x}/{n}",
|
||||
"layouts.newLayout.poster": "Poster template (competition)",
|
||||
"layouts.newLayout.posterHint": "Layout grid as guides, header with keyword and \"Plan x/n\", scale under every viewport.",
|
||||
"publish.competition.anonymous": "Competition (anonymous)",
|
||||
"publish.competition.keyword": "Keyword",
|
||||
"publish.competition.hint": "Title block, PDF title and file names show only the keyword; no office or author name, no program or date details in the PDF.",
|
||||
"publish.wbw.add": "Create competition set",
|
||||
"publish.wbw.name": "Competition submission",
|
||||
"render.toLayout": "Place in layout",
|
||||
"render.toLayout.target": "Sheet",
|
||||
"render.toLayout.none": "No layout sheet yet: create a sheet first.",
|
||||
"render.toLayout.done": "Rendering placed on sheet \"{name}\".",
|
||||
};
|
||||
@@ -30,8 +30,6 @@ export function useContextMenuState() {
|
||||
const [nativeLayerSettingsCode, setNativeLayerSettingsCode] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
// Offener Raum-Stempel-Editor (Rich-Text) — per Doppelklick/Button geöffnet.
|
||||
const [stampEditorRoomId, setStampEditorRoomId] = useState<string | null>(null);
|
||||
// Text-Inhalt-Editor: Id des per Doppelklick bearbeiteten Text-2D-Elements.
|
||||
const [editTextId, setEditTextId] = useState<string | null>(null);
|
||||
// Mindesthöhe (Meter) des Inline-Editors, wenn `editTextId` aus einem frisch
|
||||
@@ -51,8 +49,6 @@ export function useContextMenuState() {
|
||||
setEditor,
|
||||
nativeLayerSettingsCode,
|
||||
setNativeLayerSettingsCode,
|
||||
stampEditorRoomId,
|
||||
setStampEditorRoomId,
|
||||
editTextId,
|
||||
setEditTextId,
|
||||
editTextMinHeightM,
|
||||
|
||||
@@ -15,8 +15,15 @@ export const AUTO_DIM_CATEGORY = "81";
|
||||
export const LEVEL_MARK_CATEGORY = "82";
|
||||
/** Schnitt- und Ansichtsmarken im Grundriss. */
|
||||
export const SECTION_MARK_CATEGORY = "91";
|
||||
/** Kameras ([213]): Symbol mit Sichtkegel im Grundriss. */
|
||||
export const CAMERA_CATEGORY = "92";
|
||||
|
||||
export const DERIVED_CATEGORY_CODES: readonly string[] = [SHADOW_CATEGORY, AUTO_DIM_CATEGORY, LEVEL_MARK_CATEGORY, SECTION_MARK_CATEGORY];
|
||||
/** [207] Eigenes Gebäude im Situationsplan/Schwarzplan (gefüllter Umriss über alle Geschosse). */
|
||||
export const SITUATION_CATEGORY = "83";
|
||||
/** [207] Planzeichen des Situationsplans: Nordpfeil und Massstabsbalken. */
|
||||
export const SYMBOL_CATEGORY = "84";
|
||||
|
||||
export const DERIVED_CATEGORY_CODES: readonly string[] = [SHADOW_CATEGORY, AUTO_DIM_CATEGORY, LEVEL_MARK_CATEGORY, SECTION_MARK_CATEGORY, CAMERA_CATEGORY, SITUATION_CATEGORY, SYMBOL_CATEGORY];
|
||||
|
||||
/** Abgeleitete Darstellung der Klasse `code` sichtbar: Klasse eingeblendet (`shown`) oder im Projekt nicht vorhanden. */
|
||||
export function derivedVisible(layers: LayerCategory[], code: string, shown: (code: string) => boolean): boolean {
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
// Bilder auf Layout-Blättern ([208]): Einlesen (Format am Dateikopf), Seitenverhältnis, Zuschnitt, Listen-Änderungen.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Layout } from "./types";
|
||||
import {
|
||||
addImage,
|
||||
bytesToDataUrl,
|
||||
createLayoutImage,
|
||||
cropImage,
|
||||
dataUrlToBytes,
|
||||
imageAspect,
|
||||
imageGeometry,
|
||||
imageInfo,
|
||||
patchImage,
|
||||
removeImage,
|
||||
resizeImageWidth,
|
||||
} from "./layoutImages";
|
||||
import { JPEG_64X48, PNG_40X30, PNG_40X30_ALPHA } from "./layoutImages.testing";
|
||||
|
||||
const A1 = { w: 841, h: 594 };
|
||||
const layout = (): Layout => ({ id: "l1", name: "Blatt", paper: "a1", orientation: "landscape", viewports: [] });
|
||||
|
||||
describe("Blatt-Bilder", () => {
|
||||
it("liest Format und Pixelgrösse aus dem Dateikopf", () => {
|
||||
expect(imageInfo(bytesToDataUrl(JPEG_64X48, "image/jpeg"))).toEqual({ mime: "image/jpeg", width: 64, height: 48 });
|
||||
expect(imageInfo(bytesToDataUrl(PNG_40X30, "image/png"))).toEqual({ mime: "image/png", width: 40, height: 30 });
|
||||
expect(imageInfo(bytesToDataUrl(PNG_40X30_ALPHA, "image/png"))?.width).toBe(40);
|
||||
expect(imageInfo("data:image/gif;base64,R0lGODlhAQABAAAAACw=")).toBeNull();
|
||||
});
|
||||
|
||||
it("Data-URL und Bytes sind verlustfrei austauschbar", () => {
|
||||
expect(dataUrlToBytes(bytesToDataUrl(JPEG_64X48, "image/jpeg"))).toEqual(JPEG_64X48);
|
||||
});
|
||||
|
||||
it("neues Bild liegt mittig, im Seitenverhältnis, und die Dateiendung zählt nicht", () => {
|
||||
// JPEG-Bytes mit PNG-Hinweis: der Kopf entscheidet
|
||||
const img = createLayoutImage("i1", "foto.png", JPEG_64X48, A1, "image/png")!;
|
||||
expect(img.src.startsWith("data:image/jpeg;base64,")).toBe(true);
|
||||
expect([img.pixelWidth, img.pixelHeight]).toEqual([64, 48]);
|
||||
expect(img.widthMm / img.heightMm).toBeCloseTo(64 / 48, 1);
|
||||
expect(img.widthMm).toBeLessThanOrEqual(841 * 0.6 + 0.1);
|
||||
expect(img.xMm + img.widthMm / 2).toBeCloseTo(420.5, 0);
|
||||
expect(img.yMm + img.heightMm / 2).toBeCloseTo(297, 0);
|
||||
});
|
||||
|
||||
it("weist Unbrauchbares ab", () => {
|
||||
expect(createLayoutImage("i", "x", new Uint8Array([1, 2, 3]), A1)).toBeNull();
|
||||
expect(createLayoutImage("i", "x", new Uint8Array(), A1)).toBeNull();
|
||||
});
|
||||
|
||||
it("Breite ändern hält das Seitenverhältnis, Zuschnitt ändert es", () => {
|
||||
const img = createLayoutImage("i1", "a", PNG_40X30, A1)!;
|
||||
const r = resizeImageWidth(img, 200);
|
||||
expect(r).toEqual({ widthMm: 200, heightMm: 150 });
|
||||
// linke Hälfte: 20×30 px → Verhältnis 2/3
|
||||
const c = cropImage({ ...img, ...r }, { x: 0, y: 0, w: 0.5, h: 1 });
|
||||
expect(c.widthMm).toBe(200);
|
||||
expect(c.heightMm).toBe(300);
|
||||
expect(imageAspect({ ...img, crop: c.crop })).toBeCloseTo(2 / 3, 6);
|
||||
});
|
||||
|
||||
it("Zeichen-Rechteck füllt mit Zuschnitt den Rahmen; dpi folgt der Grösse", () => {
|
||||
const img = { ...createLayoutImage("i1", "a", PNG_40X30, A1)!, xMm: 100, yMm: 50, widthMm: 100, heightMm: 75 };
|
||||
const g = imageGeometry(img);
|
||||
expect(g.draw).toEqual(g.clip);
|
||||
expect(g.dpi).toBeCloseTo(40 / (100 / 25.4), 6);
|
||||
const c = imageGeometry({ ...img, crop: { x: 0.5, y: 0, w: 0.5, h: 1 }, heightMm: 150 });
|
||||
expect(c.draw.w).toBe(200);
|
||||
expect(c.draw.x).toBe(0);
|
||||
});
|
||||
|
||||
it("hängt an, ändert und entfernt Bilder am Blatt", () => {
|
||||
const img = createLayoutImage("i1", "a", PNG_40X30, A1)!;
|
||||
let l = addImage(layout(), img);
|
||||
expect(l.images).toHaveLength(1);
|
||||
l = patchImage(l, "i1", { xMm: 5, crop: { x: 0.1, y: 0.1, w: 0.5, h: 0.5 } });
|
||||
expect(l.images![0].xMm).toBe(5);
|
||||
l = patchImage(l, "i1", { crop: undefined });
|
||||
expect("crop" in l.images![0]).toBe(false);
|
||||
expect(removeImage(l, "i1").images).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
// Testbilder für Blatt-Bilder ([208]): kleine echte Dateien (JPEG 64×48, PNG 40×30 RGB, PNG 40×30 RGBA), als Base64.
|
||||
|
||||
const b64 = (s: string): Uint8Array => Uint8Array.from(Buffer.from(s, "base64"));
|
||||
|
||||
export const JPEG_64X48 = b64("/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAwAEADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD57itParsVp7VqRWntV2K09q+1qYk4cLjDLhtOnFXIrT2rVitParsVp7VxTxJ9JhcYZUNp7VditPatSK09quxWntXHPEn0uFxhlxWntVyK09q1YrT2q7Fae1cdTEn0uFxhw8Vp7VcitPatWK09quw2ntWk8SfzRhcYZUVp7VditPatSK09quxWntXHUxJ9LhcYZcNp7VcitPatWK09quxWntXHUxJ9JhcYZUVp7VditPatSK09quxWntXFPEn0uFxhw8Vp7VditPatWK09quRWntWtTEn804XGGXFae1XYrT2rUitParsNp7VxzxJ9JhcYZUVp7VditPatWK09quRWntXHPEn0uFxhlw2ntVyK09q1YrT2q7Fae1cVTEn0mFxh/9k=");
|
||||
export const PNG_40X30 = b64("iVBORw0KGgoAAAANSUhEUgAAACgAAAAeCAIAAADRv8uKAAAASklEQVR4nO3PMQ6AMAzAQCNVBX7dp7MiZuQuzpRkse6ANWHCCe/lc/7+H1xsmcG9K5xYCyfWwom1cGItnFgLJ9bCibVwYi2cWJoHuaEC5Ls5JT8AAAAASUVORK5CYII=");
|
||||
export const PNG_40X30_ALPHA = b64("iVBORw0KGgoAAAANSUhEUgAAACgAAAAeCAYAAABe3VzdAAAAWUlEQVR4nO3QMQ6AIBAF0U9CUG/NzbWxoDA2kwDFvGbJbkOmJP1uSVqS453j+2s3815zZms11+ov/LMgZUHKgpQFKQtSFqQsSFmQsiBlQcqClAUpC1LbF3wAq2UD44jvAb0AAAAASUVORK5CYII=");
|
||||
@@ -0,0 +1,137 @@
|
||||
// Bilder auf Layout-Blättern ([208]): Renderings, Fotos, Luftbilder als PNG/JPEG. Im Projekt liegt das Bild als
|
||||
// Data-URL (`LayoutImage.src`) — derselbe Weg wie bei `ContextImage` (Luftbild als Unterlage). Rechnung
|
||||
// (Dateikopf lesen, Seitenverhältnis, Zeichen-/Klipp-Rechteck mit Zuschnitt, Startgrösse) im Kern
|
||||
// (`src-tauri/core/src/layout_image.rs`); hier nur die dünne Fassade, Listen-Änderungen am Layout und das Einlesen.
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch.
|
||||
|
||||
import type { Layout, LayoutImage } from "./types";
|
||||
import { core } from "../engine/coreWasm";
|
||||
|
||||
export interface ImageInfo {
|
||||
mime: string;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** Rechteck in Papier-mm. */
|
||||
export interface RectXYWH {
|
||||
x: number;
|
||||
y: number;
|
||||
w: number;
|
||||
h: number;
|
||||
}
|
||||
|
||||
/** Mehr als 40 MB Bild in einem Projekt sprengt Speichern und Autosave. */
|
||||
export const MAX_IMAGE_BYTES = 40 * 1024 * 1024;
|
||||
|
||||
function call<T>(name: string, arg: unknown): T | null {
|
||||
const out = core().layout_call(name, JSON.stringify(arg));
|
||||
return out === "" ? null : (JSON.parse(out) as T);
|
||||
}
|
||||
|
||||
/** Format und Pixelgrösse einer PNG-/JPEG-Data-URL; `null` bei anderen Formaten oder kaputten Daten. */
|
||||
export function imageInfo(src: string): ImageInfo | null {
|
||||
return call<ImageInfo>("imageInfo", { src });
|
||||
}
|
||||
|
||||
/** Seitenverhältnis (Breite/Höhe) des gezeigten Ausschnitts, Zuschnitt eingerechnet. */
|
||||
export function imageAspect(img: Pick<LayoutImage, "pixelWidth" | "pixelHeight" | "crop">): number {
|
||||
return call<number>("imageAspect", img) ?? 1;
|
||||
}
|
||||
|
||||
/** Klipp-Rahmen, Zeichen-Rechteck des GANZEN Originals und Auflösung (dpi) des Bilds auf dem Blatt. */
|
||||
export function imageGeometry(img: LayoutImage): { clip: RectXYWH; draw: RectXYWH; dpi: number } {
|
||||
const g = call<{ clip: RectXYWH; draw: RectXYWH; dpi: number }>("imageGeometry", img);
|
||||
const r = { x: img.xMm, y: img.yMm, w: img.widthMm, h: img.heightMm };
|
||||
return g ?? { clip: r, draw: r, dpi: 0 };
|
||||
}
|
||||
|
||||
/** Startrahmen eines neuen Bilds auf einem Blatt `sheetW`×`sheetH` mm: Seitenverhältnis gehalten, mittig. */
|
||||
export function initialImageFrame(pixelWidth: number, pixelHeight: number, sheetW: number, sheetH: number): RectXYWH {
|
||||
return call<RectXYWH>("imageInitial", { pixelWidth, pixelHeight, sheetW, sheetH }) ?? { x: 0, y: 0, w: sheetW / 2, h: sheetH / 2 };
|
||||
}
|
||||
|
||||
/** Bytes → Data-URL (in Stücken, damit grosse Bilder keinen Stapel sprengen). */
|
||||
export function bytesToDataUrl(bytes: Uint8Array, mime: string): string {
|
||||
let bin = "";
|
||||
const chunk = 0x8000;
|
||||
for (let i = 0; i < bytes.length; i += chunk) bin += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
||||
return `data:${mime};base64,${btoa(bin)}`;
|
||||
}
|
||||
|
||||
/** Data-URL → Bytes (für den PDF-Export und „Speichern unter"). */
|
||||
export function dataUrlToBytes(src: string): Uint8Array {
|
||||
const bin = atob(src.slice(src.indexOf(",") + 1));
|
||||
const out = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Neues Blatt-Bild aus Dateibytes: erkennt PNG/JPEG am Kopf (nicht am Dateinamen), legt es mittig und im
|
||||
* Seitenverhältnis auf das Blatt. `null`, wenn es weder PNG noch JPEG ist oder zu gross.
|
||||
*/
|
||||
export function createLayoutImage(
|
||||
id: string,
|
||||
name: string,
|
||||
bytes: Uint8Array,
|
||||
sheet: { w: number; h: number },
|
||||
mimeHint = "image/png",
|
||||
): LayoutImage | null {
|
||||
if (bytes.length === 0 || bytes.length > MAX_IMAGE_BYTES) return null;
|
||||
const src = bytesToDataUrl(bytes, mimeHint);
|
||||
const info = imageInfo(src);
|
||||
if (!info) return null;
|
||||
// Der Kopf entscheidet über das Format, nicht der Hinweis (umbenannte Dateien).
|
||||
const real = info.mime === mimeHint ? src : bytesToDataUrl(bytes, info.mime);
|
||||
const f = initialImageFrame(info.width, info.height, sheet.w, sheet.h);
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
src: real,
|
||||
xMm: round1(f.x),
|
||||
yMm: round1(f.y),
|
||||
widthMm: round1(f.w),
|
||||
heightMm: round1(f.h),
|
||||
pixelWidth: info.width,
|
||||
pixelHeight: info.height,
|
||||
};
|
||||
}
|
||||
|
||||
function round1(v: number): number {
|
||||
return Math.round(v * 10) / 10;
|
||||
}
|
||||
|
||||
/** Breite ändern, Höhe folgt dem Seitenverhältnis des Ausschnitts. */
|
||||
export function resizeImageWidth(img: LayoutImage, widthMm: number): Pick<LayoutImage, "widthMm" | "heightMm"> {
|
||||
const w = Math.max(5, widthMm);
|
||||
return { widthMm: round1(w), heightMm: round1(w / imageAspect(img)) };
|
||||
}
|
||||
|
||||
/** Neuer Zuschnitt (Anteile 0..1): der Rahmen behält seine Breite, die Höhe folgt dem neuen Seitenverhältnis. */
|
||||
export function cropImage(img: LayoutImage, crop: LayoutImage["crop"]): Pick<LayoutImage, "crop" | "widthMm" | "heightMm"> {
|
||||
const next = { ...img, crop };
|
||||
return { crop, widthMm: img.widthMm, heightMm: round1(img.widthMm / imageAspect(next)) };
|
||||
}
|
||||
|
||||
/** Bild an das Blatt anhängen. */
|
||||
export function addImage(layout: Layout, image: LayoutImage): Layout {
|
||||
return { ...layout, images: [...(layout.images ?? []), image] };
|
||||
}
|
||||
|
||||
export function removeImage(layout: Layout, imageId: string): Layout {
|
||||
return { ...layout, images: (layout.images ?? []).filter((i) => i.id !== imageId) };
|
||||
}
|
||||
|
||||
export function patchImage(layout: Layout, imageId: string, patch: Partial<Omit<LayoutImage, "id">>): Layout {
|
||||
return {
|
||||
...layout,
|
||||
images: (layout.images ?? []).map((i) => {
|
||||
if (i.id !== imageId) return i;
|
||||
const next = { ...i, ...patch };
|
||||
for (const k of Object.keys(patch) as (keyof typeof patch)[]) if (patch[k] === undefined) delete (next as Record<string, unknown>)[k];
|
||||
return next;
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -519,6 +519,13 @@ export interface ResolvedTitleBlock {
|
||||
planNumber: string;
|
||||
/** Revisionsindex des Blatts (`Layout.revision`, [79]); fehlt = keiner. */
|
||||
revision?: string;
|
||||
/** Kennwort der Abgabe (`Project.competition.keyword`, [208]); leer ohne Wettbewerb. */
|
||||
keyword: string;
|
||||
/** Anonyme Abgabe ([208]): `projectName` ist das Kennwort, `author` leer. */
|
||||
anonymous: boolean;
|
||||
/** „Plan x/n" ([208]): Stelle des Blatts und Anzahl der Blätter, die mitzählen (Kern `resolve_title_block`). */
|
||||
planIndex: number;
|
||||
planCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -536,7 +543,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, masterId: layout.masterId, viewports: (layout.viewports ?? []).slice(0, 1) },
|
||||
master: master ? { titleBlock: master.titleBlock } : null,
|
||||
today,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// [208] Plakat-Vorlagen: Master mit Raster, Kopfzeile, Massstabsangabe; Blatt „aus Vorlage"; anonymer Plankopf.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { sampleProject } from "./sampleProject";
|
||||
import { buildComplexSampleProject } from "./sampleProjectComplex";
|
||||
import type { Layout, Project } from "./types";
|
||||
import { effectiveSheetSizeMm, findMaster, resolveTitleBlock } from "./layoutModel";
|
||||
import { createPosterMaster, findPosterMaster, POSTER_TEMPLATES, posterHeaderItems, posterMetrics, posterTemplate, viewportScaleLabel } from "./posterTemplates";
|
||||
import { addWbwSetOps, setCompetitionOps } from "../state/publishActions";
|
||||
import { applyOps } from "../core/ops";
|
||||
import { planPublish } from "../export/publishSet";
|
||||
import { placeImageOps } from "../state/layoutImageActions";
|
||||
import { PNG_40X30 } from "./layoutImages.testing";
|
||||
|
||||
function withPosters(competition?: Project["competition"]): Project {
|
||||
const m = createPosterMaster("m1", posterTemplate("poster-a1-landscape")!);
|
||||
const lay = (id: string, name: string): Layout => ({ id, name, paper: "a1", orientation: "landscape", masterId: "m1", viewports: [] });
|
||||
return { ...sampleProject, name: "Haus Muster", projectNumber: "2611", masterLayouts: [m], layouts: [lay("p1", "Situation"), lay("p2", "Grundrisse"), { ...lay("x", "Anderes"), masterId: undefined }], competition };
|
||||
}
|
||||
|
||||
describe("Plakat-Vorlagen", () => {
|
||||
it("A0 und A1, hoch und quer", () => {
|
||||
expect(POSTER_TEMPLATES.map((p) => p.key)).toEqual(["poster-a0-portrait", "poster-a0-landscape", "poster-a1-portrait", "poster-a1-landscape"]);
|
||||
for (const tpl of POSTER_TEMPLATES) {
|
||||
const m = createPosterMaster(`m-${tpl.key}`, tpl);
|
||||
const size = effectiveSheetSizeMm(m);
|
||||
expect(tpl.orientation === "landscape" ? size.w > size.h : size.h > size.w).toBe(true);
|
||||
expect(m.template).toBe(tpl.key);
|
||||
expect(m.posterHeader).toBe(true);
|
||||
expect(m.viewportScaleLabels).toBe(true);
|
||||
// Raster: 2 senkrechte Linien je Spalte, 4 waagrechte
|
||||
const mm = posterMetrics(size.w, size.h);
|
||||
expect(m.guides!.filter((g) => g.axis === "x")).toHaveLength(mm.columns * 2);
|
||||
expect(m.guides!.filter((g) => g.axis === "y")).toHaveLength(4);
|
||||
// alle Linien liegen im Blatt
|
||||
for (const g of m.guides!) {
|
||||
expect(g.posMm).toBeGreaterThan(0);
|
||||
expect(g.posMm).toBeLessThan(g.axis === "x" ? size.w : size.h);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("A1 quer misst 841 × 594 mm mit 6 Spalten", () => {
|
||||
const m = createPosterMaster("m", posterTemplate("poster-a1-landscape")!);
|
||||
expect(effectiveSheetSizeMm(m)).toEqual({ w: 841, h: 594 });
|
||||
expect(posterMetrics(841, 594).columns).toBe(6);
|
||||
});
|
||||
|
||||
it("findet den Master einer Vorlage im Projekt wieder", () => {
|
||||
const p = withPosters();
|
||||
expect(findPosterMaster(p, "poster-a1-landscape")?.id).toBe("m1");
|
||||
expect(findPosterMaster(p, "poster-a0-portrait")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("Kopfzeile: Kennwort-Feld und „Plan x/n“ zählen nur Plakate", () => {
|
||||
const p = withPosters({ anonymous: true, keyword: "FALKE 7" });
|
||||
const lay = p.layouts![1];
|
||||
const items = posterHeaderItems(p, lay, findMaster(p, lay)!, { w: 841, h: 594 });
|
||||
const texts = items.flatMap((i) => (i.kind === "text" ? [i.text] : []));
|
||||
expect(texts).toContain("Kennwort");
|
||||
expect(texts).toContain("FALKE 7");
|
||||
expect(texts).toContain("Plan 2/2");
|
||||
// anonym: kein Projektname in der Kopfzeile
|
||||
expect(texts.some((x) => x.includes("Haus Muster"))).toBe(false);
|
||||
});
|
||||
|
||||
it("offene Abgabe zeigt den Projektnamen in der Kopfzeile", () => {
|
||||
const p = withPosters({ anonymous: false, keyword: "FALKE 7" });
|
||||
const items = posterHeaderItems(p, p.layouts![0], findMaster(p, p.layouts![0])!, { w: 841, h: 594 });
|
||||
expect(items.flatMap((i) => (i.kind === "text" ? [i.text] : []))).toContain("Haus Muster");
|
||||
});
|
||||
|
||||
it("Plankopf anonym: Kennwort statt Projektname, kein Bearbeiter", () => {
|
||||
const p = withPosters({ anonymous: true, keyword: " FALKE 7 " });
|
||||
p.masterLayouts![0].titleBlock = { projectName: "Büro AG", author: "M. Muster" };
|
||||
const tb = resolveTitleBlock(p, p.layouts![0], p.masterLayouts![0]);
|
||||
expect([tb.projectName, tb.author, tb.anonymous, tb.keyword]).toEqual(["FALKE 7", "", true, "FALKE 7"]);
|
||||
});
|
||||
|
||||
it("Massstabsangabe unter dem Viewport", () => {
|
||||
const snap = buildComplexSampleProject().viewSnapshots![0];
|
||||
const p = { ...withPosters(), viewSnapshots: [{ ...snap, scaleDenominator: 200 }] };
|
||||
const vp = { id: "v", snapshotId: snap.id, xMm: 50, yMm: 100, widthMm: 300, heightMm: 200 };
|
||||
const l = viewportScaleLabel(p, vp, { w: 841, h: 594 })!;
|
||||
expect(l.text).toBe("1:200");
|
||||
expect(l.x).toBe(50);
|
||||
expect(l.y).toBeGreaterThan(300);
|
||||
expect(viewportScaleLabel(p, { ...vp, scaleDenominator: 100 }, { w: 841, h: 594 })!.text).toBe("1:100");
|
||||
expect(viewportScaleLabel(p, { ...vp, snapshotId: "gibt-es-nicht" }, { w: 841, h: 594 })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Wettbewerb und WBW-Abgabe", () => {
|
||||
it("Einstellung anonym + Kennwort als Ops; leer entfernt das Feld", () => {
|
||||
let p = withPosters();
|
||||
p = applyOps(p, setCompetitionOps(p, { anonymous: true }));
|
||||
expect(p.competition).toEqual({ anonymous: true, keyword: "" });
|
||||
p = applyOps(p, setCompetitionOps(p, { keyword: "FALKE 7" }));
|
||||
expect(p.competition).toEqual({ anonymous: true, keyword: "FALKE 7" });
|
||||
p = applyOps(p, setCompetitionOps(p, { anonymous: false, keyword: "" }));
|
||||
expect(p.competition).toBeUndefined();
|
||||
});
|
||||
|
||||
it("Satz „WBW-Abgabe“ enthält die Plakate in Blattfolge, ein PDF, Dateiname = Kennwort", () => {
|
||||
let p = withPosters({ anonymous: true, keyword: "FALKE 7" });
|
||||
p = applyOps(p, addWbwSetOps(p, "s1"));
|
||||
const set = p.publishSets!.find((s) => s.id === "s1")!;
|
||||
expect(set.layoutIds).toEqual(["p1", "p2"]);
|
||||
expect(set.format).toBe("pdf-multi");
|
||||
const plan = planPublish(p, set, "2026-11-12");
|
||||
expect(plan.files).toHaveLength(1);
|
||||
expect(plan.files[0].layoutIds).toEqual(["p1", "p2"]);
|
||||
expect(plan.files[0].fileName).toBe("FALKE 7_WBW-Abgabe.pdf");
|
||||
expect(plan.files[0].fileName).not.toMatch(/Muster|2611/);
|
||||
});
|
||||
|
||||
it("Einzeldateien (pdf-single) tragen ebenfalls kein Projekt", () => {
|
||||
let p = withPosters({ anonymous: true, keyword: "FALKE 7" });
|
||||
p = applyOps(p, addWbwSetOps(p, "s1"));
|
||||
const set = { ...p.publishSets![0], format: "pdf-single", namePattern: "{Projektnummer}_{Projekt}_{Blattnummer}" };
|
||||
const plan = planPublish(p, set, "2026-11-12");
|
||||
expect(plan.files.map((f) => f.fileName)).toEqual(["FALKE 7_01.pdf", "FALKE 7_02.pdf"]);
|
||||
});
|
||||
|
||||
it("nicht anonym bleibt der Dateiname mit Projekt", () => {
|
||||
let p = withPosters();
|
||||
p = applyOps(p, addWbwSetOps(p, "s1"));
|
||||
expect(planPublish(p, p.publishSets![0], "2026-11-12").files[0].fileName).toBe("Haus Muster_WBW-Abgabe.pdf");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Rendering ins Layout einsetzen", () => {
|
||||
it("Ops setzen das Bild mittig aufs Blatt (A1 quer)", () => {
|
||||
let p = withPosters();
|
||||
const ops = placeImageOps(p, "p1", "r.png", PNG_40X30, "img-1")!;
|
||||
p = applyOps(p, ops);
|
||||
const img = p.layouts![0].images![0];
|
||||
expect(img.id).toBe("img-1");
|
||||
expect(img.pixelWidth).toBe(40);
|
||||
expect(img.xMm + img.widthMm / 2).toBeCloseTo(420.5, 0);
|
||||
expect(img.widthMm / img.heightMm).toBeCloseTo(4 / 3, 1);
|
||||
});
|
||||
|
||||
it("unbekanntes Blatt oder kein Bild: keine Ops", () => {
|
||||
const p = withPosters();
|
||||
expect(placeImageOps(p, "gibts-nicht", "r.png", PNG_40X30, "i")).toBeNull();
|
||||
expect(placeImageOps(p, "p1", "r.png", new Uint8Array([1, 2]), "i")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
// Plakat-Vorlagen für Wettbewerbs-Abgaben ([208]): A0/A1 hoch und quer. Eine Vorlage ist ein Masterlayout
|
||||
// (`MasterLayout.template`) mit Gestaltungsraster (Hilfslinien), Plakat-Kopfzeile (Kennwort-Feld, Projekttitel,
|
||||
// „Plan x/n") und Massstabsangabe unter jedem Viewport; ein Blatt „aus Vorlage" ist ein Layout, das an diesen
|
||||
// Master gebunden ist. Masse und Kopfzeile rechnet der Kern (`src-tauri/core/src/layout_poster.rs`).
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch.
|
||||
|
||||
import type { Layout, LayoutOrientation, LayoutPaperFormat, MasterLayout, Project } from "./types";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import { t } from "../i18n/translate";
|
||||
import { findSnapshot, resolveTitleBlock, resolveViewportScale, sheetSizeMm } from "./layoutModel";
|
||||
|
||||
export interface PosterTemplate {
|
||||
/** Schlüssel in `MasterLayout.template`. */
|
||||
key: string;
|
||||
paper: LayoutPaperFormat;
|
||||
orientation: LayoutOrientation;
|
||||
}
|
||||
|
||||
export const POSTER_TEMPLATES: readonly PosterTemplate[] = [
|
||||
{ key: "poster-a0-portrait", paper: "a0", orientation: "portrait" },
|
||||
{ key: "poster-a0-landscape", paper: "a0", orientation: "landscape" },
|
||||
{ key: "poster-a1-portrait", paper: "a1", orientation: "portrait" },
|
||||
{ key: "poster-a1-landscape", paper: "a1", orientation: "landscape" },
|
||||
];
|
||||
|
||||
export function posterTemplate(key: string): PosterTemplate | undefined {
|
||||
return POSTER_TEMPLATES.find((p) => p.key === key);
|
||||
}
|
||||
|
||||
/** Anzeigename einer Vorlage („Plakat A1 quer"). */
|
||||
export function posterTemplateLabel(tpl: PosterTemplate): string {
|
||||
return t("poster.template.name", {
|
||||
format: tpl.paper.toUpperCase(),
|
||||
orientation: tpl.orientation === "landscape" ? t("layouts.landscape") : t("layouts.portrait"),
|
||||
});
|
||||
}
|
||||
|
||||
export interface PosterMetrics {
|
||||
widthMm: number;
|
||||
heightMm: number;
|
||||
marginMm: number;
|
||||
headerHeightMm: number;
|
||||
columns: number;
|
||||
gutterMm: number;
|
||||
contentTopMm: number;
|
||||
guides: { axis: "x" | "y"; posMm: number }[];
|
||||
}
|
||||
|
||||
/** Ränder, Spalten und Hilfslinien für ein Blatt `widthMm`×`heightMm`. */
|
||||
export function posterMetrics(widthMm: number, heightMm: number): PosterMetrics {
|
||||
const out = core().layout_call("posterMetrics", JSON.stringify({ widthMm, heightMm }));
|
||||
if (out === "") throw new Error("Kern: Plakat-Masse nicht berechenbar");
|
||||
return JSON.parse(out) as PosterMetrics;
|
||||
}
|
||||
|
||||
/** Master der Vorlage (Titelblock leer, Hilfslinien des Rasters, Kopfzeile, Massstabsangaben). */
|
||||
export function createPosterMaster(id: string, tpl: PosterTemplate): MasterLayout {
|
||||
const size = sheetSizeMm(tpl.paper, tpl.orientation);
|
||||
const m = posterMetrics(size.w, size.h);
|
||||
return {
|
||||
id,
|
||||
name: posterTemplateLabel(tpl),
|
||||
paper: tpl.paper,
|
||||
orientation: tpl.orientation,
|
||||
titleBlock: {},
|
||||
border: false,
|
||||
template: tpl.key,
|
||||
posterHeader: true,
|
||||
viewportScaleLabels: true,
|
||||
guides: m.guides,
|
||||
};
|
||||
}
|
||||
|
||||
/** Der vorhandene Master einer Vorlage im Projekt (Plakate teilen einen Master je Vorlage). */
|
||||
export function findPosterMaster(project: Pick<Project, "masterLayouts">, key: string): MasterLayout | undefined {
|
||||
return (project.masterLayouts ?? []).find((m) => m.template === key);
|
||||
}
|
||||
|
||||
export type HeaderItem =
|
||||
| { kind: "rect"; x: number; y: number; w: number; h: number; stroke: number }
|
||||
| { kind: "text"; x: number; y: number; text: string; sizeMm: number; align: "left" | "center" | "right"; bold: boolean };
|
||||
|
||||
/**
|
||||
* Zeichenelemente der Plakat-Kopfzeile eines Blatts: Kennwort-Feld, Projekttitel (bei anonymer Abgabe leer) und
|
||||
* „Plan x/n". Bildschirm (SVG) und PDF zeichnen dieselben Elemente.
|
||||
*/
|
||||
export function posterHeaderItems(project: Project, layout: Layout, master: MasterLayout, sheet: { w: number; h: number }): HeaderItem[] {
|
||||
const tb = resolveTitleBlock(project, layout, master);
|
||||
const title = tb.anonymous ? "" : tb.projectName;
|
||||
const planText = tb.planCount > 0 ? t("poster.header.plan", { x: tb.planIndex, n: tb.planCount }) : "";
|
||||
const out = core().layout_call(
|
||||
"posterHeader",
|
||||
JSON.stringify({ widthMm: sheet.w, heightMm: sheet.h, keywordLabel: t("poster.header.keyword"), keyword: tb.keyword, title, planText }),
|
||||
);
|
||||
return out === "" ? [] : (JSON.parse(out) as HeaderItem[]);
|
||||
}
|
||||
|
||||
/** Massstabsangabe unter einem Viewport: Text, Lage (Papier-mm, Grundlinie) und Schrifthöhe. */
|
||||
export function viewportScaleLabel(
|
||||
project: Project,
|
||||
vp: Layout["viewports"][number],
|
||||
sheet: { w: number; h: number },
|
||||
scaleOverride?: number,
|
||||
): { text: string; x: number; y: number; sizeMm: number } | null {
|
||||
const snap = findSnapshot(project, vp.snapshotId);
|
||||
if (!snap) return null;
|
||||
const n = scaleOverride ?? resolveViewportScale(vp, snap);
|
||||
const sizeMm = Math.max(3, Math.min(sheet.w, sheet.h) / 140);
|
||||
return { text: `1:${n}`, x: vp.xMm, y: vp.yMm + vp.heightMm + sizeMm * 1.3, sizeMm };
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { defaultRoomStamp, roomDisplayName } from "./roomStamp";
|
||||
import { defaultRoomStamp, roomDisplayName, setStampFontAttr } from "./roomStamp";
|
||||
import type { Room } from "./types";
|
||||
|
||||
function makeRoom(over: Partial<Room> = {}): Room {
|
||||
@@ -50,3 +50,20 @@ describe("roomDisplayName", () => {
|
||||
expect(roomDisplayName(room)).toBe("Küche");
|
||||
});
|
||||
});
|
||||
|
||||
describe("setStampFontAttr [218]", () => {
|
||||
const base = { name: "Wohnen" };
|
||||
it("setzt und entfernt Eigenschaften je Zeile, eine leere Schrift entfällt", () => {
|
||||
const a = setStampFontAttr(base, "nameFont", "sizePt", 18);
|
||||
expect(a.nameFont).toEqual({ sizePt: 18 });
|
||||
const b = setStampFontAttr(a, "nameFont", "family", "Jost");
|
||||
expect(b.nameFont).toEqual({ sizePt: 18, family: "Jost" });
|
||||
const c = setStampFontAttr(setStampFontAttr(b, "nameFont", "sizePt", undefined), "nameFont", "family", "");
|
||||
expect("nameFont" in c).toBe(false);
|
||||
expect(a).toEqual({ name: "Wohnen", nameFont: { sizePt: 18 } }); // unverändert (rein)
|
||||
});
|
||||
it("Unsinn (Grösse <= 0) setzt nichts", () => {
|
||||
expect("font" in setStampFontAttr(base, "font", "sizePt", 0)).toBe(false);
|
||||
expect(setStampFontAttr(base, "areaFont", "bold", true).areaFont).toEqual({ bold: true });
|
||||
});
|
||||
});
|
||||
+34
-1
@@ -2,7 +2,7 @@
|
||||
// für Listen. Das Stempel-Dokument und die Live-Zeilen (Fläche, Nutzung, Personen) baut der Kern
|
||||
// beim Plan-Aufbau (`src-tauri/core/src/plan/domains.rs`, [K3d]).
|
||||
|
||||
import type { Room, RoomStamp } from "./types";
|
||||
import type { Marks, Room, RoomStamp, RoomStampFont } from "./types";
|
||||
import type { Align } from "../text/richText";
|
||||
|
||||
/**
|
||||
@@ -21,6 +21,8 @@ export function defaultRoomStamp(room: Room): RoomStamp {
|
||||
export interface RoomStampLine {
|
||||
text: string;
|
||||
align: Align;
|
||||
/** [218] Schrift der Zeile (Familie, Grösse in pt bei Grundschrift 10, fett, kursiv, Farbe); fehlt: 0.8 × Grundschrift. */
|
||||
marks?: Marks;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -33,3 +35,34 @@ export function roomDisplayName(room: Room): string {
|
||||
const line2 = (stamp.nameLine2 ?? "").trim();
|
||||
return line2 ? `${stamp.name} ${line2}` : stamp.name;
|
||||
}
|
||||
|
||||
// ── [218] Schrift des Stempels (Objekteinstellungen, Abschnitt „Raumstempel") ────────────────────────
|
||||
// Der Kern setzt sie beim Plan-Aufbau um (`plan/domains.rs::stamp_line_marks`): Zeilenschrift > Stempelschrift >
|
||||
// eingebaute Werte der Zeile.
|
||||
|
||||
/** Schrift-Schlüssel am Stempel: der ganze Stempel und je Zeile. */
|
||||
export type StampFontKey = "font" | "nameFont" | "line2Font" | "numberFont" | "areaFont" | "usageFont";
|
||||
|
||||
/** Eigenschaft einer Stempelschrift. */
|
||||
export type StampFontAttr = keyof RoomStampFont;
|
||||
|
||||
/** Zeilen mit eigener Schrift in Anzeige-Reihenfolge samt den eingebauten Werten (Anzeige, wenn nichts gesetzt ist). */
|
||||
export const STAMP_FONT_LINES: readonly { key: StampFontKey; labelKey: string; size: number; bold: boolean; italic: boolean }[] = [
|
||||
{ key: "font", labelKey: "roomStamp.font.all", size: 10, bold: false, italic: false },
|
||||
{ key: "nameFont", labelKey: "roomStamp.font.name", size: 12, bold: true, italic: false },
|
||||
{ key: "line2Font", labelKey: "roomStamp.font.line2", size: 9, bold: false, italic: true },
|
||||
{ key: "numberFont", labelKey: "roomStamp.font.number", size: 9, bold: false, italic: false },
|
||||
{ key: "areaFont", labelKey: "roomStamp.font.area", size: 8, bold: false, italic: false },
|
||||
{ key: "usageFont", labelKey: "roomStamp.font.usage", size: 8, bold: false, italic: false },
|
||||
];
|
||||
|
||||
/** Schrift einer Zeile setzen (`value` = `undefined`: Eigenschaft entfernen ⇒ Vorgabe); eine leere Schrift entfällt. */
|
||||
export function setStampFontAttr<K extends StampFontAttr>(stamp: RoomStamp, key: StampFontKey, attr: K, value: RoomStampFont[K] | undefined): RoomStamp {
|
||||
const font: RoomStampFont = { ...(stamp[key] ?? {}) };
|
||||
if (value === undefined || value === "" || (typeof value === "number" && !(value > 0))) delete font[attr];
|
||||
else font[attr] = value;
|
||||
const next: RoomStamp = { ...stamp };
|
||||
if (Object.keys(font).length === 0) delete next[key];
|
||||
else next[key] = font;
|
||||
return next;
|
||||
}
|
||||
@@ -416,6 +416,10 @@ export const sampleProject: Project = {
|
||||
{ code: "82", name: "Höhenkoten", color: "#1a1a1a", lw: 0.13, visible: true, locked: false },
|
||||
{ code: "90", name: "Referenzen", color: "#1a1a1a", lw: 0.13, visible: true, locked: false },
|
||||
{ code: "91", name: "Schnittmarken", color: "#1a1a1a", lw: 0.18, visible: true, locked: false },
|
||||
{ code: "92", name: "Kameras", color: "#1a1a1a", lw: 0.18, visible: true, locked: false },
|
||||
// [207] Situationsplan/Schwarzplan: eigenes Gebäude als gefüllter Umriss, Nordpfeil und Massstabsbalken.
|
||||
{ code: "83", name: "Situation Gebäude", color: "#000000", lw: 0.13, visible: true, locked: false },
|
||||
{ code: "84", name: "Planzeichen", color: "#000000", lw: 0.18, visible: true, locked: false },
|
||||
{ code: "99", name: "Konstruktion", color: "#404040", lw: 0.13, visible: true, locked: false },
|
||||
],
|
||||
// [140] Strichstärken folgen dem Massstab (neue Projekte; bestehende behalten ihre Einstellung).
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// [207] Musterhaus komplex: Ausschnitt „Situation 1:500" nutzt die Ansichtsvorlage „Situation WBW"; Situationsplan
|
||||
// mit schwarzem eigenem Gebäude, grauen Nachbarn, Planzeichen und Klassen.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { generatePlan, planToSvgString, projectWithTemplate } from "../core";
|
||||
import { buildComplexSampleProject } from "./sampleProjectComplex";
|
||||
|
||||
const p = buildComplexSampleProject();
|
||||
const snap = p.viewSnapshots?.find((s) => s.id === "vs-situation");
|
||||
const tpl = p.viewTemplates?.find((t) => t.id === "std-vt-situation-wbw");
|
||||
|
||||
type Plan = ReturnType<typeof generatePlan>;
|
||||
type Poly = { kind: "polygon"; fill: string; wallId?: string; contextObjectId?: string; strokeWidthMm: number };
|
||||
|
||||
function planOf(hide: string[] = []): Plan {
|
||||
const tp = projectWithTemplate(p, "eg", tpl!);
|
||||
const show = new Set(Object.entries(snap!.layerVisibility).filter(([c, v]) => v && !hide.includes(c)).map(([c]) => c));
|
||||
return generatePlan(tp, "eg", show, undefined, "grob", false, true, true, 500);
|
||||
}
|
||||
const polys = (pl: Plan): Poly[] => pl.primitives.filter((q) => q.kind === "polygon") as unknown as Poly[];
|
||||
const isCtx = (q: Poly) => q.contextObjectId === "nachbarn";
|
||||
const isOwn = (q: Poly) => q.fill === "#000000" && !q.contextObjectId && q.strokeWidthMm < 0.12; // Umriss 0.1 mm (nach Massstab skaliert), Planzeichen 0.18 mm
|
||||
|
||||
describe("Situation 1:500 im Musterhaus komplex", () => {
|
||||
it("Ausschnitt ist an die Vorlage gebunden, Klassen der Vorlage sind aus", () => {
|
||||
expect(snap?.templateId).toBe("std-vt-situation-wbw");
|
||||
expect(snap?.templateLinked).toBe(true);
|
||||
expect(tpl?.modelViewOptionId).toBe("std-mv-situation-wbw");
|
||||
for (const [code, v] of Object.entries(tpl?.layerVisibility ?? {})) expect(snap?.layerVisibility[code], code).toBe(v);
|
||||
});
|
||||
|
||||
it("eigenes Gebäude schwarz, Nachbarn grau, keine Bauteile", () => {
|
||||
const ps = polys(planOf());
|
||||
expect(ps.some((q) => q.wallId)).toBe(false);
|
||||
expect(ps.filter(isOwn).length).toBeGreaterThanOrEqual(1);
|
||||
expect(ps.filter((q) => isCtx(q) && q.fill === "#b8b8b8").length).toBe(5);
|
||||
});
|
||||
|
||||
it("Klassen: Nachbarn (12), eigenes Gebäude (83), Planzeichen (84) schaltbar", () => {
|
||||
expect(polys(planOf(["12"])).filter(isCtx).length).toBe(0);
|
||||
expect(polys(planOf(["83"])).filter(isOwn).length).toBe(0);
|
||||
const hasN = (pl: Plan) => pl.primitives.some((q) => q.kind === "drawingText" && (q as unknown as { text: string }).text === "N");
|
||||
expect(hasN(planOf())).toBe(true);
|
||||
expect(hasN(planOf(["84"]))).toBe(false);
|
||||
});
|
||||
|
||||
it("SVG enthält schwarze und graue Flächen", () => {
|
||||
const svg = planToSvgString(planOf(), { scaleDenominator: 500 });
|
||||
expect(svg).toContain('fill="#000000"');
|
||||
expect(svg).toContain('fill="#b8b8b8"');
|
||||
});
|
||||
});
|
||||
@@ -43,7 +43,7 @@ describe("Musterhaus komplex", () => {
|
||||
expect(p.rooms!.length).toBeGreaterThanOrEqual(20);
|
||||
expect(p.roofs!.some((r) => (r.dormers ?? []).length === 2)).toBe(true);
|
||||
expect(p.stairs!.map((s) => s.shape).sort()).toEqual(["L", "spiral", "straight"]);
|
||||
expect(p.context!.map((c) => c.type).sort()).toEqual(["contourSet", "excavation", "terrainMesh"]);
|
||||
expect(p.context!.map((c) => c.type).sort()).toEqual(["contourSet", "excavation", "importedMesh", "terrainMesh"]);
|
||||
expect(p.extrudedSolids!.filter((s) => s.brep).length).toBe(2);
|
||||
expect(p.drawings2d.filter((d) => d.geom.shape === "dimension").length).toBeGreaterThan(8);
|
||||
const frameKinds = new Set(p.doorTypes!.map((d) => d.frameKind ?? d.kind));
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
import type {
|
||||
CeilingType,
|
||||
ContextObject,
|
||||
Drawing2D,
|
||||
Drawing2DGeom,
|
||||
DoorType,
|
||||
@@ -35,6 +36,7 @@ import type {
|
||||
} from "./types";
|
||||
import { sampleProject } from "./sampleProject";
|
||||
import { withStandards } from "./standards";
|
||||
import { buildingsToMesh, type GeoFeature } from "../io/geoContext";
|
||||
import { applyOps, type CoreOp } from "../core/ops";
|
||||
import { withDocument } from "../core/document";
|
||||
|
||||
@@ -527,6 +529,26 @@ const isMainContour = (z: number) => Math.abs((z + 2.7) * 2 - Math.round((z + 2.
|
||||
// Parzelle (Kataster) mit Nachbarparzellen; Grenzabstände je Kante, Baulinie an der Strasse (Nord).
|
||||
const PARCEL = [P(-14, -12), P(28, -13), P(29, 23), P(-15, 24)];
|
||||
|
||||
/**
|
||||
* [207] Nachbargebäude (Kataster/swisstopo-Stil): ein Volumen-Netz auf der Klasse „12 Gebäude" ([181]), im Situationsplan
|
||||
* grau (Schwarzplan: schwarz). Westen (Kat.-Nr. 2416, L-Form), Osten (2418, zwei Häuser), Norden jenseits des Musterwegs (nach Süden bleibt der Schnitt A-A ohne Fernkörper).
|
||||
*/
|
||||
function neighbours(): ContextObject {
|
||||
const b = (pts: Vec2[], height: number): GeoFeature => ({ category: "building", pts, closed: true, height });
|
||||
const mesh = buildingsToMesh(
|
||||
[
|
||||
b([P(-34, 0), P(-22, 0), P(-22, 9), P(-27, 9), P(-27, 14), P(-34, 14)], 7.5),
|
||||
b([P(36, -6), P(46, -6), P(46, 4), P(36, 4)], 6.5),
|
||||
b([P(36, 9), P(44, 9), P(44, 16), P(36, 16)], 6.5),
|
||||
b([P(-8, 35), P(16, 35), P(16, 43), P(-8, 43)], 11),
|
||||
b([P(22, 34), P(40, 34), P(40, 40), P(22, 40)], 9),
|
||||
],
|
||||
"Kataster (fiktiv)",
|
||||
);
|
||||
if (!mesh) throw new Error("Musterhaus komplex: Nachbargebäude nicht erzeugt");
|
||||
return { ...mesh, id: "nachbarn", name: "Nachbargebäude" };
|
||||
}
|
||||
|
||||
function cadastre(): Drawing2D[] {
|
||||
const d: Drawing2D[] = [];
|
||||
const add = (id: string, geom: Drawing2DGeom, extra: Partial<Drawing2D> = {}) =>
|
||||
@@ -695,7 +717,10 @@ function addRooms(p: Project): Project {
|
||||
/** Sichtbarkeit je Kategorie: Ausschnitte listen jede sichtbare Kategorie ausdrücklich (fehlt = aus). */
|
||||
const codesOf = (ls: LayerCategory[]): string[] => ls.flatMap((l) => [l.code, ...codesOf(l.children ?? [])]);
|
||||
const vis = (hidden: string[] = []): Record<string, boolean> => Object.fromEntries(codesOf(LAYERS).map((c) => [c, !hidden.includes(c)]));
|
||||
const ALL = vis();
|
||||
/** [207] Schnitte und Ansichten ohne die Nachbargebäude (Klasse „12 Gebäude"): sie weiten sonst den Ausschnitt weit über das Haus. */
|
||||
const NO_NEIGHBOURS = vis(["12"]);
|
||||
/** [207] Klassen, die die Ansichtsvorlage „Situation WBW" ausblendet (`standards.rs::SITUATION_HIDDEN`; Test `sampleProjectComplex.situation.test.ts`). */
|
||||
const SITUATION_HIDDEN = ["00", "07", "20", "21", "22", "25", "30", "35", "40", "50", "60", "80", "81", "82", "85", "90", "91", "99"];
|
||||
const LEVEL_VIS: Record<string, boolean> = Object.fromEntries(LEVELS.map((l) => [l.id, true]));
|
||||
/** Grundrisse auf Blättern: ohne Kataster, Strasse, Höhenlinien und Gelände. */
|
||||
const PLAN_VIS = vis(["01", "02", "10", "11", "13", "14"]);
|
||||
@@ -729,14 +754,15 @@ function views(): Pick<Project, "viewTemplates" | "viewSnapshots" | "viewSnapsho
|
||||
snap("vs-og", "OG 1:100", "og", 100, P(7.5, 6), { folderId: "vf-gr", templateId: "vt-gr100", templateLinked: true }),
|
||||
snap("vs-dg", "DG 1:100", "dg", 100, P(7.5, 5), { folderId: "vf-gr", templateId: "vt-gr100", templateLinked: true }),
|
||||
snap("vs-eg50", "EG 1:50 Ausschnitt Wohnen", "eg", 50, P(10, 3.5), { folderId: "vf-gr", templateId: "vt-gr50", templateLinked: true }),
|
||||
snap("vs-situation", "Situation 1:500", "eg", 500, P(7, 5), { folderId: "vf-gr", detail: "grob", layerVisibility: ALL }),
|
||||
// [207] Situationsplan: Ansichtsvorlage „Situation WBW 1:500" (Standard-Ressource, Modelldarstellung „Situation WBW").
|
||||
snap("vs-situation", "Situation 1:500", "eg", 500, P(7, 5), { folderId: "vf-gr", detail: "grob", templateId: "std-vt-situation-wbw", templateLinked: true, layerVisibility: vis(SITUATION_HIDDEN) }),
|
||||
snap("vs-brand", "EG Brandschutz", "eg", 100, P(7.5, 6), { folderId: "vf-gr", templateId: "vt-brand", templateLinked: true, enabledOverrideRuleIds: ["or-brand"] }),
|
||||
snap("vs-schnitt-a", "Schnitt A-A", "schnitt-a", 100, P(6, 3.3), { folderId: "vf-sa", layerVisibility: ALL }),
|
||||
snap("vs-schnitt-b", "Schnitt B-B", "schnitt-b", 100, P(6, 3.3), { folderId: "vf-sa", layerVisibility: ALL }),
|
||||
snap("vs-ansicht-s", "Ansicht Süd", "ansicht-sued", 100, P(6, 3.3), { folderId: "vf-sa", layerVisibility: ALL }),
|
||||
snap("vs-ansicht-o", "Ansicht Ost", "ansicht-ost", 100, P(6, 3.3), { folderId: "vf-sa", layerVisibility: ALL }),
|
||||
snap("vs-ansicht-n", "Ansicht Nord", "ansicht-nord", 100, P(6, 3.3), { folderId: "vf-sa", layerVisibility: ALL }),
|
||||
snap("vs-ansicht-w", "Ansicht West", "ansicht-west", 100, P(6, 3.3), { folderId: "vf-sa", layerVisibility: ALL }),
|
||||
snap("vs-schnitt-a", "Schnitt A-A", "schnitt-a", 100, P(6, 3.3), { folderId: "vf-sa", layerVisibility: NO_NEIGHBOURS }),
|
||||
snap("vs-schnitt-b", "Schnitt B-B", "schnitt-b", 100, P(6, 3.3), { folderId: "vf-sa", layerVisibility: NO_NEIGHBOURS }),
|
||||
snap("vs-ansicht-s", "Ansicht Süd", "ansicht-sued", 100, P(6, 3.3), { folderId: "vf-sa", layerVisibility: NO_NEIGHBOURS }),
|
||||
snap("vs-ansicht-o", "Ansicht Ost", "ansicht-ost", 100, P(6, 3.3), { folderId: "vf-sa", layerVisibility: NO_NEIGHBOURS }),
|
||||
snap("vs-ansicht-n", "Ansicht Nord", "ansicht-nord", 100, P(6, 3.3), { folderId: "vf-sa", layerVisibility: NO_NEIGHBOURS }),
|
||||
snap("vs-ansicht-w", "Ansicht West", "ansicht-west", 100, P(6, 3.3), { folderId: "vf-sa", layerVisibility: NO_NEIGHBOURS }),
|
||||
snap("vs-detail", "Detail Deckenauflager 1:10", "detail-traufe", 10, P(DETAIL_X + 0.4, 1.0), { folderId: "vf-sa", detail: "fein", layerVisibility: HIDE_SITE }),
|
||||
snap("vs-3d", "Axonometrie Südost", "eg", 100, P(7.5, 5), { folderId: "vf-3d", viewType: "perspektive", view3d: "isoFrontLeft", fov: 45 }),
|
||||
],
|
||||
@@ -832,6 +858,7 @@ export function buildComplexSampleProject(): Project {
|
||||
extrudedSolids,
|
||||
drawings2d: [...cadastre(), ...annotations()],
|
||||
context: [
|
||||
neighbours(),
|
||||
{
|
||||
type: "contourSet", id: "hoehenlinien", name: "Höhenlinien (Vermessung)", categoryCode: "14", source: "Vermessung (fiktiv)",
|
||||
contours: CONTOUR_Z.map((z) => ({ z, pts: contourAt(z), closed: false, layer: isMainContour(z) ? "HL-Haupt" : "HL" })),
|
||||
@@ -857,6 +884,14 @@ export function buildComplexSampleProject(): Project {
|
||||
roomProgramTolerance: 0.1,
|
||||
parcelArea: 1540,
|
||||
sunStudy: { when: "2026-06-21T10:00:00Z", show: true },
|
||||
// [213] Kamera aus Südost auf das Haus (Standpunkt 1.6 m über OK EG, Sonne am Abend).
|
||||
cameras: [
|
||||
{
|
||||
id: "kamera-suedost", type: "camera", name: "Südost", floorId: "eg", categoryCode: "92",
|
||||
position: P(17, -3), eyeHeight: 1.6, target: P(7.5, 5), targetHeight: 4, fovDeg: 50, projection: "perspective",
|
||||
sunWhen: "2026-06-21T16:00:00Z",
|
||||
},
|
||||
],
|
||||
siteRules: {
|
||||
parcel: PARCEL,
|
||||
// Grenzabstände je Parzellenkante (Süd, Ost, Nord, West); Baulinie entlang der Strasse.
|
||||
|
||||
@@ -36,7 +36,7 @@ describe("Standard-Bibliothek ([100]–[102])", () => {
|
||||
expect(c.lineStyles).toBeGreaterThan(5);
|
||||
expect(c.wallTypes + c.ceilingTypes + c.roofTypes).toBe(5);
|
||||
expect(c.overrideRules).toBe(2);
|
||||
expect(c.modelViewOptions).toBe(4);
|
||||
expect(c.modelViewOptions).toBe(6);
|
||||
expect(standardsMergeCounts(standardsMergeOps(withStandards(empty)))).toEqual({ lineStyles: 0, hatches: 0, components: 0, wallTypes: 0, ceilingTypes: 0, roofTypes: 0, viewTemplates: 0, blockDefs: 0, overrideRules: 0, modelViewOptions: 0 });
|
||||
});
|
||||
|
||||
|
||||
@@ -46,6 +46,50 @@ export type BlockDef = { id: string; name: string; geom2d: Array<Drawing2DGeom>
|
||||
*/
|
||||
export type BuiltinPaletteBanks = { simple?: boolean; tango?: boolean; material?: boolean; ral?: boolean };
|
||||
|
||||
/**
|
||||
* Eine Kamera ([213]) — gespeicherter Standpunkt für die 3D-Ansicht (und das Rendering): Standpunkt im
|
||||
* Grundriss mit Augenhöhe über dem Geschoss, Ziel (Grundriss und absolute Höhe), Bildwinkel, Projektion
|
||||
* und optional Datum/Uhrzeit für den Sonnenstand. Im Grundriss als Symbol mit Sichtkegel auf der Klasse
|
||||
* „Kameras" (Vorgabe "92"); „Kamera öffnen" setzt die 3D-Ansicht exakt.
|
||||
*/
|
||||
export type Camera = {
|
||||
id: string;
|
||||
type: "camera";
|
||||
name: string;
|
||||
/** Geschoss, auf dem das Symbol im Grundriss steht und auf das sich die Augenhöhe bezieht. */
|
||||
floorId: string;
|
||||
/** Klasse (Ebene), Vorgabe "92" (Kameras). */
|
||||
categoryCode: string;
|
||||
/** Objekt-Sperre, analog `Wall.locked`. */
|
||||
locked?: boolean;
|
||||
/** Standpunkt im Grundriss (Meter). */
|
||||
position: Vec2;
|
||||
/** Augenhöhe über OK Fertigboden des Geschosses (m). */
|
||||
eyeHeight: number;
|
||||
/** Ziel im Grundriss (Meter); der Abstand Standpunkt–Ziel ist die Länge des Sichtkegels. */
|
||||
target: Vec2;
|
||||
/** Höhe des Ziels (m, absolut, z des Modells). */
|
||||
targetHeight: number;
|
||||
/**
|
||||
* Vertikaler Bildwinkel (Grad, perspektivisch). Die Kleinbild-Brennweite folgt daraus (24-mm-Sensorhöhe).
|
||||
*/
|
||||
fovDeg: number;
|
||||
projection: CameraProjection;
|
||||
/** Sichthöhe in Metern (volle Bildhöhe) bei Axonometrie/Parallel; fehlt = 10 m. */
|
||||
orthoHeight?: number;
|
||||
/**
|
||||
* Zeitpunkt für den Sonnenstand (ISO-8601 in UTC wie `SunStudy.when`); „Kamera öffnen" setzt ihn in der
|
||||
* Sonnenstudie. Fehlt er, bleibt die Sonne der Studie.
|
||||
*/
|
||||
sunWhen?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Projektion einer Kamera ([213]): Perspektive, Axonometrie (Parallelprojektion mit schrägem Blick, z. B.
|
||||
* Isometrie) oder Parallelprojektion (frei ausgerichtet). Axonometrie und Parallel zeichnen im 3D orthografisch.
|
||||
*/
|
||||
export type CameraProjection = "perspective" | "axonometric" | "parallel";
|
||||
|
||||
/** Bekleidung einer Tür ([105]): auf der Aufschlagseite, der Gegenseite, beidseitig oder keine. */
|
||||
export type CasingSides = "beide" | "aufschlag" | "gegen" | "keine";
|
||||
|
||||
@@ -292,6 +336,17 @@ export type Column = {
|
||||
*/
|
||||
export type ColumnProfile = { kind: "rect"; width: number; depth: number } | { kind: "round"; radius: number };
|
||||
|
||||
/**
|
||||
* Wettbewerbs-Einstellung des Projekts ([208]): anonym = Kennwort statt Büro- und Projektname in Plankopf,
|
||||
* Dateinamen und PDF-Metadaten.
|
||||
*/
|
||||
export type CompetitionSettings = {
|
||||
/** Anonyme Abgabe: keine Büro-/Autor-Angaben in Export und Plankopf. */
|
||||
anonymous: boolean;
|
||||
/** Kennwort der Abgabe (steht in Plankopf und PDF-Titel). */
|
||||
keyword: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Ein Bauteil-Material (Component Manager) — vereint Plan-Schnittdarstellung
|
||||
* (Schraffur) und 3D-Erscheinung. Ersetzt das frühere `Material`.
|
||||
@@ -1789,6 +1844,8 @@ export type Layout = {
|
||||
legends?: Array<LayoutLegend>;
|
||||
/** Lebendige Tabellen auf dem Blatt ([111]); fehlt = keine. */
|
||||
tables?: Array<LayoutTable>;
|
||||
/** Bilder auf dem Blatt ([208]): Renderings, Fotos, Luftbilder; fehlt = keine. */
|
||||
images?: Array<LayoutImage>;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1811,6 +1868,44 @@ export type LayoutFolder = {
|
||||
kind?: "layout" | "master";
|
||||
};
|
||||
|
||||
/**
|
||||
* Hilfslinie eines Masters ([208], Gestaltungsraster): senkrecht (`x`) oder waagrecht (`y`) in Papier-mm.
|
||||
* Nur am Bildschirm, nie im Druck.
|
||||
*/
|
||||
export type LayoutGuide = {
|
||||
/** "x" = senkrechte Linie bei `posMm` von links, "y" = waagrechte Linie bei `posMm` von oben. */
|
||||
axis: string;
|
||||
posMm: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Bild auf einem Layout-Blatt ([208]): PNG oder JPEG als Data-URL (gleicher Weg wie `ContextImage.src`),
|
||||
* im Rahmen `xMm`/`yMm`/`widthMm`/`heightMm` (Papier-mm). Das Seitenverhältnis des Ausschnitts bleibt erhalten;
|
||||
* `crop` schneidet zu (Anteile 0..1 des Originals). Im PDF wird das Original unverändert eingebettet (JPEG ohne
|
||||
* Neukompression).
|
||||
*/
|
||||
export type LayoutImage = {
|
||||
id: string;
|
||||
/** Anzeigename (Dateiname). */
|
||||
name: string;
|
||||
/** Bildquelle als Data-URL (`data:image/png;base64,…` oder `data:image/jpeg;base64,…`). */
|
||||
src: string;
|
||||
/** Linke Kante auf dem Blatt (mm, von links). */
|
||||
xMm: number;
|
||||
/** Obere Kante auf dem Blatt (mm, von oben). */
|
||||
yMm: number;
|
||||
/** Breite des gezeigten Ausschnitts (mm). */
|
||||
widthMm: number;
|
||||
/** Höhe des gezeigten Ausschnitts (mm). */
|
||||
heightMm: number;
|
||||
/** Pixelbreite des Originals (aus dem Dateikopf gelesen). */
|
||||
pixelWidth: number;
|
||||
/** Pixelhöhe des Originals. */
|
||||
pixelHeight: number;
|
||||
/** Zuschnitt als Anteile des Originals (0..1); fehlt = ganzes Bild. */
|
||||
crop?: { x: number; y: number; w: number; h: number };
|
||||
};
|
||||
|
||||
/**
|
||||
* Grafische Legende auf einem Layout-Blatt ([82]): listet Schraffuren/Materialien, Linientypen und/oder
|
||||
* Kategorien der gezeigten Viewports (`manualKeys` leer) oder einer Handauswahl, mit Muster und Name.
|
||||
@@ -2041,6 +2136,18 @@ export type MasterLayout = {
|
||||
customWidthMm?: number;
|
||||
/** Freie Blatthöhe in mm (siehe {@link MasterLayout.customWidthMm}). */
|
||||
customHeightMm?: number;
|
||||
/**
|
||||
* Vorlagen-Schlüssel ([208], z. B. "poster-a1-landscape"): wiederverwendet den Master beim Anlegen weiterer Plakate.
|
||||
*/
|
||||
template?: string;
|
||||
/**
|
||||
* Plakat-Kopfzeile ([208]): Band über die Satzbreite mit Kennwort-Feld, Projekttitel und „Plan x/n".
|
||||
*/
|
||||
posterHeader?: boolean;
|
||||
/** Massstab unter jedem Viewport ausgeben ([208]). */
|
||||
viewportScaleLabels?: boolean;
|
||||
/** Hilfslinien des Gestaltungsrasters ([208]), nur am Bildschirm. */
|
||||
guides?: Array<LayoutGuide>;
|
||||
};
|
||||
|
||||
/** [173] Darstellung der Stufen über der Schnitthöhe. */
|
||||
@@ -2145,6 +2252,11 @@ export type ModelViewOption = {
|
||||
roomStamps?: ModelViewRoomStamps;
|
||||
/** [173] Bemassung: Massketten der automatischen Aussenbemassung, Höhenkoten. */
|
||||
dimensions?: ModelViewDimensions;
|
||||
/**
|
||||
* [207] Situationsplan / Schwarzplan: fehlt ⇒ gewöhnlicher Grundriss; vorhanden ⇒ statt der Bauteile das
|
||||
* eigene Gebäude als gefüllter Umriss, die Kontextgebäude gefüllt, dazu Nordpfeil und Massstabsbalken.
|
||||
*/
|
||||
situation?: ModelViewSituation;
|
||||
};
|
||||
|
||||
/** [173] Dächer in der Modelldarstellung (fehlt ⇒ wie Basis). */
|
||||
@@ -2189,6 +2301,23 @@ export type ModelViewSite = {
|
||||
terrain?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* [207] Situationsplan in der Modelldarstellung (≙ Schwarzplan): jede Option fehlt ⇒ Standard des
|
||||
* Situationsplans (eigenes Gebäude schwarz, Kontext grau, mit Planzeichen).
|
||||
*/
|
||||
export type ModelViewSituation = {
|
||||
/**
|
||||
* Eigenes Gebäude: Umriss über alle Geschosse über Terrain und die Dächer, gefüllt (Basis: schwarz).
|
||||
*/
|
||||
own?: SituationFill;
|
||||
/**
|
||||
* Kontextgebäude (importierte Netze, Grundfläche aus der Aufsicht), gefüllt (Basis: grau; „Schwarzplan": schwarz).
|
||||
*/
|
||||
context?: SituationFill;
|
||||
/** Nordpfeil und Massstabsbalken zeichnen (Basis: ja). */
|
||||
symbols?: boolean;
|
||||
};
|
||||
|
||||
/** [173] Decken und Böden in der Modelldarstellung. */
|
||||
export type ModelViewSlabs = {
|
||||
/** Bodenbelag-Muster im Grundriss (die Ebene geht vor; Basis: automatisch). */
|
||||
@@ -2844,6 +2973,11 @@ export type Project = {
|
||||
* bestehende Projekte ohne `trees` gültig bleiben (Default: leer behandeln).
|
||||
*/
|
||||
trees?: Array<Tree>;
|
||||
/**
|
||||
* Kameras ([213]) — gespeicherte Standpunkte für 3D-Ansicht und Rendering, siehe {@link Camera}. Optional
|
||||
* (Default: leer behandeln).
|
||||
*/
|
||||
cameras?: Array<Camera>;
|
||||
/**
|
||||
* Gruppen (Vectorworks-artig: Cmd+G fasst die Auswahl zu einer Einheit
|
||||
* zusammen; Doppelklick betritt die Gruppe zum Bearbeiten, alles andere
|
||||
@@ -2916,6 +3050,8 @@ export type Project = {
|
||||
publishLog?: Array<PublishLogEntry>;
|
||||
/** Projektnummer für Titelblock und Dateinamen ([79]). */
|
||||
projectNumber?: string;
|
||||
/** Wettbewerb ([208]): anonyme Abgabe mit Kennwort. */
|
||||
competition?: CompetitionSettings;
|
||||
/**
|
||||
* Höhe von ±0.00 (OK fertig Boden des Bezugsgeschosses, `DrawingLevel.zeroLevel`)
|
||||
* in Metern über Meer (m ü. M.), editierbar im Einstellungs-Fenster. Optional.
|
||||
@@ -3322,6 +3458,34 @@ export type RoomStamp = {
|
||||
showFinish?: boolean;
|
||||
/** [177] Trennlinie unter dem Namen anzeigen. Fehlt/false: keine Linie. */
|
||||
showDivider?: boolean;
|
||||
/** [218] Schrift des ganzen Stempels (Vorgabe für alle Zeilen ohne eigene Angabe). */
|
||||
font?: RoomStampFont;
|
||||
/** [218] Schrift der Namenszeile (Vorgabe: Stempelschrift, sonst 12 pt fett). */
|
||||
nameFont?: RoomStampFont;
|
||||
/** [218] Schrift der zweiten Namenszeile (Vorgabe: Stempelschrift, sonst 9 pt kursiv). */
|
||||
line2Font?: RoomStampFont;
|
||||
/** [218] Schrift der Raumnummer (Vorgabe: Stempelschrift, sonst 9 pt). */
|
||||
numberFont?: RoomStampFont;
|
||||
/** [218] Schrift der Bodenflächen-Zeile (Vorgabe: Stempelschrift, sonst 0.8 × Grundschrift). */
|
||||
areaFont?: RoomStampFont;
|
||||
/** [218] Schrift der Nutzungs-Zeile (Vorgabe: Stempelschrift, sonst 0.8 × Grundschrift). */
|
||||
usageFont?: RoomStampFont;
|
||||
};
|
||||
|
||||
/**
|
||||
* [218] Schrift einer Zeile des Raumstempels; fehlende Werte gelten als „wie die Vorgabe" (Stempelschrift, dann
|
||||
* die eingebauten Werte der Zeile). Grösse in typografischen Punkt auf dem Papier bei der Grundschrift 10 pt
|
||||
* (kleinere Massstäbe verkleinern sie im Verhältnis).
|
||||
*/
|
||||
export type RoomStampFont = {
|
||||
/** Schriftfamilie (eine der gebündelten Schriften, z. B. "Work Sans"). */
|
||||
family?: string;
|
||||
/** Schriftgrösse in pt. */
|
||||
sizePt?: number;
|
||||
bold?: boolean;
|
||||
italic?: boolean;
|
||||
/** Farbe als "#rrggbb". */
|
||||
color?: string;
|
||||
};
|
||||
|
||||
/** [158] Nutzung eines Raums (Raumbuch). Nassräume: Bad, WC, Dusche, Waschküche. */
|
||||
@@ -3447,6 +3611,9 @@ export type SiteRules = {
|
||||
profileHeight?: number;
|
||||
};
|
||||
|
||||
/** [207] Füllung eines Gebäudes im Situationsplan. */
|
||||
export type SituationFill = "black" | "grey" | "off";
|
||||
|
||||
/** Terminierungs-Regel einer Wand am Deckenanschluss (siehe {@link Wall.sliceTermination}). */
|
||||
export type SliceTermination = "both" | "below" | "above";
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { isTauriRuntime } from "./projectFile";
|
||||
import { t } from "../i18n";
|
||||
import { openRenderDialog } from "../state/renderDialogHook";
|
||||
import { APP_VERSION } from "../ui/TopBar";
|
||||
import type { View3d, ViewType } from "../model/viewTypes";
|
||||
import type { SelectionActionId } from "../state/selectionActions";
|
||||
@@ -422,6 +423,12 @@ export function useNativeAppMenu(
|
||||
accelerator: "CmdOrCtrl+Shift+T",
|
||||
action: () => handlersRef.current.onSelectionAction?.("toggleTrace"),
|
||||
}),
|
||||
// [211] Rendering mit Blender/Cycles (Dialog in App montiert, Öffner über den Modul-Hook).
|
||||
await PredefinedMenuItem.new({ item: "Separator" }),
|
||||
await MenuItem.new({
|
||||
text: t("menu.view.rendering"),
|
||||
action: () => openRenderDialog(),
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
// Blender als eigener Prozess aus der App ([211], Rendering mit Blender/Cycles): Gastgeber für
|
||||
// `export/blenderRender.ts` (`BlenderHost`) unter Tauri (Rust-Befehle in `src-tauri/src/blender.rs`, Dateien über
|
||||
// das fs-Plugin im Ordner `$TEMP/dossier-render`) und Electron (`window.dossierBlender`, Hauptprozess
|
||||
// `scripts/electron-blender.cjs`). Im reinen Browser gibt es keinen Prozess: `blenderHost()` liefert null, die
|
||||
// App bietet dort das Paket als ZIP an (`ui/RenderDialog.tsx`).
|
||||
//
|
||||
// Die Tauri-Plugins werden NUR dynamisch importiert (Muster `saveFile.ts`): Browser-Build und vitest brauchen
|
||||
// die Module nicht. Nicht auf dem Mac geprüft: Tauri-Teil nach Muster geschrieben (nur im Linux-Container
|
||||
// kompiliert und die Rust-Logik getestet).
|
||||
|
||||
import type { BlenderHost } from "../core";
|
||||
|
||||
/** Von electron-preload.cjs injiziert (nur Electron/Linux). */
|
||||
export interface DossierBlenderApi {
|
||||
find: (custom?: string) => Promise<string | null>;
|
||||
prepare: (files: { path: string; bytes: Uint8Array }[]) => Promise<string>;
|
||||
start: (jobId: string, exe: string, args: string[]) => Promise<void>;
|
||||
cancel: (jobId: string) => void;
|
||||
readFile: (path: string) => Promise<Uint8Array>;
|
||||
onLine: (cb: (e: { jobId: string; line: string }) => void) => () => void;
|
||||
onExit: (cb: (e: { jobId: string; code: number }) => void) => () => void;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
dossierBlender?: DossierBlenderApi;
|
||||
}
|
||||
}
|
||||
|
||||
export function isTauri(): boolean {
|
||||
return typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
|
||||
}
|
||||
|
||||
let counter = 0;
|
||||
const newJobId = (): string => `render-${Date.now().toString(36)}-${counter++}`;
|
||||
|
||||
const join = (dir: string, rel: string): string => `${dir.replace(/[\\/]+$/, "")}/${rel}`;
|
||||
|
||||
/**
|
||||
* Tauri-Gastgeber. Befehle: `blender_find`, `blender_job_dir`, `blender_start`, `blender_cancel`;
|
||||
* Ereignisse `blender://line` und `blender://exit` mit der Auftragskennung.
|
||||
*/
|
||||
async function tauriHost(): Promise<BlenderHost> {
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
const { listen } = await import("@tauri-apps/api/event");
|
||||
const fs = await import("@tauri-apps/plugin-fs");
|
||||
return {
|
||||
find: (custom) => invoke<string | null>("blender_find", { custom: custom?.trim() || null }),
|
||||
async prepare(files) {
|
||||
const dir = await invoke<string>("blender_job_dir");
|
||||
const made = new Set<string>();
|
||||
for (const f of files) {
|
||||
const slash = f.path.lastIndexOf("/");
|
||||
if (slash > 0) {
|
||||
const sub = join(dir, f.path.slice(0, slash));
|
||||
if (!made.has(sub)) {
|
||||
await fs.mkdir(sub, { recursive: true });
|
||||
made.add(sub);
|
||||
}
|
||||
}
|
||||
await fs.writeFile(join(dir, f.path), f.bytes);
|
||||
}
|
||||
return dir;
|
||||
},
|
||||
spawn(exe, args, onLine) {
|
||||
const jobId = newJobId();
|
||||
const done = (async () => {
|
||||
let resolveExit!: (code: number) => void;
|
||||
const exit = new Promise<number>((r) => (resolveExit = r));
|
||||
const offLine = await listen<{ jobId: string; line: string }>("blender://line", (e) => {
|
||||
if (e.payload.jobId === jobId) onLine(e.payload.line);
|
||||
});
|
||||
const offExit = await listen<{ jobId: string; code: number }>("blender://exit", (e) => {
|
||||
if (e.payload.jobId === jobId) resolveExit(e.payload.code);
|
||||
});
|
||||
try {
|
||||
await invoke("blender_start", { jobId, exe, args });
|
||||
return await exit;
|
||||
} finally {
|
||||
offLine();
|
||||
offExit();
|
||||
}
|
||||
})();
|
||||
return { done, cancel: () => void invoke("blender_cancel", { jobId }).catch(() => undefined) };
|
||||
},
|
||||
readFile: (path) => fs.readFile(path),
|
||||
join,
|
||||
};
|
||||
}
|
||||
|
||||
/** Electron-Gastgeber über die Brücke aus `electron-preload.cjs`. */
|
||||
function electronHost(api: DossierBlenderApi): BlenderHost {
|
||||
return {
|
||||
find: (custom) => api.find(custom?.trim() || undefined),
|
||||
prepare: (files) => api.prepare(files),
|
||||
spawn(exe, args, onLine) {
|
||||
const jobId = newJobId();
|
||||
let resolveExit!: (code: number) => void;
|
||||
const exit = new Promise<number>((r) => (resolveExit = r));
|
||||
const offLine = api.onLine((e) => {
|
||||
if (e.jobId === jobId) onLine(e.line);
|
||||
});
|
||||
const offExit = api.onExit((e) => {
|
||||
if (e.jobId === jobId) resolveExit(e.code);
|
||||
});
|
||||
const done = api
|
||||
.start(jobId, exe, args)
|
||||
.then(() => exit)
|
||||
.finally(() => {
|
||||
offLine();
|
||||
offExit();
|
||||
});
|
||||
return { done, cancel: () => api.cancel(jobId) };
|
||||
},
|
||||
readFile: (path) => api.readFile(path),
|
||||
join,
|
||||
};
|
||||
}
|
||||
|
||||
/** Gastgeber der laufenden Umgebung, oder null (reiner Browser: kein Prozess möglich). */
|
||||
export async function blenderHost(): Promise<BlenderHost | null> {
|
||||
if (typeof window === "undefined") return null;
|
||||
if (window.dossierBlender) return electronHost(window.dossierBlender);
|
||||
if (isTauri()) return tauriHost();
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Öffnet eine Web-Adresse im System-Browser (Tauri: shell-Plugin; sonst neuer Tab). */
|
||||
export async function openExternalUrl(url: string): Promise<void> {
|
||||
if (isTauri()) {
|
||||
const { open } = await import("@tauri-apps/plugin-shell");
|
||||
await open(url);
|
||||
return;
|
||||
}
|
||||
window.open(url, "_blank", "noopener,noreferrer");
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Text des Blender-Skripts `scripts/blender/render_dossier.py` ([211]), vom Bundler eingebettet: die App schreibt ihn
|
||||
// zusammen mit dem Paket in den Arbeitsordner, so braucht sie keinen Pfad zu Dateien neben der Anwendung.
|
||||
|
||||
import script from "../../scripts/blender/render_dossier.py?raw";
|
||||
|
||||
export const RENDER_SCRIPT: string = script;
|
||||
@@ -0,0 +1,75 @@
|
||||
// Gruppe „Kameras" im Ausschnitte-Panel ([213]): die gespeicherten Kameras des Projekts als Liste. Klick wählt die
|
||||
// Kamera (Objekt-Info, Symbol im Grundriss), Doppelklick bzw. „↗" setzt die 3D-Ansicht exakt, „+" legt aus der
|
||||
// aktuellen 3D-Ansicht eine neue an, „✕" löscht. Die Kameras selbst sind Modell-Elemente (`Project.cameras`).
|
||||
|
||||
import { removeItems } from "../core";
|
||||
import { t } from "../i18n";
|
||||
import { createCameraFromView, openCamera } from "../state/cameraActions";
|
||||
import { getState, useStore } from "../state/appStore";
|
||||
import { fromIds } from "../state/selection";
|
||||
|
||||
export function CamerasGroup() {
|
||||
const cameras = useStore((s) => s.project.cameras);
|
||||
const levels = useStore((s) => s.project.drawingLevels);
|
||||
const selected = useStore((s) => s.selection.cameras);
|
||||
const list = cameras ?? [];
|
||||
return (
|
||||
<section className="nav-group" data-testid="cameras-group">
|
||||
<header className="nav-group-head">
|
||||
<span className="nav-group-title">{t("camera.title")}</span>
|
||||
<span className="nav-group-actions">
|
||||
<button className="nav-add" style={{ display: "inline-flex", padding: "1px 5px" }} title={t("camera.createFromView")} data-testid="camera-create" onClick={() => createCameraFromView()}>
|
||||
+
|
||||
</button>
|
||||
</span>
|
||||
</header>
|
||||
{list.length === 0 ? (
|
||||
<div style={{ padding: "10px 10px", fontSize: 12, color: "var(--muted)" }}>{t("camera.empty")}</div>
|
||||
) : (
|
||||
<div className="nav-list">
|
||||
{list.map((c) => (
|
||||
<div
|
||||
key={c.id}
|
||||
className={`nav-row${selected.includes(c.id) ? " active" : ""}`}
|
||||
data-testid={`camera-row-${c.id}`}
|
||||
title={t("camera.rowHint")}
|
||||
onClick={() => getState().setSelection(fromIds("cameras", [c.id]))}
|
||||
onDoubleClick={() => void openCamera(c.id)}
|
||||
style={{ display: "flex", alignItems: "center", gap: 4, paddingLeft: 10 }}
|
||||
>
|
||||
<span className="nav-label" style={{ flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
|
||||
{c.name}
|
||||
<span style={{ color: "var(--muted)", marginLeft: 6 }}>{levels.find((l) => l.id === c.floorId)?.name ?? ""}</span>
|
||||
</span>
|
||||
<button
|
||||
className="nav-add"
|
||||
style={{ padding: "1px 5px" }}
|
||||
title={t("camera.open")}
|
||||
data-testid={`camera-open-${c.id}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
void openCamera(c.id);
|
||||
}}
|
||||
>
|
||||
↗
|
||||
</button>
|
||||
<button
|
||||
className="nav-add"
|
||||
style={{ padding: "1px 5px" }}
|
||||
title={t("camera.delete")}
|
||||
disabled={!!c.locked}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
getState().applyChange((p) => removeItems(p, "cameras", [c.id]));
|
||||
getState().setSelection(fromIds("cameras", []));
|
||||
}}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -460,6 +460,7 @@ export function LayoutsPanel() {
|
||||
orientation: start.orientation,
|
||||
customWidthMm: start.customWidthMm,
|
||||
customHeightMm: start.customHeightMm,
|
||||
posterTemplate: start.posterTemplate,
|
||||
});
|
||||
if (activeFolderId) expandFolder(activeFolderId);
|
||||
setDialog(null);
|
||||
|
||||
@@ -31,6 +31,7 @@ import { ContextObjectProps } from "./ContextObjectProps";
|
||||
import { SunStudySection } from "./SunStudySection";
|
||||
import { SiteRulesSection } from "./SiteRulesSection";
|
||||
import { TreeSection } from "./objectInfo/TreeSection";
|
||||
import { CameraSection } from "./objectInfo/CameraSection";
|
||||
import { ViewShadowsInfo, MeasurementSection } from "./objectInfo/InfoBlocks";
|
||||
import { DimensionField, RotateField } from "./objectInfo/fields";
|
||||
import { elementDimensions } from "./objectInfo/elementDims";
|
||||
@@ -54,7 +55,11 @@ function toDeg360(rad: number): number {
|
||||
}
|
||||
|
||||
|
||||
export function ObjectInfoPanel() {
|
||||
/**
|
||||
* `showPlacement` = false: ohne Bezugspunkt/Lage und Masse (Breite/Höhe/Drehen) — so zeigt sie das Fenster
|
||||
* Objekteinstellungen ([218], Wunsch Maintainer: Platzierung und Masse gehören nur ins Objekt-Info-Panel).
|
||||
*/
|
||||
export function ObjectInfoPanel({ showPlacement = true }: { showPlacement?: boolean } = {}) {
|
||||
const host = usePanelHost();
|
||||
const storeProject = useStore((st) => st.project);
|
||||
const sel = useSelectionInfo();
|
||||
@@ -74,6 +79,7 @@ export function ObjectInfoPanel() {
|
||||
// [137] Lage-Darstellung angeklickt (Schattenfläche / Baurechtslinie): Einstellungen der Quelle.
|
||||
const site = useStore((s) => s.selection.site);
|
||||
const treeSel = useStore((s) => s.selection.trees);
|
||||
const cameraSel = useStore((s) => s.selection.cameras);
|
||||
const ctxObj = sel?.kind === "contextObject" ? (storeProject.context ?? []).find((o) => o.id === sel.id) : undefined;
|
||||
const quantities = useMemo(
|
||||
() => (ctxObj?.type === "excavation" ? excavationQuantities(storeProject) : []),
|
||||
@@ -83,6 +89,8 @@ export function ObjectInfoPanel() {
|
||||
// ── Leerzustand ───────────────────────────────────────────────────────────
|
||||
// [149] Baum gewählt: eigene Felder (Lage, Masse, Form, Bestand).
|
||||
if (sel === null && treeSel.length > 0) return <TreeSection ids={treeSel} />;
|
||||
// [213] Kamera gewählt: Standpunkt, Ziel, Bildwinkel, Projektion, Sonne und „Kamera öffnen".
|
||||
if (sel === null && cameraSel.length > 0) return <CameraSection ids={cameraSel} />;
|
||||
if (sel === null && site[0] === "viewShadows") return <ViewShadowsInfo />;
|
||||
if (sel === null && site.length > 0) {
|
||||
const sun = site[0] === "sunStudy";
|
||||
@@ -183,10 +191,9 @@ export function ObjectInfoPanel() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="objinfo-sep" />
|
||||
|
||||
{(
|
||||
{showPlacement && (
|
||||
<>
|
||||
<div className="objinfo-sep" />
|
||||
{/* Bezugspunkt-Würfel (3×3, immer quadratisch) links, X/Y/Z als Spalte
|
||||
rechts daneben (Nutzer-Wunsch). */}
|
||||
<div className="objinfo-section-label">{t("objinfo.refpoint")}</div>
|
||||
|
||||
@@ -173,6 +173,32 @@ export function PublishSection() {
|
||||
onChange={(e) => host.onSetProjectNumber(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{/* Wettbewerb ([208]): anonyme Abgabe mit Kennwort; WBW-Satz mit allen Plakaten. */}
|
||||
<div style={{ padding: "2px 10px", display: "grid", gap: 4, fontSize: 12 }} data-competition>
|
||||
<label style={{ display: "flex", gap: 6, alignItems: "center" }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
data-testid="competition-anonymous"
|
||||
checked={project.competition?.anonymous === true}
|
||||
onChange={(e) => host.onSetCompetition({ anonymous: e.target.checked })}
|
||||
/>
|
||||
<span>{t("publish.competition.anonymous")}</span>
|
||||
</label>
|
||||
<label style={{ display: "flex", gap: 6, alignItems: "center" }}>
|
||||
<span>{t("publish.competition.keyword")}</span>
|
||||
<input
|
||||
className="res-input mono"
|
||||
style={{ flex: 1 }}
|
||||
data-testid="competition-keyword"
|
||||
value={project.competition?.keyword ?? ""}
|
||||
onChange={(e) => host.onSetCompetition({ keyword: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
{project.competition?.anonymous === true && <div style={{ color: "var(--muted)" }}>{t("publish.competition.hint")}</div>}
|
||||
<button className="nav-add" style={{ justifySelf: "start", whiteSpace: "nowrap", padding: "1px 6px", fontSize: 12 }} data-testid="publish-add-wbw" onClick={() => setOpen(host.onAddWbwSet())}>
|
||||
+ {t("publish.wbw.add")}
|
||||
</button>
|
||||
</div>
|
||||
{sets.length === 0 && <div style={{ padding: "4px 10px 8px", fontSize: 12, color: "var(--muted)" }}>{t("publish.none")}</div>}
|
||||
{sets.map((s) => (
|
||||
<div key={s.id} data-publish-set={s.id}>
|
||||
|
||||
@@ -21,10 +21,10 @@ Kern; hier stehen Eingabe und Darstellung. Zustand über den Store (`src/state`)
|
||||
|---|---|
|
||||
| `ToolsPanel.tsx`, `AttributesPanel.tsx`, `ObjectInfoPanel.tsx` | Werkzeug-Palette, Attribute, Objekt-Info der Auswahl (`ContextObjectProps.tsx`, `UValueRow.tsx`, `SurfacePatternPlacement.tsx` sind Teile davon) |
|
||||
| `objectSettings/` | Fenster „Objekteinstellungen" ([195], Taste T): `ObjectSettingsPanel` (schwebendes Panel `object-settings`) zeigt Bereich Objekt = `ObjectInfoPanel` und Darstellung = `AttributesPanel` (dieselben Komponenten, keine Doppelspur); `areas.ts` = Bereichs-Zuordnung, `areaState.ts` = gewählter Bereich |
|
||||
| `objectInfo/*.tsx` | Abschnitte je Element-Art (`WallSection`, `CeilingSection`, `RoofSections`, `OpeningSections`, `StairSection`, `RoomSection`, `SolidSections`, `SectionLineSection`, `RefSections`, `TreeSection`), gemeinsame Felder (`fields.tsx`) und Info-Blöcke (`InfoBlocks.tsx`); `ObjectInfoPanel` zeigt sie als einklappbare Gruppen (`InfoGroups.tsx`, `InfoGroup.tsx`, Zustand `infoGroupState.ts`); `groups.ts` hält die Zuordnung (Attribute = nur Gestaltung, Objekt-Info = Bauteil/BIM) und das Ziel der Taste T (`[189]`) |
|
||||
| `objectInfo/*.tsx` | Abschnitte je Element-Art (`WallSection`, `CeilingSection`, `RoofSections`, `OpeningSections`, `StairSection`, `RoomSection`, `RoomStampSection` (Raumstempel samt Schrift, [218]), `SolidSections`, `SectionLineSection`, `RefSections`, `TreeSection`), gemeinsame Felder (`fields.tsx`) und Info-Blöcke (`InfoBlocks.tsx`); `ObjectInfoPanel` zeigt sie als einklappbare Gruppen (`InfoGroups.tsx`, `InfoGroup.tsx`, Zustand `infoGroupState.ts`); `groups.ts` hält die Zuordnung (Attribute = nur Gestaltung, Objekt-Info = Bauteil/BIM) und das Ziel der Taste T (`[189]`) |
|
||||
| `DrawingLevelsPanel.tsx`, `LayersPanel.tsx`, `ElementTreePanel.tsx` | Zeichnungsebenen, Ebenen, Baum Geschoss → Bauteilklasse → Element |
|
||||
| `LayoutsPanel.tsx`, `PublishSection.tsx`, `ViewSnapshotsPanel.tsx` | Layouts als Baum, Publikationssätze (`[79]`), gespeicherte Ansichten |
|
||||
| `RoomBalancePanel.tsx` | Flächenbilanz mit den Abschnitten `AreaTableSection.tsx`, `KennzahlenSection.tsx`, `ProgramCompareSection.tsx`, `ElementScheduleSection.tsx`, `OpeningScheduleSection.tsx`, `RoomBookSection.tsx`; Stempel-Editor `RoomStampEditor.tsx` |
|
||||
| `RoomBalancePanel.tsx` | Flächenbilanz mit den Abschnitten `AreaTableSection.tsx`, `KennzahlenSection.tsx`, `ProgramCompareSection.tsx`, `ElementScheduleSection.tsx`, `OpeningScheduleSection.tsx`, `RoomBookSection.tsx` |
|
||||
| `SitePanel.tsx` | Aktionen zu Gelände und Lage (Import, Gelände erzeugen, Baugrube; keine Import-Liste, [181]), mit `SiteRulesSection.tsx` (Baurecht), `SunStudySection.tsx` (Schatten) und `PointCloudSection.tsx` |
|
||||
| `BcfPanel.tsx`, `ClashPanel.tsx` | BCF-Themen und Kollisionsliste; Sitzungszustand in `bcfSession.ts` und `clashSession.ts` |
|
||||
| `HistoryPanel.tsx` | Undo-Verlauf mit Sprung auf einen Schritt |
|
||||
|
||||
@@ -1,276 +0,0 @@
|
||||
// Schwebender Dialog zum Bearbeiten des strukturierten Raum-Stempels (Feldmodell):
|
||||
// Raumnummer, Raumname (+ Zeile 2), Bodenfläche (mit Präfix) und Nutzung. Jede
|
||||
// Zeile trägt zusätzlich eine eigene Ausrichtung (links/mitte/rechts). Ersetzt
|
||||
// für neue Räume den freien Text-Editor. Kontrolliert (value/onApply/onCancel);
|
||||
// arbeitet auf einem lokalen Entwurf, erst „Übernehmen" schreibt zurück.
|
||||
// Bezeichner englisch, UI-Text über t().
|
||||
//
|
||||
// Folge-Arbeit: Zeilen-Layout-Editor (welches Feld auf welche Zeile),
|
||||
// Per-Feld-Typografie, Fensterfläche.
|
||||
|
||||
import { useState } from "react";
|
||||
import { t } from "../i18n";
|
||||
import type { RoomStamp } from "../model/types";
|
||||
import type { Align } from "../text/richText";
|
||||
|
||||
export interface RoomStampEditorProps {
|
||||
/** Ausgangsstempel (wird beim Öffnen kopiert; Editor arbeitet lokal). */
|
||||
value: RoomStamp;
|
||||
/** „Übernehmen" — den bearbeiteten Stempel zurückschreiben. */
|
||||
onApply: (stamp: RoomStamp) => void;
|
||||
/** „Abbrechen"/Schliessen — ohne Übernahme. */
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
/** Die drei Ausrichtungen mit Icon und Beschriftung (für die Umschalter). */
|
||||
const ALIGN_CELLS: { align: Align; icon: string; titleKey: string }[] = [
|
||||
{ align: "left", icon: "format_align_left", titleKey: "text.align.left" },
|
||||
{ align: "center", icon: "format_align_center", titleKey: "text.align.center" },
|
||||
{ align: "right", icon: "format_align_right", titleKey: "text.align.right" },
|
||||
];
|
||||
|
||||
/**
|
||||
* Drei-Wege-Umschalter für die Zeilen-Ausrichtung. `value` ist der aktuelle Wert
|
||||
* (fehlt er, gilt `fallback`); `onChange` liefert die gewählte Ausrichtung.
|
||||
*/
|
||||
function AlignToggle({
|
||||
value,
|
||||
fallback,
|
||||
onChange,
|
||||
disabled,
|
||||
label,
|
||||
}: {
|
||||
value: Align | undefined;
|
||||
fallback: Align;
|
||||
onChange: (align: Align) => void;
|
||||
disabled?: boolean;
|
||||
label: string;
|
||||
}) {
|
||||
const current = value ?? fallback;
|
||||
return (
|
||||
<div className="roomstamp-align" role="group" aria-label={label}>
|
||||
{ALIGN_CELLS.map((cell) => (
|
||||
<button
|
||||
key={cell.align}
|
||||
type="button"
|
||||
className={`roomstamp-align-btn${current === cell.align ? " active" : ""}`}
|
||||
disabled={disabled}
|
||||
aria-pressed={current === cell.align}
|
||||
title={t(cell.titleKey)}
|
||||
aria-label={t(cell.titleKey)}
|
||||
onClick={() => onChange(cell.align)}
|
||||
>
|
||||
<span className="material-symbols-outlined" aria-hidden="true">
|
||||
{cell.icon}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** [173] Dreifach-Wahl: fehlt = wie Modelldarstellung (Stufe), sonst an/aus am Stempel. */
|
||||
function TriState({ value, onChange }: { value: boolean | undefined; onChange: (v: boolean | undefined) => void }) {
|
||||
return (
|
||||
<select
|
||||
value={value === undefined ? "" : value ? "1" : "0"}
|
||||
onChange={(e) => onChange(e.target.value === "" ? undefined : e.target.value === "1")}
|
||||
>
|
||||
<option value="">{t("roomStamp.asModelView")}</option>
|
||||
<option value="1">{t("roomStamp.on")}</option>
|
||||
<option value="0">{t("roomStamp.off")}</option>
|
||||
</select>
|
||||
);
|
||||
}
|
||||
|
||||
export function RoomStampEditor({ value, onApply, onCancel }: RoomStampEditorProps) {
|
||||
const [draft, setDraft] = useState<RoomStamp>(value);
|
||||
|
||||
const patch = (p: Partial<RoomStamp>) => setDraft((d) => ({ ...d, ...p }));
|
||||
|
||||
const hasLine2 = (draft.nameLine2 ?? "").trim().length > 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="texteditor-overlay"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={t("roomStamp.title")}
|
||||
onMouseDown={(e) => {
|
||||
if (e.target === e.currentTarget) onCancel();
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Escape") onCancel();
|
||||
}}
|
||||
>
|
||||
<div className="texteditor-dialog roomstamp-dialog">
|
||||
<div className="texteditor-head">
|
||||
<span className="texteditor-title">{t("roomStamp.title")}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="texteditor-x"
|
||||
onClick={onCancel}
|
||||
title={t("text.cancel")}
|
||||
aria-label={t("text.cancel")}
|
||||
>
|
||||
<span className="material-symbols-outlined" aria-hidden="true">
|
||||
close
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="texteditor-body roomstamp-body">
|
||||
<label className="roomstamp-field">
|
||||
<span className="roomstamp-label">{t("roomStamp.number")}</span>
|
||||
<input
|
||||
type="text"
|
||||
className="roomstamp-input"
|
||||
value={draft.number ?? ""}
|
||||
onChange={(e) => patch({ number: e.target.value })}
|
||||
autoFocus
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div className="roomstamp-row">
|
||||
<label className="roomstamp-field">
|
||||
<span className="roomstamp-label">{t("roomStamp.name")}</span>
|
||||
<input
|
||||
type="text"
|
||||
className="roomstamp-input"
|
||||
value={draft.name}
|
||||
onChange={(e) => patch({ name: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<AlignToggle
|
||||
value={draft.nameAlign}
|
||||
fallback="left"
|
||||
label={`${t("roomStamp.name")} — ${t("text.group")}`}
|
||||
onChange={(nameAlign) => patch({ nameAlign })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="roomstamp-row">
|
||||
<label className="roomstamp-field">
|
||||
<span className="roomstamp-label">{t("roomStamp.nameLine2")}</span>
|
||||
<input
|
||||
type="text"
|
||||
className="roomstamp-input"
|
||||
value={draft.nameLine2 ?? ""}
|
||||
onChange={(e) => patch({ nameLine2: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<AlignToggle
|
||||
value={draft.line2Align}
|
||||
fallback="left"
|
||||
disabled={!hasLine2}
|
||||
label={`${t("roomStamp.nameLine2")} — ${t("text.group")}`}
|
||||
onChange={(line2Align) => patch({ line2Align })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="roomstamp-row">
|
||||
<label className="roomstamp-check">
|
||||
<span>{t("roomStamp.showFloorArea")}</span>
|
||||
<TriState value={draft.showFloorArea} onChange={(showFloorArea) => patch({ showFloorArea })} />
|
||||
</label>
|
||||
<AlignToggle
|
||||
value={draft.floorAreaAlign}
|
||||
fallback="left"
|
||||
disabled={draft.showFloorArea === false}
|
||||
label={`${t("roomStamp.showFloorArea")} — ${t("text.group")}`}
|
||||
onChange={(floorAreaAlign) => patch({ floorAreaAlign })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<label className="roomstamp-field">
|
||||
<span className="roomstamp-label">{t("roomStamp.floorAreaPrefix")}</span>
|
||||
<input
|
||||
type="text"
|
||||
className="roomstamp-input"
|
||||
value={draft.floorAreaPrefix ?? ""}
|
||||
disabled={draft.showFloorArea === false}
|
||||
onChange={(e) => patch({ floorAreaPrefix: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="roomstamp-field">
|
||||
<span className="roomstamp-label">{t("roomStamp.roundingStep")}</span>
|
||||
<select
|
||||
className="roomstamp-input"
|
||||
value={draft.roundingStep ?? ""}
|
||||
disabled={draft.showFloorArea === false}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
patch({ roundingStep: v === "" ? undefined : Number(v) });
|
||||
}}
|
||||
>
|
||||
<option value="">{t("roomStamp.roundingStepDefault")}</option>
|
||||
<option value="0.01">0.01 m²</option>
|
||||
<option value="0.1">0.1 m²</option>
|
||||
<option value="0.5">0.5 m²</option>
|
||||
<option value="1">1 m²</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<div className="roomstamp-row">
|
||||
<label className="roomstamp-check">
|
||||
<span>{t("roomStamp.showUsage")}</span>
|
||||
<TriState value={draft.showUsage} onChange={(showUsage) => patch({ showUsage })} />
|
||||
</label>
|
||||
<AlignToggle
|
||||
value={draft.usageAlign}
|
||||
fallback="left"
|
||||
disabled={draft.showUsage === false}
|
||||
label={`${t("roomStamp.showUsage")} — ${t("text.group")}`}
|
||||
onChange={(usageAlign) => patch({ usageAlign })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="roomstamp-row">
|
||||
<label className="roomstamp-check">
|
||||
<input type="checkbox" checked={draft.showDivider === true} onChange={(e) => patch({ showDivider: e.target.checked ? true : undefined })} />
|
||||
<span>{t("roomStamp.showDivider")}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="roomstamp-row">
|
||||
<label className="roomstamp-check">
|
||||
<input type="checkbox" checked={draft.showFinish === true} onChange={(e) => patch({ showFinish: e.target.checked ? true : undefined })} />
|
||||
<span>{t("roomStamp.showFinish")}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label className="roomstamp-field">
|
||||
<span className="roomstamp-label">{t("roomStamp.occupancy")}</span>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
step={1}
|
||||
className="roomstamp-input"
|
||||
value={draft.occupancy ?? ""}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
patch({ occupancy: v === "" ? undefined : Number(v) });
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="texteditor-foot">
|
||||
<button type="button" className="texteditor-btn" onClick={onCancel}>
|
||||
{t("text.cancel")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="texteditor-btn texteditor-btn-primary"
|
||||
onClick={() => onApply(draft)}
|
||||
>
|
||||
{t("text.apply")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default RoomStampEditor;
|
||||
@@ -39,6 +39,7 @@ import { applyToSnapshotOps } from "../state/viewTemplates";
|
||||
import { getState } from "../state/appStore";
|
||||
import { patchItem } from "../core";
|
||||
import { t } from "../i18n";
|
||||
import { CamerasGroup } from "./CamerasGroup";
|
||||
|
||||
// ── Baum-Icons (inline-SVG im Panel-Stil: 14px, stroke currentColor 1.4) ──────
|
||||
|
||||
@@ -518,6 +519,7 @@ export function ViewSnapshotsPanel() {
|
||||
tree.rootFolders.length === 0 && tree.rootSnapshots.length === 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<section className="nav-group">
|
||||
<header className="nav-group-head">
|
||||
<span className="nav-group-title">{t("viewsnap.title")}</span>
|
||||
@@ -687,6 +689,9 @@ export function ViewSnapshotsPanel() {
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
{/* [213] Kameras des Projekts (öffnen, anlegen, löschen). */}
|
||||
<CamerasGroup />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+6
-2
@@ -573,8 +573,6 @@ export interface PanelHostValue {
|
||||
onSetRoomName: (name: string) => void;
|
||||
/** Setzt die SIA-416-Blatt-Kategorie des Raums. */
|
||||
onSetRoomSia: (category: SiaCategory) => void;
|
||||
/** Öffnet den Rich-Text-Editor des Raum-Stempels (per ID). */
|
||||
onEditRoomStamp: (roomId: string) => void;
|
||||
|
||||
// ── Extrusions-Attribute (truck-Integration; nur der selektierte Körper) ──
|
||||
/** Setzt die Extrusionshöhe (Meter, > 0) — löst eine Re-Extrusion aus. */
|
||||
@@ -803,6 +801,10 @@ export interface PanelHostValue {
|
||||
onPublishSet: (id: string) => void;
|
||||
/** Setzt die Projektnummer (Dateinamen-Muster `{Projektnummer}`). */
|
||||
onSetProjectNumber: (value: string) => void;
|
||||
/** Wettbewerb ([208]): anonyme Abgabe und Kennwort setzen (Teil-Patch). */
|
||||
onSetCompetition: (patch: { anonymous?: boolean; keyword?: string }) => void;
|
||||
/** Legt den Publikationssatz „WBW-Abgabe" mit allen Plakaten an; liefert dessen Id. */
|
||||
onAddWbwSet: () => string;
|
||||
}
|
||||
|
||||
/** Startwerte eines neuen Layouts (aus dem „Neues Layout"-Dialog). */
|
||||
@@ -815,6 +817,8 @@ export interface CreateLayoutOptions {
|
||||
orientation: LayoutOrientation;
|
||||
customWidthMm?: number;
|
||||
customHeightMm?: number;
|
||||
/** Plakat-Vorlage ([208], Schlüssel aus `model/posterTemplates`): legt den Vorlagen-Master an bzw. verwendet ihn. */
|
||||
posterTemplate?: string;
|
||||
}
|
||||
|
||||
/** Startwerte eines neuen Masterlayouts (aus dem „Neues Masterlayout"-Dialog). */
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
// Abschnitt „Kamera" der Objekt-Info ([213]): Standpunkt und Augenhöhe, Ziel, Bildwinkel/Brennweite, Projektion,
|
||||
// Sonnenstand und die Aktionen „Kamera öffnen" / „Aus aktueller Ansicht" / „Isometrisch". Jede Änderung ein Undo-Schritt
|
||||
// (der Kern prüft die Op); bei mehreren gewählten Kameras wirken die Auswahlfelder auf alle.
|
||||
|
||||
import type { Camera, CameraProjection } from "../../model/types";
|
||||
import { useStore } from "../../state/appStore";
|
||||
import { openCamera, updateCameraFromView } from "../../state/cameraActions";
|
||||
import { t } from "../../i18n";
|
||||
import type { TranslationKey } from "../../i18n";
|
||||
import { patchItem } from "../../core";
|
||||
import { Dropdown } from "../../ui/Dropdown";
|
||||
import { clampFov, focalFromFov, fovFromFocal, isometricAim } from "../../viewport/cameraView";
|
||||
import { DimensionField } from "./fields";
|
||||
|
||||
const PROJECTIONS: CameraProjection[] = ["perspective", "axonometric", "parallel"];
|
||||
|
||||
/** ISO-UTC-Text → Wert für `<input type="datetime-local">` (UTC-Anzeige, ohne Zeitzonen-Überraschung). */
|
||||
function toLocalInput(iso: string | undefined): string {
|
||||
if (!iso) return "";
|
||||
const d = new Date(iso);
|
||||
return Number.isFinite(d.getTime()) ? d.toISOString().slice(0, 16) : "";
|
||||
}
|
||||
|
||||
export function CameraSection({ ids }: { ids: readonly string[] }) {
|
||||
const project = useStore((st) => st.project);
|
||||
const applyChange = useStore((s) => s.applyChange);
|
||||
const cams = (project.cameras ?? []).filter((x) => ids.includes(x.id));
|
||||
const cam = cams[0];
|
||||
if (!cam) return <div className="objinfo-panel"><div className="objinfo-empty">{t("objinfo.empty")}</div></div>;
|
||||
const locked = !!cam.locked;
|
||||
const set = (patch: Partial<Camera>, all = false) =>
|
||||
applyChange((p) => (all ? cams : [cam]).filter((x) => !x.locked).flatMap((x) => patchItem(p, "cameras", x.id, patch)));
|
||||
const level = project.drawingLevels.find((l) => l.id === cam.floorId);
|
||||
const parallel = cam.projection !== "perspective";
|
||||
return (
|
||||
<div className="objinfo-panel objinfo-camera" data-testid="camera-section">
|
||||
<div className="objinfo-head">
|
||||
<span className="objinfo-kind">{cams.length > 1 ? t("objinfo.camera.many", { n: cams.length }) : t("objinfo.kind.camera")}</span>
|
||||
</div>
|
||||
<div className="objinfo-section-label">{t("objinfo.camera.section")}</div>
|
||||
<label className="objinfo-field">
|
||||
<span className="objinfo-flabel">{t("objinfo.camera.name")}</span>
|
||||
<input
|
||||
className="objinfo-text"
|
||||
type="text"
|
||||
defaultValue={cam.name}
|
||||
key={`nm-${cam.id}-${cam.name}`}
|
||||
disabled={locked}
|
||||
data-testid="camera-name"
|
||||
onBlur={(e) => {
|
||||
const v = e.target.value.trim();
|
||||
if (v && v !== cam.name) set({ name: v });
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") (e.target as HTMLInputElement).blur();
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<div className="objinfo-field">
|
||||
<span className="objinfo-flabel">{t("objinfo.camera.projection")}</span>
|
||||
<Dropdown
|
||||
value={cam.projection}
|
||||
onChange={(v) => set({ projection: v as CameraProjection }, true)}
|
||||
options={PROJECTIONS.map((v) => ({ value: v, label: t(`objinfo.camera.projection.${v}` as TranslationKey) }))}
|
||||
title={t("objinfo.camera.projection")}
|
||||
width={150}
|
||||
/>
|
||||
</div>
|
||||
<div className="objinfo-section-label">{t("objinfo.camera.stand")}</div>
|
||||
<DimensionField label="X" value={cam.position.x} min={-Infinity} onCommit={(v) => set({ position: { x: v, y: cam.position.y } })} />
|
||||
<DimensionField label="Y" value={cam.position.y} min={-Infinity} onCommit={(v) => set({ position: { x: cam.position.x, y: v } })} />
|
||||
<DimensionField label={t("objinfo.camera.eyeHeight")} value={cam.eyeHeight} min={0} onCommit={(v) => set({ eyeHeight: v })} />
|
||||
<div className="objinfo-section-label">{t("objinfo.camera.target")}</div>
|
||||
<DimensionField label="X" value={cam.target.x} min={-Infinity} onCommit={(v) => set({ target: { x: v, y: cam.target.y } })} />
|
||||
<DimensionField label="Y" value={cam.target.y} min={-Infinity} onCommit={(v) => set({ target: { x: cam.target.x, y: v } })} />
|
||||
<DimensionField label={t("objinfo.camera.targetHeight")} value={cam.targetHeight} min={-Infinity} onCommit={(v) => set({ targetHeight: v })} />
|
||||
{parallel ? (
|
||||
<DimensionField label={t("objinfo.camera.orthoHeight")} value={cam.orthoHeight ?? 10} min={0.1} onCommit={(v) => set({ orthoHeight: v })} />
|
||||
) : (
|
||||
<>
|
||||
<DimensionField label={t("objinfo.camera.fov")} value={cam.fovDeg} min={5} unit="°" step={1} digits={1} onCommit={(v) => set({ fovDeg: clampFov(v) })} />
|
||||
<DimensionField
|
||||
label={t("objinfo.camera.focal")}
|
||||
value={focalFromFov(cam.fovDeg)}
|
||||
min={5}
|
||||
unit="mm"
|
||||
step={1}
|
||||
digits={1}
|
||||
onCommit={(v) => set({ fovDeg: clampFov(fovFromFocal(v)) })}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<label className="objinfo-field">
|
||||
<span className="objinfo-flabel">{t("objinfo.camera.sun")}</span>
|
||||
<input
|
||||
className="objinfo-text"
|
||||
type="datetime-local"
|
||||
value={toLocalInput(cam.sunWhen)}
|
||||
disabled={locked}
|
||||
title={t("objinfo.camera.sunHint")}
|
||||
data-testid="camera-sun"
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
if (!v) {
|
||||
set({ sunWhen: undefined });
|
||||
return;
|
||||
}
|
||||
const d = new Date(`${v}:00Z`);
|
||||
if (Number.isFinite(d.getTime())) set({ sunWhen: d.toISOString().replace(".000Z", "Z") });
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<div className="objinfo-field">
|
||||
<span className="objinfo-flabel">{t("objinfo.column.floor")}</span>
|
||||
<span className="objinfo-fval">{level?.name ?? cam.floorId}</span>
|
||||
</div>
|
||||
<div className="objinfo-actions">
|
||||
<button type="button" className="btn" data-testid="camera-open" onClick={() => void openCamera(cam.id)}>
|
||||
{t("camera.open")}
|
||||
</button>
|
||||
<button type="button" className="btn" disabled={locked} data-testid="camera-update" onClick={() => updateCameraFromView(cam.id)} title={t("camera.updateHint")}>
|
||||
{t("camera.update")}
|
||||
</button>
|
||||
{parallel && (
|
||||
<button type="button" className="btn" disabled={locked} data-testid="camera-iso" onClick={() => set(isometricAim(project, cam))} title={t("camera.isoHint")}>
|
||||
{t("camera.iso")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{locked && <div className="objinfo-muted">{t("objinfo.camera.locked")}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import { OpeningSection } from "./OpeningSections";
|
||||
import { DetailRefSection, DimRefsSection, DimTextSection } from "./RefSections";
|
||||
import { RoofSection } from "./RoofSections";
|
||||
import { RoomSection } from "./RoomSection";
|
||||
import { RoomStampSection } from "./RoomStampSection";
|
||||
import { SectionLineSection } from "./SectionLineSection";
|
||||
import { ColumnSection, ExtrudedSolidSection } from "./SolidSections";
|
||||
import { StairSection } from "./StairSection";
|
||||
@@ -50,6 +51,7 @@ export function InfoGroups({ sel, drawing, host }: { sel: SelectionInfo | null;
|
||||
case "openingEditor": return sel?.opening ? <OpeningEditorSection openingId={sel.opening.id} host={host} /> : null;
|
||||
case "stair": return sel?.stair ? <StairSection stair={sel.stair} host={host} /> : null;
|
||||
case "room": return sel?.room ? <RoomSection room={sel.room} roomId={sel.id} host={host} /> : null;
|
||||
case "roomStamp": return sel?.room ? <RoomStampSection roomId={sel.id} /> : null;
|
||||
case "extrudedSolid": return sel?.extrudedSolid ? <ExtrudedSolidSection solid={sel.extrudedSolid} host={host} /> : null;
|
||||
case "column": return sel?.column ? <ColumnSection column={sel.column} host={host} /> : null;
|
||||
case "detailRef": return sel?.detailRef ? <DetailRefSection detailRef={sel.detailRef} drawingId={sel.id} host={host} /> : null;
|
||||
|
||||
@@ -16,8 +16,8 @@ import { useMulti } from "./useMulti";
|
||||
|
||||
// ── Raum-Attribut-Abschnitt ──────────────────────────────────────────────────
|
||||
// Editierbarer Name, SIA-416-Kategorie (5 Blatt-Kategorien), abgeleitete Fläche
|
||||
// + Umfang (read-only), Referenzgeschoss, sowie ein Button, der den Rich-Text-
|
||||
// Stempel-Editor öffnet. Alle Werte/Setter über den Host.
|
||||
// + Umfang (read-only), Referenzgeschoss. Alle Werte/Setter über den Host. Der Stempel hat seit [218] einen
|
||||
// eigenen Abschnitt (`RoomStampSection`).
|
||||
export function RoomSection({
|
||||
room,
|
||||
roomId,
|
||||
@@ -82,15 +82,6 @@ export function RoomSection({
|
||||
|
||||
{/* [158] Raumbuch: Nutzung und Oberflächen. */}
|
||||
<RoomFinishFields roomId={roomId} />
|
||||
|
||||
{/* Stempel bearbeiten (öffnet den Rich-Text-Editor). */}
|
||||
<button
|
||||
type="button"
|
||||
className="objinfo-btn"
|
||||
onClick={() => host.onEditRoomStamp(roomId)}
|
||||
>
|
||||
{t("objinfo.room.editStamp")}
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// [218] Raumstempel als Abschnitt der Objekteinstellungen (kein Dialog im Fenster): Abschnitt vorhanden, Schrift je Zeile,
|
||||
// „gemischt" bei Mehrfachauswahl, eine Änderung für alle Räume in einem Undo-Schritt; Bezugspunkt und Masse nur im
|
||||
// Objekt-Info-Panel, nicht im Fenster. Ohne DOM: Server-Render der Panels.
|
||||
import { createElement } from "react";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildComplexSampleProject } from "../../model/sampleProjectComplex";
|
||||
import { setStampFontAttr } from "../../model/roomStamp";
|
||||
import { editRoomStamps } from "../../state/roomStampEdit";
|
||||
import { getState, setState } from "../../state/appStore";
|
||||
import { EMPTY_SELECTION } from "../../state/selection";
|
||||
import { PanelHostProvider } from "../host";
|
||||
import type { PanelHost } from "../types";
|
||||
import { ObjectInfoPanel } from "../ObjectInfoPanel";
|
||||
import { ObjectSettingsPanel } from "../objectSettings/ObjectSettingsPanel";
|
||||
|
||||
const host = { activeTool: "select", sectionLine: null, displayMode: { mode: "all", setMode: () => {} } } as unknown as PanelHost;
|
||||
const wrap = (el: ReturnType<typeof createElement>) => renderToString(createElement(PanelHostProvider, { value: host }, el));
|
||||
const windowHtml = () => wrap(createElement(ObjectSettingsPanel));
|
||||
const panelHtml = () => wrap(createElement(ObjectInfoPanel));
|
||||
|
||||
function twoRooms() {
|
||||
getState().loadProject(buildComplexSampleProject());
|
||||
const rooms = getState().project.rooms!;
|
||||
return [rooms[0].id, rooms[1].id] as const;
|
||||
}
|
||||
|
||||
describe("Raumstempel in den Objekteinstellungen [218]", () => {
|
||||
it("Raum gewählt: Abschnitt „Raumstempel“ mit Schrift je Zeile, kein Overlay-Dialog", () => {
|
||||
const [a] = twoRooms();
|
||||
setState({ selection: { ...EMPTY_SELECTION, rooms: [a] } });
|
||||
const html = windowHtml();
|
||||
expect(html).toContain('data-group="roomStamp"');
|
||||
expect(html).toContain('data-testid="roomstamp-section"');
|
||||
for (const k of ["font", "nameFont", "line2Font", "numberFont", "areaFont", "usageFont"]) expect(html).toContain(`data-testid="roomstamp-font-${k}"`);
|
||||
expect(html).not.toContain("texteditor-overlay");
|
||||
expect(html).not.toContain('role="dialog"');
|
||||
});
|
||||
|
||||
it("Bezugspunkt und Masse nur im Objekt-Info-Panel, nicht im Fenster (Raum und Wand)", () => {
|
||||
const p = buildComplexSampleProject();
|
||||
getState().loadProject(p);
|
||||
for (const sel of [{ rooms: [p.rooms![0].id] }, { walls: [p.walls[0].id] }]) {
|
||||
setState({ selection: { ...EMPTY_SELECTION, ...sel } });
|
||||
const panel = panelHtml();
|
||||
expect(panel).toContain("objinfo-cube");
|
||||
expect(panel).toContain("objinfo-refrow");
|
||||
const win = windowHtml();
|
||||
expect(win).not.toContain("objinfo-cube");
|
||||
expect(win).not.toContain("objinfo-refrow");
|
||||
expect(win).not.toContain("objinfo-xyzcol");
|
||||
expect(win).not.toContain('data-testid="objinfo-dim"');
|
||||
}
|
||||
});
|
||||
|
||||
it("zwei Räume mit abweichender Namensschrift: „gemischt“, bei gleicher nicht", () => {
|
||||
const [a, b] = twoRooms();
|
||||
editRoomStamps([a], (st) => ({ ...st, nameFont: { sizePt: 20 } }), "k1");
|
||||
editRoomStamps([b], (st) => ({ ...st, nameFont: { sizePt: 14 } }), "k2");
|
||||
setState({ selection: { ...EMPTY_SELECTION, rooms: [a, b] } });
|
||||
expect(windowHtml()).toContain('data-mixed="font-nameFont"');
|
||||
// Nummer und Namen bleiben je Raum eigen: gesperrt.
|
||||
expect(windowHtml()).toMatch(/data-testid="roomstamp-number"[^>]*disabled/);
|
||||
setState({ selection: { ...EMPTY_SELECTION, rooms: [a] } });
|
||||
expect(windowHtml()).not.toContain('data-mixed="font-nameFont"');
|
||||
});
|
||||
|
||||
it("Schrift für alle gewählten Räume in EINEM Undo-Schritt", () => {
|
||||
const [a, b] = twoRooms();
|
||||
setState({ selection: { ...EMPTY_SELECTION, rooms: [a, b] } });
|
||||
const before = JSON.stringify(getState().project.rooms!.map((r) => r.stamp ?? null));
|
||||
editRoomStamps([a, b], (s) => setStampFontAttr(setStampFontAttr(s, "nameFont", "family", "Jost"), "nameFont", "sizePt", 18), "stamp:test");
|
||||
const sizes = () => getState().project.rooms!.filter((r) => r.id === a || r.id === b).map((r) => [r.stamp?.nameFont?.family, r.stamp?.nameFont?.sizePt]);
|
||||
expect(sizes()).toEqual([["Jost", 18], ["Jost", 18]]);
|
||||
getState().undo();
|
||||
expect(JSON.stringify(getState().project.rooms!.map((r) => r.stamp ?? null))).toBe(before);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,275 @@
|
||||
// [218] Abschnitt „Raumstempel" der Objekteinstellungen (Doppelklick auf einen Stempel öffnet das Fenster mit diesem
|
||||
// Abschnitt; vorher Overlay-Dialog „Fenster im Fenster"): Nummer, Namenszeilen mit Ausrichtung, Flächen-/Nutzungs-/
|
||||
// Belagszeile und die Schrift (Familie, Grösse, fett, kursiv, Farbe) für den ganzen Stempel und je Zeile.
|
||||
// Schreibt über die Ops des Stores (`applyChange`, wie die Oberflächenfelder des Raums), darum läuft der Abschnitt
|
||||
// im Nebenfenster unverändert über die Spiegelung. Mehrfachauswahl: gleiche Werte zeigen, abweichende „gemischt";
|
||||
// eine Änderung gilt für alle gewählten Räume in EINEM Undo-Schritt; Nummer und Namen bleiben je Raum eigen.
|
||||
|
||||
import { t } from "../../i18n";
|
||||
import type { TranslationKey } from "../../i18n";
|
||||
import { defaultRoomStamp, setStampFontAttr, STAMP_FONT_LINES, type StampFontAttr, type StampFontKey } from "../../model/roomStamp";
|
||||
import type { Room, RoomStamp, RoomStampFont } from "../../model/types";
|
||||
import { useStore } from "../../state/appStore";
|
||||
import { commonValue, type Common } from "../../state/mixedValues";
|
||||
import { editRoomStamps, stampTargetIds } from "../../state/roomStampEdit";
|
||||
import { TEXT_FONTS } from "../../text/fontList";
|
||||
import type { Align } from "../../text/richText";
|
||||
import { Dropdown } from "../../ui/Dropdown";
|
||||
import { MixedMark } from "./fields";
|
||||
|
||||
const NO_ROOMS: Room[] = [];
|
||||
type AlignKey = "nameAlign" | "line2Align" | "floorAreaAlign" | "usageAlign";
|
||||
const RESET_ICON = "restart_alt";
|
||||
const ALIGN_CELLS: { align: Align; icon: string; titleKey: TranslationKey }[] = [
|
||||
{ align: "left", icon: "format_align_left", titleKey: "text.align.left" },
|
||||
{ align: "center", icon: "format_align_center", titleKey: "text.align.center" },
|
||||
{ align: "right", icon: "format_align_right", titleKey: "text.align.right" },
|
||||
];
|
||||
|
||||
function AlignToggle({ value, mixed, disabled, label, onChange }: { value: Align | undefined; mixed?: boolean; disabled?: boolean; label: string; onChange: (a: Align) => void }) {
|
||||
const current = mixed ? undefined : (value ?? "left");
|
||||
return (
|
||||
<div className="roomstamp-align" role="group" aria-label={label}>
|
||||
{ALIGN_CELLS.map((cell) => (
|
||||
<button
|
||||
key={cell.align}
|
||||
type="button"
|
||||
className={`roomstamp-align-btn${current === cell.align ? " active" : ""}`}
|
||||
disabled={disabled}
|
||||
aria-pressed={current === cell.align}
|
||||
title={t(cell.titleKey)}
|
||||
aria-label={t(cell.titleKey)}
|
||||
onClick={() => onChange(cell.align)}
|
||||
>
|
||||
<span className="material-symbols-outlined" aria-hidden="true">{cell.icon}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Dreifach-Wahl: fehlt = wie Modelldarstellung (Stufe), sonst an/aus am Stempel. */
|
||||
function TriState({ value, mixed, onChange, testId }: { value: boolean | undefined; mixed?: boolean; onChange: (v: boolean | undefined) => void; testId?: string }) {
|
||||
return (
|
||||
<select
|
||||
className="objinfo-text"
|
||||
data-testid={testId}
|
||||
value={mixed ? "mixed" : value === undefined ? "" : value ? "1" : "0"}
|
||||
onChange={(e) => onChange(e.target.value === "" ? undefined : e.target.value === "1")}
|
||||
>
|
||||
{mixed && <option value="mixed" disabled>{t("objsettings.mixed")}</option>}
|
||||
<option value="">{t("roomStamp.asModelView")}</option>
|
||||
<option value="1">{t("roomStamp.on")}</option>
|
||||
<option value="0">{t("roomStamp.off")}</option>
|
||||
</select>
|
||||
);
|
||||
}
|
||||
|
||||
export function RoomStampSection({ roomId }: { roomId: string }) {
|
||||
const rooms = useStore((s) => s.project.rooms) ?? NO_ROOMS;
|
||||
const selected = useStore((s) => s.selection.rooms);
|
||||
const ids = stampTargetIds(selected, roomId);
|
||||
const multi = ids.length > 1;
|
||||
const targets = rooms.filter((r) => ids.includes(r.id));
|
||||
const stamps = targets.map((r) => r.stamp ?? defaultRoomStamp(r));
|
||||
|
||||
/** Gemeinsamer Wert eines Stempelfelds über die gewählten Räume. */
|
||||
const common = <T,>(pick: (s: RoomStamp) => T): Common<T> => commonValue(stamps.map(pick));
|
||||
/** Änderung am Stempel aller gewählten Räume (ein Undo-Schritt; gleicher Schlüssel = ein Schritt beim Tippen). */
|
||||
const edit = (fn: (s: RoomStamp) => RoomStamp, key: string) => editRoomStamps(ids, fn, `stamp:${roomId}:${key}`);
|
||||
/** Feld setzen; leer/`undefined` entfernt es (⇒ Vorgabe). */
|
||||
const setField = <K extends keyof RoomStamp>(key: K, value: RoomStamp[K] | undefined) =>
|
||||
edit((s) => {
|
||||
const next = { ...s };
|
||||
if (value === undefined || value === "") delete next[key];
|
||||
else next[key] = value as RoomStamp[K];
|
||||
return next;
|
||||
}, String(key));
|
||||
|
||||
if (targets.length === 0) return null;
|
||||
|
||||
const alignOf = (key: AlignKey, label: TranslationKey, disabled = false) => {
|
||||
const c = common((s) => s[key] ?? "left");
|
||||
return <AlignToggle value={c.value} mixed={c.mixed} disabled={disabled} label={t(label)} onChange={(a) => setField(key, a)} />;
|
||||
};
|
||||
const text = (label: TranslationKey, key: "number" | "name" | "nameLine2" | "floorAreaPrefix", perRoom: boolean, testId: string, align?: AlignKey) => {
|
||||
const c = common((s) => (s[key] as string | undefined) ?? "");
|
||||
const locked = perRoom && multi;
|
||||
return (
|
||||
<div className="objinfo-field">
|
||||
<span className="objinfo-flabel" title={t(label)}>{t(label)}</span>
|
||||
<input
|
||||
type="text"
|
||||
className="objinfo-text"
|
||||
data-testid={testId}
|
||||
value={locked ? "" : (c.value ?? "")}
|
||||
placeholder={c.mixed ? t("objsettings.mixed") : undefined}
|
||||
disabled={locked}
|
||||
onChange={(e) => setField(key, key === "name" ? e.target.value : e.target.value || undefined)}
|
||||
title={t(label)}
|
||||
/>
|
||||
{align && alignOf(align, label)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
const tri = (label: TranslationKey, key: "showFloorArea" | "showUsage", testId: string, align: AlignKey, off: boolean) => {
|
||||
const c = common((s) => s[key]);
|
||||
return (
|
||||
<div className="objinfo-field">
|
||||
<span className="objinfo-flabel" title={t(label)}>{t(label)}</span>
|
||||
<TriState testId={testId} value={c.value} mixed={c.mixed} onChange={(v) => setField(key, v)} />
|
||||
{alignOf(align, label, off)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
const check = (label: TranslationKey, key: "showDivider" | "showFinish") => {
|
||||
const c = common((s) => s[key] === true);
|
||||
return (
|
||||
<div className="objinfo-field">
|
||||
<span className="objinfo-flabel">{t(label)}</span>
|
||||
<input type="checkbox" checked={c.value === true} ref={(el) => { if (el) el.indeterminate = c.mixed; }} onChange={(e) => setField(key, e.target.checked ? true : undefined)} />
|
||||
<MixedMark on={c.mixed} what={key} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
const floorOff = common((s) => s.showFloorArea === false).value === true;
|
||||
const usageOff = common((s) => s.showUsage === false).value === true;
|
||||
const rounding = common((s) => s.roundingStep);
|
||||
const occupancy = common((s) => s.occupancy);
|
||||
|
||||
return (
|
||||
<div data-testid="roomstamp-section">
|
||||
{text("roomStamp.number", "number", true, "roomstamp-number")}
|
||||
{text("roomStamp.name", "name", true, "roomstamp-name", "nameAlign")}
|
||||
{text("roomStamp.nameLine2", "nameLine2", true, "roomstamp-line2", "line2Align")}
|
||||
{tri("roomStamp.showFloorArea", "showFloorArea", "roomstamp-showFloorArea", "floorAreaAlign", floorOff)}
|
||||
{text("roomStamp.floorAreaPrefix", "floorAreaPrefix", false, "roomstamp-prefix")}
|
||||
<div className="objinfo-field">
|
||||
<span className="objinfo-flabel">{t("roomStamp.roundingStep")}</span>
|
||||
<select
|
||||
className="objinfo-text"
|
||||
value={rounding.mixed ? "mixed" : (rounding.value ?? "")}
|
||||
disabled={floorOff}
|
||||
onChange={(e) => setField("roundingStep", e.target.value === "" ? undefined : Number(e.target.value))}
|
||||
>
|
||||
{rounding.mixed && <option value="mixed" disabled>{t("objsettings.mixed")}</option>}
|
||||
<option value="">{t("roomStamp.roundingStepDefault")}</option>
|
||||
<option value="0.01">0.01 m²</option>
|
||||
<option value="0.1">0.1 m²</option>
|
||||
<option value="0.5">0.5 m²</option>
|
||||
<option value="1">1 m²</option>
|
||||
</select>
|
||||
</div>
|
||||
{tri("roomStamp.showUsage", "showUsage", "roomstamp-showUsage", "usageAlign", usageOff)}
|
||||
{check("roomStamp.showDivider", "showDivider")}
|
||||
{check("roomStamp.showFinish", "showFinish")}
|
||||
<div className="objinfo-field">
|
||||
<span className="objinfo-flabel">{t("roomStamp.occupancy")}</span>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
step={1}
|
||||
className="objinfo-text"
|
||||
value={occupancy.mixed ? "" : (occupancy.value ?? "")}
|
||||
placeholder={occupancy.mixed ? t("objsettings.mixed") : undefined}
|
||||
onChange={(e) => setField("occupancy", e.target.value === "" ? undefined : Number(e.target.value))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="objinfo-section-label">{t("roomStamp.font.section")}</div>
|
||||
{STAMP_FONT_LINES.map((line) => (
|
||||
<FontRow key={line.key} line={line} stamps={stamps} edit={edit} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Eine Schriftzeile: Familie, Grösse (pt), fett, kursiv, Farbe, Zurücksetzen auf die Vorgabe. */
|
||||
function FontRow({
|
||||
line,
|
||||
stamps,
|
||||
edit,
|
||||
}: {
|
||||
line: (typeof STAMP_FONT_LINES)[number];
|
||||
stamps: readonly RoomStamp[];
|
||||
edit: (fn: (s: RoomStamp) => RoomStamp, key: string) => void;
|
||||
}) {
|
||||
const key: StampFontKey = line.key;
|
||||
const attr = <K extends StampFontAttr>(a: K): Common<RoomStampFont[K]> => commonValue(stamps.map((s) => s[key]?.[a]));
|
||||
const set = <K extends StampFontAttr>(a: K, v: RoomStampFont[K] | undefined) => edit((s) => setStampFontAttr(s, key, a, v), `${key}.${a}`);
|
||||
const family = attr("family");
|
||||
const size = attr("sizePt");
|
||||
const bold = attr("bold");
|
||||
const italic = attr("italic");
|
||||
const color = attr("color");
|
||||
const anySet = stamps.some((s) => s[key] !== undefined);
|
||||
const label = t(line.labelKey as TranslationKey);
|
||||
const toggle = (a: "bold" | "italic", c: Common<boolean | undefined>, builtin: boolean, icon: string) => {
|
||||
const on = c.mixed ? false : (c.value ?? builtin);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`roomstamp-align-btn roomstamp-fontbtn${on ? " active" : ""}`}
|
||||
data-testid={`roomstamp-${key}-${a}`}
|
||||
aria-pressed={on}
|
||||
title={t(a === "bold" ? "text.bold" : "text.italic")}
|
||||
aria-label={t(a === "bold" ? "text.bold" : "text.italic")}
|
||||
onClick={() => set(a, !on)}
|
||||
>
|
||||
<span className="material-symbols-outlined" aria-hidden="true">{icon}</span>
|
||||
</button>
|
||||
);
|
||||
};
|
||||
return (
|
||||
<div className="roomstamp-fontrow" data-testid={`roomstamp-font-${key}`}>
|
||||
<div className="objinfo-field">
|
||||
<span className="objinfo-flabel" title={label}>{label}</span>
|
||||
<Dropdown
|
||||
value={family.mixed ? "" : (family.value ?? "")}
|
||||
onChange={(v) => set("family", v || undefined)}
|
||||
options={[{ value: "", label: family.mixed ? t("objsettings.mixed") : t("roomStamp.font.default") }, ...TEXT_FONTS.map((f) => ({ value: f, label: f }))]}
|
||||
title={`${label} — ${t("roomStamp.font.family")}`}
|
||||
width={150}
|
||||
/>
|
||||
</div>
|
||||
<div className="objinfo-field roomstamp-fontattrs">
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={200}
|
||||
step={0.5}
|
||||
className="objinfo-text roomstamp-size"
|
||||
data-testid={`roomstamp-${key}-size`}
|
||||
value={size.mixed ? "" : (size.value ?? "")}
|
||||
placeholder={size.mixed ? t("objsettings.mixed") : String(line.size)}
|
||||
title={`${label} — ${t("roomStamp.font.size")}`}
|
||||
aria-label={`${label} — ${t("roomStamp.font.size")}`}
|
||||
onChange={(e) => set("sizePt", e.target.value === "" ? undefined : Number(e.target.value))}
|
||||
/>
|
||||
<span className="objinfo-muted">pt</span>
|
||||
{toggle("bold", bold, line.bold, "format_bold")}
|
||||
{toggle("italic", italic, line.italic, "format_italic")}
|
||||
<input
|
||||
type="color"
|
||||
className="roomstamp-color"
|
||||
data-testid={`roomstamp-${key}-color`}
|
||||
value={color.mixed ? "#000000" : (color.value ?? "#000000")}
|
||||
title={`${label} — ${t("roomStamp.font.color")}`}
|
||||
aria-label={`${label} — ${t("roomStamp.font.color")}`}
|
||||
onChange={(e) => set("color", e.target.value)}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="roomstamp-align-btn roomstamp-fontbtn"
|
||||
disabled={!anySet}
|
||||
title={t("roomStamp.font.reset")}
|
||||
aria-label={t("roomStamp.font.reset")}
|
||||
onClick={() => edit((s) => { const n = { ...s }; delete n[key]; return n; }, `${key}.reset`)}
|
||||
>
|
||||
<span className="material-symbols-outlined" aria-hidden="true">{RESET_ICON}</span>
|
||||
</button>
|
||||
<MixedMark on={family.mixed || size.mixed || bold.mixed || italic.mixed || color.mixed} what={`font-${key}`} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -50,7 +50,7 @@ describe("Panel-Zuordnung [189]", () => {
|
||||
});
|
||||
|
||||
it("jede Gruppe hat einen Titel", () => {
|
||||
const all: InfoGroupId[] = ["newComponent", "sectionLine", "wall", "ceiling", "roof", "surfacePattern", "opening", "openingEditor", "stair", "room", "extrudedSolid", "column", "detailRef", "dimRefs", "dimText", "grid"];
|
||||
const all: InfoGroupId[] = ["newComponent", "sectionLine", "wall", "ceiling", "roof", "surfacePattern", "opening", "openingEditor", "stair", "room", "roomStamp", "extrudedSolid", "column", "detailRef", "dimRefs", "dimText", "grid"];
|
||||
for (const g of all) expect(INFO_GROUP_TITLE[g]).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,6 +18,7 @@ export type InfoGroupId =
|
||||
| "openingEditor"
|
||||
| "stair"
|
||||
| "room"
|
||||
| "roomStamp"
|
||||
| "extrudedSolid"
|
||||
| "column"
|
||||
| "detailRef"
|
||||
@@ -36,6 +37,7 @@ export const INFO_GROUP_TITLE: Record<InfoGroupId, TranslationKey> = {
|
||||
openingEditor: "objinfo.openingEditor.section",
|
||||
stair: "objinfo.stair.section",
|
||||
room: "objinfo.room.section",
|
||||
roomStamp: "roomStamp.title",
|
||||
extrudedSolid: "objinfo.extrudedSolid.section",
|
||||
column: "objinfo.column.section",
|
||||
detailRef: "objinfo.detailRef.section",
|
||||
@@ -69,7 +71,7 @@ export function infoGroups(c: InfoGroupContext): InfoGroupId[] {
|
||||
if (sel.wall || sel.roof) out.push("surfacePattern");
|
||||
if (sel.opening) out.push("opening", "openingEditor");
|
||||
if (sel.stair) out.push("stair");
|
||||
if (sel.room) out.push("room");
|
||||
if (sel.room) out.push("room", "roomStamp");
|
||||
if (sel.extrudedSolid) out.push("extrudedSolid");
|
||||
if (sel.column) out.push("column");
|
||||
if (sel.detailRef) out.push("detailRef");
|
||||
|
||||
@@ -18,7 +18,7 @@ const AREA_TITLE = { object: "objsettings.area.object", appearance: "objsettings
|
||||
export function ObjectSettingsPanel() {
|
||||
const host = usePanelHost();
|
||||
const sel = useSelectionInfo();
|
||||
const otherSelected = useStore((s) => s.selection.trees.length + s.selection.site.length > 0);
|
||||
const otherSelected = useStore((s) => s.selection.trees.length + s.selection.cameras.length + s.selection.site.length > 0);
|
||||
const isGrid = useStore((s) => (sel?.kind === "drawing2d" ? s.project.drawings2d.find((d) => d.id === sel.id)?.geom.shape === "grid" : false));
|
||||
const wanted = useSyncExternalStore(subscribeSettingsArea, getSettingsArea, getSettingsArea);
|
||||
|
||||
@@ -58,7 +58,7 @@ export function ObjectSettingsPanel() {
|
||||
</div>
|
||||
)}
|
||||
<div className="objset-body" role="tabpanel" aria-label={t(AREA_TITLE[area])}>
|
||||
{area === "object" ? <ObjectInfoPanel /> : <AttributesPanel />}
|
||||
{area === "object" ? <ObjectInfoPanel showPlacement={false} /> : <AttributesPanel />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
viewBox -4.2 0 37.045 18.478
|
||||
bytes 207135
|
||||
viewBox -25.5 0 81 18.478
|
||||
bytes 209902
|
||||
circle 4
|
||||
g 1
|
||||
line 495
|
||||
line 503
|
||||
path 3
|
||||
polygon 998
|
||||
polyline 179
|
||||
polygon 1031
|
||||
polyline 184
|
||||
rect 1
|
||||
svg 1
|
||||
text 4
|
||||
hash 7dd0774a2af69fe3
|
||||
hash d3224b3989291365
|
||||
@@ -1,13 +1,13 @@
|
||||
viewBox -41.5 0 95 63.6
|
||||
bytes 66764
|
||||
bytes 68382
|
||||
circle 16
|
||||
g 1
|
||||
line 137
|
||||
line 141
|
||||
path 36
|
||||
polygon 93
|
||||
polyline 92
|
||||
polygon 101
|
||||
polyline 93
|
||||
rect 1
|
||||
svg 1
|
||||
text 115
|
||||
tspan 24
|
||||
hash 0337f7fc77078b7c
|
||||
text 116
|
||||
tspan 25
|
||||
hash daf3fc044edd6954
|
||||
@@ -1,13 +1,13 @@
|
||||
viewBox -41.5 0 95 63.6
|
||||
bytes 107266
|
||||
bytes 108906
|
||||
circle 16
|
||||
g 1
|
||||
line 361
|
||||
line 365
|
||||
path 67
|
||||
polygon 216
|
||||
polyline 101
|
||||
polygon 224
|
||||
polyline 102
|
||||
rect 1
|
||||
svg 1
|
||||
text 115
|
||||
tspan 24
|
||||
hash e0c7011ad7ac9ebe
|
||||
text 116
|
||||
tspan 25
|
||||
hash c0d58c87e618c222
|
||||
@@ -1,5 +1,5 @@
|
||||
viewBox -13.448 0 38.615 33.813
|
||||
bytes 45053
|
||||
bytes 45051
|
||||
circle 14
|
||||
g 1
|
||||
line 114
|
||||
@@ -10,4 +10,4 @@ rect 1
|
||||
svg 1
|
||||
text 87
|
||||
tspan 19
|
||||
hash f30c0333f3f14e8b
|
||||
hash 1c84c9ae17eb227f
|
||||
@@ -1,5 +1,5 @@
|
||||
viewBox -12.974 0 37.808 33.406
|
||||
bytes 353509
|
||||
bytes 353505
|
||||
circle 14
|
||||
g 1
|
||||
line 3254
|
||||
@@ -10,4 +10,4 @@ rect 1
|
||||
svg 1
|
||||
text 86
|
||||
tspan 18
|
||||
hash 5af2107785b177d7
|
||||
hash b617e6093f9e52f1
|
||||
@@ -1,5 +1,5 @@
|
||||
viewBox -13.693 0 38.86 33.813
|
||||
bytes 41777
|
||||
bytes 41775
|
||||
circle 16
|
||||
g 1
|
||||
line 97
|
||||
@@ -10,4 +10,4 @@ rect 1
|
||||
svg 1
|
||||
text 71
|
||||
tspan 15
|
||||
hash 235c8589f957f6b0
|
||||
hash f4ea57ac9b383644
|
||||
@@ -1,5 +1,5 @@
|
||||
viewBox -13.693 0 38.527 33.406
|
||||
bytes 48000
|
||||
bytes 47998
|
||||
circle 16
|
||||
g 1
|
||||
line 94
|
||||
@@ -10,4 +10,4 @@ rect 1
|
||||
svg 1
|
||||
text 71
|
||||
tspan 15
|
||||
hash ddeb757dc7ffc097
|
||||
hash db285960e8796a2f
|
||||
@@ -1,5 +1,5 @@
|
||||
meshes [1211]
|
||||
meshes[].color [3] x1211
|
||||
meshes [1212]
|
||||
meshes[].color [3] x1212
|
||||
meshes[].indices [108] x6
|
||||
meshes[].indices [1152] x3
|
||||
meshes[].indices [1224]
|
||||
@@ -13,6 +13,7 @@ meshes[].indices [154014]
|
||||
meshes[].indices [1584]
|
||||
meshes[].indices [1716]
|
||||
meshes[].indices [180]
|
||||
meshes[].indices [204]
|
||||
meshes[].indices [2118]
|
||||
meshes[].indices [2124] x2
|
||||
meshes[].indices [2130]
|
||||
@@ -42,6 +43,7 @@ meshes[].positions [1089]
|
||||
meshes[].positions [108] x30
|
||||
meshes[].positions [1188]
|
||||
meshes[].positions [120]
|
||||
meshes[].positions [132]
|
||||
meshes[].positions [1368] x2
|
||||
meshes[].positions [162]
|
||||
meshes[].positions [16428]
|
||||
@@ -99,4 +101,4 @@ walls[].start [2] x1192
|
||||
walls[].startCut [4] x832
|
||||
walls[].topDrop [2] x89
|
||||
walls[].topPlane [3] x245
|
||||
hash 11d1505c4650cdb4
|
||||
hash 534b551bfdb4405a
|
||||
@@ -0,0 +1,12 @@
|
||||
viewBox -41.5 0 95 63.6
|
||||
bytes 5218
|
||||
g 1
|
||||
line 7
|
||||
path 1
|
||||
polygon 18
|
||||
polyline 3
|
||||
rect 1
|
||||
svg 1
|
||||
text 9
|
||||
tspan 1
|
||||
hash 3d1684b3659e8901
|
||||
@@ -0,0 +1,12 @@
|
||||
viewBox -41.5 0 95 63.6
|
||||
bytes 5218
|
||||
g 1
|
||||
line 7
|
||||
path 1
|
||||
polygon 18
|
||||
polyline 3
|
||||
rect 1
|
||||
svg 1
|
||||
text 9
|
||||
tspan 1
|
||||
hash 3d1684b3659e8901
|
||||
+13
-1
@@ -5,7 +5,7 @@
|
||||
// und den Diff der Dateien im Commit ansehen. Zahlen sind gerundet (Plan 1e-3 m, 3D 1e-4 m).
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createHash } from "node:crypto";
|
||||
import { computeSection, generateElevationPlan, generatePlan, generateSectionPlan, planToSvgString, projectToModel3d } from "../core";
|
||||
import { computeSection, generateElevationPlan, generatePlan, generateSectionPlan, planToSvgString, projectToModel3d, projectWithTemplate } from "../core";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { buildComplexSampleProject } from "../model/sampleProjectComplex";
|
||||
import type { Project } from "../model/types";
|
||||
@@ -77,6 +77,18 @@ for (const [name, make] of projects) {
|
||||
}
|
||||
}
|
||||
|
||||
// [207] Situationsplan 1:500 (Ansichtsvorlage „Situation WBW") und Schwarzplan.
|
||||
for (const [id, file] of [["std-vt-situation-wbw", "situation"], ["std-vt-schwarzplan", "schwarzplan"]]) {
|
||||
it(`${file} 1:500`, async () => {
|
||||
const tpl = p.viewTemplates?.find((t) => t.id === id);
|
||||
if (!tpl) return;
|
||||
const tp = projectWithTemplate(p, "eg", tpl);
|
||||
const show = new Set([...codes].filter((c) => tpl.layerVisibility?.[c] !== false));
|
||||
const svg = planToSvgString(generatePlan(tp, "eg", show, undefined, tpl.detail ?? "grob", false, true, true, 500), { scaleDenominator: 500 });
|
||||
await expect(svgDigest(svg)).toMatchFileSnapshot(`__golden__/${name}-${file}-500.txt`);
|
||||
});
|
||||
}
|
||||
|
||||
it("Schnitt", async () => {
|
||||
const sec = p.drawingLevels.find((l) => l.kind === "section");
|
||||
if (!sec) return;
|
||||
|
||||
@@ -8,7 +8,7 @@ import { flattenCategories } from "../model/types";
|
||||
/** Art eines auswählbaren Objekts an einer Klickstelle (Reihenfolge = Standard-Priorität). */
|
||||
export type PickKind =
|
||||
| "section" | "opening" | "wall" | "column" | "drawing" | "solid"
|
||||
| "tree" | "ceiling" | "stair" | "room" | "roof" | "site" | "context";
|
||||
| "tree" | "camera" | "ceiling" | "stair" | "room" | "roof" | "site" | "context";
|
||||
|
||||
type WithCategory = { id: string; categoryCode?: string };
|
||||
|
||||
@@ -26,6 +26,7 @@ function collection(project: Project, kind: PickKind): readonly WithCategory[] {
|
||||
case "context": return p.context ?? [];
|
||||
case "solid": return p.extrudedSolids ?? [];
|
||||
case "tree": return p.trees ?? [];
|
||||
case "camera": return p.cameras ?? [];
|
||||
case "section":
|
||||
case "site": return [];
|
||||
}
|
||||
|
||||
+4
-2
@@ -29,7 +29,8 @@ import type { HatchRender, Primitive } from "./generatePlan";
|
||||
import type { Vec2 } from "../model/types";
|
||||
|
||||
export const PLAN_BUF_MAGIC = 0x504c4232;
|
||||
export const PLAN_BUF_VERSION = 2;
|
||||
/** Gleich wie Kern `plan::buf::VERSION`; bei Formatänderung beide erhöhen (3: Kopf 20 Wörter, [204]). */
|
||||
export const PLAN_BUF_VERSION = 3;
|
||||
/** Fehlerpuffer einer Kern-Abfrage ("PLBe"): `[ERR_MAGIC, nUnits]` + Meldung (UTF-16). */
|
||||
export const PLAN_BUF_ERR_MAGIC = 0x504c4265;
|
||||
const HEAD = 20;
|
||||
@@ -520,7 +521,8 @@ export function decodePlanBuf(input: Uint8Array): DecodedPlanBuf {
|
||||
}
|
||||
if (bytes.byteLength < HEAD * 8) bad("zu kurz");
|
||||
const hd = new Float64Array(bytes.buffer, bytes.byteOffset, HEAD);
|
||||
if (hd[0] !== PLAN_BUF_MAGIC || hd[1] !== PLAN_BUF_VERSION) bad("fremde Version");
|
||||
if (hd[0] !== PLAN_BUF_MAGIC || hd[1] !== PLAN_BUF_VERSION)
|
||||
bad(`Kern-Version ${hd[1]} passt nicht zur Oberfläche (${PLAN_BUF_VERSION}) — WASM-Kern veraltet, \`npm run build:core\` ausführen`);
|
||||
const [, , flags, nStrings, nHatches, nHatchWords, nGroups, nPrims, nRec, nPool, nUnits] = hd;
|
||||
const hashes = (flags & 1) !== 0;
|
||||
const strAt = HEAD;
|
||||
|
||||
@@ -78,7 +78,8 @@ describe("[66] Präsentationsplan", () => {
|
||||
st().undo();
|
||||
expect((st().project.layouts ?? []).length).toBe(layoutsBefore);
|
||||
expect(st().project.viewSnapshots?.some((s) => s.id.startsWith("vs-pres-"))).toBe(false);
|
||||
});
|
||||
// [207] 60 s: mit den Nachbargebäuden des Musterhauses rechnet das Blatt im Container knapp über die 30 s des Standards.
|
||||
}, 60_000);
|
||||
|
||||
it("gewählte Geschosse, ohne Ansichten/Schnitt, Skizze an, A3: kleinerer Massstab", () => {
|
||||
const floors = project.drawingLevels.filter((l) => l.kind === "floor" && !l.layoutId).slice(0, 2).map((l) => l.id);
|
||||
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
// Vite-Import `…?raw` (Dateiinhalt als Text, z. B. das Blender-Skript `native/blenderScript.ts`); das Projekt bindet
|
||||
// die vite/client-Typen nicht ein.
|
||||
declare module "*?raw" {
|
||||
const content: string;
|
||||
export default content;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// [211] Einstellung „Blender-Programmdatei" (Rendering mit Blender/Cycles). Pro Rechner, nicht im Projekt:
|
||||
// localStorage (die Einstellungsfenster sind eigene Dokumente ohne gemeinsamen Store, derselbe Ursprung teilt
|
||||
// aber localStorage — Muster `commandAliasOverrides`). Leer = automatisch suchen (PATH, übliche Orte).
|
||||
|
||||
const KEY = "dossier.blenderPath";
|
||||
|
||||
/** Eigener Blender-Pfad oder leer. Fehlender/gesperrter Speicher ⇒ leer. */
|
||||
export function getBlenderPath(): string {
|
||||
try {
|
||||
return localStorage.getItem(KEY)?.trim() ?? "";
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export function setBlenderPath(path: string): void {
|
||||
try {
|
||||
const p = path.trim();
|
||||
if (p) localStorage.setItem(KEY, p);
|
||||
else localStorage.removeItem(KEY);
|
||||
} catch {
|
||||
/* privates Fenster / Speicher gesperrt: Einstellung gilt nur bis zum Schliessen */
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// [213] Aktionen zu Kamera-Elementen (`Project.cameras`): aus der aktuellen 3D-Ansicht anlegen, eine Kamera im 3D
|
||||
// öffnen (Ansicht exakt setzen, Sonne übernehmen), die Kamera mit der aktuellen Ansicht überschreiben. Die Umrechnung
|
||||
// Kamera ↔ Ansicht steht rein in `viewport/cameraView.ts`; hier hängt sie am Store, an den Reitern und am Viewport.
|
||||
|
||||
import { addItems, patchItem, setField } from "../core";
|
||||
import { t } from "../i18n";
|
||||
import type { Camera } from "../model/types";
|
||||
import { getCamera, getCameraTargetDistance, setCamera, viewportAvailable } from "../viewport/cameraBridge";
|
||||
import { cameraFromView, cameraToView, nextCameraName } from "../viewport/cameraView";
|
||||
import { getState } from "./appStore";
|
||||
import { fromIds } from "./selection";
|
||||
import { switchViewType } from "./tabNavigation";
|
||||
|
||||
function newCameraId(): string {
|
||||
const r = typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID().slice(0, 8) : Math.random().toString(36).slice(2, 10);
|
||||
return `cam-${r}`;
|
||||
}
|
||||
|
||||
/** Kamera aus der aktuellen 3D-Ansicht anlegen und wählen. Gibt die id zurück, `null` ohne 3D-Ansicht. */
|
||||
export function createCameraFromView(): string | null {
|
||||
const st = getState();
|
||||
const view = viewportAvailable() ? getCamera() : null;
|
||||
if (!view) {
|
||||
st.notify(t("camera.noViewport"), "warning");
|
||||
return null;
|
||||
}
|
||||
const cam = cameraFromView(st.project, view, {
|
||||
id: newCameraId(),
|
||||
name: nextCameraName(st.project, t("camera.defaultName")),
|
||||
fallbackFloorId: st.activeLevelId,
|
||||
distance: getCameraTargetDistance() ?? undefined,
|
||||
});
|
||||
st.applyChange(addItems("cameras", [cam]));
|
||||
st.setSelection(fromIds("cameras", [cam.id]));
|
||||
st.notify(t("camera.created", { name: cam.name }), "info");
|
||||
return cam.id;
|
||||
}
|
||||
|
||||
/** Wartet (höchstens `timeoutMs`), bis der 3D-Viewport Kamera-Zugriff meldet — nach dem Wechsel in den 3D-Reiter. */
|
||||
function whenViewportReady(timeoutMs = 3000): Promise<boolean> {
|
||||
if (viewportAvailable()) return Promise.resolve(true);
|
||||
return new Promise((resolve) => {
|
||||
const t0 = performance.now();
|
||||
const poll = () => {
|
||||
if (viewportAvailable()) resolve(true);
|
||||
else if (performance.now() - t0 > timeoutMs) resolve(false);
|
||||
else requestAnimationFrame(poll);
|
||||
};
|
||||
requestAnimationFrame(poll);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Kamera im 3D öffnen: in den 3D-Reiter wechseln, die Ansicht exakt setzen (Standpunkt, Blickrichtung, Bildwinkel,
|
||||
* Projektion) und — hat die Kamera einen Sonnenstand — die Sonnenstudie darauf stellen (Schatten im 3D an).
|
||||
*/
|
||||
export async function openCamera(id: string): Promise<boolean> {
|
||||
const st = getState();
|
||||
const cam = (st.project.cameras ?? []).find((c) => c.id === id);
|
||||
if (!cam) return false;
|
||||
const view = cameraToView(st.project, cam);
|
||||
if (!view) {
|
||||
st.notify(t("camera.invalid", { name: cam.name }), "warning");
|
||||
return false;
|
||||
}
|
||||
if (!viewportAvailable()) switchViewType("perspektive");
|
||||
if (!(await whenViewportReady())) {
|
||||
st.notify(t("camera.noViewport"), "warning");
|
||||
return false;
|
||||
}
|
||||
// Seitenverhältnis des Viewports behalten (die Brücke füllt es aus der Live-Kamera).
|
||||
const live = getCamera();
|
||||
const placed = setCamera({ ...view, aspect: live?.aspect ?? view.aspect }, { animate: true });
|
||||
if (!placed) {
|
||||
st.notify(t("camera.invalid", { name: cam.name }), "warning");
|
||||
return false;
|
||||
}
|
||||
if (cam.sunWhen && Number.isFinite(new Date(cam.sunWhen).getTime())) {
|
||||
const study = getState().project.sunStudy;
|
||||
if (study?.when !== cam.sunWhen || study.shadows3d !== true) {
|
||||
getState().applyChange([setField("sunStudy", { ...(study ?? { show: false }), when: cam.sunWhen, shadows3d: true } as NonNullable<typeof study>)]);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Kamera mit der aktuellen 3D-Ansicht überschreiben (Standpunkt, Ziel, Bildwinkel, Projektion; Name und Klasse bleiben). */
|
||||
export function updateCameraFromView(id: string): boolean {
|
||||
const st = getState();
|
||||
const old = (st.project.cameras ?? []).find((c) => c.id === id);
|
||||
const view = viewportAvailable() ? getCamera() : null;
|
||||
if (!old || !view) {
|
||||
st.notify(t("camera.noViewport"), "warning");
|
||||
return false;
|
||||
}
|
||||
const fresh = cameraFromView(st.project, view, {
|
||||
id: old.id,
|
||||
name: old.name,
|
||||
fallbackFloorId: old.floorId,
|
||||
distance: getCameraTargetDistance() ?? undefined,
|
||||
categoryCode: old.categoryCode,
|
||||
});
|
||||
const next: Camera = { ...old, ...fresh, locked: old.locked, sunWhen: old.sunWhen };
|
||||
if (fresh.projection === "perspective") delete next.orthoHeight;
|
||||
st.applyChange((p) => patchItem(p, "cameras", id, () => next));
|
||||
st.notify(t("camera.updated", { name: old.name }), "info");
|
||||
return true;
|
||||
}
|
||||
@@ -61,7 +61,8 @@ export type ShortcutId =
|
||||
| "fitAll"
|
||||
| "fitSelection"
|
||||
| "isolateLayer"
|
||||
| "toggleTrace";
|
||||
| "toggleTrace"
|
||||
| "walkMode";
|
||||
|
||||
export type ShortcutCategory =
|
||||
| "general"
|
||||
@@ -236,6 +237,9 @@ export const SHORTCUT_DEFS: ShortcutDef[] = [
|
||||
{ id: "isolateLayer", category: "navigation", labelKey: "shortcut.isolateLayer", defaultCombo: "mod+shift+l" },
|
||||
// [205] Pausfolie ein/aus (Archicad „Referenz ein/aus"); T wie Trace, frei neben den übrigen Cmd+Shift-Kürzeln.
|
||||
{ id: "toggleTrace", category: "navigation", labelKey: "shortcut.toggleTrace", defaultCombo: "mod+shift+t" },
|
||||
// [213] Begehen im 3D (WASD): Umschalt+F schaltet den Begehen-Modus; die Bewegungstasten selbst (W/A/S/D, Q/E, Pfeile) gelten nur
|
||||
// darin, damit sie nicht mit „s" (Spiegeln), „d" (Drehen) und „q" (Messen) kollidieren (`viewport/walk.ts`).
|
||||
{ id: "walkMode", category: "navigation", labelKey: "shortcut.walkMode", defaultCombo: "shift+f" },
|
||||
];
|
||||
|
||||
const DEFS_BY_ID = new Map<ShortcutId, ShortcutDef>(SHORTCUT_DEFS.map((d) => [d.id, d]));
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// Bilder aufs Layout-Blatt setzen ([208]): aus dem Rendering-Dialog („Ins Layout einsetzen"), später auch für
|
||||
// Fotos. Reine Ops-Bildung (`placeImageOps`) getrennt vom Store-Aufruf, damit sie ohne DOM testbar ist.
|
||||
|
||||
import { patchItem, type CoreOp } from "../core";
|
||||
import type { Layout, Project } from "../model/types";
|
||||
import { addImage, createLayoutImage } from "../model/layoutImages";
|
||||
import { effectiveSheetSizeMm, findMaster, sheetLevelOf } from "../model/layoutModel";
|
||||
import { getState } from "./appStore";
|
||||
|
||||
/** Blatt, das beim Einsetzen vorgewählt ist: das Blatt der aktiven Ebene (offenes Layout), sonst das letzte. */
|
||||
export function defaultTargetLayout(project: Pick<Project, "layouts" | "drawingLevels">, activeLevelId: string): Layout | undefined {
|
||||
const layouts = project.layouts ?? [];
|
||||
const level = project.drawingLevels.find((l) => l.id === activeLevelId);
|
||||
return layouts.find((l) => l.id === level?.layoutId) ?? layouts[layouts.length - 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Ops, die `bytes` (PNG/JPEG) mittig und im Seitenverhältnis auf das Blatt `layoutId` setzen; `null`, wenn das Blatt
|
||||
* fehlt oder die Bytes kein PNG/JPEG sind. `id` ist die Bild-Id (Aufrufer: Zeitstempel).
|
||||
*/
|
||||
export function placeImageOps(project: Project, layoutId: string, name: string, bytes: Uint8Array, id: string, mime = "image/png"): CoreOp[] | null {
|
||||
const layout = (project.layouts ?? []).find((l) => l.id === layoutId);
|
||||
if (!layout) return null;
|
||||
const image = createLayoutImage(id, name, bytes, effectiveSheetSizeMm(findMaster(project, layout) ?? layout), mime);
|
||||
if (!image) return null;
|
||||
return patchItem(project, "layouts", layoutId, (l) => addImage(l, image));
|
||||
}
|
||||
|
||||
/** Setzt das Bild auf das Blatt (ein Undo-Schritt); `false`, wenn nichts eingesetzt werden konnte. */
|
||||
export function placeImageOnLayout(layoutId: string, name: string, bytes: Uint8Array, mime = "image/png"): boolean {
|
||||
const st = getState();
|
||||
const ops = placeImageOps(st.project, layoutId, name, bytes, `img-${Date.now()}`, mime);
|
||||
if (!ops) return false;
|
||||
st.applyChange(ops);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Blatt-Ebene eines Layouts (für „Blatt öffnen" nach dem Einsetzen). */
|
||||
export function layoutSheetLevelId(project: Project, layoutId: string): string | undefined {
|
||||
return sheetLevelOf(project, layoutId)?.id;
|
||||
}
|
||||
@@ -34,7 +34,7 @@ export interface SelectionAppearance {
|
||||
|
||||
/** Zahl der gewählten Elemente (ohne Gruppen, Schnittlinien, Lage-Darstellung, Bäume). */
|
||||
export function selectedCount(sel: Selection): number {
|
||||
return ELEMENT_KINDS.filter((k) => k !== "sectionLines" && k !== "site" && k !== "trees").reduce((n, k) => n + sel[k].length, 0);
|
||||
return ELEMENT_KINDS.filter((k) => k !== "sectionLines" && k !== "site" && k !== "trees" && k !== "cameras").reduce((n, k) => n + sel[k].length, 0);
|
||||
}
|
||||
|
||||
/** Effektive Strichstärke und Farbe über die gewählten Wände/Decken/2D-Elemente. */
|
||||
|
||||
@@ -136,7 +136,7 @@ describe("modelViews", () => {
|
||||
|
||||
it("[173] Etappe 3: Vorlagen aus den Standards übernehmen; wirken auf Raumstempel und Treppe", () => {
|
||||
const lib = standardModelViews(sampleProject);
|
||||
expect(lib.map((m) => m.id)).toEqual(["std-mv-wettbewerb-200", "std-mv-baueingabe-100", "std-mv-ausfuehrung-50", "std-mv-rohbau"]);
|
||||
expect(lib.map((m) => m.id)).toEqual(["std-mv-wettbewerb-200", "std-mv-baueingabe-100", "std-mv-ausfuehrung-50", "std-mv-situation-wbw", "std-mv-schwarzplan", "std-mv-rohbau"]);
|
||||
let p = applyOps(sampleProject, adoptModelViewOps(sampleProject, lib[2]!));
|
||||
expect(p.modelViewOptions?.map((m) => m.id)).toEqual(["std-mv-ausfuehrung-50"]);
|
||||
expect(adoptModelViewOps(p, lib[2]!)).toEqual([]);
|
||||
|
||||
@@ -34,7 +34,8 @@ export type ModelViewSection =
|
||||
| "site"
|
||||
| "sectionMarks"
|
||||
| "roomStamps"
|
||||
| "dimensions";
|
||||
| "dimensions"
|
||||
| "situation";
|
||||
|
||||
/** Ein Eintrag der Auswahl (Werkzeugleiste, Vorlage): eingebaute Stufen zuerst, dann die eigenen. */
|
||||
export interface ModelViewChoice {
|
||||
@@ -216,6 +217,10 @@ export const MODEL_VIEW_FIELDS: readonly ModelViewField[] = [
|
||||
{ section: "roomStamps", key: "divider", values: "bool" },
|
||||
{ section: "dimensions", key: "chains", values: ["all", "outer", "total"] },
|
||||
{ section: "dimensions", key: "levelMarks", values: "bool" },
|
||||
// [207] Situationsplan/Schwarzplan: Füllung des eigenen Gebäudes und der Kontextgebäude, Nordpfeil + Massstabsbalken.
|
||||
{ section: "situation", key: "own", values: ["black", "grey", "off"] },
|
||||
{ section: "situation", key: "context", values: ["black", "grey", "off"] },
|
||||
{ section: "situation", key: "symbols", values: "bool" },
|
||||
];
|
||||
|
||||
/** Auswahlwert eines Feldes als Text (`""` = wie Basis); Gegenstück: {@link parseFieldValue}. */
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
// [218] Doppelklick auf einen Raumstempel öffnet die Objekteinstellungen mit fokussiertem Abschnitt „Raumstempel"
|
||||
// (Taste T dagegen mit dem ersten Abschnitt der Auswahl).
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { buildComplexSampleProject } from "../model/sampleProjectComplex";
|
||||
import { getInfoGroupState, resetInfoGroupsForTest } from "../panels/objectInfo/infoGroupState";
|
||||
import { getSettingsArea } from "../panels/objectSettings/areaState";
|
||||
import { getState, setState } from "./appStore";
|
||||
import { openObjectSettings } from "./objectSettings";
|
||||
import { EMPTY_SELECTION } from "./selection";
|
||||
|
||||
describe("openObjectSettings [218]", () => {
|
||||
let revealed: (string | null)[] = [];
|
||||
const deps = { activeTool: "select", revealObjectSettings: (g: string | null) => void revealed.push(g) };
|
||||
beforeEach(() => {
|
||||
revealed = [];
|
||||
resetInfoGroupsForTest();
|
||||
getState().loadProject(buildComplexSampleProject());
|
||||
});
|
||||
|
||||
it("Raum gewählt: T zeigt den Abschnitt „Raum“, der Doppelklick auf den Stempel „Raumstempel“", () => {
|
||||
setState({ selection: { ...EMPTY_SELECTION, rooms: [getState().project.rooms![0].id] } });
|
||||
expect(openObjectSettings(deps)).toBe(true);
|
||||
expect(revealed).toEqual(["room"]);
|
||||
expect(openObjectSettings(deps, "roomStamp")).toBe(true);
|
||||
expect(revealed).toEqual(["room", "roomStamp"]);
|
||||
expect(getInfoGroupState().focus?.id).toBe("roomStamp");
|
||||
expect(getSettingsArea()).toBe("object");
|
||||
});
|
||||
|
||||
it("ein Abschnitt, den die Auswahl nicht hat, wird nicht erzwungen", () => {
|
||||
setState({ selection: { ...EMPTY_SELECTION, walls: [getState().project.walls[0].id] } });
|
||||
openObjectSettings(deps, "roomStamp");
|
||||
expect(revealed).toEqual(["wall"]);
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@
|
||||
// und fokussiert; ohne Auswahl die Voreinstellung des aktiven Werkzeugs (Wand/Decke: Typ des neuen Bauteils), sonst
|
||||
// nichts. Die Zuordnung Auswahl → Abschnitt ist rein (`panels/objectInfo/groups.ts::objectSettingsTarget`).
|
||||
|
||||
import { objectSettingsTarget, type InfoGroupId } from "../panels/objectInfo/groups";
|
||||
import { infoGroups, objectSettingsTarget, type InfoGroupId } from "../panels/objectInfo/groups";
|
||||
import { setSettingsArea } from "../panels/objectSettings/areaState";
|
||||
import { expandAndFocusInfoGroup } from "../panels/objectInfo/infoGroupState";
|
||||
import { getState } from "./appStore";
|
||||
@@ -17,16 +17,20 @@ export interface ObjectSettingsDeps {
|
||||
revealObjectSettings: (group: InfoGroupId | null) => void;
|
||||
}
|
||||
|
||||
/** Öffnet die Einstellungen; `false`, wenn es nichts zu öffnen gibt. */
|
||||
export function openObjectSettings(deps: ObjectSettingsDeps): boolean {
|
||||
/**
|
||||
* Öffnet die Einstellungen; `false`, wenn es nichts zu öffnen gibt. `group` wählt den Abschnitt (statt des ersten der
|
||||
* Auswahl), z. B. „roomStamp" beim Doppelklick auf einen Raumstempel ([218]); er muss zur Auswahl gehören.
|
||||
*/
|
||||
export function openObjectSettings(deps: ObjectSettingsDeps, group?: InfoGroupId): boolean {
|
||||
const { project, selection } = getState();
|
||||
const sel = selectionInfoFor(project, selection);
|
||||
let target = objectSettingsTarget(sel, deps.activeTool, isGridDrawing(sel?.kind === "drawing2d" ? sel.id : undefined));
|
||||
// Baum, Lage-Darstellung und Schnittlinie sind keine `SelectionInfo`, haben aber ihre Felder in der Objekt-Info.
|
||||
if (!target && (selection.trees.length > 0 || selection.site.length > 0 || selection.sectionLines.length > 0)) {
|
||||
if (!target && (selection.trees.length > 0 || selection.cameras.length > 0 || selection.site.length > 0 || selection.sectionLines.length > 0)) {
|
||||
target = { group: selection.sectionLines.length > 0 ? "sectionLine" : null };
|
||||
}
|
||||
if (!target) return false;
|
||||
if (group && sel && infoGroups({ sel, isGrid: false, sectionLine: false, newComponentTool: false }).includes(group)) target = { group };
|
||||
setSettingsArea("object");
|
||||
if (target.group) expandAndFocusInfoGroup(target.group);
|
||||
deps.revealObjectSettings(target.group);
|
||||
|
||||
@@ -45,7 +45,7 @@ function targetIds(collection: MultiCollection, id: string): string[] {
|
||||
const ROOF_OWN_KEYS: ReadonlySet<string> = new Set(["outline", "holes", "outlineBulge", "holesBulge", "edgePitchDeg", "dormers"]);
|
||||
|
||||
export function buildElementAttributesHost(c: FlatHostOpts) {
|
||||
const { applyChange, onOpenStampEditor, onToggleSection3dCut, openResources, patchLevel, project, section3dCutId, sectionLine, selection, patchDoorType, patchWindowType, saveOpeningStyle, setCeilingThickness, setWallThickness, slideOpening, updateCeiling, updateOpening, updateRoof, updateRoom, updateStair, updateWall } = c;
|
||||
const { applyChange, onToggleSection3dCut, openResources, patchLevel, project, section3dCutId, sectionLine, selection, patchDoorType, patchWindowType, saveOpeningStyle, setCeilingThickness, setWallThickness, slideOpening, updateCeiling, updateOpening, updateRoof, updateRoom, updateStair, updateWall } = c;
|
||||
/** Wie {@link patchAll}, aber mit Änderungsfunktion je Element (z. B. Stützen-Profil). */
|
||||
function mapAll<K extends MultiCollection>(collection: K, id: string, fn: (e: EntityOf<(typeof PROJECT_LIST)[K]>) => EntityOf<(typeof PROJECT_LIST)[K]>, coalesceKey?: string): void {
|
||||
const ids = targetIds(collection, id);
|
||||
@@ -308,7 +308,6 @@ export function buildElementAttributesHost(c: FlatHostOpts) {
|
||||
onSetRoomSia: (category) => {
|
||||
if (selection?.kind === "room") patchAll("rooms", selection.id, { siaCategory: category });
|
||||
},
|
||||
onEditRoomStamp: (roomId) => onOpenStampEditor(roomId),
|
||||
// ── Extrusions-Attribute (truck-Integration; nur bei selektiertem Körper) ──
|
||||
onSetExtrudedSolidHeight: (height) => {
|
||||
if (selection?.kind !== "extrudedSolid" || !(height > 0)) return;
|
||||
|
||||
@@ -5,9 +5,10 @@ import { addItems, fieldOps, patchItem, patchItems, removeItems } from "../../co
|
||||
import { t } from "../../i18n";
|
||||
import { createLayout, createLayoutFolder, createMasterLayout, deleteFolder as deleteLayoutFolder, deleteMasterFolder, moveLayoutToFolder, moveFolderToFolder, createSheetLevel } from "../../model/layoutModel";
|
||||
import { folderPdfBytes } from "../../export/layoutPdf";
|
||||
import { addPublishSetOps, deletePublishSetOps, patchPublishSetOps, publishSet } from "../publishActions";
|
||||
import { addPublishSetOps, addWbwSetOps, deletePublishSetOps, patchPublishSetOps, publishSet, setCompetitionOps } from "../publishActions";
|
||||
import { openLayoutTab } from "../tabNavigation";
|
||||
import { saveBinaryFile } from "../../native/saveFile";
|
||||
import { createPosterMaster, findPosterMaster, posterTemplate } from "../../model/posterTemplates";
|
||||
import type { FlatHostOpts, HostPart } from "./types";
|
||||
|
||||
export function buildLayoutsHost(c: FlatHostOpts) {
|
||||
@@ -105,10 +106,15 @@ export function buildLayoutsHost(c: FlatHostOpts) {
|
||||
},
|
||||
onCreateLayout: (opts) => {
|
||||
const id = `lay-${Date.now()}`;
|
||||
// Plakat-Vorlage ([208]): der Master der Vorlage wird angelegt, falls das Projekt noch keinen hat.
|
||||
const tpl = opts.posterTemplate ? posterTemplate(opts.posterTemplate) : undefined;
|
||||
const posterMaster = tpl ? (findPosterMaster(project, tpl.key) ?? createPosterMaster(`mas-${tpl.key}`, tpl)) : undefined;
|
||||
const newMaster = posterMaster && !findPosterMaster(project, posterMaster.template ?? "") ? posterMaster : undefined;
|
||||
const masterId = posterMaster?.id ?? opts.masterId;
|
||||
// Bei gebundenem Master erbt das Blatt dessen Papier/Ausrichtung/Grösse.
|
||||
const master = opts.masterId
|
||||
const master = posterMaster ?? (opts.masterId
|
||||
? (project.masterLayouts ?? []).find((m) => m.id === opts.masterId)
|
||||
: undefined;
|
||||
: undefined);
|
||||
const paper = master?.paper ?? opts.paper;
|
||||
const orientation = master?.orientation ?? opts.orientation;
|
||||
const customWidthMm = master ? master.customWidthMm : opts.customWidthMm;
|
||||
@@ -116,13 +122,17 @@ export function buildLayoutsHost(c: FlatHostOpts) {
|
||||
const lay = createLayout(id, t("layouts.defaultName"), paper, orientation);
|
||||
const full = {
|
||||
...lay,
|
||||
...(opts.masterId ? { masterId: opts.masterId } : {}),
|
||||
...(masterId ? { masterId } : {}),
|
||||
...(opts.folderId ? { folderId: opts.folderId } : {}),
|
||||
...(customWidthMm !== undefined && customHeightMm !== undefined
|
||||
? { customWidthMm, customHeightMm }
|
||||
: {}),
|
||||
};
|
||||
applyChange([...addItems("layouts", [full]), ...addItems("drawingLevels", [createSheetLevel(`sheet-${id}`, full)])]);
|
||||
applyChange([
|
||||
...(newMaster ? addItems("masterLayouts", [newMaster]) : []),
|
||||
...addItems("layouts", [full]),
|
||||
...addItems("drawingLevels", [createSheetLevel(`sheet-${id}`, full)]),
|
||||
]);
|
||||
return id;
|
||||
},
|
||||
onCreateMasterLayout: (opts) => {
|
||||
@@ -163,6 +173,12 @@ export function buildLayoutsHost(c: FlatHostOpts) {
|
||||
return id;
|
||||
},
|
||||
onPatchPublishSet: (id, patch) => applyChange((p) => patchPublishSetOps(p, id, patch), `pubset-${id}`),
|
||||
onSetCompetition: (patch) => applyChange((p) => setCompetitionOps(p, patch), "competition"),
|
||||
onAddWbwSet: () => {
|
||||
const id = `pubset-${Date.now()}`;
|
||||
applyChange((p) => addWbwSetOps(p, id));
|
||||
return id;
|
||||
},
|
||||
onSetProjectNumber: (value) => applyChange((p) => fieldOps(p, "projectNumber", value.trim() ? value : undefined), "projectNumber"),
|
||||
onDeletePublishSet: (id) => applyChange((p) => deletePublishSetOps(p, id)),
|
||||
onPublishSet: (id) => {
|
||||
|
||||
@@ -48,7 +48,6 @@ export type PanelHostOpts = {
|
||||
onToggleSection3dCut: (id: string) => void;
|
||||
openLayerSettings: (code: string, x: number, y: number) => void;
|
||||
openSettings: () => void;
|
||||
onOpenStampEditor: (roomId: string) => void;
|
||||
openResources: (tab?: ResourceTabId) => void;
|
||||
dxfInputRef: RefObject<HTMLInputElement | null>;
|
||||
planViewRef: RefObject<PlanViewHandle | null>;
|
||||
|
||||
@@ -390,6 +390,8 @@ export interface ProjectSlice {
|
||||
moveExcavationGrip: (id: string, index: number, pt: Vec2) => void;
|
||||
/** [176] Griff einer Schnittlinie: 0 = Anfang, dann die Knickpunkte, zuletzt das Ende. */
|
||||
moveSectionLineGrip: (id: string, index: number, pt: Vec2, coalesceKey?: string) => void;
|
||||
/** [213] Griff einer Kamera: 0 = Standpunkt, 1 = Ziel, 2 = Bildwinkel/Sichtbreite. */
|
||||
moveCameraGrip: (id: string, index: number, pt: Vec2) => void;
|
||||
/** [176] Knick in Segment `seg` (Mittel-Griff) einfügen; `coalesceKey` fasst den anschliessenden Zug zusammen. */
|
||||
insertSectionBend: (id: string, seg: number, pt: Vec2, coalesceKey?: string) => void;
|
||||
/** [176] Knick löschen (`index` wie bei {@link moveSectionLineGrip}; Anfang/Ende lassen sich nicht löschen). */
|
||||
@@ -497,11 +499,6 @@ export interface ProjectSlice {
|
||||
roomId: string,
|
||||
doc: import("../model/types").RichTextDoc,
|
||||
) => void;
|
||||
/** Setzt den strukturierten Raum-Stempel (Feldmodell). */
|
||||
setRoomStamp: (
|
||||
roomId: string,
|
||||
stamp: import("../model/types").RoomStamp,
|
||||
) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1298,6 +1295,7 @@ export function createProjectSlice(
|
||||
moveExcavationGrip: (id, index, pt) => applyGrip({ op: "excavationGrip", id, index, pt: gripPt(pt) }, `moveExcavationGrip:${id}:${index}`),
|
||||
moveSectionLineGrip: (id, index, pt, coalesceKey) =>
|
||||
applyGrip({ op: "sectionLineGrip", id, index, pt: gripPt(pt) }, coalesceKey ?? `moveSectionLineGrip:${id}:${index}`),
|
||||
moveCameraGrip: (id, index, pt) => applyGrip({ op: "cameraGrip", id, index, pt: gripPt(pt) }, `moveCameraGrip:${id}:${index}`),
|
||||
insertSectionBend: (id, seg, pt, coalesceKey) => applyGrip({ op: "sectionBendInsert", id, seg, pt: gripPt(pt) }, coalesceKey),
|
||||
deleteSectionBend: (id, index) => applyGrip({ op: "sectionBendDelete", id, index }),
|
||||
moveRingVertex: (kind, id, index, pt, coalesceKey) => {
|
||||
@@ -1412,9 +1410,6 @@ export function createProjectSlice(
|
||||
|
||||
setRoomStampDoc: (roomId, doc) =>
|
||||
applyChange((p) => mapRoom(p, roomId, (r) => ({ ...r, stampDoc: doc }))),
|
||||
|
||||
setRoomStamp: (roomId, stamp) =>
|
||||
applyChange((p) => mapRoom(p, roomId, (r) => ({ ...r, stamp }))),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,30 @@ export function addPublishSetOps(p: Project, id: string): CoreOp[] {
|
||||
return fieldOps(p, "publishSets", [...(p.publishSets ?? []), set]);
|
||||
}
|
||||
|
||||
/** Publikationssatz „WBW-Abgabe" ([208]): alle Plakate (Blätter mit Plakat-Master, sonst alle Blätter) als ein PDF. */
|
||||
export function addWbwSetOps(p: Project, id: string): CoreOp[] {
|
||||
const posterMasters = new Set((p.masterLayouts ?? []).filter((m) => m.posterHeader).map((m) => m.id));
|
||||
const posters = (p.layouts ?? []).filter((l) => l.masterId && posterMasters.has(l.masterId));
|
||||
const layoutIds = (posters.length > 0 ? posters : (p.layouts ?? [])).map((l) => l.id);
|
||||
const set: PublishSet = {
|
||||
id,
|
||||
name: t("publish.wbw.name"),
|
||||
layoutIds,
|
||||
format: "pdf-multi",
|
||||
namePattern: "{Projekt}_{Satz}",
|
||||
includeRevision: false,
|
||||
bumpRevision: false,
|
||||
pdfLayers: false,
|
||||
};
|
||||
return fieldOps(p, "publishSets", [...(p.publishSets ?? []), set]);
|
||||
}
|
||||
|
||||
/** Wettbewerbs-Einstellung ([208]) ändern; ohne Kennwort und nicht anonym entfällt das Feld. */
|
||||
export function setCompetitionOps(p: Project, patch: { anonymous?: boolean; keyword?: string }): CoreOp[] {
|
||||
const next = { anonymous: false, keyword: "", ...p.competition, ...patch };
|
||||
return fieldOps(p, "competition", next.anonymous || next.keyword.trim() ? next : undefined);
|
||||
}
|
||||
|
||||
export function patchPublishSetOps(p: Project, id: string, patch: Partial<Omit<PublishSet, "id">>): CoreOp[] {
|
||||
return fieldOps(p, "publishSets", (p.publishSets ?? []).map((s) => (s.id === id ? { ...s, ...patch } : s)));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
// [211] Rendering mit Blender/Cycles aus der App: Kamera der aktiven 3D-Ansicht, Paket bauen, Blender starten
|
||||
// (Tauri/Electron) oder das Paket als ZIP anbieten (Browser). Die Teile ohne Oberfläche, damit der Dialog
|
||||
// (`ui/RenderDialog.tsx`) dünn bleibt und sich vitest-bar prüfen lässt.
|
||||
|
||||
import JSZip from "jszip";
|
||||
import {
|
||||
BlenderMissingError,
|
||||
buildRenderPackage,
|
||||
loadFileio,
|
||||
runBlenderRender,
|
||||
type RenderCameraSpec,
|
||||
type RenderOptions,
|
||||
type RenderPackage,
|
||||
type RenderResult,
|
||||
type RenderViewPreset,
|
||||
type TextureLoader,
|
||||
} from "../core";
|
||||
import type { BlenderHost } from "../core";
|
||||
import type { Project } from "../model/types";
|
||||
import type { View3d } from "../model/viewTypes";
|
||||
import { netFetch } from "../net/net";
|
||||
import { blenderHost } from "../native/blender";
|
||||
import { RENDER_SCRIPT } from "../native/blenderScript";
|
||||
import { getCamera } from "../viewport/cameraBridge";
|
||||
import { getBlenderPath } from "./blenderSettings";
|
||||
import { getState } from "./appStore";
|
||||
import { t } from "../i18n";
|
||||
|
||||
/** Voreinstellung der Blickrichtung zur gewählten 3D-Ansicht (Ansichtsleiste). */
|
||||
export function presetForView3d(view: View3d): RenderViewPreset {
|
||||
switch (view) {
|
||||
case "front":
|
||||
case "back":
|
||||
case "side":
|
||||
case "left":
|
||||
case "top":
|
||||
case "perspective":
|
||||
return view;
|
||||
default:
|
||||
return "iso";
|
||||
}
|
||||
}
|
||||
|
||||
/** Kamera der aktiven 3D-Ansicht (frei gedreht oder Voreinstellung); ohne Viewport (nativer Pfad) die Voreinstellung. */
|
||||
export function currentRenderCamera(view: View3d = getState().view3d): RenderCameraSpec {
|
||||
const cam = getCamera();
|
||||
if (cam) {
|
||||
return { kind: cam.kind, position: cam.position, direction: cam.direction, up: cam.up, fovDeg: cam.fovDeg, orthoHeight: cam.orthoHeight };
|
||||
}
|
||||
return { preset: presetForView3d(view) };
|
||||
}
|
||||
|
||||
/** Bytes einer Bildkarte: mitgelieferte (`/assets/…`) und Blob-URLs direkt, Web-Adressen über `netFetch`. */
|
||||
export const loadTextureBytes: TextureLoader = async (url) => {
|
||||
try {
|
||||
const res = await netFetch(url); // lokale Pfade lässt netFetch ohne Prüfung durch
|
||||
if (!res.ok) return null;
|
||||
return new Uint8Array(await res.arrayBuffer());
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export interface RenderRequest extends Omit<RenderOptions, "camera"> {
|
||||
camera: RenderCameraSpec;
|
||||
}
|
||||
|
||||
/** Baut das Export-Paket des Projekts für Blender (lädt dafür das Format-Modul). */
|
||||
export async function buildPackage(project: Project, req: RenderRequest): Promise<RenderPackage> {
|
||||
await loadFileio();
|
||||
return buildRenderPackage(project, req, loadTextureBytes);
|
||||
}
|
||||
|
||||
/** Rendert über ein installiertes Blender. Wirft `BlenderMissingError`, `RenderCancelled` oder Fehler des Skripts. */
|
||||
export async function renderWithBlender(
|
||||
host: BlenderHost,
|
||||
pkg: RenderPackage,
|
||||
hooks: { onProgress?: (e: { fraction: number; stage: string; done: number; total: number }) => void; onLine?: (l: string) => void; signal?: AbortSignal },
|
||||
): Promise<RenderResult> {
|
||||
return runBlenderRender(host, pkg, { script: RENDER_SCRIPT, blenderPath: getBlenderPath(), ...hooks });
|
||||
}
|
||||
|
||||
/** Ob in dieser Umgebung ein Blender gesucht werden kann (Tauri/Electron); im Browser nicht. */
|
||||
export async function renderHost(): Promise<BlenderHost | null> {
|
||||
return blenderHost();
|
||||
}
|
||||
|
||||
/** Anleitung im ZIP des Browsers (Sprache der Oberfläche). */
|
||||
function zipReadme(): string {
|
||||
return [t("render.zip.readme.title"), "", t("render.zip.readme.steps"), "", " blender -b --python render_dossier.py -- scene.json", "", t("render.zip.readme.result")].join("\n");
|
||||
}
|
||||
|
||||
/** Browser: Paket + Skript + Anleitung als ZIP (Blender läuft dort nicht von der Seite aus). */
|
||||
export async function packageAsZip(pkg: RenderPackage): Promise<Uint8Array> {
|
||||
const zip = new JSZip();
|
||||
for (const f of pkg.files) zip.file(f.path, f.bytes);
|
||||
zip.file("render_dossier.py", RENDER_SCRIPT);
|
||||
zip.file("README.txt", zipReadme());
|
||||
return zip.generateAsync({ type: "uint8array" });
|
||||
}
|
||||
|
||||
export { BlenderMissingError };
|
||||
@@ -0,0 +1,14 @@
|
||||
// [211] Modul-Hook: App registriert den Öffner des Dialogs „Rendering…" (Blender/Cycles); Befehl `rendering`,
|
||||
// Menüpunkt und Einstellungen rufen ihn auf, ohne an React/App gekoppelt zu sein (Muster `presentationSheetHook`).
|
||||
|
||||
let opener: (() => void) | null = null;
|
||||
|
||||
/** App registriert hier den Öffner (oder hebt ihn beim Unmount auf). */
|
||||
export function setRenderDialogOpener(fn: (() => void) | null): void {
|
||||
opener = fn;
|
||||
}
|
||||
|
||||
/** Öffnet den Rendering-Dialog, falls App ihn registriert hat. */
|
||||
export function openRenderDialog(): void {
|
||||
opener?.();
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// [218] Raumstempel mehrerer Räume in EINEM Undo-Schritt ändern (Abschnitt „Raumstempel" der Objekteinstellungen).
|
||||
// Fehlt einem Raum der Stempel, beginnt die Änderung beim Standard-Stempel des Raums. Gleicher `key` (Tippen,
|
||||
// Regler) fasst aufeinanderfolgende Änderungen zu einem Schritt zusammen.
|
||||
|
||||
import { patchItems } from "../core";
|
||||
import { defaultRoomStamp } from "../model/roomStamp";
|
||||
import type { Project, Room, RoomStamp } from "../model/types";
|
||||
import { getState } from "./appStore";
|
||||
|
||||
export function editRoomStamps(ids: readonly string[], fn: (stamp: RoomStamp) => RoomStamp, key: string): void {
|
||||
getState().applyChange((p: Project) => patchItems(p, "rooms", [...ids], (r) => ({ ...r, stamp: fn(r.stamp ?? defaultRoomStamp(r)) }) as Room), key);
|
||||
}
|
||||
|
||||
/** Räume, die eine Änderung trifft: bei Mehrfachauswahl alle gewählten (wenn `roomId` dazugehört), sonst nur `roomId`. */
|
||||
export function stampTargetIds(selected: readonly string[], roomId: string): string[] {
|
||||
return selected.length > 1 && selected.includes(roomId) ? [...selected] : [roomId];
|
||||
}
|
||||
@@ -24,6 +24,8 @@ export function selectAllIds(project: Project, levelId: string): Partial<Selecti
|
||||
const roomIds = (project.rooms ?? []).filter((r) => r.floorId === levelId).map((r) => r.id);
|
||||
const solids = (project.extrudedSolids ?? []).filter((s) => s.levelId === levelId).map((s) => s.id);
|
||||
const columnIds = (project.columns ?? []).filter((c) => c.floorId === levelId).map((c) => c.id);
|
||||
// [213] Kameras des Geschosses (Symbol im Grundriss), gesperrte bleiben.
|
||||
const cameras = (project.cameras ?? []).filter((c) => c.floorId === levelId && !c.locked).map((c) => c.id);
|
||||
// Schnittführungs-Symbole sind projektweit (kein floorId; plan/context.rs, plan_section_lines).
|
||||
const sectionLines = project.drawingLevels
|
||||
.filter((l) => (l.kind === "section" || l.kind === "elevation") && l.linePoints)
|
||||
@@ -50,6 +52,7 @@ export function selectAllIds(project: Project, levelId: string): Partial<Selecti
|
||||
rooms: roomIds,
|
||||
solids,
|
||||
columns: columnIds,
|
||||
cameras,
|
||||
roofs: roofIds,
|
||||
contextObjects,
|
||||
sectionLines,
|
||||
|
||||
@@ -39,6 +39,8 @@ export interface Selection {
|
||||
site: string[];
|
||||
/** [149] Bäume (`Project.trees`). */
|
||||
trees: string[];
|
||||
/** [213] Kameras (`Project.cameras`). */
|
||||
cameras: string[];
|
||||
/**
|
||||
* Gewählte Gruppen — rein informativ (Bounding-Box, Doppelklick-Ziel); die
|
||||
* Mitglieder stehen zusätzlich in den übrigen Arten (s. `groupActions.ts`).
|
||||
@@ -63,6 +65,7 @@ export const SELECTION_KINDS: readonly SelectionKind[] = [
|
||||
"sectionLines",
|
||||
"site",
|
||||
"trees",
|
||||
"cameras",
|
||||
"groups",
|
||||
];
|
||||
|
||||
@@ -184,6 +187,8 @@ export interface SelectionIdLists {
|
||||
groupIds: string[];
|
||||
/** [149] Bäume (nicht gruppierbar; Zwischenablage, Nachauswahl). */
|
||||
treeIds?: string[];
|
||||
/** [213] Kameras (nicht gruppierbar). */
|
||||
cameraIds?: string[];
|
||||
}
|
||||
|
||||
const ID_LIST_KEYS: [SelectionKind, keyof SelectionIdLists][] = [
|
||||
@@ -200,6 +205,7 @@ const ID_LIST_KEYS: [SelectionKind, keyof SelectionIdLists][] = [
|
||||
["sectionLines", "sectionLineIds"],
|
||||
["groups", "groupIds"],
|
||||
["trees", "treeIds"],
|
||||
["cameras", "cameraIds"],
|
||||
];
|
||||
|
||||
/** Auswahl → `…Ids`-Listen (passt strukturell auf `GroupMembership` und `BcfSelection`). */
|
||||
|
||||
@@ -63,5 +63,5 @@ export function hideSelectionIn3d(): void {
|
||||
const ids = selectionIds3d(st.selection);
|
||||
if (!ids.length) return;
|
||||
setView3dFilter(hideSelection3d(getView3dFilter(), ids));
|
||||
st.setSelection(clearKinds("walls", "ceilings", "openings", "stairs", "solids", "columns", "roofs", "contextObjects", "trees", "drawings", "groups"));
|
||||
st.setSelection(clearKinds("walls", "ceilings", "openings", "stairs", "solids", "columns", "roofs", "contextObjects", "trees", "cameras", "drawings", "groups"));
|
||||
}
|
||||
+32
-1
@@ -79,6 +79,10 @@ declare global {
|
||||
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 };
|
||||
};
|
||||
@@ -156,7 +160,17 @@ export function installTestHooks(): void {
|
||||
}
|
||||
};
|
||||
walk(s.project.layers);
|
||||
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").length;
|
||||
// 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;
|
||||
},
|
||||
terrainZ: () => {
|
||||
const t = (getState().project.context ?? []).find((c) => c.type === "terrainMesh");
|
||||
@@ -219,6 +233,23 @@ export function installTestHooks(): void {
|
||||
}
|
||||
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);
|
||||
|
||||
@@ -12,6 +12,7 @@ import type { CategoryDisplayResolver } from "../core";
|
||||
import type { DetailLevel } from "../model/viewTypes";
|
||||
import type { DisplayResolver } from "../viewport/Viewport3D";
|
||||
import { savePlanPdf } from "../export/exportPdf";
|
||||
import { exportProjectName } from "../export/pdfInfo";
|
||||
import { savePlanSvg } from "../export/exportSvg";
|
||||
import { savePlanDxf } from "../export/exportDxf";
|
||||
import type { ExportPdfDecision } from "../ui/ExportPdfDialog";
|
||||
@@ -110,8 +111,10 @@ export function useExportHandlers(opts: {
|
||||
paper: decision.paper,
|
||||
orientation: decision.orientation,
|
||||
title: activeLevelName,
|
||||
subtitle: getState().project.name,
|
||||
fileName: `${getState().project.name}-${activeLevelName}`,
|
||||
// Wettbewerb anonym ([208]): Kennwort statt Projektname in Schriftfeld und Dateiname.
|
||||
subtitle: exportProjectName(getState().project),
|
||||
fileName: `${exportProjectName(getState().project)}-${activeLevelName}`,
|
||||
competition: getState().project.competition,
|
||||
});
|
||||
setExportOpen(false);
|
||||
};
|
||||
@@ -137,7 +140,7 @@ export function useExportHandlers(opts: {
|
||||
scaleDenominator: decision.scaleDenominator,
|
||||
paper: decision.paper,
|
||||
orientation: decision.orientation,
|
||||
fileName: `${getState().project.name}-${activeLevelName}`,
|
||||
fileName: `${exportProjectName(getState().project)}-${activeLevelName}`,
|
||||
});
|
||||
setExportOpen(false);
|
||||
};
|
||||
@@ -194,7 +197,7 @@ export function useExportHandlers(opts: {
|
||||
dimUnit: decision.dimUnit,
|
||||
paperLayout: decision.paperLayout,
|
||||
levelId: activeLevelId,
|
||||
fileName: `${getState().project.name}-${activeLevelName}`,
|
||||
fileName: `${exportProjectName(getState().project)}-${activeLevelName}`,
|
||||
});
|
||||
} catch (err) {
|
||||
getState().notify(`${t("exportDxf.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error");
|
||||
|
||||
@@ -51,6 +51,7 @@ import { getPlanViewport, subscribePlanViewport } from "./planViewport";
|
||||
import { growRect, meshGripIndices } from "../core";
|
||||
import { patchItem, verticalExtents } from "../core";
|
||||
import { treeGripPatch, treeGripPoints } from "./treeGrips";
|
||||
import { cameraGripPoints } from "../core";
|
||||
import type { Selection } from "./selection";
|
||||
|
||||
export interface GripEditFieldsState {
|
||||
@@ -209,6 +210,9 @@ export function useGripEditing(opts: {
|
||||
const meshViewport = useSyncExternalStore(subscribePlanViewport, () => (selectedMesh && selectedMesh.positions.length / 3 > 600 ? getPlanViewport() : null));
|
||||
const selectedTreeId = single(selection, "trees");
|
||||
const selectedTree = selectedTreeId ? (project.trees ?? []).find((x) => x.id === selectedTreeId) : undefined;
|
||||
// [213] Kamera: Griffe an Standpunkt, Ziel und Sichtkegel-Rand (Bildwinkel); nur auf dem Geschoss der Kamera.
|
||||
const selectedCameraId = single(selection, "cameras");
|
||||
const selectedCamera = selectedCameraId ? (project.cameras ?? []).find((x) => x.id === selectedCameraId && x.floorId === levelId) : undefined;
|
||||
// [176] Schnitt-/Ansichtslinie im Grundriss: Griffe an Anfang, Knickpunkten (`bendPoints`) und Ende.
|
||||
const selectedSectionLineId = single(selection, "sectionLines");
|
||||
const selectedSectionLine = modelEditable && selectedSectionLineId
|
||||
@@ -510,6 +514,11 @@ export function useGripEditing(opts: {
|
||||
pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); });
|
||||
return pts;
|
||||
}
|
||||
if (selectedCamera && modelEditable && !selectedCamera.locked) {
|
||||
const pts = cameraGripPoints(selectedCamera, scaleDenominator);
|
||||
pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); });
|
||||
return pts;
|
||||
}
|
||||
if (selectedTree && modelEditable && !selectedTree.locked) {
|
||||
const pts = treeGrips(selectedTree);
|
||||
pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); });
|
||||
@@ -1238,6 +1247,11 @@ export function useGripEditing(opts: {
|
||||
else if (st) moveStairBy(st.id, sub(pt, stairMoveHandle(st)));
|
||||
return;
|
||||
}
|
||||
// [213] Kamera: Standpunkt, Ziel bzw. Sichtkegel-Rand live (Kern `camera::grip_edit`), ein Undo-Schritt je Zug.
|
||||
if (selectedCamera) {
|
||||
if (!selectedCamera.locked) storeState().moveCameraGrip(selectedCamera.id, index, pt);
|
||||
return;
|
||||
}
|
||||
// [149] Baum: Stammmitte, Kronenrand bzw. Beschriftung live, ein Undo-Schritt je Zug (gleicher coalesceKey).
|
||||
if (selectedTree) {
|
||||
const tr = selectedTree;
|
||||
|
||||
@@ -58,22 +58,24 @@ export function useMouseSelectionHandlers(opts: {
|
||||
selectionState: Pick<ReturnType<typeof useSelectionState>, "selection" | "setSelection" | "groupPath">;
|
||||
contextMenuState: Pick<
|
||||
ReturnType<typeof useContextMenuState>,
|
||||
"setMenu" | "setStampEditorRoomId" | "editTextId" | "setEditTextId" | "setEditTextMinHeightM"
|
||||
"setMenu" | "editTextId" | "setEditTextId" | "setEditTextMinHeightM"
|
||||
>;
|
||||
/** [218] Fenster Objekteinstellungen mit dem Abschnitt „Raumstempel" öffnen (Doppelklick auf einen Stempel). */
|
||||
openRoomStampSettings: () => void;
|
||||
}) {
|
||||
// [121] Das Projekt liest jeder Handler beim Aufruf aus dem Store (App abonniert es nicht mehr).
|
||||
const { setProject, activeLevelId, visibleCodes, categoryDisplay, floorDisplay, selectionState, contextMenuState } = opts;
|
||||
const { selection, setSelection, groupPath } = selectionState;
|
||||
const { setMenu, setStampEditorRoomId, editTextId, setEditTextId, setEditTextMinHeightM } = contextMenuState;
|
||||
const { setMenu, editTextId, setEditTextId, setEditTextMinHeightM } = contextMenuState;
|
||||
|
||||
// ── Maus-Schema: Auswahl + Kontextmenü aus Grundriss / 3D ─────────────────
|
||||
// Links-Klick im Grundriss: genau eine Wand wählen (Menge ersetzen) bzw.
|
||||
// Leerraum → Auswahl löschen.
|
||||
// Doppelklick auf einen Raum-Stempel: den Raum wählen + den Stempel-Editor
|
||||
// öffnen (Rich-Text-Popup).
|
||||
// Doppelklick auf einen Raum-Stempel: den Raum wählen + die Objekteinstellungen mit dem Abschnitt „Raumstempel"
|
||||
// öffnen ([218], kein Dialog im Fenster mehr). Gehört der Raum schon zur Auswahl, bleibt sie (Mehrfachwerte).
|
||||
const onOpenStampEditor = (roomId: string) => {
|
||||
setSelection({ ...clearKinds(), rooms: [roomId] });
|
||||
setStampEditorRoomId(roomId);
|
||||
if (!getState().selection.rooms.includes(roomId)) setSelection({ ...clearKinds(), rooms: [roomId] });
|
||||
opts.openRoomStampSettings();
|
||||
};
|
||||
// Doppelklick auf ein Text-2D-Element: selektieren + Inhalts-Editor öffnen.
|
||||
const onEditDrawingText = (drawingId: string) => {
|
||||
@@ -215,6 +217,7 @@ export function useMouseSelectionHandlers(opts: {
|
||||
context: "contextObjects",
|
||||
site: "site",
|
||||
tree: "trees",
|
||||
camera: "cameras",
|
||||
} as const satisfies Record<string, SelectionKind>;
|
||||
type Kind = keyof typeof channels;
|
||||
const target: { kind: Kind; id: string } | null = sel.sectionLineId
|
||||
@@ -235,6 +238,8 @@ export function useMouseSelectionHandlers(opts: {
|
||||
? { kind: "solid", id: sel.extrudedSolidId }
|
||||
: sel.treeId
|
||||
? { kind: "tree", id: sel.treeId }
|
||||
: sel.cameraId
|
||||
? { kind: "camera", id: sel.cameraId }
|
||||
: sel.columnId
|
||||
? { kind: "column", id: sel.columnId }
|
||||
: sel.roofId
|
||||
@@ -301,7 +306,9 @@ export function useMouseSelectionHandlers(opts: {
|
||||
? ["site", sel.siteId]
|
||||
: sel.treeId
|
||||
? ["trees", sel.treeId]
|
||||
: null;
|
||||
: sel.cameraId
|
||||
? ["cameras", sel.cameraId]
|
||||
: null;
|
||||
setSelection({ ...clearKinds(), groups: [], ...(one ? { [one[0]]: [one[1]] } : {}) });
|
||||
};
|
||||
// Links-Drag (Marquee) im Grundriss: die getroffene Wand-MENGE übernehmen
|
||||
@@ -353,6 +360,7 @@ export function useMouseSelectionHandlers(opts: {
|
||||
stairs: expanded.stairIds,
|
||||
rooms: expanded.roomIds,
|
||||
trees: expanded.treeIds,
|
||||
cameras: sel.cameraIds ?? [],
|
||||
groups: groupIds,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -398,7 +398,6 @@ export function useProjectActions(
|
||||
const moveRoomEdge = useStore((s) => s.moveRoomEdge);
|
||||
const moveRoomStamp = useStore((s) => s.moveRoomStamp);
|
||||
const setRoomStampDoc = useStore((s) => s.setRoomStampDoc);
|
||||
const setRoomStamp = useStore((s) => s.setRoomStamp);
|
||||
|
||||
return {
|
||||
toggleLevelVisible,
|
||||
@@ -523,6 +522,5 @@ export function useProjectActions(
|
||||
moveRoomEdge,
|
||||
moveRoomStamp,
|
||||
setRoomStampDoc,
|
||||
setRoomStamp,
|
||||
};
|
||||
}
|
||||
@@ -151,6 +151,8 @@ export function useSelectionCommands(opts: {
|
||||
const ctxids = new Set(selection.contextObjects);
|
||||
// [149] Bäume (gesperrte bleiben).
|
||||
const treeids = new Set(selection.trees.filter((id) => !(project.trees ?? []).find((t) => t.id === id)?.locked));
|
||||
// [213] Kameras (gesperrte bleiben).
|
||||
const camids = new Set(selection.cameras.filter((id) => !(project.cameras ?? []).find((c) => c.id === id)?.locked));
|
||||
// [193] Abgeleitete Lage-Darstellung (Schatten, Baurecht) ist kein Element: Entf blendet sie aus
|
||||
// (`show: false`; über die Lage-Panels wieder einschaltbar).
|
||||
const siteHide: ReturnType<typeof fieldOps> = [];
|
||||
@@ -175,6 +177,7 @@ export function useSelectionCommands(opts: {
|
||||
...removeItems(p, "openings", (o) => oids.has(o.id) || wids.has(o.hostWallId) || (!!o.hostRoofId && rfids.has(o.hostRoofId)) || (!!o.hostCeilingId && cids.has(o.hostCeilingId))),
|
||||
...removeItems(p, "context", ctxids),
|
||||
...removeItems(p, "trees", treeids),
|
||||
...removeItems(p, "cameras", camids),
|
||||
]),
|
||||
);
|
||||
};
|
||||
|
||||
Loaded 100 of 231 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user