Merge branch 'worktree-agent-a6589ce996b5be4f8' into claude/practical-noether-1hb2s1
This commit is contained in:
23 files changed
+2185
-53
No files matched your search
+102
-7
@@ -43,6 +43,9 @@
|
||||
// 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] [--excavation] [--blender pfad] [--keep] [211] [227] (--excavation: Baugrube im Bild lassen) Rendering mit Blender/Cycles
|
||||
// dossier-cli <projekt.obp> render --engine cycles [--cycles pfad|$DOSSIER_CYCLES] --out bild.png [--view …|--camera …] [--when …] [--samples 64] [--size 1280x720]
|
||||
// [--exposure EV] [--look filmic|standard] [--no-denoise] [--cpu|--device CPU] [--exr roh.exr] [--no-context] [--excavation] [--keep] [--verbose]
|
||||
// [215] Rendering mit dem mitgelieferten Cycles (Szene aus dem Kern, Tonwert in Dossier); `--engine blender` (Standard) = Blender-Weg [211]
|
||||
// dossier-cli <projekt.obp> blend --out x.blend [--view …] [--camera …] [--when …] [--samples 128] [--size 1920x1080] [--cpu] [--excavation] [--blender pfad] [--keep] [228] Szene als .blend (Collections nach Bauteil, Bilder eingepackt, Kamera «Dossier-Kamera»), ohne zu rendern
|
||||
// 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]
|
||||
@@ -61,8 +64,9 @@
|
||||
//
|
||||
// WASM-Pakete (src/engine/pkg*) werden aus DOSSIER_WASM_DIR bzw. `<repo>/src/engine` gelesen.
|
||||
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
||||
import { spawn } from "node:child_process";
|
||||
import { deflateSync, inflateSync } from "node:zlib";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -176,8 +180,11 @@ import {
|
||||
RENDER_VIEW_PRESETS,
|
||||
findRenderCamera,
|
||||
projectRenderCameras,
|
||||
buildCyclesPackage,
|
||||
runCyclesRender,
|
||||
CyclesMissingError,
|
||||
} from "../core";
|
||||
import type { BlenderHost, Filter3d, Project, RenderMode, RenderPackage, RenderViewPreset, TextureLoader, ViewTemplate } from "../core";
|
||||
import type { BlenderHost, CyclesHost, Filter3d, Project, RenderMode, RenderPackage, RenderViewPreset, TextureLoader, ViewTemplate } from "../core";
|
||||
import { serveStdio } from "./mcp";
|
||||
import { startBridge } from "./mcpBridge";
|
||||
|
||||
@@ -810,8 +817,8 @@ function nodeBlenderHost(keep: boolean): BlenderHost {
|
||||
};
|
||||
}
|
||||
|
||||
/** Optionen von `render` und `blend` ([211] [228]): Kamera, Zeit, Grösse, Samples → Paket (bei ungültigen Optionen beendet `fail()` den Prozess). */
|
||||
async function buildCliPackage(project: Project, args: Args, mode: RenderMode): Promise<RenderPackage> {
|
||||
/** Gemeinsame Optionen von `render` (Blender und Cycles) und `blend`: Kamera, Zeit, Grösse, Samples (bei ungültigen Optionen beendet `fail()` den Prozess). */
|
||||
function cliRenderParams(project: Project, args: Args, defaultSamples = 128, defaultSize = "1920x1080") {
|
||||
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).
|
||||
@@ -821,15 +828,21 @@ async function buildCliPackage(project: Project, args: Args, mode: RenderMode):
|
||||
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);
|
||||
const samples = Number(args.flags.get("samples") ?? defaultSamples);
|
||||
if (!Number.isFinite(samples) || samples < 1) return fail("--samples: Zahl ≥ 1");
|
||||
const sizeText = args.flags.get("size") ?? "1920x1080";
|
||||
const sizeText = args.flags.get("size") ?? defaultSize;
|
||||
const m = /^(\d+)x(\d+)$/i.exec(sizeText);
|
||||
if (!m) return fail("--size: BreitexHöhe in Pixeln, z. B. 1920x1080");
|
||||
return { view, choice, when, samples, width: Number(m[1]), height: Number(m[2]) };
|
||||
}
|
||||
|
||||
/** Optionen von `render` und `blend` ([211] [228]): Kamera, Zeit, Grösse, Samples → Paket. */
|
||||
async function buildCliPackage(project: Project, args: Args, mode: RenderMode): Promise<RenderPackage> {
|
||||
const { view, choice, when, samples, width, height } = cliRenderParams(project, args);
|
||||
await loadFileio();
|
||||
const pkg = await buildRenderPackage(
|
||||
project,
|
||||
{ mode, width: Number(m[1]), height: Number(m[2]), samples, when, camera: choice ? choice.camera : { preset: view }, device: args.flags.has("cpu") ? "cpu" : "auto", backfilled: !args.flags.has("excavation") },
|
||||
{ mode, width, height, samples, when, camera: choice ? choice.camera : { preset: view }, device: args.flags.has("cpu") ? "cpu" : "auto", backfilled: !args.flags.has("excavation") },
|
||||
localTextureLoader(),
|
||||
);
|
||||
if (pkg.missingTextures.length > 0) process.stderr.write(`Hinweis: ${pkg.missingTextures.length} Bildkarten nicht lesbar (Material erscheint einfarbig)\n`);
|
||||
@@ -848,6 +861,9 @@ function blenderFailure(e: unknown): number {
|
||||
|
||||
/** `dossier-cli … render`: Paket bauen, Blender starten, Bild nach `--out`. Rückgabe = Exit-Code. */
|
||||
async function runRender(project: Project, args: Args): Promise<number> {
|
||||
const engine = args.flags.get("engine") ?? "blender";
|
||||
if (engine === "cycles") return runCyclesRenderCli(project, args);
|
||||
if (engine !== "blender") return fail("--engine: cycles|blender");
|
||||
const pkg = await buildCliPackage(project, args, "render");
|
||||
const target = args.flags.get("out") ?? `${exportProjectName(project) || "projekt"}.png`;
|
||||
try {
|
||||
@@ -868,6 +884,85 @@ async function runRender(project: Project, args: Args): Promise<number> {
|
||||
}
|
||||
}
|
||||
|
||||
/** [215] Zlib des Node-Gastgebers für EXR (ZIP) und PNG. */
|
||||
const nodeCodec = {
|
||||
inflate: (d: Uint8Array): Uint8Array => new Uint8Array(inflateSync(d)),
|
||||
deflate: (d: Uint8Array): Uint8Array => new Uint8Array(deflateSync(d, { level: 6 })),
|
||||
};
|
||||
|
||||
/** [215] Cycles als Kindprozess (Node): Programm aus `--cycles`, `DOSSIER_CYCLES`, neben der CLI (`cycles`, `cycles/cycles`) oder im PATH. */
|
||||
function nodeCyclesHost(keep: boolean): CyclesHost {
|
||||
const exeName = process.platform === "win32" ? "cycles.exe" : "cycles";
|
||||
const isFile = (p: string) => existsSync(p) && statSync(p).isFile();
|
||||
return {
|
||||
...nodeBlenderHost(keep),
|
||||
async find(custom) {
|
||||
const given = custom?.trim() || process.env.DOSSIER_CYCLES?.trim();
|
||||
if (given) {
|
||||
if (isFile(given)) return given;
|
||||
const inner = join(given, exeName);
|
||||
return isFile(inner) ? inner : null;
|
||||
}
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
for (const c of [join(here, exeName), join(here, "cycles", exeName), join(here, "..", "cycles", exeName)]) if (isFile(c)) return c;
|
||||
for (const d of (process.env.PATH ?? "").split(process.platform === "win32" ? ";" : ":")) {
|
||||
if (d && isFile(join(d, exeName))) return join(d, exeName);
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** `dossier-cli … render --engine cycles` [215]: Szene aus dem Kern, `cycles` starten, EXR → Tonwert → PNG. Rückgabe = Exit-Code (3 = Cycles fehlt). */
|
||||
async function runCyclesRenderCli(project: Project, args: Args): Promise<number> {
|
||||
const { view, choice, when, samples, width, height } = cliRenderParams(project, args, 64, "1280x720");
|
||||
const evText = args.flags.get("exposure");
|
||||
const exposureEv = evText === undefined ? undefined : Number(evText);
|
||||
if (exposureEv !== undefined && !Number.isFinite(exposureEv)) return fail("--exposure: Zahl (EV)");
|
||||
const look = args.flags.get("look") ?? "filmic";
|
||||
if (look !== "filmic" && look !== "standard") return fail("--look: filmic|standard");
|
||||
const pkg = await buildCyclesPackage(
|
||||
project,
|
||||
{ width, height, samples, denoise: !args.flags.has("no-denoise"), whenMs: when.getTime(), camera: choice ? choice.camera : { preset: view }, backfilled: !args.flags.has("excavation"), context: !args.flags.has("no-context"), exposureEv },
|
||||
localTextureLoader(),
|
||||
);
|
||||
if (pkg.info.meshes === 0) return fail("render: Das Modell enthält keine 3D-Geometrie");
|
||||
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") ?? `${exportProjectName(project) || "projekt"}.png`;
|
||||
process.stderr.write(`Szene: ${pkg.info.meshes} Netze, ${pkg.info.triangles} Dreiecke, Sonne ${pkg.info.sunAzimuth.toFixed(0)}° / ${pkg.info.sunElevation.toFixed(0)}° hoch, Belichtung ×${pkg.info.exposure.toPrecision(3)}\n`);
|
||||
let lastShown = 0;
|
||||
try {
|
||||
const res = await runCyclesRender(nodeCyclesHost(args.flags.has("keep")), pkg, {
|
||||
cyclesPath: args.flags.get("cycles"),
|
||||
device: args.flags.has("cpu") ? "CPU" : args.flags.get("device"),
|
||||
look,
|
||||
codec: nodeCodec,
|
||||
onLine: args.flags.has("verbose") ? (l) => process.stderr.write(` ${l}\n`) : undefined,
|
||||
onProgress: (e) => {
|
||||
// Cycles meldet jeden Stand mehrfach; je Achtel und am Ende genau einmal anzeigen.
|
||||
if (e.stage === "render" && e.done > lastShown && e.total > 0 && (e.done === e.total || e.done % Math.max(1, Math.floor(e.total / 8)) === 0)) {
|
||||
lastShown = e.done;
|
||||
process.stderr.write(`Sample ${e.done}/${e.total}\n`);
|
||||
}
|
||||
},
|
||||
});
|
||||
writeFileSync(target, res.png);
|
||||
const exrTarget = args.flags.get("exr");
|
||||
if (exrTarget) writeFileSync(exrTarget, res.exr);
|
||||
lastOutput = target;
|
||||
process.stderr.write(`geschrieben: ${target} (${res.png.length} Bytes, ${res.width}x${res.height}, ${samples} Samples, Cycles ${(res.millis / 1000).toFixed(1)} s)\n`);
|
||||
for (const n of pkg.info.notes) process.stderr.write(`Hinweis: ${n}\n`);
|
||||
return 0;
|
||||
} catch (e) {
|
||||
if (e instanceof CyclesMissingError) {
|
||||
process.stderr.write("Cycles nicht gefunden: --cycles <pfad> angeben, DOSSIER_CYCLES setzen oder das Programm neben die CLI legen.\n");
|
||||
return 3;
|
||||
}
|
||||
process.stderr.write(`dossier-cli: ${e instanceof Error ? e.message : String(e)}\n`);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/** [228] `dossier-cli … blend`: Szene wie fürs Rendering aufbauen und als .blend nach `--out` speichern (nicht rendern). */
|
||||
async function runBlend(project: Project, args: Args): Promise<number> {
|
||||
const pkg = await buildCliPackage(project, args, "save");
|
||||
|
||||
@@ -9,6 +9,7 @@ import { spawnSync } from "node:child_process";
|
||||
import { run } from "./main";
|
||||
import { serializeProject } from "../core";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { makeExr } from "../export/cyclesExr.testutil";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "dossier-cli-render-"));
|
||||
const file = join(dir, "demo.obp");
|
||||
@@ -187,3 +188,119 @@ print("PROBE " + json.dumps({
|
||||
expect(info.persp).toEqual(["CAMERA"]);
|
||||
}, 300_000);
|
||||
});
|
||||
|
||||
// [215] `render --engine cycles`: Szene aus dem Kern, Ersatz-`cycles` (Shell-Skript) schreibt ein EXR; die CLI macht daraus das PNG.
|
||||
describe("dossier-cli render --engine cycles", () => {
|
||||
const fakeCycles = join(dir, "cycles-fake");
|
||||
const fakeExr = join(dir, "fake.exr");
|
||||
beforeAll(() => {
|
||||
writeFileSync(fakeExr, makeExr(8, 4, new Float32Array(8 * 4 * 3).fill(0.4), true));
|
||||
writeFileSync(
|
||||
fakeCycles,
|
||||
`#!/bin/sh
|
||||
echo "args: $@" > "${dir}/fake-cycles-args.txt"
|
||||
out=""
|
||||
prev=""
|
||||
for a in "$@"; do
|
||||
[ "$prev" = "--output" ] && out="$a"
|
||||
prev="$a"
|
||||
scene="$a"
|
||||
done
|
||||
cp "$scene" "${dir}/fake-cycles-scene.xml"
|
||||
printf 'Progress 50.00 Sample 4/8\\rProgress 100.00 Sample 8/8\\n'
|
||||
cp "${fakeExr}" "$out"
|
||||
echo "Finished Rendering."
|
||||
`,
|
||||
);
|
||||
chmodSync(fakeCycles, 0o755);
|
||||
});
|
||||
const quiet = async <T,>(f: () => Promise<T>): Promise<{ result: T; err: string }> => {
|
||||
const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
|
||||
try {
|
||||
const result = await f();
|
||||
return { result, err: err.mock.calls.map((c) => String(c[0])).join("") };
|
||||
} finally {
|
||||
err.mockRestore();
|
||||
}
|
||||
};
|
||||
|
||||
it("schreibt Szene, startet cycles mit Grösse/Samples und macht ein PNG", async () => {
|
||||
const png = join(dir, "cy.png");
|
||||
const { result, err } = await quiet(() => run([":musterhaus-komplex", "render", "--engine", "cycles", "--cycles", fakeCycles, "--out", png, "--camera", "Südost", "--samples", "8", "--size", "8x4"]));
|
||||
expect(result).toBe(0);
|
||||
expect(Array.from(readFileSync(png).subarray(1, 4))).toEqual([80, 78, 71]);
|
||||
expect(err).toContain("geschrieben:");
|
||||
const args = readFileSync(join(dir, "fake-cycles-args.txt"), "utf8");
|
||||
expect(args).toMatch(/--background --samples 8 --width 8 --height 4 --output .*render\.exr .*scene\.xml/);
|
||||
const xml = readFileSync(join(dir, "fake-cycles-scene.xml"), "utf8");
|
||||
expect(xml).toContain("<cycles>");
|
||||
expect(xml).toContain("camera_type=\"perspective\"");
|
||||
expect(xml).toMatch(/<mesh P=/);
|
||||
// Bildkarten der Bibliothek (Gelände: Wiese) liegen neben der XML.
|
||||
expect(xml).toContain("textures/");
|
||||
}, 120_000);
|
||||
|
||||
it("Programm aus DOSSIER_CYCLES; fehlt es: Hinweis und Exit-Code 3", async () => {
|
||||
const png = join(dir, "cy2.png");
|
||||
const old = process.env.DOSSIER_CYCLES;
|
||||
try {
|
||||
process.env.DOSSIER_CYCLES = fakeCycles;
|
||||
expect((await quiet(() => run([file, "render", "--engine", "cycles", "--out", png, "--samples", "8", "--size", "8x4"]))).result).toBe(0);
|
||||
expect(existsSync(png)).toBe(true);
|
||||
process.env.DOSSIER_CYCLES = join(dir, "gibt-es-nicht");
|
||||
const r = await quiet(() => run([file, "render", "--engine", "cycles", "--out", join(dir, "cy3.png")]));
|
||||
expect(r.result).toBe(3);
|
||||
expect(r.err).toContain("Cycles nicht gefunden");
|
||||
} finally {
|
||||
if (old === undefined) delete process.env.DOSSIER_CYCLES;
|
||||
else process.env.DOSSIER_CYCLES = old;
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
it("--engine blender bleibt der Standardweg; unbekannte Engine/Look beenden mit Fehler", async () => {
|
||||
const exit = vi.spyOn(process, "exit").mockImplementation((() => {
|
||||
throw new Error("exit");
|
||||
}) as never);
|
||||
try {
|
||||
await quiet(async () => {
|
||||
await expect(run([file, "render", "--engine", "unity", "--out", join(dir, "u.png")])).rejects.toThrow("exit");
|
||||
await expect(run([file, "render", "--engine", "cycles", "--look", "grell", "--cycles", fakeCycles, "--out", join(dir, "u.png")])).rejects.toThrow("exit");
|
||||
});
|
||||
} finally {
|
||||
exit.mockRestore();
|
||||
}
|
||||
expect((await quiet(() => run([file, "render", "--engine", "blender", "--out", join(dir, "b.png"), "--blender", fake, "--size", "320x180", "--samples", "8"]))).result).toBe(0);
|
||||
}, 120_000);
|
||||
});
|
||||
|
||||
// Echter Lauf mit dem gebauten Cycles (nur wenn `DOSSIER_CYCLES` auf das Programm zeigt): `:beispiel` klein mit 8 Samples.
|
||||
const realCycles = process.env.DOSSIER_CYCLES;
|
||||
describe.skipIf(!realCycles || !existsSync(realCycles))("dossier-cli render --engine cycles mit echtem Cycles", () => {
|
||||
it(":beispiel 320x180, 8 Samples → PNG mit Himmel, Haus und Boden", async () => {
|
||||
const png = join(dir, "echt.png");
|
||||
const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
|
||||
try {
|
||||
expect(await run([":beispiel", "render", "--engine", "cycles", "--out", png, "--samples", "8", "--size", "320x180", "--cpu"])).toBe(0);
|
||||
} finally {
|
||||
err.mockRestore();
|
||||
}
|
||||
const bytes = readFileSync(png);
|
||||
expect(Array.from(bytes.subarray(1, 4))).toEqual([80, 78, 71]);
|
||||
const dv = new DataView(bytes.buffer, bytes.byteOffset);
|
||||
expect([dv.getUint32(16), dv.getUint32(20)]).toEqual([320, 180]);
|
||||
const { inflateSync } = await import("node:zlib");
|
||||
const raw = inflateSync(bytes.subarray(41, 41 + dv.getUint32(33)));
|
||||
// Nicht einfarbig und nicht schwarz: Mittelwert hell genug, Streuung vorhanden.
|
||||
let sum = 0;
|
||||
let min = 255;
|
||||
let max = 0;
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
if (i % (320 * 3 + 1) === 0) continue;
|
||||
sum += raw[i];
|
||||
min = Math.min(min, raw[i]);
|
||||
max = Math.max(max, raw[i]);
|
||||
}
|
||||
expect(sum / (raw.length - 180)).toBeGreaterThan(40);
|
||||
expect(max - min).toBeGreaterThan(80);
|
||||
}, 240_000);
|
||||
});
|
||||
@@ -188,6 +188,7 @@ export type QueryName =
|
||||
| "ivhb"
|
||||
| "siteProof"
|
||||
| "siteCheck"
|
||||
| "cyclesScene"
|
||||
| "excavationQuantities"
|
||||
| "dormerStatus"
|
||||
| "buildingFootprint"
|
||||
|
||||
@@ -113,6 +113,9 @@ export {
|
||||
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, RenderMode, BlendResult } from "../export/blenderRender";
|
||||
// [215] Rendering mit dem mitgelieferten Cycles: Szene aus dem Kern (cyclesScene), Prozess-Ablauf, EXR/PNG
|
||||
export { buildCyclesPackage, cyclesSceneInfo, runCyclesRender, parseCyclesLine, cyclesArgs, readExr, encodePng, exrToPng, CyclesMissingError, CyclesCancelled } from "../export/cyclesRender";
|
||||
export type { CyclesHost, CyclesPackage, CyclesSceneInfo, CyclesSceneOptions, CyclesRunOptions, CyclesResult, CyclesEvent, Codec, ExrImage } from "../export/cyclesRender";
|
||||
// [209] Kostenschätzung grob (Kern kosten.rs): Rechnung, Beispielwerte, Bericht (CSV/PDF wie der Flächen-Nachweis)
|
||||
export { computeCostEstimate, defaultCostEstimate, formatChf } from "../analysis/costEstimate";
|
||||
export type { CostResult, CostRow, CostQuantities, CostEstimate, CostGroup, CostMethod, CostBasis } from "../analysis/costEstimate";
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
// [215] Test-Hilfe: kleines OpenEXR (B, G, R als Float, ZIP oder unkomprimiert) in der Form, die `cycles` schreibt.
|
||||
import { deflateSync } from "node:zlib";
|
||||
|
||||
/** Kleines OpenEXR (B, G, R als Float, wie das Programm; ZIP oder unkomprimiert) für die Tests. */
|
||||
export function makeExr(width: number, height: number, rgb: Float32Array, zip: boolean): Uint8Array {
|
||||
const enc = new TextEncoder();
|
||||
const parts: number[] = [0x76, 0x2f, 0x31, 0x01, 2, 0, 0, 0];
|
||||
const str = (s: string) => parts.push(...enc.encode(s), 0);
|
||||
const i32 = (v: number) => parts.push(v & 255, (v >> 8) & 255, (v >> 16) & 255, (v >>> 24) & 255);
|
||||
const attr = (name: string, type: string, body: number[]) => {
|
||||
str(name);
|
||||
str(type);
|
||||
i32(body.length);
|
||||
parts.push(...body);
|
||||
};
|
||||
const chBody: number[] = [];
|
||||
for (const n of ["B", "G", "R"]) chBody.push(...enc.encode(n), 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0);
|
||||
chBody.push(0);
|
||||
attr("channels", "chlist", chBody);
|
||||
attr("compression", "compression", [zip ? 3 : 0]);
|
||||
const le = (v: number) => [v & 255, (v >> 8) & 255, (v >> 16) & 255, (v >>> 24) & 255];
|
||||
attr("dataWindow", "box2i", [...le(0), ...le(0), ...le(width - 1), ...le(height - 1)]);
|
||||
attr("displayWindow", "box2i", [...le(0), ...le(0), ...le(width - 1), ...le(height - 1)]);
|
||||
parts.push(0);
|
||||
const rows = zip ? 16 : 1;
|
||||
const blocks = Math.ceil(height / rows);
|
||||
const data: Uint8Array[] = [];
|
||||
for (let b = 0; b < blocks; b++) {
|
||||
const lines = Math.min(rows, height - b * rows);
|
||||
const raw = new Uint8Array(lines * width * 12);
|
||||
const dv = new DataView(raw.buffer);
|
||||
let q = 0;
|
||||
for (let l = 0; l < lines; l++) {
|
||||
for (const slot of [2, 1, 0]) for (let x = 0; x < width; x++, q += 4) dv.setFloat32(q, rgb[((b * rows + l) * width + x) * 3 + slot], true);
|
||||
}
|
||||
let body = raw;
|
||||
if (zip) {
|
||||
const half = (raw.length + 1) >> 1;
|
||||
const re = new Uint8Array(raw.length);
|
||||
for (let i = 0, k = 0; i < raw.length; i += 2, k++) re[k] = raw[i];
|
||||
for (let i = 1, k = half; i < raw.length; i += 2, k++) re[k] = raw[i];
|
||||
const delta = new Uint8Array(raw.length);
|
||||
delta[0] = re[0];
|
||||
for (let i = 1; i < re.length; i++) delta[i] = (re[i] - re[i - 1] + 128 + 256) & 255;
|
||||
body = new Uint8Array(deflateSync(delta));
|
||||
}
|
||||
const head = new Uint8Array(8);
|
||||
new DataView(head.buffer).setInt32(0, b * rows, true);
|
||||
new DataView(head.buffer).setInt32(4, body.length, true);
|
||||
data.push(head, body);
|
||||
}
|
||||
const tableStart = parts.length;
|
||||
let off = tableStart + blocks * 8;
|
||||
const table = new Uint8Array(blocks * 8);
|
||||
const tv = new DataView(table.buffer);
|
||||
for (let b = 0; b < blocks; b++) {
|
||||
tv.setBigUint64(b * 8, BigInt(off), true);
|
||||
off += data[b * 2].length + data[b * 2 + 1].length;
|
||||
}
|
||||
return Uint8Array.from([...parts, ...table, ...data.flatMap((d) => [...d])]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
// [215] Cycles: Szene aus dem Kern, Zeilen des Programms, EXR lesen, PNG schreiben, Ablauf mit Ersatz-Host. Ein echter
|
||||
// Lauf steht in `cyclesRender.integration.test.ts` (nur mit `DOSSIER_CYCLES`).
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { deflateSync, inflateSync } from "node:zlib";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { makeExr } from "./cyclesExr.testutil";
|
||||
import {
|
||||
buildCyclesPackage,
|
||||
cyclesArgs,
|
||||
cyclesSceneInfo,
|
||||
encodePng,
|
||||
exrToPng,
|
||||
parseCyclesLine,
|
||||
readExr,
|
||||
runCyclesRender,
|
||||
CyclesMissingError,
|
||||
type CyclesHost,
|
||||
} from "./cyclesRender";
|
||||
|
||||
const codec = {
|
||||
inflate: (d: Uint8Array) => new Uint8Array(inflateSync(d)),
|
||||
deflate: (d: Uint8Array) => new Uint8Array(deflateSync(d)),
|
||||
};
|
||||
|
||||
describe("parseCyclesLine", () => {
|
||||
it("Fortschritt, Phasen, Fehler", () => {
|
||||
expect(parseCyclesLine("Progress 06.25 Sample 1/16")).toEqual({ kind: "sample", done: 1, total: 16 });
|
||||
expect(parseCyclesLine("Progress 00.00 Loading render kernels (may take a few minutes the first time)")).toEqual({ kind: "stage", stage: "kernels" });
|
||||
expect(parseCyclesLine("Writing image /tmp/x/render.exr")).toEqual({ kind: "stage", stage: "write" });
|
||||
expect(parseCyclesLine("Finished Rendering.")).toEqual({ kind: "done" });
|
||||
expect(parseCyclesLine("00:00.00 | ERROR: Unknown input socket name \"vector\" on \"alb\"")).toEqual({ kind: "error", message: "Unknown input socket name \"vector\" on \"alb\"" });
|
||||
expect(parseCyclesLine("Progress 00.00 Updating Meshes")).toEqual({ kind: "stage", stage: "scene" });
|
||||
expect(parseCyclesLine("irgendwas")).toBeNull();
|
||||
});
|
||||
|
||||
it("Kommandozeile", () => {
|
||||
expect(cyclesArgs({ width: 640, height: 360, samples: 8 }, "/t/scene.xml", "/t/render.exr", { device: "CPU", threads: 2 })).toEqual([
|
||||
"--background", "--samples", "8", "--width", "640", "--height", "360", "--output", "/t/render.exr", "--device", "CPU", "--threads", "2", "/t/scene.xml",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("EXR und PNG", () => {
|
||||
const rgb = new Float32Array(20 * 18 * 3).map((_, i) => (i % 7) * 0.5 + (i % 3) * 0.125);
|
||||
|
||||
it.each([false, true])("EXR lesen (ZIP: %s) gibt die Pixel zurück", (zip) => {
|
||||
const img = readExr(makeExr(20, 18, rgb, zip), codec.inflate);
|
||||
expect([img.width, img.height]).toEqual([20, 18]);
|
||||
expect(Array.from(img.rgb)).toEqual(Array.from(rgb));
|
||||
});
|
||||
|
||||
it("EXR mit anderer Kompression/Unsinn wirft statt zu raten", () => {
|
||||
expect(() => readExr(new Uint8Array(40), codec.inflate)).toThrow("Kein OpenEXR");
|
||||
const exr = makeExr(4, 4, new Float32Array(48), false);
|
||||
// Kompression PIZ (4) eintragen: Position des Wertes hinter dem Attribut `compression`.
|
||||
const at = new TextDecoder("latin1").decode(exr).indexOf("compression\0compression\0") + "compression\0compression\0".length + 4;
|
||||
exr[at] = 4;
|
||||
expect(() => readExr(exr, codec.inflate)).toThrow("Kompression 4");
|
||||
});
|
||||
|
||||
it("PNG: Kopf, Prüfsummen, Rückweg über zlib", () => {
|
||||
const px = new Uint8Array(5 * 3 * 3).map((_, i) => (i * 7) & 255);
|
||||
const png = encodePng(5, 3, px, codec.deflate);
|
||||
expect(Array.from(png.subarray(0, 8))).toEqual([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||
const dv = new DataView(png.buffer, png.byteOffset);
|
||||
expect([dv.getUint32(16), dv.getUint32(20), png[24], png[25]]).toEqual([5, 3, 8, 2]);
|
||||
// IDAT entpacken: je Zeile Filter 0 + RGB.
|
||||
const len = dv.getUint32(33);
|
||||
expect(new TextDecoder().decode(png.subarray(37, 41))).toBe("IDAT");
|
||||
const raw = inflateSync(png.subarray(41, 41 + len));
|
||||
expect(raw.length).toBe((5 * 3 + 1) * 3);
|
||||
expect(raw[0]).toBe(0);
|
||||
expect(Array.from(raw.subarray(1, 16))).toEqual(Array.from(px.subarray(0, 15)));
|
||||
// CRC des IDAT-Chunks prüfen (Standardverfahren, zlib.crc32 ab Node 22 nicht nötig: eigene Tabelle).
|
||||
let c = 0xffffffff;
|
||||
for (const b of png.subarray(37, 41 + len)) {
|
||||
c ^= b;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
}
|
||||
expect((c ^ 0xffffffff) >>> 0).toBe(dv.getUint32(41 + len));
|
||||
});
|
||||
|
||||
it("Tonwert im Kern: Szenenwerte → sichtbares Bild (Weiss besonnt unter 255, Schwarz 0)", () => {
|
||||
const img = { width: 2, height: 1, rgb: new Float32Array([0, 0, 0, 1.2, 1.2, 1.2]) };
|
||||
const png = exrToPng(img, "filmic", 0, codec.deflate);
|
||||
const raw = inflateSync(png.subarray(41, 41 + new DataView(png.buffer, png.byteOffset).getUint32(33)));
|
||||
expect(Array.from(raw.subarray(1, 4))).toEqual([0, 0, 0]);
|
||||
expect(raw[4]).toBeGreaterThan(215);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Szene aus dem Kern", () => {
|
||||
it("Beispielprojekt: XML mit Netzen, Glas, Kamera, Sonne; Optionen kommen an", () => {
|
||||
const info = cyclesSceneInfo(sampleProject, { width: 640, height: 360, samples: 8, camera: { preset: "iso" }, whenMs: Date.UTC(2026, 5, 21, 12, 0, 0) });
|
||||
expect(info.meshes).toBeGreaterThan(5);
|
||||
expect([info.width, info.height, info.samples]).toEqual([640, 360, 8]);
|
||||
expect(info.xml).toContain("<cycles>");
|
||||
expect(info.xml).toContain("camera_type=\"orthograph\"");
|
||||
expect(info.sunElevation).toBeGreaterThan(60);
|
||||
});
|
||||
|
||||
it("Bildkarten: geladene kommen als Dateien neben die XML, fehlende fallen auf Einfarbig zurück", async () => {
|
||||
const p = { ...sampleProject, components: sampleProject.components.map((c) => ({ ...c, material: { color: "/assets/materials/Bricks104/color.jpg", sizeM: 2 } })) };
|
||||
const base = { width: 320, height: 180, samples: 4 };
|
||||
const ok = await buildCyclesPackage(p, base, async () => new Uint8Array([1, 2, 3]));
|
||||
expect(ok.files.map((f) => f.path)).toContain("scene.xml");
|
||||
expect(ok.files.some((f) => f.path.startsWith("textures/0_color."))).toBe(true);
|
||||
expect(ok.info.xml).toContain("image_texture");
|
||||
const none = await buildCyclesPackage(p, base, async () => null);
|
||||
expect(none.files.map((f) => f.path)).toEqual(["scene.xml"]);
|
||||
expect(none.missingTextures.length).toBeGreaterThan(0);
|
||||
expect(none.info.xml).not.toContain("filename=");
|
||||
// Ohne Lader (Browser ohne Bilder): nie eine Datei erwähnen, die fehlt.
|
||||
const noLoader = await buildCyclesPackage(p, base);
|
||||
expect(noLoader.info.xml).not.toContain("filename=");
|
||||
});
|
||||
});
|
||||
|
||||
describe("runCyclesRender", () => {
|
||||
/** Ersatz-Gastgeber: schreibt ein EXR, meldet Zeilen wie Cycles. */
|
||||
function fakeHost(exr: Uint8Array | null, code = 0, lines: string[] = ["Progress 50.00 Sample 4/8", "Progress 100.00 Sample 8/8", "Finished Rendering."]) {
|
||||
const written = new Map<string, Uint8Array>();
|
||||
const calls: string[][] = [];
|
||||
const host: CyclesHost = {
|
||||
find: async (custom) => (custom === "fehlt" ? null : "/fake/cycles"),
|
||||
prepare: async (files) => {
|
||||
for (const f of files) written.set(f.path, f.bytes);
|
||||
return "/work";
|
||||
},
|
||||
spawn: (_exe, args, onLine) => {
|
||||
calls.push(args);
|
||||
for (const l of lines) onLine(l);
|
||||
if (exr) written.set("render.exr", exr);
|
||||
return { done: Promise.resolve(code), cancel: () => {} };
|
||||
},
|
||||
readFile: async (path) => {
|
||||
const b = written.get(path.replace("/work/", ""));
|
||||
if (!b) throw new Error("fehlt");
|
||||
return b;
|
||||
},
|
||||
join: (d, r) => `${d}/${r}`,
|
||||
};
|
||||
return { host, calls, written };
|
||||
}
|
||||
|
||||
it("Ablauf: Paket auspacken, Programm starten, Fortschritt melden, PNG liefern", async () => {
|
||||
const pkg = await buildCyclesPackage(sampleProject, { width: 4, height: 2, samples: 8 });
|
||||
const exr = makeExr(4, 2, new Float32Array(24).fill(0.3), true);
|
||||
const { host, calls, written } = fakeHost(exr);
|
||||
const seen: number[] = [];
|
||||
const res = await runCyclesRender(host, pkg, { codec, device: "CPU", onProgress: (e) => seen.push(e.fraction) });
|
||||
expect(written.has("scene.xml")).toBe(true);
|
||||
expect(calls[0]).toContain("--device");
|
||||
expect(calls[0].slice(-1)[0]).toBe("/work/scene.xml");
|
||||
expect(seen).toContain(0.5);
|
||||
expect(seen.at(-1)).toBe(1);
|
||||
expect([res.width, res.height]).toEqual([4, 2]);
|
||||
expect(Array.from(res.png.subarray(1, 4))).toEqual([80, 78, 71]);
|
||||
});
|
||||
|
||||
it("Fehler: Programm fehlt, Exit-Code ≠ 0, kein Bild", async () => {
|
||||
const pkg = await buildCyclesPackage(sampleProject, { width: 4, height: 2, samples: 8 });
|
||||
await expect(runCyclesRender(fakeHost(null).host, pkg, { codec, cyclesPath: "fehlt" })).rejects.toBeInstanceOf(CyclesMissingError);
|
||||
await expect(runCyclesRender(fakeHost(null, 3, ["00:00.00 | ERROR: kaputt"]).host, pkg, { codec })).rejects.toThrow(/Code 3.*kaputt/);
|
||||
await expect(runCyclesRender(fakeHost(null).host, pkg, { codec })).rejects.toThrow("kein Bild");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,403 @@
|
||||
// [215] Rendering mit dem mitgelieferten Cycles-Programm (Standalone, Apache-2.0; Plan: `doc/CYCLES.md`).
|
||||
//
|
||||
// Die Szene schreibt der Rust-Kern (`src-tauri/core/src/cycles_scene.rs`, Abfrage `cyclesScene`): Cycles-XML mit allen
|
||||
// 3D-Netzen des Modells (gleiche Quelle wie glTF-Export und 3D-Anzeige), Materialien, Kamera, Sonne und Himmel. Dieses Modul
|
||||
// reicht die Optionen weiter, lädt die Bildkarten (der Kern liest keine Dateien), startet das Programm über einen Gastgeber
|
||||
// (Node-CLI heute; Tauri/Electron später wie `BlenderHost`), liest den Fortschritt und macht aus dem linearen EXR ein PNG:
|
||||
// EXR lesen (Zeilenblöcke, unkomprimiert/ZIP, Half/Float) → Tonwert im Kern (`cycles_post.rs`) → PNG.
|
||||
//
|
||||
// Das Programm hat keine Tonwert-Abbildung und keine Farbverwaltung (ohne OCIO gebaut): `<film exposure>` der Szene belichtet,
|
||||
// der Tonwert (Filmic-artig, `filmic`, oder `standard`) liegt hier. Zlib (EXR-ZIP, PNG) kommt vom Gastgeber (`Codec`).
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { documentFor } from "../core/document";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import type { RenderCamera, RenderViewPreset, TextureLoader } from "./blenderRender";
|
||||
|
||||
/** Optionen der Szene (JSON an den Kern, camelCase; `cyclesScene` in `cycles_scene.rs`). */
|
||||
export interface CyclesSceneOptions {
|
||||
width: number;
|
||||
height: number;
|
||||
samples: number;
|
||||
denoise?: boolean;
|
||||
/** Zeitpunkt der Sonne (Unix-ms); fehlt er, gilt der 21.6.2026 12:00 UTC. */
|
||||
whenMs?: number;
|
||||
/** Fester Sonnenstand statt Zeit/Ort. */
|
||||
sun?: { azimuth: number; elevation: number };
|
||||
sunIntensity?: number;
|
||||
/** Belichtung in EV; fehlt sie, belichtet der Kern automatisch nach Sonnenhöhe. */
|
||||
exposureEv?: number;
|
||||
/** Voreinstellung (rahmt das Gebäude ein) oder explizit (gespeicherte/aktuelle Kamera). */
|
||||
camera?: { preset: RenderViewPreset } | RenderCamera;
|
||||
/** [227] Gelände ohne Baugrube (Standard: ja). */
|
||||
backfilled?: boolean;
|
||||
/** Gelände und Kontext (Standard: ja). */
|
||||
context?: boolean;
|
||||
/** Bodenplatte (Standard: ja). */
|
||||
ground?: boolean;
|
||||
/** Bild-URLs, die geladen werden können (`undefined` = alle). */
|
||||
textures?: string[];
|
||||
}
|
||||
|
||||
/** Antwort des Kerns. */
|
||||
export interface CyclesSceneInfo {
|
||||
xml: string;
|
||||
textures: { path: string; url: string }[];
|
||||
meshes: number;
|
||||
triangles: number;
|
||||
width: number;
|
||||
height: number;
|
||||
samples: number;
|
||||
sunAzimuth: number;
|
||||
sunElevation: number;
|
||||
exposure: number;
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
/** Szene mit geladenen Bildkarten: Dateien relativ zu `scene.xml`. */
|
||||
export interface CyclesPackage {
|
||||
info: CyclesSceneInfo;
|
||||
/** `scene.xml` und `textures/…`. */
|
||||
files: { path: string; bytes: Uint8Array }[];
|
||||
missingTextures: string[];
|
||||
}
|
||||
|
||||
/** Szene aus dem Kern (ohne Bilddateien). */
|
||||
export function cyclesSceneInfo(project: Project, opts: CyclesSceneOptions): CyclesSceneInfo {
|
||||
return documentFor(project).query<CyclesSceneInfo>("cyclesScene", [], JSON.stringify(opts));
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut das Paket: Szene aus dem Kern, Bildkarten über `loadTexture` (nicht ladbare fallen im zweiten Durchgang auf den
|
||||
* Ersatzlook des Kerns zurück, damit die XML keine fehlenden Dateien nennt).
|
||||
*/
|
||||
export async function buildCyclesPackage(project: Project, opts: CyclesSceneOptions, loadTexture?: TextureLoader): Promise<CyclesPackage> {
|
||||
let info = cyclesSceneInfo(project, opts.textures || !loadTexture ? opts : { ...opts, textures: undefined });
|
||||
const bytes = new Map<string, Uint8Array>();
|
||||
const missing: string[] = [];
|
||||
if (loadTexture) {
|
||||
for (const t of info.textures) {
|
||||
if (bytes.has(t.url) || missing.includes(t.url)) continue;
|
||||
const b = await loadTexture(t.url).catch(() => null);
|
||||
if (b && b.length > 0) bytes.set(t.url, b);
|
||||
else missing.push(t.url);
|
||||
}
|
||||
if (missing.length > 0) info = cyclesSceneInfo(project, { ...opts, textures: [...bytes.keys()] });
|
||||
} else if (info.textures.length > 0) {
|
||||
info = cyclesSceneInfo(project, { ...opts, textures: [] });
|
||||
}
|
||||
const files: CyclesPackage["files"] = [{ path: "scene.xml", bytes: new TextEncoder().encode(info.xml) }];
|
||||
for (const t of info.textures) {
|
||||
const b = bytes.get(t.url);
|
||||
if (b) files.push({ path: t.path, bytes: b });
|
||||
}
|
||||
return { info, files, missingTextures: missing };
|
||||
}
|
||||
|
||||
// ── Programm starten, Ausgabe lesen ─────────────────────────────────────────
|
||||
|
||||
export type CyclesEvent =
|
||||
| { kind: "sample"; done: number; total: number }
|
||||
| { kind: "stage"; stage: "scene" | "kernels" | "write" }
|
||||
| { kind: "done" }
|
||||
| { kind: "error"; message: string };
|
||||
|
||||
/**
|
||||
* Eine Ausgabezeile von `cycles` (Fortschritt mit Wagenrücklauf: `Progress 06.25 Sample 1/16`, dazu
|
||||
* `Updating …`, `Loading render kernels …`, `Writing image …`, `Finished Rendering.`, Fehler `… | ERROR: …`).
|
||||
*/
|
||||
export function parseCyclesLine(line: string): CyclesEvent | 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 e = /\bERROR:\s*(.*)$/.exec(line);
|
||||
if (e) return { kind: "error", message: e[1].trim() };
|
||||
if (/Loading (render|denoising) kernels/.test(line)) return { kind: "stage", stage: "kernels" };
|
||||
if (/Writing image/.test(line)) return { kind: "stage", stage: "write" };
|
||||
if (/Finished Rendering/.test(line)) return { kind: "done" };
|
||||
if (/Updating /.test(line)) return { kind: "stage", stage: "scene" };
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Aufruf-Gastgeber (Node, später Tauri/Electron): Prozess und Dateisystem. */
|
||||
export interface CyclesHost {
|
||||
/** Pfad des Programms (eigene Angabe, `DOSSIER_CYCLES`, neben der App), oder null. */
|
||||
find(custom?: string): Promise<string | null>;
|
||||
/** Neuer Arbeitsordner, Dateien hinein, Ordner zurück. */
|
||||
prepare(files: { path: string; bytes: Uint8Array }[]): Promise<string>;
|
||||
/** Startet das Programm; `onLine` je Ausgabezeile (stdout und stderr, Wagenrücklauf trennt). */
|
||||
spawn(exe: string, args: string[], onLine: (line: string) => void): { done: Promise<number>; cancel(): void };
|
||||
readFile(path: string): Promise<Uint8Array>;
|
||||
join(dir: string, rel: string): string;
|
||||
}
|
||||
|
||||
export class CyclesMissingError extends Error {
|
||||
constructor() {
|
||||
super("Cycles nicht gefunden");
|
||||
this.name = "CyclesMissingError";
|
||||
}
|
||||
}
|
||||
|
||||
export class CyclesCancelled extends Error {
|
||||
constructor() {
|
||||
super("Rendering abgebrochen");
|
||||
this.name = "CyclesCancelled";
|
||||
}
|
||||
}
|
||||
|
||||
/** Zlib des Gastgebers (Node: `zlib`; Browser: Kompressions-Ströme). */
|
||||
export interface Codec {
|
||||
inflate(data: Uint8Array): Uint8Array;
|
||||
deflate(data: Uint8Array): Uint8Array;
|
||||
}
|
||||
|
||||
export interface CyclesRunOptions {
|
||||
/** Eigener Programmpfad. */
|
||||
cyclesPath?: string;
|
||||
/** `CPU` erzwingt die CPU (`--device CPU`); sonst Wahl des Programms. */
|
||||
device?: string;
|
||||
threads?: number;
|
||||
/** Tonwert: `filmic` (Standard) oder `standard`; Zusatzbelichtung in EV. */
|
||||
look?: "filmic" | "standard";
|
||||
extraEv?: number;
|
||||
codec: Codec;
|
||||
onProgress?: (e: { fraction: number; stage: string; done: number; total: number }) => void;
|
||||
onLine?: (line: string) => void;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface CyclesResult {
|
||||
png: Uint8Array;
|
||||
/** Rohes lineares Bild des Programms (EXR). */
|
||||
exr: Uint8Array;
|
||||
width: number;
|
||||
height: number;
|
||||
dir: string;
|
||||
/** Wandzeit von Programmstart bis Ende (ms). */
|
||||
millis: number;
|
||||
/** Fehler-/Warnzeilen des Programms (leer = sauber). */
|
||||
messages: string[];
|
||||
}
|
||||
|
||||
/** Kommandozeile für `cycles`. */
|
||||
export function cyclesArgs(info: Pick<CyclesSceneInfo, "width" | "height" | "samples">, scenePath: string, outPath: string, o: Pick<CyclesRunOptions, "device" | "threads"> = {}): string[] {
|
||||
const a = ["--background", "--samples", String(info.samples), "--width", String(info.width), "--height", String(info.height), "--output", outPath];
|
||||
if (o.device) a.push("--device", o.device);
|
||||
if (o.threads && o.threads > 0) a.push("--threads", String(Math.round(o.threads)));
|
||||
a.push(scenePath);
|
||||
return a;
|
||||
}
|
||||
|
||||
/** Paket auspacken, `cycles` laufen lassen, Fortschritt melden, EXR → Tonwert → PNG. */
|
||||
export async function runCyclesRender(host: CyclesHost, pkg: CyclesPackage, opts: CyclesRunOptions): Promise<CyclesResult> {
|
||||
const exe = await host.find(opts.cyclesPath);
|
||||
if (!exe) throw new CyclesMissingError();
|
||||
const dir = await host.prepare(pkg.files);
|
||||
const out = host.join(dir, "render.exr");
|
||||
const total = pkg.info.samples;
|
||||
const messages: string[] = [];
|
||||
const t0 = Date.now();
|
||||
let stage = "scene";
|
||||
const job = host.spawn(exe, cyclesArgs(pkg.info, host.join(dir, "scene.xml"), out, opts), (line) => {
|
||||
opts.onLine?.(line);
|
||||
const ev = parseCyclesLine(line);
|
||||
if (!ev) return;
|
||||
if (ev.kind === "error") messages.push(ev.message);
|
||||
else 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 });
|
||||
}
|
||||
});
|
||||
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 CyclesCancelled();
|
||||
const millis = Date.now() - t0;
|
||||
if (code !== 0) throw new Error(`Cycles beendet mit Code ${code}${messages.length ? `: ${messages.slice(-3).join(" | ")}` : ""}`);
|
||||
const exr = await host.readFile(out).catch(() => null);
|
||||
if (!exr || exr.length === 0) throw new Error(messages.length ? `Cycles hat kein Bild geschrieben: ${messages.slice(-3).join(" | ")}` : "Cycles hat kein Bild geschrieben");
|
||||
const img = readExr(exr, opts.codec.inflate);
|
||||
const png = exrToPng(img, opts.look ?? "filmic", opts.extraEv ?? 0, opts.codec.deflate);
|
||||
opts.onProgress?.({ fraction: 1, stage: "done", done: total, total });
|
||||
return { png, exr, width: img.width, height: img.height, dir, millis, messages };
|
||||
}
|
||||
|
||||
// ── EXR lesen ───────────────────────────────────────────────────────────────
|
||||
|
||||
export interface ExrImage {
|
||||
width: number;
|
||||
height: number;
|
||||
/** RGB, zeilenweise von oben, linear. */
|
||||
rgb: Float32Array;
|
||||
}
|
||||
|
||||
/** Half → Float (IEEE 754 binary16). */
|
||||
function halfToFloat(h: number): number {
|
||||
const s = (h & 0x8000) !== 0 ? -1 : 1;
|
||||
const e = (h >> 10) & 0x1f;
|
||||
const f = h & 0x3ff;
|
||||
if (e === 0) return s * f * 2 ** -24;
|
||||
if (e === 31) return f === 0 ? s * Infinity : NaN;
|
||||
return s * (1 + f / 1024) * 2 ** (e - 15);
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenEXR (einteilig, Zeilenblöcke) lesen: Kompression keine/ZIPS/ZIP, Kanäle R, G, B (Half, Float oder UInt32). Anderes (PIZ,
|
||||
* Kacheln, mehrteilig) wirft einen Fehler; das Programm schreibt sein EXR mit ZIP und Float.
|
||||
*/
|
||||
export function readExr(bytes: Uint8Array, inflate: (d: Uint8Array) => Uint8Array): ExrImage {
|
||||
const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
if (bytes.length < 16 || dv.getUint32(0, true) !== 0x01312f76) throw new Error("Kein OpenEXR-Bild");
|
||||
const flags = dv.getUint32(4, true);
|
||||
if (flags & 0x1a00) throw new Error("OpenEXR: Kacheln/mehrteilig/lange Namen werden nicht gelesen");
|
||||
let pos = 8;
|
||||
const text = new TextDecoder();
|
||||
const cstr = (): string => {
|
||||
const start = pos;
|
||||
while (pos < bytes.length && bytes[pos] !== 0) pos++;
|
||||
const s = text.decode(bytes.subarray(start, pos));
|
||||
pos++;
|
||||
return s;
|
||||
};
|
||||
let channels: { name: string; type: number }[] = [];
|
||||
let win: [number, number, number, number] = [0, 0, -1, -1];
|
||||
let compression = 0;
|
||||
for (;;) {
|
||||
const name = cstr();
|
||||
if (name === "") break;
|
||||
cstr();
|
||||
const size = dv.getInt32(pos, true);
|
||||
pos += 4;
|
||||
const end = pos + size;
|
||||
if (name === "channels") {
|
||||
let p = pos;
|
||||
channels = [];
|
||||
while (p < end && bytes[p] !== 0) {
|
||||
let q = p;
|
||||
while (bytes[q] !== 0) q++;
|
||||
const chName = text.decode(bytes.subarray(p, q));
|
||||
p = q + 1;
|
||||
channels.push({ name: chName, type: dv.getInt32(p, true) });
|
||||
p += 16;
|
||||
}
|
||||
} else if (name === "dataWindow") {
|
||||
win = [dv.getInt32(pos, true), dv.getInt32(pos + 4, true), dv.getInt32(pos + 8, true), dv.getInt32(pos + 12, true)];
|
||||
} else if (name === "compression") {
|
||||
compression = bytes[pos];
|
||||
}
|
||||
pos = end;
|
||||
}
|
||||
const width = win[2] - win[0] + 1;
|
||||
const height = win[3] - win[1] + 1;
|
||||
if (!(width > 0 && height > 0) || width * height > 2 ** 28) throw new Error("OpenEXR: ungültige Bildgrösse");
|
||||
if (compression !== 0 && compression !== 2 && compression !== 3) throw new Error(`OpenEXR: Kompression ${compression} wird nicht gelesen (erwartet: keine, ZIPS, ZIP)`);
|
||||
const rows = compression === 3 ? 16 : 1;
|
||||
const blocks = Math.ceil(height / rows);
|
||||
const idx = (n: string) => channels.findIndex((c) => c.name === n);
|
||||
const [ri, gi, bi] = [idx("R"), idx("G"), idx("B")];
|
||||
if (ri < 0 || gi < 0 || bi < 0) throw new Error("OpenEXR: Kanäle R, G, B fehlen");
|
||||
const size = (t: number) => (t === 1 ? 2 : 4);
|
||||
const rowBytes = channels.reduce((n, c) => n + width * size(c.type), 0);
|
||||
const out = new Float32Array(width * height * 3);
|
||||
const table = pos;
|
||||
for (let b = 0; b < blocks; b++) {
|
||||
const off = Number(dv.getBigUint64(table + b * 8, true));
|
||||
const y0 = dv.getInt32(off, true) - win[1];
|
||||
const n = dv.getInt32(off + 4, true);
|
||||
let raw = bytes.subarray(off + 8, off + 8 + n);
|
||||
const lines = Math.min(rows, height - y0);
|
||||
const want = rowBytes * lines;
|
||||
if (compression !== 0 && n < want) {
|
||||
const d = inflate(raw);
|
||||
// Vorhersage rückgängig machen, Hälften wieder verschränken.
|
||||
const t = new Uint8Array(d.length);
|
||||
t[0] = d[0];
|
||||
for (let i = 1; i < d.length; i++) t[i] = (t[i - 1] + d[i] - 128) & 255;
|
||||
const half = (d.length + 1) >> 1;
|
||||
const un = new Uint8Array(d.length);
|
||||
for (let i = 0, k = 0; k < half; i += 2, k++) un[i] = t[k];
|
||||
for (let i = 1, k = half; k < d.length; i += 2, k++) un[i] = t[k];
|
||||
raw = un;
|
||||
}
|
||||
if (raw.length < want) throw new Error("OpenEXR: Zeilenblock zu kurz");
|
||||
const rv = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
|
||||
let q = 0;
|
||||
for (let l = 0; l < lines; l++) {
|
||||
const y = y0 + l;
|
||||
for (let ci = 0; ci < channels.length; ci++) {
|
||||
const c = channels[ci];
|
||||
const slot = ci === ri ? 0 : ci === gi ? 1 : ci === bi ? 2 : -1;
|
||||
const sz = size(c.type);
|
||||
if (slot >= 0) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
const o = q + x * sz;
|
||||
out[(y * width + x) * 3 + slot] = c.type === 1 ? halfToFloat(rv.getUint16(o, true)) : c.type === 2 ? rv.getFloat32(o, true) : rv.getUint32(o, true);
|
||||
}
|
||||
}
|
||||
q += width * sz;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { width, height, rgb: out };
|
||||
}
|
||||
|
||||
// ── PNG schreiben ───────────────────────────────────────────────────────────
|
||||
|
||||
let crcTable: Uint32Array | null = null;
|
||||
function crc32(parts: Uint8Array[]): number {
|
||||
if (!crcTable) {
|
||||
crcTable = new Uint32Array(256);
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
crcTable[n] = c >>> 0;
|
||||
}
|
||||
}
|
||||
let c = 0xffffffff;
|
||||
for (const p of parts) for (let i = 0; i < p.length; i++) c = crcTable[(c ^ p[i]) & 255] ^ (c >>> 8);
|
||||
return (c ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
/** PNG (RGB, 8 Bit) aus einem RGB-Puffer; `deflate` = Zlib des Gastgebers. */
|
||||
export function encodePng(width: number, height: number, rgb: Uint8Array, deflate: (d: Uint8Array) => Uint8Array): Uint8Array {
|
||||
const raw = new Uint8Array((width * 3 + 1) * height);
|
||||
for (let y = 0; y < height; y++) raw.set(rgb.subarray(y * width * 3, (y + 1) * width * 3), y * (width * 3 + 1) + 1);
|
||||
const idat = deflate(raw);
|
||||
const chunk = (type: string, data: Uint8Array): Uint8Array => {
|
||||
const t = new TextEncoder().encode(type);
|
||||
const out = new Uint8Array(12 + data.length);
|
||||
const dv = new DataView(out.buffer);
|
||||
dv.setUint32(0, data.length);
|
||||
out.set(t, 4);
|
||||
out.set(data, 8);
|
||||
dv.setUint32(8 + data.length, crc32([t, data]));
|
||||
return out;
|
||||
};
|
||||
const head = new Uint8Array(13);
|
||||
const hv = new DataView(head.buffer);
|
||||
hv.setUint32(0, width);
|
||||
hv.setUint32(4, height);
|
||||
head.set([8, 2, 0, 0, 0], 8);
|
||||
const parts = [new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", head), chunk("IDAT", idat), chunk("IEND", new Uint8Array(0))];
|
||||
const png = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
||||
let o = 0;
|
||||
for (const p of parts) {
|
||||
png.set(p, o);
|
||||
o += p.length;
|
||||
}
|
||||
return png;
|
||||
}
|
||||
|
||||
/** Lineares Bild → Tonwert (Kern) → PNG. */
|
||||
export function exrToPng(img: ExrImage, look: "filmic" | "standard", extraEv: number, deflate: (d: Uint8Array) => Uint8Array): Uint8Array {
|
||||
const rgb8 = core().cycles_tonemap(img.rgb, 3, extraEv, look);
|
||||
if (rgb8.length !== img.width * img.height * 3) throw new Error("Tonwert-Abbildung fehlgeschlagen");
|
||||
return encodePng(img.width, img.height, rgb8, deflate);
|
||||
}
|
||||
Reference in new issue
Block a user