Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

chore(render-service): settle the line endings, then lint the subsystem (#94)

Matthew Kissinger3ffe3e59f0f4
diff --git a/.gitattributes b/.gitattributes
index 0a6fe3a4..35dee8d3 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -20,9 +20,18 @@ bun.lock -diff linguist-generated=true
src/** -text
dist/** -text
skills/** -text
-render-service/src/** -text
scripts/create-workspace.mjs -text
package.json -text
plugin.json -text
.claude-plugin/** -text
docs/**/*.mjs -text
+
+# `render-service/src/**` was in the list above and is deliberately not any more.
+# Its bytes ARE hashed -- `fingerprintRendererInputs` walks that directory into the
+# renderer's capture identity -- but `-text` only froze whatever was committed, and
+# what was committed was inconsistent: four files fully CRLF, `renderer.mjs` at
+# 395 of 399 lines, three carrying a single stray CRLF line, four fully LF. The
+# `* text=auto eol=lf` rule at the top gives what the fingerprint actually needs,
+# which is ONE line ending on every platform, and it makes the directory editable
+# by ordinary tooling. Provenance receipts record the identity a poster was made
+# under; a later renderer build hashing differently is the point of recording it.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0986736e..99353e95 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,34 @@
Changes to `@kiln/engine`. Source and installable packages are distributed through
GitHub. The package is not published on the npm registry.
+## render-service joins the lint surface — 2026-09-12
+
+- It was left out because `render-service/src/**` is `-text` in `.gitattributes` and the
+ formatter would rewrite the line endings. Looking at what the attribute protected
+ turned that reason into the finding.
+- **It was sweeping, not deliberate.** The line arrived in the OSS release commit
+ alongside the other `-text` entries, and what it froze is inconsistent: four files
+ fully CRLF, `renderer.mjs` at 395 of 399 lines, three carrying a single stray CRLF
+ line, four fully LF. One stray CRLF line in an otherwise-LF file is an editor's
+ signature, not a decision.
+- **Those bytes are genuinely hashed**, so the replacement matters:
+ `fingerprintRendererInputs` walks that directory into the renderer's capture identity.
+ But `-text` only guarantees "whatever was committed", while the `* text=auto eol=lf`
+ rule guarantees what the fingerprint needs — one line ending on every platform. The
+ normalization is a stricter guarantee than the attribute it replaces.
+- **Nothing re-validates the old digest.** `capture-producer.v1` fingerprints in
+ checked-in provenance receipts record the renderer build a poster was made under; no
+ test recomputes one. 13.6 already edited two of these files and every gate stayed
+ green — a later build hashing differently is the point of recording it.
+- Eight files to LF, the attribute removed with the reasoning left where the next reader
+ will ask, and the directory linted: **442 files where 416 were.** Twenty-two format
+ findings, then five real ones. One of them, `useIterableCallbackReturn` in
+ `presentation-presets.mjs`, is the same defect 13.5 fixed in the Bradley-Terry fit —
+ a one-expression arrow in a `forEach` returning a value the contract discards — sitting
+ in production render-service code that was outside every lint gate this repo has.
+- `reliability.test.mjs` pins both include patterns and asserts the `-text` line stays
+ gone. render-service's own 37 tests pass on the normalized sources.
+
## The coverage ratchet has a scope now — 2026-09-12
- The previous entry blamed 162 lines of lost coverage slack on helper scripts being
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e98c4fe1..61b52962 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -23,9 +23,9 @@ bun run test:coverage
tolerated baseline to compare against, so any diagnostic your change produces is
yours -- either fix it, or suppress it with a `biome-ignore` comment that says why.
-The surface is `src/`, `site/src/`, `site/*.ts`, and in `scripts/` the gates and
-their tests (`check-*.mjs`, `**/*.test.mjs`). The one-off tools beside them and
-`render-service/` are out -- see ledger 14.4 for what taking them costs. If you add
+The surface is `src/`, `site/src/`, `site/*.ts`, `render-service/`, and in `scripts/`
+the gates and their tests (`check-*.mjs`, `**/*.test.mjs`). The one-off tools beside
+them are out -- see ledger 14.4 for what taking them costs. If you add
a directory, add it to `files.includes` in `biome.json`: Biome silently processes
nothing outside that list, which is how `scripts/` went unlinted while the coverage
run measured it. Note that `biome` prints at most 20 diagnostics by default, so a
diff --git a/biome.json b/biome.json
index 258862b6..64c7914d 100644
--- a/biome.json
+++ b/biome.json
@@ -7,7 +7,9 @@
"site/src/**/*.{ts,tsx}",
"site/*.ts",
"scripts/check-*.mjs",
- "scripts/**/*.test.mjs"
+ "scripts/**/*.test.mjs",
+ "render-service/src/**/*.mjs",
+ "render-service/test/**/*.mjs"
],
"maxSize": 4194304
},
diff --git a/docs/plans/repo-size-and-r2-migration-2026-09-10.md b/docs/plans/repo-size-and-r2-migration-2026-09-10.md
index c9b8db04..f8a87f4d 100644
--- a/docs/plans/repo-size-and-r2-migration-2026-09-10.md
+++ b/docs/plans/repo-size-and-r2-migration-2026-09-10.md
@@ -1679,6 +1679,7 @@ the installed tree.
| 14.1 | Re-ground 7.12 / SEP-2640 against an authoritative source | **Done 2026-09-12.** Deferred still, for a stronger reason. See below |
| 14.2 | Establish what actually blocks the `ai` 7 family, and gate it | **Done 2026-09-12.** `@strands-agents/[email protected]` is latest, declares peer `@ai-sdk/provider: ^3.0.0`, and its `VercelModel` is typed on `LanguageModelV3` in 21 places. `@openrouter/[email protected]` requires `ai: ^7.0.0`; `[email protected]` depends on `@ai-sdk/[email protected]`. The family cannot be taken until Strands ships a release accepting the v4 spec -- no budget changes that. `scripts/peer-ranges.test.mjs` now fails on a peer range the version beside it does not meet, verified by patching the installed `@openrouter/ai-sdk-provider` manifest to peer `ai: ^7.0.0` and watching it report `installed 6.0.282` |
| 14.3 | Assert the prompt-cache breakpoint on the wire, offline | **Done 2026-09-12.** Both native transports captured in `src/agent/providers.test.ts`, both differential. See below |
+| 14.6 | `render-service/` into the lint surface, which needed its line endings settled first | **Done 2026-09-12.** 442 files where 416 were. See below |
| 14.5 | Give the coverage ratchet a scope, so repo-only code cannot move the engine's contract | **Done 2026-09-12.** Measured over `src/` alone; baseline re-measured at 95.39% functions / 92.59% lines; `lines` raised 92 to 92.1 so the narrowing does not quietly hand back slack. See below |
| 14.4 | Bring the repository's own gates under the lint gate, which they were never under | **Done 2026-09-12** for the gates and their tests: 416 files checked where 405 were, and the tree reports nothing. The one-off tools beside them are measured and deliberately left, below |
@@ -1846,3 +1847,46 @@ plausible enough to write down. Verified by a case in
`AGENTS.md` states the scope where an agent reads it, beside the existing rule that
the ratchet must not vary by whether the runner has a GPU. Same class of rule: the
contract must not depend on things that are not the engine.
+
+### 14.6 -- render-service was kept out by a frozen accident
+
+14.4 left `render-service/` out because its `src/**` is `-text` in
+`.gitattributes` and Biome's formatter would rewrite the line endings. Looking at
+what the attribute was protecting turned that from a reason into the finding.
+
+**The attribute was sweeping, not deliberate.** It arrived in the OSS release
+commit (#51) alongside the other `-text` entries, and what it froze is
+*inconsistent*: `contract.mjs`, `health-contract.mjs`, `presentation-presets.mjs`
+and `server.mjs` fully CRLF; `renderer.mjs` at 395 of 399 lines; `cache-identity.mjs`,
+`display-output.mjs` and `readback.mjs` each carrying a single stray CRLF line;
+`framing.mjs`, `gpu.mjs`, `register-hooks.mjs` and `three-alias-hooks.mjs` fully LF.
+A single stray CRLF line in an otherwise-LF file is the signature of an editor, not
+of a decision.
+
+**Those bytes really are hashed, which is why the replacement matters.**
+`fingerprintRendererInputs` walks `render-service/src/` and hashes the file bytes
+into the renderer's capture identity, so this is not a directory where line endings
+are cosmetic. But `-text` only guarantees "whatever was committed"; the
+`* text=auto eol=lf` rule at the top of the file guarantees what the fingerprint
+actually needs, which is ONE line ending on every platform. Normalizing is a
+strictly better guarantee than the attribute it replaces.
+
+**Nothing re-validates the old fingerprint.** `capture-producer.v1` digests appear
+in checked-in `examples/*.provenance.json` and evaluation results, but they are
+records of the renderer build a poster was made under -- no test recomputes one and
+compares. The precedent settles it: 13.6 edited `presentation-presets.mjs` and
+`renderer.mjs` (#86), changing the fingerprint, and every gate stayed green. A later
+build hashing differently is the point of recording it.
+
+Eight files converted to LF, the attribute removed with the reasoning left in
+`.gitattributes` where the next reader will ask, and the directory joined the lint
+surface: 442 files where 416 were. Twenty-two format findings, then five real ones
+-- three `useIterableCallbackReturn` and two `useTemplate`. The
+`useIterableCallbackReturn` in `presentation-presets.mjs` is the same defect 13.5
+fixed in the Bradley-Terry fit: a one-expression arrow in a `forEach` returning a
+value the callback's contract discards. That is production render-service code, and
+it was outside every lint gate this repository has.
+
+`reliability.test.mjs` pins both include patterns and asserts the `-text` line stays
+gone, since the next edit to a CRLF-era file is what would reintroduce the mix.
+render-service's own 37 tests pass on the normalized sources.
diff --git a/render-service/src/cache-identity.mjs b/render-service/src/cache-identity.mjs
index 578532e5..e533bd16 100644
--- a/render-service/src/cache-identity.mjs
+++ b/render-service/src/cache-identity.mjs
@@ -1,8 +1,65 @@
-import {createHash,randomUUID} from 'node:crypto';
-import {readFileSync,readdirSync,statSync,realpathSync} from 'node:fs';
-import {dirname,join,relative,parse} from 'node:path';
-import {fileURLToPath} from 'node:url';
+import { createHash, randomUUID } from 'node:crypto';
+import { readFileSync, readdirSync, statSync, realpathSync } from 'node:fs';
+import { dirname, join, relative, parse } from 'node:path';
+import { fileURLToPath } from 'node:url';
/** Hash loaded service code and installed renderer package bytes once at boot. No URLs or secrets. */
-export function fingerprintRendererInputs(roots,gpuState){const hash=createHash('sha256');hash.update(JSON.stringify({version:'kiln.capture-producer.v1',node:process.version,platform:process.platform,arch:process.arch,rendererId:gpuState.rendererId,backend:gpuState.backend,adapter:gpuState.summary}));for(let i=0;i<roots.length;i++){const root=realpathSync(roots[i]);const visit=path=>{if(statSync(path).isDirectory()){for(const name of readdirSync(path).sort()){if(name==='node_modules')continue;visit(join(path,name));}}else{const bytes=readFileSync(path);hash.update(JSON.stringify([i,relative(root,path).replaceAll('\\','/'),bytes.length]));hash.update(bytes);}};visit(root);}return `sha256:${hash.digest('hex')}`;}
-function packageRoot(name){let dir=dirname(fileURLToPath(import.meta.resolve(name)));for(;;){try{if(JSON.parse(readFileSync(join(dir,'package.json'),'utf8')).name===name)return dir;}catch{}const parent=dirname(dir);if(parent===dir||dir===parse(dir).root)throw new Error(`Missing installed renderer dependency ${name}`);dir=parent;}}
-export function createRendererCaptureIdentity(gpuState){try{return Object.freeze({version:'kiln.capture-producer.v1',fingerprint:fingerprintRendererInputs([fileURLToPath(new URL('.',import.meta.url)),...['three','webgpu','pngjs'].map(packageRoot)],gpuState),instanceId:randomUUID()});}catch{return undefined;}}
+export function fingerprintRendererInputs(roots, gpuState) {
+ const hash = createHash('sha256');
+ hash.update(
+ JSON.stringify({
+ version: 'kiln.capture-producer.v1',
+ node: process.version,
+ platform: process.platform,
+ arch: process.arch,
+ rendererId: gpuState.rendererId,
+ backend: gpuState.backend,
+ adapter: gpuState.summary,
+ }),
+ );
+ for (let i = 0; i < roots.length; i++) {
+ const root = realpathSync(roots[i]);
+ const visit = (path) => {
+ if (statSync(path).isDirectory()) {
+ for (const name of readdirSync(path).sort()) {
+ if (name === 'node_modules') continue;
+ visit(join(path, name));
+ }
+ } else {
+ const bytes = readFileSync(path);
+ hash.update(JSON.stringify([i, relative(root, path).replaceAll('\\', '/'), bytes.length]));
+ hash.update(bytes);
+ }
+ };
+ visit(root);
+ }
+ return `sha256:${hash.digest('hex')}`;
+}
+function packageRoot(name) {
+ let dir = dirname(fileURLToPath(import.meta.resolve(name)));
+ for (;;) {
+ try {
+ if (JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).name === name) return dir;
+ } catch {}
+ const parent = dirname(dir);
+ if (parent === dir || dir === parse(dir).root)
+ throw new Error(`Missing installed renderer dependency ${name}`);
+ dir = parent;
+ }
+}
+export function createRendererCaptureIdentity(gpuState) {
+ try {
+ return Object.freeze({
+ version: 'kiln.capture-producer.v1',
+ fingerprint: fingerprintRendererInputs(
+ [
+ fileURLToPath(new URL('.', import.meta.url)),
+ ...['three', 'webgpu', 'pngjs'].map(packageRoot),
+ ],
+ gpuState,
+ ),
+ instanceId: randomUUID(),
+ });
+ } catch {
+ return undefined;
+ }
+}
diff --git a/render-service/src/contract.mjs b/render-service/src/contract.mjs
index 1e145499..cb974ced 100644
--- a/render-service/src/contract.mjs
+++ b/render-service/src/contract.mjs
@@ -1,481 +1,521 @@
-import { createHash } from 'node:crypto';
-import {
- DEFAULT_PRESENTATION_PRESET_ID,
- PRESENTATION_PRESET_IDS,
- isPresentationPresetId,
-} from './presentation-presets.mjs';
-
-// Singular export retained for existing Engine/Studio callers. The plural list
-// is the registry-backed source of truth for strict ID validation and discovery.
-export const SUPPORTED_LIGHTING_PRESET_ID = DEFAULT_PRESENTATION_PRESET_ID;
-export const SUPPORTED_LIGHTING_PRESET_IDS = PRESENTATION_PRESET_IDS;
-export const RENDER_FIDELITY_VERSION = 'kiln.render-fidelity.v1';
-export const RENDER_FIDELITY_PRODUCER = 'kiln-render-service';
-export const RENDER_OPERATIONAL_EVIDENCE_VERSION = 'kiln.render-operational.v1';
-export const RENDER_OUTCOME_CODES = Object.freeze([
- 'health_ok',
- 'gpu_success',
- 'auth_rejected',
- 'request_rejected',
- 'not_implemented',
- 'route_not_found',
- 'render_failed',
-]);
-export const MAX_VIEW_DIRS = 12;
-export const MAX_CAMERAS = 12;
-export const MIN_CAMERA_DIMENSION = 1;
-export const MAX_CAMERA_DIMENSION = 4096;
-// Includes every camera in the request. This admits one 4K frame, eight 1080p
-// frames, or twelve 720p frames while bounding transient MSAA/depth allocation.
-export const MAX_CAMERA_TOTAL_PIXELS = 16_777_216;
-
-export const DEFAULT_VIEW_DIRS = Object.freeze([
- Object.freeze([1, 0.35, 1]),
- Object.freeze([-1, 0.35, 1]),
- Object.freeze([1, 0.35, -1]),
- Object.freeze([-1, 0.35, -1]),
- Object.freeze([0, 1, 0.001]),
- Object.freeze([0.001, -1, 0.001]),
-]);
-
-function badRequest(message) {
- return Object.assign(new Error(message), { status: 400 });
-}
-
-function supportedPresetMessage(field) {
- return SUPPORTED_LIGHTING_PRESET_IDS.length === 1
- ? `${field} must be ${SUPPORTED_LIGHTING_PRESET_ID}`
- : `${field} must be one of: ${SUPPORTED_LIGHTING_PRESET_IDS.join(', ')}`;
-}
-
-const RENDER_OUTCOME_CODE_SET = new Set(RENDER_OUTCOME_CODES);
-const MAX_OPERATIONAL_MS = 86_400_000;
-const MAX_OPERATIONAL_QUEUE_DEPTH = 10_000;
-const OPERATIONAL_EVIDENCE_KEYS = new Set([
- 'outcomeCode',
- 'queueWaitMs',
- 'queueDepthAtEnqueue',
- 'concurrencyAtStart',
- 'firstRenderInProcess',
- 'workerAgeMsAtStart',
-]);
-
-/** Stable low-cardinality outcome for structured request logs and metrics extraction. */
-export function httpRenderOutcomeCode({ method, path, status }) {
- if (status === 401) return 'auth_rejected';
- if (status === 501) return 'not_implemented';
- if (status === 404) return 'route_not_found';
- if (status === 400 || status === 413) return 'request_rejected';
- if (method === 'GET' && (path === '/health' || path === '/ping') && status >= 200 && status < 300) {
- return 'health_ok';
- }
- if (method === 'POST' && path === '/render' && status >= 200 && status < 300) {
- return 'gpu_success';
- }
- return 'render_failed';
-}
-
-function nonNegativeFinite(value, path) {
- if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
- throw badRequest(`${path} must be a non-negative finite number`);
- }
- return value;
-}
-
-/**
- * Produce the bounded, identifier-free queue/worker envelope consumed by R2.8
- * metrics extraction. Oversized valid observations are capped rather than
- * failing a completed render; malformed internal values still fail closed.
- */
-export function buildRenderOperationalEvidenceV1(input) {
- if (!input || typeof input !== 'object' || Array.isArray(input)) {
- throw badRequest('render operational evidence must be an object');
- }
- for (const key of Object.keys(input)) {
- if (!OPERATIONAL_EVIDENCE_KEYS.has(key)) throw badRequest(`${key} is unknown`);
- }
- if (!RENDER_OUTCOME_CODE_SET.has(input.outcomeCode)) {
- throw badRequest('outcomeCode is not supported');
- }
- const queueWaitMs = nonNegativeFinite(input.queueWaitMs, 'queueWaitMs');
- const workerAgeMsAtStart = nonNegativeFinite(input.workerAgeMsAtStart, 'workerAgeMsAtStart');
- if (!Number.isInteger(input.queueDepthAtEnqueue) || input.queueDepthAtEnqueue < 0) {
- throw badRequest('queueDepthAtEnqueue must be a non-negative integer');
- }
- if (input.concurrencyAtStart !== 1) {
- throw badRequest('concurrencyAtStart must be 1 for the serial GPU queue');
- }
- if (typeof input.firstRenderInProcess !== 'boolean') {
- throw badRequest('firstRenderInProcess must be boolean');
- }
-
- const evidenceClamped = queueWaitMs > MAX_OPERATIONAL_MS
- || workerAgeMsAtStart > MAX_OPERATIONAL_MS
- || input.queueDepthAtEnqueue > MAX_OPERATIONAL_QUEUE_DEPTH;
- return {
- version: RENDER_OPERATIONAL_EVIDENCE_VERSION,
- outcomeCode: input.outcomeCode,
- queueWaitMs: +Math.min(queueWaitMs, MAX_OPERATIONAL_MS).toFixed(1),
- queueDepthAtEnqueue: Math.min(input.queueDepthAtEnqueue, MAX_OPERATIONAL_QUEUE_DEPTH),
- concurrencyAtStart: 1,
- concurrencyLimit: 1,
- workerPhase: input.firstRenderInProcess ? 'first-render' : 'warm-render',
- workerAgeMsAtStart: +Math.min(workerAgeMsAtStart, MAX_OPERATIONAL_MS).toFixed(1),
- evidenceClamped,
- };
-}
-
-/** Provider/GPU-free serial queue with explicit start evidence for every job. */
-export function createSerialRenderQueue(options = {}) {
- const now = options.now ?? (() => performance.now());
- if (typeof now !== 'function') throw badRequest('serial render queue now must be a function');
- const processStartedAt = options.processStartedAt ?? now();
- if (!Number.isFinite(processStartedAt)) {
- throw badRequest('serial render queue processStartedAt must be finite');
- }
-
- let tail = Promise.resolve();
- let queuedJobs = 0;
- let activeJobs = 0;
- let renderJobsStarted = 0;
- return Object.freeze({
- enqueue(job) {
- if (typeof job !== 'function') throw badRequest('serial render queue job must be a function');
- const enqueuedAt = now();
- const queueDepthAtEnqueue = activeJobs + queuedJobs;
- queuedJobs++;
- const runJob = async () => {
- queuedJobs--;
- activeJobs++;
- const firstRenderInProcess = renderJobsStarted === 0;
- renderJobsStarted++;
- const startedAt = now();
- const start = {
- queueWaitMs: startedAt - enqueuedAt,
- queueDepthAtEnqueue,
- concurrencyAtStart: activeJobs,
- firstRenderInProcess,
- workerAgeMsAtStart: startedAt - processStartedAt,
- };
- try {
- return await job(start);
- } finally {
- activeJobs--;
- }
- };
- const run = tail.then(runJob, runJob);
- tail = run.catch(() => { });
- return run;
- },
- });
-}
-
-function finiteTuple3(value, path) {
- if (!Array.isArray(value) || value.length !== 3 || !value.every(Number.isFinite)) {
- throw badRequest(`${path} must be [x,y,z] finite numbers`);
- }
- return [...value];
-}
-
-function finiteNumber(value, path) {
- if (!Number.isFinite(value)) throw badRequest(`${path} must be finite`);
- return value;
-}
-
-function pixelDimension(value, path) {
- if (
- !Number.isInteger(value)
- || value < MIN_CAMERA_DIMENSION
- || value > MAX_CAMERA_DIMENSION
- ) {
- throw badRequest(
- `${path} must be an integer in [${MIN_CAMERA_DIMENSION},${MAX_CAMERA_DIMENSION}]`,
- );
- }
- return value;
-}
-
-/** Legacy direction validation. Returned arrays are cloned; defaults are mutable copies. */
-export function validateViewDirs(views) {
- if (views === undefined || views === null || (Array.isArray(views) && views.length === 0)) {
- return DEFAULT_VIEW_DIRS.map((view) => [...view]);
- }
- if (!Array.isArray(views)) throw badRequest('views must be an array of [x,y,z] directions');
- if (views.length > MAX_VIEW_DIRS) {
- throw badRequest(`views has ${views.length} entries; the maximum is ${MAX_VIEW_DIRS}`);
- }
- return views.map((value, index) => {
- const direction = finiteTuple3(value, `views[${index}]`);
- if (Math.hypot(...direction) < 1e-9) {
- throw badRequest(`views[${index}] must not be the zero vector`);
- }
- return direction;
- });
-}
-
-/** Strict camera-mode parser shared by HTTP and direct renderer callers. */
-export function validateCameraMode(input) {
- if (!input || typeof input !== 'object' || Array.isArray(input)) {
- throw badRequest('camera render options must be an object');
- }
- if (!Array.isArray(input.cameras) || input.cameras.length < 1 || input.cameras.length > MAX_CAMERAS) {
- throw badRequest(`cameras must contain 1..${MAX_CAMERAS} entries`);
- }
- const width = pixelDimension(input.width, 'width');
- const height = pixelDimension(input.height, 'height');
- const totalPixels = width * height * input.cameras.length;
- if (!Number.isSafeInteger(totalPixels) || totalPixels > MAX_CAMERA_TOTAL_PIXELS) {
- throw badRequest(
- `camera request has ${totalPixels} total pixels; maximum is ${MAX_CAMERA_TOTAL_PIXELS}`,
- );
- }
- const targetAspect = width / height;
- const cameras = input.cameras.map((value, index) => {
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
- throw badRequest(`cameras[${index}] must be an object`);
- }
- const allowed = new Set(['position', 'target', 'up', 'fovDeg', 'aspect', 'near', 'far', 'version', 'projection', 'halfHeight']);
- for (const key of Object.keys(value)) {
- if (!allowed.has(key)) throw badRequest(`cameras[${index}].${key} is unknown`);
- }
- const position = finiteTuple3(value.position, `cameras[${index}].position`);
- const target = finiteTuple3(value.target, `cameras[${index}].target`);
- const up = finiteTuple3(value.up, `cameras[${index}].up`);
- const view = target.map((component, axis) => component - position[axis]);
- const viewLength = Math.hypot(...view);
- const upLength = Math.hypot(...up);
- if (viewLength < 1e-9) throw badRequest(`cameras[${index}].target must differ from position`);
- if (upLength < 1e-9) throw badRequest(`cameras[${index}].up must be non-zero`);
- const cross = [
- view[1] * up[2] - view[2] * up[1],
- view[2] * up[0] - view[0] * up[2],
- view[0] * up[1] - view[1] * up[0],
- ];
- if (Math.hypot(...cross) <= viewLength * upLength * 1e-9) {
- throw badRequest(`cameras[${index}].up must not be collinear with view`);
- }
- const versioned = value.version !== undefined || value.projection !== undefined;
- if (versioned && (value.version !== 'kiln.camera.v1' || !['orthographic','perspective'].includes(value.projection))) throw badRequest('invalid versioned camera');
- const orthographic = value.projection === 'orthographic';
- if (orthographic && value.fovDeg !== undefined) throw badRequest('orthographic camera cannot use fovDeg');
- if (!orthographic && value.halfHeight !== undefined) throw badRequest('perspective camera cannot use halfHeight');
- const halfHeight = orthographic ? finiteNumber(value.halfHeight, `cameras[${index}].halfHeight`) : undefined;
- if (orthographic && halfHeight <= 0) throw badRequest('halfHeight must be positive');
- const fovDeg = orthographic ? undefined : finiteNumber(value.fovDeg, `cameras[${index}].fovDeg`);
- const aspect = finiteNumber(value.aspect, `cameras[${index}].aspect`);
- const near = finiteNumber(value.near, `cameras[${index}].near`);
- const far = finiteNumber(value.far, `cameras[${index}].far`);
- if (!orthographic && (fovDeg <= 0 || fovDeg >= 180)) {
- throw badRequest(`cameras[${index}].fovDeg must be in (0,180)`);
- }
- if (aspect <= 0) throw badRequest(`cameras[${index}].aspect must be positive`);
- if (near <= 0) throw badRequest(`cameras[${index}].near must be positive`);
- if (far <= near) throw badRequest(`cameras[${index}].far must exceed near`);
- if (Math.abs(aspect - targetAspect) > Math.max(1, targetAspect) * 1e-9) {
- throw badRequest(`cameras[${index}].aspect must equal width/height`);
- }
- return { position, target, up, ...(orthographic ? {halfHeight} : {fovDeg}), aspect, near, far, ...(versioned ? {version:value.version,projection:value.projection} : {}) };
- });
- const lightingPresetId = input.lightingPresetId === undefined
- ? SUPPORTED_LIGHTING_PRESET_ID
- : input.lightingPresetId;
- if (!isPresentationPresetId(lightingPresetId)) {
- throw badRequest(supportedPresetMessage('lighting_preset_id'));
- }
- return { cameras, width, height, lightingPresetId, totalPixels };
-}
-
-/** Parse only render-mode fields; GLB/auth/body-size validation remains in the server. */
-export function validateRenderMode(body) {
- if (!body || typeof body !== 'object' || Array.isArray(body)) {
- throw badRequest('render body must be an object');
- }
- if (body.cameras !== undefined) {
- if (body.views !== undefined || body.size !== undefined || body.beauty_size !== undefined) {
- throw badRequest('camera mode is mutually exclusive with views, size, and beauty_size');
- }
- if (body.background !== undefined) {
- throw badRequest('camera mode cannot override the neutral-studio-v1 background');
- }
- const allowed = new Set([
- 'glb_base64',
- 'input_glb_sha256',
- 'cameras',
- 'width',
- 'height',
- 'lighting_preset_id',
- ]);
- for (const key of Object.keys(body)) {
- if (body[key] !== undefined && !allowed.has(key)) {
- throw badRequest(`camera mode field ${key} is unknown`);
- }
- }
- const camera = validateCameraMode({
- cameras: body.cameras,
- width: body.width,
- height: body.height,
- lightingPresetId: body.lighting_preset_id,
- });
- return { mode: 'camera', ...camera };
- }
- if (body.width !== undefined || body.height !== undefined || body.lighting_preset_id !== undefined) {
- throw badRequest('width, height, and lighting_preset_id require cameras');
- }
- return {
- mode: 'legacy',
- viewDirs: validateViewDirs(body.views),
- size: body.size,
- beautySize: body.beauty_size,
- background: body.background,
- };
-}
-
-export function sha256(bytes) {
- return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
-}
-
-const SHA256_IDENTITY_RE = /^sha256:[0-9a-f]{64}$/;
-
-/**
- * Compute the identity of the exact GLB bytes the renderer will consume. A new
- * caller may also assert its expected identity; legacy callers omit the claim
- * and still receive the computed identity in the response.
- */
-export function validateInputGlbIdentity(bytes, claimedIdentity) {
- if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) {
- throw badRequest('GLB identity requires non-empty bytes');
- }
- const actual = sha256(bytes);
- if (claimedIdentity === undefined) return actual;
- if (typeof claimedIdentity !== 'string' || !SHA256_IDENTITY_RE.test(claimedIdentity)) {
- throw badRequest('input_glb_sha256 must be sha256:<64 lowercase hex characters>');
- }
- if (claimedIdentity !== actual) {
- throw badRequest('input_glb_sha256 does not match glb_base64 bytes');
- }
- return actual;
-}
-
-const FIDELITY_TIMING_KEYS = new Set([
- 'loadMs',
- 'viewsMs',
- 'beautyMs',
- 'totalMs',
- 'queueWaitMs',
- 'queueAndTotalMs',
-]);
-
-function cloneCamera(camera) {
- return {
- position: [...camera.position],
- target: [...camera.target],
- up: [...camera.up],
- ...(camera.projection === 'orthographic' ? {halfHeight:camera.halfHeight} : {fovDeg:camera.fovDeg}),
- aspect: camera.aspect,
- near: camera.near,
- far: camera.far,
- ...(camera.version ? {version:camera.version,projection:camera.projection} : {}),
- };
-}
-
-/**
- * Mint the additive renderer-side fidelity receipt only after all identity and
- * camera/profile claims have been checked against the request and actual result.
- *
- * `exactArtifact` is deliberately false: this service attests the exact GLB
- * bytes it rendered, but only the caller knows whether those bytes are the
- * persisted/final artifact rather than an in-loop or derivative GLB.
- */
-export function buildRenderFidelityV1({
- rendererId,
- inputGlbSha256,
- presentationProfile,
- renderMode,
- resolvedCameras,
- timings,
-}) {
- if (
- typeof rendererId !== 'string'
- || rendererId.trim() !== rendererId
- || rendererId.length < 1
- || rendererId.length > 160
- ) {
- throw badRequest('rendererId must be a non-empty string of at most 160 characters');
- }
- if (typeof inputGlbSha256 !== 'string' || !SHA256_IDENTITY_RE.test(inputGlbSha256)) {
- throw badRequest('inputGlbSha256 must be sha256:<64 lowercase hex characters>');
- }
- if (!isPresentationPresetId(presentationProfile)) {
- throw badRequest(supportedPresetMessage('presentationProfile'));
- }
- if (!renderMode || (renderMode.mode !== 'camera' && renderMode.mode !== 'legacy')) {
- throw badRequest('renderMode must be a validated camera or legacy render mode');
- }
- if (!Array.isArray(resolvedCameras)) {
- throw badRequest('resolvedCameras must be an array');
- }
-
- const requestedCameras = renderMode.mode === 'camera'
- ? renderMode.cameras.map(cloneCamera)
- : [];
- if (
- resolvedCameras.length !== requestedCameras.length
- || JSON.stringify(resolvedCameras) !== JSON.stringify(requestedCameras)
- ) {
- throw badRequest('resolved cameras do not match the validated requested cameras');
- }
-
- if (!timings || typeof timings !== 'object' || Array.isArray(timings)) {
- throw badRequest('timings must be an object');
- }
- const checkedTimings = {};
- for (const [key, value] of Object.entries(timings)) {
- if (!FIDELITY_TIMING_KEYS.has(key)) throw badRequest(`timings.${key} is unknown`);
- if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
- throw badRequest(`timings.${key} must be a non-negative finite number`);
- }
- checkedTimings[key] = value;
- }
- if (checkedTimings.totalMs === undefined || checkedTimings.queueAndTotalMs === undefined) {
- throw badRequest('timings must include totalMs and queueAndTotalMs');
- }
- if (checkedTimings.queueAndTotalMs < checkedTimings.totalMs) {
- throw badRequest('timings.queueAndTotalMs must be at least totalMs');
- }
- if (
- checkedTimings.queueWaitMs !== undefined
- && checkedTimings.queueWaitMs > checkedTimings.queueAndTotalMs
- ) {
- throw badRequest('timings.queueWaitMs must not exceed queueAndTotalMs');
- }
-
- return {
- version: RENDER_FIDELITY_VERSION,
- producer: RENDER_FIDELITY_PRODUCER,
- requested: 'full-preferred',
- delivered: 'full-material',
- materialFaithful: true,
- exactArtifact: false,
- rendererId,
- inputGlbSha256,
- degraded: false,
- presentationProfile,
- renderMode: renderMode.mode,
- requestedCameras,
- resolvedCameras: resolvedCameras.map(cloneCamera),
- timings: checkedTimings,
- };
-}
-
-/** Canonical identity of an ordered output set; it is not a composite-image hash. */
-export function outputSetSha256(outputs) {
- const hash = createHash('sha256');
- hash.update('kiln-render-output-set-v1\0');
- for (const output of outputs) {
- const size = Buffer.allocUnsafe(4);
- size.writeUInt32BE(output.byteLength);
- hash.update(size);
- hash.update(output);
- }
- return `sha256:${hash.digest('hex')}`;
-}
+import { createHash } from 'node:crypto';
+import {
+ DEFAULT_PRESENTATION_PRESET_ID,
+ PRESENTATION_PRESET_IDS,
+ isPresentationPresetId,
+} from './presentation-presets.mjs';
+
+// Singular export retained for existing Engine/Studio callers. The plural list
+// is the registry-backed source of truth for strict ID validation and discovery.
+export const SUPPORTED_LIGHTING_PRESET_ID = DEFAULT_PRESENTATION_PRESET_ID;
+export const SUPPORTED_LIGHTING_PRESET_IDS = PRESENTATION_PRESET_IDS;
+export const RENDER_FIDELITY_VERSION = 'kiln.render-fidelity.v1';
+export const RENDER_FIDELITY_PRODUCER = 'kiln-render-service';
+export const RENDER_OPERATIONAL_EVIDENCE_VERSION = 'kiln.render-operational.v1';
+export const RENDER_OUTCOME_CODES = Object.freeze([
+ 'health_ok',
+ 'gpu_success',
+ 'auth_rejected',
+ 'request_rejected',
+ 'not_implemented',
+ 'route_not_found',
+ 'render_failed',
+]);
+export const MAX_VIEW_DIRS = 12;
+export const MAX_CAMERAS = 12;
+export const MIN_CAMERA_DIMENSION = 1;
+export const MAX_CAMERA_DIMENSION = 4096;
+// Includes every camera in the request. This admits one 4K frame, eight 1080p
+// frames, or twelve 720p frames while bounding transient MSAA/depth allocation.
+export const MAX_CAMERA_TOTAL_PIXELS = 16_777_216;
+
+export const DEFAULT_VIEW_DIRS = Object.freeze([
+ Object.freeze([1, 0.35, 1]),
+ Object.freeze([-1, 0.35, 1]),
+ Object.freeze([1, 0.35, -1]),
+ Object.freeze([-1, 0.35, -1]),
+ Object.freeze([0, 1, 0.001]),
+ Object.freeze([0.001, -1, 0.001]),
+]);
+
+function badRequest(message) {
+ return Object.assign(new Error(message), { status: 400 });
+}
+
+function supportedPresetMessage(field) {
+ return SUPPORTED_LIGHTING_PRESET_IDS.length === 1
+ ? `${field} must be ${SUPPORTED_LIGHTING_PRESET_ID}`
+ : `${field} must be one of: ${SUPPORTED_LIGHTING_PRESET_IDS.join(', ')}`;
+}
+
+const RENDER_OUTCOME_CODE_SET = new Set(RENDER_OUTCOME_CODES);
+const MAX_OPERATIONAL_MS = 86_400_000;
+const MAX_OPERATIONAL_QUEUE_DEPTH = 10_000;
+const OPERATIONAL_EVIDENCE_KEYS = new Set([
+ 'outcomeCode',
+ 'queueWaitMs',
+ 'queueDepthAtEnqueue',
+ 'concurrencyAtStart',
+ 'firstRenderInProcess',
+ 'workerAgeMsAtStart',
+]);
+
+/** Stable low-cardinality outcome for structured request logs and metrics extraction. */
+export function httpRenderOutcomeCode({ method, path, status }) {
+ if (status === 401) return 'auth_rejected';
+ if (status === 501) return 'not_implemented';
+ if (status === 404) return 'route_not_found';
+ if (status === 400 || status === 413) return 'request_rejected';
+ if (
+ method === 'GET' &&
+ (path === '/health' || path === '/ping') &&
+ status >= 200 &&
+ status < 300
+ ) {
+ return 'health_ok';
+ }
+ if (method === 'POST' && path === '/render' && status >= 200 && status < 300) {
+ return 'gpu_success';
+ }
+ return 'render_failed';
+}
+
+function nonNegativeFinite(value, path) {
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
+ throw badRequest(`${path} must be a non-negative finite number`);
+ }
+ return value;
+}
+
+/**
+ * Produce the bounded, identifier-free queue/worker envelope consumed by R2.8
+ * metrics extraction. Oversized valid observations are capped rather than
+ * failing a completed render; malformed internal values still fail closed.
+ */
+export function buildRenderOperationalEvidenceV1(input) {
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
+ throw badRequest('render operational evidence must be an object');
+ }
+ for (const key of Object.keys(input)) {
+ if (!OPERATIONAL_EVIDENCE_KEYS.has(key)) throw badRequest(`${key} is unknown`);
+ }
+ if (!RENDER_OUTCOME_CODE_SET.has(input.outcomeCode)) {
+ throw badRequest('outcomeCode is not supported');
+ }
+ const queueWaitMs = nonNegativeFinite(input.queueWaitMs, 'queueWaitMs');
+ const workerAgeMsAtStart = nonNegativeFinite(input.workerAgeMsAtStart, 'workerAgeMsAtStart');
+ if (!Number.isInteger(input.queueDepthAtEnqueue) || input.queueDepthAtEnqueue < 0) {
+ throw badRequest('queueDepthAtEnqueue must be a non-negative integer');
+ }
+ if (input.concurrencyAtStart !== 1) {
+ throw badRequest('concurrencyAtStart must be 1 for the serial GPU queue');
+ }
+ if (typeof input.firstRenderInProcess !== 'boolean') {
+ throw badRequest('firstRenderInProcess must be boolean');
+ }
+
+ const evidenceClamped =
+ queueWaitMs > MAX_OPERATIONAL_MS ||
+ workerAgeMsAtStart > MAX_OPERATIONAL_MS ||
+ input.queueDepthAtEnqueue > MAX_OPERATIONAL_QUEUE_DEPTH;
+ return {
+ version: RENDER_OPERATIONAL_EVIDENCE_VERSION,
+ outcomeCode: input.outcomeCode,
+ queueWaitMs: +Math.min(queueWaitMs, MAX_OPERATIONAL_MS).toFixed(1),
+ queueDepthAtEnqueue: Math.min(input.queueDepthAtEnqueue, MAX_OPERATIONAL_QUEUE_DEPTH),
+ concurrencyAtStart: 1,
+ concurrencyLimit: 1,
+ workerPhase: input.firstRenderInProcess ? 'first-render' : 'warm-render',
+ workerAgeMsAtStart: +Math.min(workerAgeMsAtStart, MAX_OPERATIONAL_MS).toFixed(1),
+ evidenceClamped,
+ };
+}
+
+/** Provider/GPU-free serial queue with explicit start evidence for every job. */
+export function createSerialRenderQueue(options = {}) {
+ const now = options.now ?? (() => performance.now());
+ if (typeof now !== 'function') throw badRequest('serial render queue now must be a function');
+ const processStartedAt = options.processStartedAt ?? now();
+ if (!Number.isFinite(processStartedAt)) {
+ throw badRequest('serial render queue processStartedAt must be finite');
+ }
+
+ let tail = Promise.resolve();
+ let queuedJobs = 0;
+ let activeJobs = 0;
+ let renderJobsStarted = 0;
+ return Object.freeze({
+ enqueue(job) {
+ if (typeof job !== 'function') throw badRequest('serial render queue job must be a function');
+ const enqueuedAt = now();
+ const queueDepthAtEnqueue = activeJobs + queuedJobs;
+ queuedJobs++;
+ const runJob = async () => {
+ queuedJobs--;
+ activeJobs++;
+ const firstRenderInProcess = renderJobsStarted === 0;
+ renderJobsStarted++;
+ const startedAt = now();
+ const start = {
+ queueWaitMs: startedAt - enqueuedAt,
+ queueDepthAtEnqueue,
+ concurrencyAtStart: activeJobs,
+ firstRenderInProcess,
+ workerAgeMsAtStart: startedAt - processStartedAt,
+ };
+ try {
+ return await job(start);
+ } finally {
+ activeJobs--;
+ }
+ };
+ const run = tail.then(runJob, runJob);
+ tail = run.catch(() => {});
+ return run;
+ },
+ });
+}
+
+function finiteTuple3(value, path) {
+ if (!Array.isArray(value) || value.length !== 3 || !value.every(Number.isFinite)) {
+ throw badRequest(`${path} must be [x,y,z] finite numbers`);
+ }
+ return [...value];
+}
+
+function finiteNumber(value, path) {
+ if (!Number.isFinite(value)) throw badRequest(`${path} must be finite`);
+ return value;
+}
+
+function pixelDimension(value, path) {
+ if (!Number.isInteger(value) || value < MIN_CAMERA_DIMENSION || value > MAX_CAMERA_DIMENSION) {
+ throw badRequest(
+ `${path} must be an integer in [${MIN_CAMERA_DIMENSION},${MAX_CAMERA_DIMENSION}]`,
+ );
+ }
+ return value;
+}
+
+/** Legacy direction validation. Returned arrays are cloned; defaults are mutable copies. */
+export function validateViewDirs(views) {
+ if (views === undefined || views === null || (Array.isArray(views) && views.length === 0)) {
+ return DEFAULT_VIEW_DIRS.map((view) => [...view]);
+ }
+ if (!Array.isArray(views)) throw badRequest('views must be an array of [x,y,z] directions');
+ if (views.length > MAX_VIEW_DIRS) {
+ throw badRequest(`views has ${views.length} entries; the maximum is ${MAX_VIEW_DIRS}`);
+ }
+ return views.map((value, index) => {
+ const direction = finiteTuple3(value, `views[${index}]`);
+ if (Math.hypot(...direction) < 1e-9) {
+ throw badRequest(`views[${index}] must not be the zero vector`);
+ }
+ return direction;
+ });
+}
+
+/** Strict camera-mode parser shared by HTTP and direct renderer callers. */
+export function validateCameraMode(input) {
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
+ throw badRequest('camera render options must be an object');
+ }
+ if (
+ !Array.isArray(input.cameras) ||
+ input.cameras.length < 1 ||
+ input.cameras.length > MAX_CAMERAS
+ ) {
+ throw badRequest(`cameras must contain 1..${MAX_CAMERAS} entries`);
+ }
+ const width = pixelDimension(input.width, 'width');
+ const height = pixelDimension(input.height, 'height');
+ const totalPixels = width * height * input.cameras.length;
+ if (!Number.isSafeInteger(totalPixels) || totalPixels > MAX_CAMERA_TOTAL_PIXELS) {
+ throw badRequest(
+ `camera request has ${totalPixels} total pixels; maximum is ${MAX_CAMERA_TOTAL_PIXELS}`,
+ );
+ }
+ const targetAspect = width / height;
+ const cameras = input.cameras.map((value, index) => {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw badRequest(`cameras[${index}] must be an object`);
+ }
+ const allowed = new Set([
+ 'position',
+ 'target',
+ 'up',
+ 'fovDeg',
+ 'aspect',
+ 'near',
+ 'far',
+ 'version',
+ 'projection',
+ 'halfHeight',
+ ]);
+ for (const key of Object.keys(value)) {
+ if (!allowed.has(key)) throw badRequest(`cameras[${index}].${key} is unknown`);
+ }
+ const position = finiteTuple3(value.position, `cameras[${index}].position`);
+ const target = finiteTuple3(value.target, `cameras[${index}].target`);
+ const up = finiteTuple3(value.up, `cameras[${index}].up`);
+ const view = target.map((component, axis) => component - position[axis]);
+ const viewLength = Math.hypot(...view);
+ const upLength = Math.hypot(...up);
+ if (viewLength < 1e-9) throw badRequest(`cameras[${index}].target must differ from position`);
+ if (upLength < 1e-9) throw badRequest(`cameras[${index}].up must be non-zero`);
+ const cross = [
+ view[1] * up[2] - view[2] * up[1],
+ view[2] * up[0] - view[0] * up[2],
+ view[0] * up[1] - view[1] * up[0],
+ ];
+ if (Math.hypot(...cross) <= viewLength * upLength * 1e-9) {
+ throw badRequest(`cameras[${index}].up must not be collinear with view`);
+ }
+ const versioned = value.version !== undefined || value.projection !== undefined;
+ if (
+ versioned &&
+ (value.version !== 'kiln.camera.v1' ||
+ !['orthographic', 'perspective'].includes(value.projection))
+ )
+ throw badRequest('invalid versioned camera');
+ const orthographic = value.projection === 'orthographic';
+ if (orthographic && value.fovDeg !== undefined)
+ throw badRequest('orthographic camera cannot use fovDeg');
+ if (!orthographic && value.halfHeight !== undefined)
+ throw badRequest('perspective camera cannot use halfHeight');
+ const halfHeight = orthographic
+ ? finiteNumber(value.halfHeight, `cameras[${index}].halfHeight`)
+ : undefined;
+ if (orthographic && halfHeight <= 0) throw badRequest('halfHeight must be positive');
+ const fovDeg = orthographic
+ ? undefined
+ : finiteNumber(value.fovDeg, `cameras[${index}].fovDeg`);
+ const aspect = finiteNumber(value.aspect, `cameras[${index}].aspect`);
+ const near = finiteNumber(value.near, `cameras[${index}].near`);
+ const far = finiteNumber(value.far, `cameras[${index}].far`);
+ if (!orthographic && (fovDeg <= 0 || fovDeg >= 180)) {
+ throw badRequest(`cameras[${index}].fovDeg must be in (0,180)`);
+ }
+ if (aspect <= 0) throw badRequest(`cameras[${index}].aspect must be positive`);
+ if (near <= 0) throw badRequest(`cameras[${index}].near must be positive`);
+ if (far <= near) throw badRequest(`cameras[${index}].far must exceed near`);
+ if (Math.abs(aspect - targetAspect) > Math.max(1, targetAspect) * 1e-9) {
+ throw badRequest(`cameras[${index}].aspect must equal width/height`);
+ }
+ return {
+ position,
+ target,
+ up,
+ ...(orthographic ? { halfHeight } : { fovDeg }),
+ aspect,
+ near,
+ far,
+ ...(versioned ? { version: value.version, projection: value.projection } : {}),
+ };
+ });
+ const lightingPresetId =
+ input.lightingPresetId === undefined ? SUPPORTED_LIGHTING_PRESET_ID : input.lightingPresetId;
+ if (!isPresentationPresetId(lightingPresetId)) {
+ throw badRequest(supportedPresetMessage('lighting_preset_id'));
+ }
+ return { cameras, width, height, lightingPresetId, totalPixels };
+}
+
+/** Parse only render-mode fields; GLB/auth/body-size validation remains in the server. */
+export function validateRenderMode(body) {
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
+ throw badRequest('render body must be an object');
+ }
+ if (body.cameras !== undefined) {
+ if (body.views !== undefined || body.size !== undefined || body.beauty_size !== undefined) {
+ throw badRequest('camera mode is mutually exclusive with views, size, and beauty_size');
+ }
+ if (body.background !== undefined) {
+ throw badRequest('camera mode cannot override the neutral-studio-v1 background');
+ }
+ const allowed = new Set([
+ 'glb_base64',
+ 'input_glb_sha256',
+ 'cameras',
+ 'width',
+ 'height',
+ 'lighting_preset_id',
+ ]);
+ for (const key of Object.keys(body)) {
+ if (body[key] !== undefined && !allowed.has(key)) {
+ throw badRequest(`camera mode field ${key} is unknown`);
+ }
+ }
+ const camera = validateCameraMode({
+ cameras: body.cameras,
+ width: body.width,
+ height: body.height,
+ lightingPresetId: body.lighting_preset_id,
+ });
+ return { mode: 'camera', ...camera };
+ }
+ if (
+ body.width !== undefined ||
+ body.height !== undefined ||
+ body.lighting_preset_id !== undefined
+ ) {
+ throw badRequest('width, height, and lighting_preset_id require cameras');
+ }
+ return {
+ mode: 'legacy',
+ viewDirs: validateViewDirs(body.views),
+ size: body.size,
+ beautySize: body.beauty_size,
+ background: body.background,
+ };
+}
+
+export function sha256(bytes) {
+ return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
+}
+
+const SHA256_IDENTITY_RE = /^sha256:[0-9a-f]{64}$/;
+
+/**
+ * Compute the identity of the exact GLB bytes the renderer will consume. A new
+ * caller may also assert its expected identity; legacy callers omit the claim
+ * and still receive the computed identity in the response.
+ */
+export function validateInputGlbIdentity(bytes, claimedIdentity) {
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) {
+ throw badRequest('GLB identity requires non-empty bytes');
+ }
+ const actual = sha256(bytes);
+ if (claimedIdentity === undefined) return actual;
+ if (typeof claimedIdentity !== 'string' || !SHA256_IDENTITY_RE.test(claimedIdentity)) {
+ throw badRequest('input_glb_sha256 must be sha256:<64 lowercase hex characters>');
+ }
+ if (claimedIdentity !== actual) {
+ throw badRequest('input_glb_sha256 does not match glb_base64 bytes');
+ }
+ return actual;
+}
+
+const FIDELITY_TIMING_KEYS = new Set([
+ 'loadMs',
+ 'viewsMs',
+ 'beautyMs',
+ 'totalMs',
+ 'queueWaitMs',
+ 'queueAndTotalMs',
+]);
+
+function cloneCamera(camera) {
+ return {
+ position: [...camera.position],
+ target: [...camera.target],
+ up: [...camera.up],
+ ...(camera.projection === 'orthographic'
+ ? { halfHeight: camera.halfHeight }
+ : { fovDeg: camera.fovDeg }),
+ aspect: camera.aspect,
+ near: camera.near,
+ far: camera.far,
+ ...(camera.version ? { version: camera.version, projection: camera.projection } : {}),
+ };
+}
+
+/**
+ * Mint the additive renderer-side fidelity receipt only after all identity and
+ * camera/profile claims have been checked against the request and actual result.
+ *
+ * `exactArtifact` is deliberately false: this service attests the exact GLB
+ * bytes it rendered, but only the caller knows whether those bytes are the
+ * persisted/final artifact rather than an in-loop or derivative GLB.
+ */
+export function buildRenderFidelityV1({
+ rendererId,
+ inputGlbSha256,
+ presentationProfile,
+ renderMode,
+ resolvedCameras,
+ timings,
+}) {
+ if (
+ typeof rendererId !== 'string' ||
+ rendererId.trim() !== rendererId ||
+ rendererId.length < 1 ||
+ rendererId.length > 160
+ ) {
+ throw badRequest('rendererId must be a non-empty string of at most 160 characters');
+ }
+ if (typeof inputGlbSha256 !== 'string' || !SHA256_IDENTITY_RE.test(inputGlbSha256)) {
+ throw badRequest('inputGlbSha256 must be sha256:<64 lowercase hex characters>');
+ }
+ if (!isPresentationPresetId(presentationProfile)) {
+ throw badRequest(supportedPresetMessage('presentationProfile'));
+ }
+ if (!renderMode || (renderMode.mode !== 'camera' && renderMode.mode !== 'legacy')) {
+ throw badRequest('renderMode must be a validated camera or legacy render mode');
+ }
+ if (!Array.isArray(resolvedCameras)) {
+ throw badRequest('resolvedCameras must be an array');
+ }
+
+ const requestedCameras = renderMode.mode === 'camera' ? renderMode.cameras.map(cloneCamera) : [];
+ if (
+ resolvedCameras.length !== requestedCameras.length ||
+ JSON.stringify(resolvedCameras) !== JSON.stringify(requestedCameras)
+ ) {
+ throw badRequest('resolved cameras do not match the validated requested cameras');
+ }
+
+ if (!timings || typeof timings !== 'object' || Array.isArray(timings)) {
+ throw badRequest('timings must be an object');
+ }
+ const checkedTimings = {};
+ for (const [key, value] of Object.entries(timings)) {
+ if (!FIDELITY_TIMING_KEYS.has(key)) throw badRequest(`timings.${key} is unknown`);
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
+ throw badRequest(`timings.${key} must be a non-negative finite number`);
+ }
+ checkedTimings[key] = value;
+ }
+ if (checkedTimings.totalMs === undefined || checkedTimings.queueAndTotalMs === undefined) {
+ throw badRequest('timings must include totalMs and queueAndTotalMs');
+ }
+ if (checkedTimings.queueAndTotalMs < checkedTimings.totalMs) {
+ throw badRequest('timings.queueAndTotalMs must be at least totalMs');
+ }
+ if (
+ checkedTimings.queueWaitMs !== undefined &&
+ checkedTimings.queueWaitMs > checkedTimings.queueAndTotalMs
+ ) {
+ throw badRequest('timings.queueWaitMs must not exceed queueAndTotalMs');
+ }
+
+ return {
+ version: RENDER_FIDELITY_VERSION,
+ producer: RENDER_FIDELITY_PRODUCER,
+ requested: 'full-preferred',
+ delivered: 'full-material',
+ materialFaithful: true,
+ exactArtifact: false,
+ rendererId,
+ inputGlbSha256,
+ degraded: false,
+ presentationProfile,
+ renderMode: renderMode.mode,
+ requestedCameras,
+ resolvedCameras: resolvedCameras.map(cloneCamera),
+ timings: checkedTimings,
+ };
+}
+
+/** Canonical identity of an ordered output set; it is not a composite-image hash. */
+export function outputSetSha256(outputs) {
+ const hash = createHash('sha256');
+ hash.update('kiln-render-output-set-v1\0');
+ for (const output of outputs) {
+ const size = Buffer.allocUnsafe(4);
+ size.writeUInt32BE(output.byteLength);
+ hash.update(size);
+ hash.update(output);
+ }
+ return `sha256:${hash.digest('hex')}`;
+}
diff --git a/render-service/src/display-output.mjs b/render-service/src/display-output.mjs
index 943d8bec..8c2f7c6d 100644
--- a/render-service/src/display-output.mjs
+++ b/render-service/src/display-output.mjs
@@ -15,4 +15,4 @@ export function renderDisplayTarget(renderer, scene, camera, target) {
renderer.setRenderTarget(previousTarget);
renderer.setOutputRenderTarget(previousOutput);
}
-}
+}
diff --git a/render-service/src/framing.mjs b/render-service/src/framing.mjs
index dcb8b10c..8eb33412 100644
--- a/render-service/src/framing.mjs
+++ b/render-service/src/framing.mjs
@@ -23,15 +23,24 @@ const MARGIN = 1 / 0.9;
/** Perspective beauty framing around a world-space bounding sphere. */
export function beautyCameraSpec(center, radius) {
- if (!Array.isArray(center) || center.length !== 3 || !center.every(Number.isFinite)
- || !Number.isFinite(radius) || radius <= 0) throw new Error('Invalid beauty bounds');
+ if (
+ !Array.isArray(center) ||
+ center.length !== 3 ||
+ !center.every(Number.isFinite) ||
+ !Number.isFinite(radius) ||
+ radius <= 0
+ )
+ throw new Error('Invalid beauty bounds');
const fovDeg = 35;
- const distance = radius / Math.sin(fovDeg * Math.PI / 360) * 1.08;
+ const distance = (radius / Math.sin((fovDeg * Math.PI) / 360)) * 1.08;
const length = Math.hypot(1, 0.65, 1);
return {
projection: 'perspective',
- position: center.map((value, i) => value + [1, 0.65, 1][i] / length * distance),
- target: [...center], up: [0, 1, 0], fovDeg, aspect: 1,
+ position: center.map((value, i) => value + ([1, 0.65, 1][i] / length) * distance),
+ target: [...center],
+ up: [0, 1, 0],
+ fovDeg,
+ aspect: 1,
near: Math.max(radius * 0.001, distance - radius * 1.5),
far: distance + radius * 2,
};
@@ -99,8 +108,7 @@ export function orthoHalfExtent(min, max, dir) {
* it.
*/
export function orthoDepth(min, max, half) {
- const halfDiag =
- Math.hypot(max[0] - min[0], max[1] - min[1], max[2] - min[2]) / 2 + 1e-3;
+ const halfDiag = Math.hypot(max[0] - min[0], max[1] - min[1], max[2] - min[2]) / 2 + 1e-3;
const distance = halfDiag + half * 2 + 1;
return { distance, far: distance + halfDiag + 1 };
}
diff --git a/render-service/src/gpu.mjs b/render-service/src/gpu.mjs
index 4116fcf2..64ee1102 100644
--- a/render-service/src/gpu.mjs
+++ b/render-service/src/gpu.mjs
@@ -56,15 +56,22 @@ export async function acquireGpu({ allowSoftware = false } = {}) {
try {
Object.defineProperty(globalThis, 'navigator', { value: { gpu }, configurable: true });
} catch {
- try { Object.defineProperty(globalThis.navigator, 'gpu', { value: gpu, configurable: true }); } catch { /* three gets device directly */ }
+ try {
+ Object.defineProperty(globalThis.navigator, 'gpu', { value: gpu, configurable: true });
+ } catch {
+ /* three gets device directly */
+ }
}
const adapter = await gpu.requestAdapter({ powerPreference: 'high-performance' });
- if (!adapter) throw new Error('no WebGPU adapter: no usable Vulkan/D3D12/Metal device visible to Dawn');
+ if (!adapter)
+ throw new Error('no WebGPU adapter: no usable Vulkan/D3D12/Metal device visible to Dawn');
const software = isSoftwareAdapter(adapter);
if (software && !allowSoftware) {
const { description } = adapterSummary(adapter);
- throw new Error(`software adapter refused (fail closed): ${description}. ` +
- 'On Linux this usually means the NVIDIA Vulkan ICD failed to init - check GLVND libs (libegl1/libgl1/libglvnd0).');
+ throw new Error(
+ `software adapter refused (fail closed): ${description}. ` +
+ 'On Linux this usually means the NVIDIA Vulkan ICD failed to init - check GLVND libs (libegl1/libgl1/libglvnd0).',
+ );
}
const device = await adapter.requestDevice({
requiredFeatures: [...adapter.features],
@@ -75,16 +82,20 @@ export async function acquireGpu({ allowSoftware = false } = {}) {
process.once('beforeExit', markGpuShutdown);
device.lost.then((info) => {
if (!shouldExitOnDeviceLost(info)) return;
- console.error(JSON.stringify({
- evt: 'device_lost',
- reason: info?.reason ?? 'unknown',
- message: info?.message ?? '',
- }));
+ console.error(
+ JSON.stringify({
+ evt: 'device_lost',
+ reason: info?.reason ?? 'unknown',
+ message: info?.message ?? '',
+ }),
+ );
process.exit(1);
});
const summary = adapterSummary(adapter);
- const backend = process.platform === 'win32' ? 'd3d12' : process.platform === 'darwin' ? 'metal' : 'vulkan';
- const rendererId = `dawn-${backend}:${summary.device || summary.vendor}:${summary.description}`.slice(0, 160);
+ const backend =
+ process.platform === 'win32' ? 'd3d12' : process.platform === 'darwin' ? 'metal' : 'vulkan';
+ const rendererId =
+ `dawn-${backend}:${summary.device || summary.vendor}:${summary.description}`.slice(0, 160);
state = { gpu, adapter, device, summary, software, backend, rendererId };
return state;
}
diff --git a/render-service/src/health-contract.mjs b/render-service/src/health-contract.mjs
index 16492797..f86de311 100644
--- a/render-service/src/health-contract.mjs
+++ b/render-service/src/health-contract.mjs
@@ -1,33 +1,33 @@
-import {
- DEFAULT_PRESENTATION_PRESET_ID,
- PRESENTATION_PRESET_CAPABILITIES,
- PRESENTATION_PRESET_IDS,
-} from './presentation-presets.mjs';
-
-/** Provider-free health contract shared by the HTTP route and unit tests. */
-export const RENDER_CAPABILITIES = Object.freeze([
- 'render.views',
- 'render.views.checked',
- 'render.cameras.perspective-v1',
- 'render.targets.rectangular-v1',
- 'render.outputs.sha256-v1',
- 'render.fidelity.v1',
- 'render.operational-evidence.v1',
- ...PRESENTATION_PRESET_CAPABILITIES,
- 'render.beauty',
- 'auth.x-render-token',
-]);
-
-export function buildHealthDocument(gpuState, authRequired) {
- return {
- ok: true,
- ...(gpuState.captureIdentity?{captureIdentity:gpuState.captureIdentity}:{}),
- rendererId: gpuState.rendererId,
- backend: gpuState.backend,
- adapter: gpuState.summary,
- capabilities: RENDER_CAPABILITIES,
- presentationProfile: DEFAULT_PRESENTATION_PRESET_ID,
- lightingPresetIds: [...PRESENTATION_PRESET_IDS],
- authRequired: Boolean(authRequired),
- };
-}
+import {
+ DEFAULT_PRESENTATION_PRESET_ID,
+ PRESENTATION_PRESET_CAPABILITIES,
+ PRESENTATION_PRESET_IDS,
+} from './presentation-presets.mjs';
+
+/** Provider-free health contract shared by the HTTP route and unit tests. */
+export const RENDER_CAPABILITIES = Object.freeze([
+ 'render.views',
+ 'render.views.checked',
+ 'render.cameras.perspective-v1',
+ 'render.targets.rectangular-v1',
+ 'render.outputs.sha256-v1',
+ 'render.fidelity.v1',
+ 'render.operational-evidence.v1',
+ ...PRESENTATION_PRESET_CAPABILITIES,
+ 'render.beauty',
+ 'auth.x-render-token',
+]);
+
+export function buildHealthDocument(gpuState, authRequired) {
+ return {
+ ok: true,
+ ...(gpuState.captureIdentity ? { captureIdentity: gpuState.captureIdentity } : {}),
+ rendererId: gpuState.rendererId,
+ backend: gpuState.backend,
+ adapter: gpuState.summary,
+ capabilities: RENDER_CAPABILITIES,
+ presentationProfile: DEFAULT_PRESENTATION_PRESET_ID,
+ lightingPresetIds: [...PRESENTATION_PRESET_IDS],
+ authRequired: Boolean(authRequired),
+ };
+}
diff --git a/render-service/src/presentation-presets.mjs b/render-service/src/presentation-presets.mjs
index 74fe7677..fec67bec 100644
--- a/render-service/src/presentation-presets.mjs
+++ b/render-service/src/presentation-presets.mjs
@@ -1,146 +1,193 @@
-// Renderer-owned, versioned presentation definitions. Requests select an ID;
-// no caller-controlled light/color/exposure object crosses the HTTP boundary.
-
-const PRESET_KEYS = Object.freeze([
- 'id', 'environment', 'background', 'exposure', 'ambient',
- 'sun', 'key', 'fill', 'rim', 'shadows',
-]);
-const ACTIVE_DIRECTIONAL_KEYS = Object.freeze([
- 'enabled', 'color', 'intensity', 'position', 'castsShadow',
-]);
-const DISABLED_DIRECTIONAL_KEYS = Object.freeze(['enabled']);
-
-function exactKeys(value, expected, path) {
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
- throw new TypeError(`${path} must be an object`);
- }
- const actual = Object.keys(value).sort();
- const wanted = [...expected].sort();
- if (JSON.stringify(actual) !== JSON.stringify(wanted)) {
- throw new TypeError(`${path} keys must be exactly ${wanted.join(', ')}`);
- }
-}
-
-function finite(value, path, { minimum = -Infinity } = {}) {
- if (!Number.isFinite(value) || value < minimum) throw new TypeError(`${path} must be finite >= ${minimum}`);
-}
-
-function color(value, path) {
- if (!Number.isInteger(value) || value < 0 || value > 0xffffff) {
- throw new TypeError(`${path} must be a 24-bit color integer`);
- }
-}
-
-function tuple(value, length, path, validate) {
- if (!Array.isArray(value) || value.length !== length) throw new TypeError(`${path} must have ${length} entries`);
- value.forEach((entry, index) => validate(entry, `${path}[${index}]`));
-}
-
-function validateDirectional(value, path) {
- exactKeys(value, value?.enabled === false ? DISABLED_DIRECTIONAL_KEYS : ACTIVE_DIRECTIONAL_KEYS, path);
- if (typeof value.enabled !== 'boolean') throw new TypeError(`${path}.enabled must be boolean`);
- if (!value.enabled) return;
- color(value.color, `${path}.color`);
- finite(value.intensity, `${path}.intensity`, { minimum: 0 });
- tuple(value.position, 3, `${path}.position`, finite);
- if (typeof value.castsShadow !== 'boolean') throw new TypeError(`${path}.castsShadow must be boolean`);
-}
-
-/**
- * The shadow filters that exist, as preset-facing names.
- *
- * `pcf-soft` was here until r186 deleted the PCFSoft implementation. three kept the
- * constant, warns on it, and substitutes PCFShadowMap -- so a preset naming it was
- * asking for a filter that no longer exists and quietly receiving a different one.
- * These three survive, and `renderer.mjs` maps each to its three constant, which is
- * what makes this field select a filter rather than describe one. `vsm` is the soft
- * option now, with one behavioural catch worth knowing before choosing it: under VSM
- * every shadow receiver also casts, so a ground plane starts casting too.
- */
-export const SHADOW_FILTERS = Object.freeze(['basic', 'pcf', 'vsm']);
-
-function validatePreset(preset) {
- exactKeys(preset, PRESET_KEYS, 'presentation preset');
- if (!/^[a-z0-9]+(?:-[a-z0-9]+)*-v[1-9][0-9]*$/.test(preset.id)) {
- throw new TypeError('presentation preset id must end in a positive version');
- }
- exactKeys(preset.environment, ['type', 'sigma'], `${preset.id}.environment`);
- if (preset.environment.type !== 'room') throw new TypeError(`${preset.id}.environment.type must be room`);
- finite(preset.environment.sigma, `${preset.id}.environment.sigma`, { minimum: 0 });
- if (!/^#[0-9a-f]{6}$/.test(preset.background)) {
- throw new TypeError(`${preset.id}.background must be lowercase #rrggbb`);
- }
- finite(preset.exposure, `${preset.id}.exposure`, { minimum: 0 });
- exactKeys(preset.ambient, ['type', 'sky', 'ground', 'intensity'], `${preset.id}.ambient`);
- if (preset.ambient.type !== 'hemisphere') throw new TypeError(`${preset.id}.ambient.type must be hemisphere`);
- color(preset.ambient.sky, `${preset.id}.ambient.sky`);
- color(preset.ambient.ground, `${preset.id}.ambient.ground`);
- finite(preset.ambient.intensity, `${preset.id}.ambient.intensity`, { minimum: 0 });
- for (const role of ['sun', 'key', 'fill', 'rim']) validateDirectional(preset[role], `${preset.id}.${role}`);
- exactKeys(
- preset.shadows,
- ['enabled', 'type', 'mapSize', 'bias', 'normalBias', 'radius'],
- `${preset.id}.shadows`,
- );
- if (typeof preset.shadows.enabled !== 'boolean') throw new TypeError(`${preset.id}.shadows.enabled must be boolean`);
- if (!SHADOW_FILTERS.includes(preset.shadows.type))
- throw new TypeError(`${preset.id}.shadows.type must be one of ${SHADOW_FILTERS.join(', ')}`);
- tuple(preset.shadows.mapSize, 2, `${preset.id}.shadows.mapSize`, (entry, path) => {
- if (!Number.isInteger(entry) || entry < 1 || entry > 8192) throw new TypeError(`${path} must be an integer in [1,8192]`);
- });
- finite(preset.shadows.bias, `${preset.id}.shadows.bias`);
- finite(preset.shadows.normalBias, `${preset.id}.shadows.normalBias`, { minimum: 0 });
- finite(preset.shadows.radius, `${preset.id}.shadows.radius`, { minimum: 0 });
- return preset;
-}
-
-function deepFreeze(value) {
- if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
- for (const child of Object.values(value)) deepFreeze(child);
- return Object.freeze(value);
-}
-
-const definitions = [
- validatePreset({
- id: 'neutral-studio-v1',
- environment: { type: 'room', sigma: 0.04 },
- background: '#aab1bc',
- exposure: 1.38,
- ambient: { type: 'hemisphere', sky: 0xffffff, ground: 0x6f7888, intensity: 2 },
- // The v1 studio rig has no separate sun. Retaining this explicit disabled
- // role lets future world-oriented IDs add one without changing the schema.
- sun: { enabled: false },
- key: { enabled: true, color: 0xffffff, intensity: 3, position: [4, 7, 5], castsShadow: false },
- fill: { enabled: true, color: 0xdce8ff, intensity: 1.8, position: [-4, 3, 2], castsShadow: false },
- rim: { enabled: true, color: 0xffead6, intensity: 1.2, position: [-2, 5, -5], castsShadow: false },
- // These are the WebGPU/three.js controls the renderer knows how to apply.
- // Disabled preserves the exact pre-registry v1 visual behavior.
- shadows: {
- enabled: false,
- type: 'pcf',
- mapSize: [1024, 1024],
- bias: 0,
- normalBias: 0,
- radius: 1,
- },
- }),
-];
-
-// Gallery photography uses a lower exposure without changing the default tool rig.
-definitions.push(validatePreset({ ...definitions[0], id: 'gallery-studio-v1', exposure: 0.9, background: '#747474' }));
-
-for (const definition of definitions) deepFreeze(definition);
-export const PRESENTATION_PRESET_IDS = Object.freeze(definitions.map(({ id }) => id));
-export const DEFAULT_PRESENTATION_PRESET_ID = PRESENTATION_PRESET_IDS[0];
-export const PRESENTATION_PRESET_CAPABILITIES = Object.freeze(
- PRESENTATION_PRESET_IDS.map((id) => `render.profile.${id}`),
-);
-const registry = Object.freeze(Object.fromEntries(definitions.map((preset) => [preset.id, preset])));
-
-export function isPresentationPresetId(id) {
- return typeof id === 'string' && Object.hasOwn(registry, id);
-}
-
-export function getPresentationPreset(id) {
- return isPresentationPresetId(id) ? registry[id] : undefined;
-}
+// Renderer-owned, versioned presentation definitions. Requests select an ID;
+// no caller-controlled light/color/exposure object crosses the HTTP boundary.
+
+const PRESET_KEYS = Object.freeze([
+ 'id',
+ 'environment',
+ 'background',
+ 'exposure',
+ 'ambient',
+ 'sun',
+ 'key',
+ 'fill',
+ 'rim',
+ 'shadows',
+]);
+const ACTIVE_DIRECTIONAL_KEYS = Object.freeze([
+ 'enabled',
+ 'color',
+ 'intensity',
+ 'position',
+ 'castsShadow',
+]);
+const DISABLED_DIRECTIONAL_KEYS = Object.freeze(['enabled']);
+
+function exactKeys(value, expected, path) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw new TypeError(`${path} must be an object`);
+ }
+ const actual = Object.keys(value).sort();
+ const wanted = [...expected].sort();
+ if (JSON.stringify(actual) !== JSON.stringify(wanted)) {
+ throw new TypeError(`${path} keys must be exactly ${wanted.join(', ')}`);
+ }
+}
+
+function finite(value, path, { minimum = -Infinity } = {}) {
+ if (!Number.isFinite(value) || value < minimum)
+ throw new TypeError(`${path} must be finite >= ${minimum}`);
+}
+
+function color(value, path) {
+ if (!Number.isInteger(value) || value < 0 || value > 0xffffff) {
+ throw new TypeError(`${path} must be a 24-bit color integer`);
+ }
+}
+
+function tuple(value, length, path, validate) {
+ if (!Array.isArray(value) || value.length !== length)
+ throw new TypeError(`${path} must have ${length} entries`);
+ value.forEach((entry, index) => {
+ validate(entry, `${path}[${index}]`);
+ });
+}
+
+function validateDirectional(value, path) {
+ exactKeys(
+ value,
+ value?.enabled === false ? DISABLED_DIRECTIONAL_KEYS : ACTIVE_DIRECTIONAL_KEYS,
+ path,
+ );
+ if (typeof value.enabled !== 'boolean') throw new TypeError(`${path}.enabled must be boolean`);
+ if (!value.enabled) return;
+ color(value.color, `${path}.color`);
+ finite(value.intensity, `${path}.intensity`, { minimum: 0 });
+ tuple(value.position, 3, `${path}.position`, finite);
+ if (typeof value.castsShadow !== 'boolean')
+ throw new TypeError(`${path}.castsShadow must be boolean`);
+}
+
+/**
+ * The shadow filters that exist, as preset-facing names.
+ *
+ * `pcf-soft` was here until r186 deleted the PCFSoft implementation. three kept the
+ * constant, warns on it, and substitutes PCFShadowMap -- so a preset naming it was
+ * asking for a filter that no longer exists and quietly receiving a different one.
+ * These three survive, and `renderer.mjs` maps each to its three constant, which is
+ * what makes this field select a filter rather than describe one. `vsm` is the soft
+ * option now, with one behavioural catch worth knowing before choosing it: under VSM
+ * every shadow receiver also casts, so a ground plane starts casting too.
+ */
+export const SHADOW_FILTERS = Object.freeze(['basic', 'pcf', 'vsm']);
+
+function validatePreset(preset) {
+ exactKeys(preset, PRESET_KEYS, 'presentation preset');
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*-v[1-9][0-9]*$/.test(preset.id)) {
+ throw new TypeError('presentation preset id must end in a positive version');
+ }
+ exactKeys(preset.environment, ['type', 'sigma'], `${preset.id}.environment`);
+ if (preset.environment.type !== 'room')
+ throw new TypeError(`${preset.id}.environment.type must be room`);
+ finite(preset.environment.sigma, `${preset.id}.environment.sigma`, { minimum: 0 });
+ if (!/^#[0-9a-f]{6}$/.test(preset.background)) {
+ throw new TypeError(`${preset.id}.background must be lowercase #rrggbb`);
+ }
+ finite(preset.exposure, `${preset.id}.exposure`, { minimum: 0 });
+ exactKeys(preset.ambient, ['type', 'sky', 'ground', 'intensity'], `${preset.id}.ambient`);
+ if (preset.ambient.type !== 'hemisphere')
+ throw new TypeError(`${preset.id}.ambient.type must be hemisphere`);
+ color(preset.ambient.sky, `${preset.id}.ambient.sky`);
+ color(preset.ambient.ground, `${preset.id}.ambient.ground`);
+ finite(preset.ambient.intensity, `${preset.id}.ambient.intensity`, { minimum: 0 });
+ for (const role of ['sun', 'key', 'fill', 'rim'])
+ validateDirectional(preset[role], `${preset.id}.${role}`);
+ exactKeys(
+ preset.shadows,
+ ['enabled', 'type', 'mapSize', 'bias', 'normalBias', 'radius'],
+ `${preset.id}.shadows`,
+ );
+ if (typeof preset.shadows.enabled !== 'boolean')
+ throw new TypeError(`${preset.id}.shadows.enabled must be boolean`);
+ if (!SHADOW_FILTERS.includes(preset.shadows.type))
+ throw new TypeError(`${preset.id}.shadows.type must be one of ${SHADOW_FILTERS.join(', ')}`);
+ tuple(preset.shadows.mapSize, 2, `${preset.id}.shadows.mapSize`, (entry, path) => {
+ if (!Number.isInteger(entry) || entry < 1 || entry > 8192)
+ throw new TypeError(`${path} must be an integer in [1,8192]`);
+ });
+ finite(preset.shadows.bias, `${preset.id}.shadows.bias`);
+ finite(preset.shadows.normalBias, `${preset.id}.shadows.normalBias`, { minimum: 0 });
+ finite(preset.shadows.radius, `${preset.id}.shadows.radius`, { minimum: 0 });
+ return preset;
+}
+
+function deepFreeze(value) {
+ if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
+ for (const child of Object.values(value)) deepFreeze(child);
+ return Object.freeze(value);
+}
+
+const definitions = [
+ validatePreset({
+ id: 'neutral-studio-v1',
+ environment: { type: 'room', sigma: 0.04 },
+ background: '#aab1bc',
+ exposure: 1.38,
+ ambient: { type: 'hemisphere', sky: 0xffffff, ground: 0x6f7888, intensity: 2 },
+ // The v1 studio rig has no separate sun. Retaining this explicit disabled
+ // role lets future world-oriented IDs add one without changing the schema.
+ sun: { enabled: false },
+ key: { enabled: true, color: 0xffffff, intensity: 3, position: [4, 7, 5], castsShadow: false },
+ fill: {
+ enabled: true,
+ color: 0xdce8ff,
+ intensity: 1.8,
+ position: [-4, 3, 2],
+ castsShadow: false,
+ },
+ rim: {
+ enabled: true,
+ color: 0xffead6,
+ intensity: 1.2,
+ position: [-2, 5, -5],
+ castsShadow: false,
+ },
+ // These are the WebGPU/three.js controls the renderer knows how to apply.
+ // Disabled preserves the exact pre-registry v1 visual behavior.
+ shadows: {
+ enabled: false,
+ type: 'pcf',
+ mapSize: [1024, 1024],
+ bias: 0,
+ normalBias: 0,
+ radius: 1,
+ },
+ }),
+];
+
+// Gallery photography uses a lower exposure without changing the default tool rig.
+definitions.push(
+ validatePreset({
+ ...definitions[0],
+ id: 'gallery-studio-v1',
+ exposure: 0.9,
+ background: '#747474',
+ }),
+);
+
+for (const definition of definitions) deepFreeze(definition);
+export const PRESENTATION_PRESET_IDS = Object.freeze(definitions.map(({ id }) => id));
+export const DEFAULT_PRESENTATION_PRESET_ID = PRESENTATION_PRESET_IDS[0];
+export const PRESENTATION_PRESET_CAPABILITIES = Object.freeze(
+ PRESENTATION_PRESET_IDS.map((id) => `render.profile.${id}`),
+);
+const registry = Object.freeze(
+ Object.fromEntries(definitions.map((preset) => [preset.id, preset])),
+);
+
+export function isPresentationPresetId(id) {
+ return typeof id === 'string' && Object.hasOwn(registry, id);
+}
+
+export function getPresentationPreset(id) {
+ return isPresentationPresetId(id) ? registry[id] : undefined;
+}
diff --git a/render-service/src/readback.mjs b/render-service/src/readback.mjs
index cc8040a1..e83bf90d 100644
--- a/render-service/src/readback.mjs
+++ b/render-service/src/readback.mjs
@@ -1,11 +1,16 @@
/** Three/WebGPU returns 256-byte-aligned rows, without trailing padding on the final row. */
-export function packRgbaReadback(pixels,width,height){
- if(!Number.isSafeInteger(width)||!Number.isSafeInteger(height)||width<1||height<1)throw new Error('invalid readback dimensions');
- const rowBytes=width*4,packedBytes=rowBytes*height,stride=Math.ceil(rowBytes/256)*256;
- const input=Buffer.from(pixels.buffer,pixels.byteOffset,pixels.byteLength);
- if(input.length===packedBytes)return Buffer.from(input);
- if(input.length!==(height-1)*stride+rowBytes&&input.length!==height*stride)throw new Error('unexpected GPU readback byte length');
- const output=Buffer.allocUnsafe(packedBytes);
- for(let row=0;row<height;row++)input.copy(output,row*rowBytes,row*stride,row*stride+rowBytes);
+export function packRgbaReadback(pixels, width, height) {
+ if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1)
+ throw new Error('invalid readback dimensions');
+ const rowBytes = width * 4,
+ packedBytes = rowBytes * height,
+ stride = Math.ceil(rowBytes / 256) * 256;
+ const input = Buffer.from(pixels.buffer, pixels.byteOffset, pixels.byteLength);
+ if (input.length === packedBytes) return Buffer.from(input);
+ if (input.length !== (height - 1) * stride + rowBytes && input.length !== height * stride)
+ throw new Error('unexpected GPU readback byte length');
+ const output = Buffer.allocUnsafe(packedBytes);
+ for (let row = 0; row < height; row++)
+ input.copy(output, row * rowBytes, row * stride, row * stride + rowBytes);
return output;
-}
+}
diff --git a/render-service/src/renderer.mjs b/render-service/src/renderer.mjs
index 8c7657a3..8d2b71ad 100644
--- a/render-service/src/renderer.mjs
+++ b/render-service/src/renderer.mjs
@@ -1,399 +1,455 @@
-import {renderDisplayTarget} from './display-output.mjs';
-import {packRgbaReadback} from './readback.mjs';
-// GLB bytes -> PBR PNG views. Headless three.js WebGPURenderer, RenderTarget-only.
-//
-// B1a engineering notes encoded here:
-// - bare 'three' is aliased to 'three/webgpu' via module hooks (see register-hooks.mjs);
-// loading this module without the hooks would split three's class identity.
-// - Renderer.init() starts an internal loop via self.requestAnimationFrame — shimmed.
-// - GLTFLoader's ImageBitmapLoader path yields fake bitmaps that Dawn uploads as
-// black; decoded images are converted to DataTexture (writeTexture path).
-// - WebGPU readback rows are already top-down: no Y flip.
-import { PNG } from 'pngjs';
-import { acquireGpu } from './gpu.mjs';
-import { validateRenderMode } from './contract.mjs';
-import {
- DEFAULT_PRESENTATION_PRESET_ID,
- PRESENTATION_PRESET_IDS,
- SHADOW_FILTERS,
- getPresentationPreset,
-} from './presentation-presets.mjs';
-
-export { MAX_VIEW_DIRS, validateViewDirs } from './contract.mjs';
+import { renderDisplayTarget } from './display-output.mjs';
+import { packRgbaReadback } from './readback.mjs';
+// GLB bytes -> PBR PNG views. Headless three.js WebGPURenderer, RenderTarget-only.
+//
+// B1a engineering notes encoded here:
+// - bare 'three' is aliased to 'three/webgpu' via module hooks (see register-hooks.mjs);
+// loading this module without the hooks would split three's class identity.
+// - Renderer.init() starts an internal loop via self.requestAnimationFrame — shimmed.
+// - GLTFLoader's ImageBitmapLoader path yields fake bitmaps that Dawn uploads as
+// black; decoded images are converted to DataTexture (writeTexture path).
+// - WebGPU readback rows are already top-down: no Y flip.
+import { PNG } from 'pngjs';
+import { acquireGpu } from './gpu.mjs';
+import { validateRenderMode } from './contract.mjs';
+import {
+ DEFAULT_PRESENTATION_PRESET_ID,
+ PRESENTATION_PRESET_IDS,
+ SHADOW_FILTERS,
+ getPresentationPreset,
+} from './presentation-presets.mjs';
+
+export { MAX_VIEW_DIRS, validateViewDirs } from './contract.mjs';
import { beautyCameraSpec, orthoDepth, orthoHalfExtent } from './framing.mjs';
-
-globalThis.self = globalThis;
-globalThis.requestAnimationFrame = (cb) => setTimeout(() => cb(performance.now()), 16);
-globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
-
-// PNG-only decode for GLB-embedded images; JPEG assets degrade to materials without maps.
-globalThis.createImageBitmap = async (blob) => {
- const buf = Buffer.from(await blob.arrayBuffer());
- if (buf[0] !== 0x89 || buf[1] !== 0x50) throw new Error('only PNG images supported in GLB');
- const png = PNG.sync.read(buf);
- return { width: png.width, height: png.height, data: new Uint8Array(png.data), close() { } };
-};
-
-const THREE = await import('three/webgpu');
-const { GLTFLoader } = await import('three/addons/loaders/GLTFLoader.js');
-const { RoomEnvironment } = await import('three/addons/environments/RoomEnvironment.js');
-
-/**
- * Fixed, versioned presentation profile for every GPU view sheet. The GPU path
- * is the intentional beauty/inspection upgrade; it does not try to imitate the
- * flat CPU fallback. Keep these values deterministic so sheets remain directly
- * comparable across models and runs.
- */
-export const PRESENTATION_PROFILE_ID = DEFAULT_PRESENTATION_PRESET_ID;
-const defaultPresentation = getPresentationPreset(PRESENTATION_PROFILE_ID);
-// Compatibility exports retain their exact shapes/values while the renderer
-// itself now consumes the registry definition below.
-export const PRESENTATION_BACKGROUND = defaultPresentation.background;
-export const PRESENTATION_EXPOSURE = defaultPresentation.exposure;
-export const PRESENTATION_LIGHTS = Object.freeze({
- hemisphere: Object.freeze({
- sky: defaultPresentation.ambient.sky,
- ground: defaultPresentation.ambient.ground,
- intensity: defaultPresentation.ambient.intensity,
- }),
- ...Object.fromEntries(['key', 'fill', 'rim'].map((role) => [role, Object.freeze({
- color: defaultPresentation[role].color,
- intensity: defaultPresentation[role].intensity,
- position: defaultPresentation[role].position,
- })])),
-});
-
-/**
- * Ceiling on views per request. One render target is pooled per view at each
- * size, and the caller pays for every extra render, so this is a real resource
- * bound rather than a formality. The engine caps its own grid at 9 cells; the
- * headroom is for a caller that wants a few diagnostic angles alongside.
- */
-let ctx = null;
-
-/**
- * Render sizes a caller may ask for. Pools are keyed by size, hold MSAA targets,
- * and are never evicted — so a free 64..2048 range would let a caller mint ~1985
- * of them (hundreds of MB apiece at the top end) and exhaust VRAM on a warm
- * worker. Requests snap UP to the next allowed size, so a caller always gets at
- * least the detail it asked for. Add a rung only if a real consumer needs it.
- */
-export const ALLOWED_RENDER_SIZES = Object.freeze([128, 256, 384, 512, 768, 1024, 2048]);
-
-/** Snap to the smallest allowed size that is >= requested (largest if beyond). */
-export function snapRenderSize(requested) {
- const n = Number.isFinite(requested) ? requested : 384;
- return ALLOWED_RENDER_SIZES.find((s) => s >= n) ?? ALLOWED_RENDER_SIZES.at(-1);
-}
-
-const _rtPools = new Map();
-function rtPool(size, count) {
- const pool = _rtPools.get(size) ?? [];
- while (pool.length < count) pool.push(new THREE.RenderTarget(size, size, { depthBuffer: true, samples: 4 }));
- _rtPools.set(size, pool);
- return pool.slice(0, count);
-}
-
-export async function initRenderer(opts = {}) {
- if (ctx) return ctx;
- const gpuState = await acquireGpu(opts);
- const fakeCanvas = {
- width: 4, height: 4, style: {},
- addEventListener() { }, removeEventListener() { }, dispatchEvent() { },
- getContext() { throw new Error('default canvas context requested — RT-only expectation violated'); },
- };
- const renderer = new THREE.WebGPURenderer({ canvas: fakeCanvas, device: gpuState.device, antialias: false, samples: 4, outputBufferType: THREE.HalfFloatType });
- await renderer.init();
- renderer.toneMapping = THREE.ACESFilmicToneMapping;
- renderer.outputColorSpace = THREE.SRGBColorSpace;
- renderer.toneMappingExposure = PRESENTATION_EXPOSURE;
-
- const pmrem = new THREE.PMREMGenerator(renderer);
- const environments = new Map(PRESENTATION_PRESET_IDS.map((id) => {
- const preset = getPresentationPreset(id);
- return [id, pmrem.fromScene(new RoomEnvironment(), preset.environment.sigma).texture];
- }));
- const environment = environments.get(PRESENTATION_PROFILE_ID);
-
- const loader = new GLTFLoader();
- ctx = { renderer, environment, environments, loader, gpuState, device: gpuState.device };
- return ctx;
-}
-
-function toDataTextures(root) {
- root.traverse((o) => {
- for (const mat of Array.isArray(o.material) ? o.material : o.material ? [o.material] : []) {
- for (const slot of ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'aoMap', 'emissiveMap']) {
- const tex = mat[slot];
- if (tex?.image?.data && !tex.isDataTexture) {
- const dt = new THREE.DataTexture(tex.image.data, tex.image.width, tex.image.height, THREE.RGBAFormat);
- dt.colorSpace = tex.colorSpace; dt.flipY = tex.flipY;
- dt.wrapS = tex.wrapS; dt.wrapT = tex.wrapT;
- dt.magFilter = tex.magFilter; dt.minFilter = THREE.LinearMipmapLinearFilter;
- dt.generateMipmaps = true; dt.needsUpdate = true;
- mat[slot] = dt; mat.needsUpdate = true;
- }
- }
- }
- });
-}
-
-/**
- * Release the GPU resources this request's parse allocated. `ctx.environment` is
- * seeded into the visited set because it is shared across every request and
- * disposing it would break every later render; pooled render targets are never
- * reached from here for the same reason. three removes its own dispose listener
- * on the first call, so re-disposing a shared texture is a no-op.
- */
-function disposeGltf(gltf) {
- const seen = new Set(ctx?.environments?.values() ?? [ctx?.environment]);
- const dispose = (r) => {
- if (!r || seen.has(r)) return;
- seen.add(r);
- r.dispose();
- };
- for (const root of gltf.scenes?.length ? gltf.scenes : [gltf.scene]) {
- root?.traverse((o) => {
- dispose(o.geometry);
- for (const mat of Array.isArray(o.material) ? o.material : o.material ? [o.material] : []) {
- if (seen.has(mat)) continue;
- for (const v of Object.values(mat)) if (v?.isTexture) dispose(v);
- dispose(mat);
- }
- });
- }
-}
-
-/**
- * Preset filter name -> three constant. The schema owns the names because it validates
- * them; this owns the constants because it is the module that imports three.
- *
- * The two have to cover each other, so that is checked here rather than remembered: a
- * name the validator accepts and this map lacks would set `shadowMap.type` to undefined
- * at render time, which is not a crash -- just a quietly different image. Note the
- * comparison is against undefined, since BasicShadowMap is 0.
- */
-const SHADOW_MAP_TYPES = {
- basic: THREE.BasicShadowMap,
- pcf: THREE.PCFShadowMap,
- vsm: THREE.VSMShadowMap,
-};
-for (const name of SHADOW_FILTERS) {
- if (SHADOW_MAP_TYPES[name] === undefined) {
- throw new Error(`presentation preset shadow filter '${name}' has no three constant`);
- }
-}
-
-function applyPresentationPreset(renderer, scene, root, preset, environment) {
- renderer.toneMappingExposure = preset.exposure;
- renderer.shadowMap.enabled = preset.shadows.enabled;
- if (preset.shadows.enabled) renderer.shadowMap.type = SHADOW_MAP_TYPES[preset.shadows.type];
- scene.background = new THREE.Color(preset.background);
- scene.environment = environment;
-
- const ambient = preset.ambient;
- scene.add(new THREE.HemisphereLight(ambient.sky, ambient.ground, ambient.intensity));
- for (const role of ['sun', 'key', 'fill', 'rim']) {
- const lightSpec = preset[role];
- if (!lightSpec.enabled) continue;
- const light = new THREE.DirectionalLight(lightSpec.color, lightSpec.intensity);
- light.position.set(...lightSpec.position);
- light.castShadow = preset.shadows.enabled && lightSpec.castsShadow;
- if (light.castShadow) {
- light.shadow.mapSize.set(...preset.shadows.mapSize);
- light.shadow.bias = preset.shadows.bias;
- light.shadow.normalBias = preset.shadows.normalBias;
- light.shadow.radius = preset.shadows.radius;
- }
- scene.add(light);
- }
- if (preset.shadows.enabled) {
- root.traverse((object) => {
- if (!object.isMesh) return;
- object.castShadow = true;
- object.receiveShadow = true;
- });
- }
-}
-
-/**
- * Camera for one view. The fit itself lives in `framing.mjs`, which is pure
- * arithmetic and therefore testable without a GPU; see the note there for why
- * the old `max(sizes) * 0.72` had to go.
- */
-function orthoCam(center, min, max, dir) {
- const half = orthoHalfExtent(min, max, dir);
- const { distance, far } = orthoDepth(min, max, half);
- const cam = new THREE.OrthographicCamera(-half, half, half, -half, 0.01, far);
- cam.position.copy(
- center.clone().add(new THREE.Vector3(...dir).normalize().multiplyScalar(distance)),
- );
- cam.lookAt(center);
- cam.updateMatrixWorld();
- return cam;
-}
-
-function exactPerspectiveCam(spec) {
- const cam = spec.projection === 'orthographic'
- ? new THREE.OrthographicCamera(-spec.halfHeight * spec.aspect, spec.halfHeight * spec.aspect, spec.halfHeight, -spec.halfHeight, spec.near, spec.far)
- : new THREE.PerspectiveCamera(spec.fovDeg, spec.aspect, spec.near, spec.far);
- cam.position.set(...spec.position);
- cam.up.set(...spec.up);
- cam.lookAt(new THREE.Vector3(...spec.target));
- cam.updateProjectionMatrix();
- cam.updateMatrixWorld(true);
- return cam;
-}
-
-async function readPng(renderer, rt, w, h) {
- const pixels = await renderer.readRenderTargetPixelsAsync(rt, 0, 0, w, h);
- const png = new PNG({ width: w, height: h });
- packRgbaReadback(pixels,w,h).copy(png.data);
- // Fast encode: deflate 1 + no row filtering is ~10x quicker than the adaptive
- // default and consumers read pixels, not bytes (image tokens scale with
- // dimensions, not file size).
- return PNG.sync.write(png, { deflateLevel: 1, filterType: 0 });
-}
-
-/**
- * Render a GLB into PNG views.
- * @param {Buffer} glbBytes
- * @param {{size?: number, viewDirs?: number[][], beautySize?: number, background?: string,
- * cameras?: object[], width?: number, height?: number, lightingPresetId?: string}} opts
- * @returns {Promise<{views: Buffer[], beauty: Buffer|null, timings: object,
- * cameras?: object[], width?: number, height?: number, lightingPresetId?: string}>}
- */
-export async function renderGlb(glbBytes, opts = {}) {
- const { renderer, environments, loader } = await initRenderer();
- const renderMode = validateRenderMode({
- cameras: opts.cameras,
- width: opts.width,
- height: opts.height,
- lighting_preset_id: opts.lightingPresetId,
- views: opts.viewDirs,
- size: opts.size,
- beauty_size: opts.beautySize,
- background: opts.background,
- });
- // Snapped, not clamped: pooled render targets are keyed by size and never
- // evicted, so an unbounded key space is a caller-controlled VRAM leak. The
- // beauty target below is allocated per request and disposed, so it keeps a
- // plain clamp — it has no pool to poison.
- const size = renderMode.mode === 'legacy' ? snapRenderSize(renderMode.size ?? 384) : null;
- const beautySize = renderMode.mode === 'legacy' && renderMode.beautySize
- ? Math.min(Math.max(renderMode.beautySize, 128), 4096)
- : null;
- const viewDirs = renderMode.mode === 'legacy' ? renderMode.viewDirs : null;
- const presentationPresetId = renderMode.mode === 'camera'
- ? renderMode.lightingPresetId
- : PRESENTATION_PROFILE_ID;
- const presentation = getPresentationPreset(presentationPresetId);
-
- const t0 = performance.now();
- const ab = glbBytes.buffer.slice(glbBytes.byteOffset, glbBytes.byteOffset + glbBytes.byteLength);
- const gltf = await new Promise((res, rej) => loader.parse(ab, '', res, rej));
- let scene = null;
- const requestTargets = [];
- try {
- toDataTextures(gltf.scene);
- const tLoad = performance.now();
-
- scene = new THREE.Scene();
- applyPresentationPreset(renderer, scene, gltf.scene, presentation, environments.get(presentationPresetId));
- // Legacy callers retain their historical escape hatch. Exact camera mode is
- // preset-ID-only and validateRenderMode rejects a background field.
- if (renderMode.mode === 'legacy' && opts.background !== undefined) {
- scene.background = new THREE.Color(opts.background);
- }
- scene.add(gltf.scene);
-
- if (renderMode.mode === 'camera') {
- // Exact milestone targets are deliberately request-owned and rectangular;
- // unlike the bounded square legacy pool, no camera dimensions survive the
- // request. Submit every camera first, then read back in request order.
- for (const camera of renderMode.cameras) {
- const target = new THREE.RenderTarget(renderMode.width, renderMode.height, {
- depthBuffer: true,
- samples: 4,
- });
- requestTargets.push(target);
- renderDisplayTarget(renderer, scene, exactPerspectiveCam(camera), target);
- }
- const views = [];
- for (const target of requestTargets) {
- views.push(await readPng(renderer, target, renderMode.width, renderMode.height));
- }
- const tEnd = performance.now();
- return {
- views,
- beauty: null,
- cameras: renderMode.cameras,
- width: renderMode.width,
- height: renderMode.height,
- lightingPresetId: renderMode.lightingPresetId,
- timings: {
- loadMs: +(tLoad - t0).toFixed(1),
- viewsMs: +(tEnd - tLoad).toFixed(1),
- beautyMs: 0,
- totalMs: +(tEnd - t0).toFixed(1),
- },
- };
- }
-
- const box = new THREE.Box3().setFromObject(gltf.scene);
- const center = box.getCenter(new THREE.Vector3());
- const sizes = box.getSize(new THREE.Vector3());
- const boxMin = [box.min.x, box.min.y, box.min.z];
- const boxMax = [box.max.x, box.max.y, box.max.z];
-
- // One RT per view, pooled across requests (alloc is pure overhead). Submit
- // every render first, then read back — a mid-loop readback forces a full GPU
- // sync per view.
- const rts = rtPool(size, viewDirs.length);
- viewDirs.forEach((dir, i) => {
- renderDisplayTarget(renderer, scene, orthoCam(center, boxMin, boxMax, dir), rts[i]);
- });
- const views = [];
- for (const vrt of rts) {
- views.push(await readPng(renderer, vrt, size, size));
- }
- const tViews = performance.now();
-
- let beauty = null;
- if (beautySize) {
+
+globalThis.self = globalThis;
+globalThis.requestAnimationFrame = (cb) => setTimeout(() => cb(performance.now()), 16);
+globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
+
+// PNG-only decode for GLB-embedded images; JPEG assets degrade to materials without maps.
+globalThis.createImageBitmap = async (blob) => {
+ const buf = Buffer.from(await blob.arrayBuffer());
+ if (buf[0] !== 0x89 || buf[1] !== 0x50) throw new Error('only PNG images supported in GLB');
+ const png = PNG.sync.read(buf);
+ return { width: png.width, height: png.height, data: new Uint8Array(png.data), close() {} };
+};
+
+const THREE = await import('three/webgpu');
+const { GLTFLoader } = await import('three/addons/loaders/GLTFLoader.js');
+const { RoomEnvironment } = await import('three/addons/environments/RoomEnvironment.js');
+
+/**
+ * Fixed, versioned presentation profile for every GPU view sheet. The GPU path
+ * is the intentional beauty/inspection upgrade; it does not try to imitate the
+ * flat CPU fallback. Keep these values deterministic so sheets remain directly
+ * comparable across models and runs.
+ */
+export const PRESENTATION_PROFILE_ID = DEFAULT_PRESENTATION_PRESET_ID;
+const defaultPresentation = getPresentationPreset(PRESENTATION_PROFILE_ID);
+// Compatibility exports retain their exact shapes/values while the renderer
+// itself now consumes the registry definition below.
+export const PRESENTATION_BACKGROUND = defaultPresentation.background;
+export const PRESENTATION_EXPOSURE = defaultPresentation.exposure;
+export const PRESENTATION_LIGHTS = Object.freeze({
+ hemisphere: Object.freeze({
+ sky: defaultPresentation.ambient.sky,
+ ground: defaultPresentation.ambient.ground,
+ intensity: defaultPresentation.ambient.intensity,
+ }),
+ ...Object.fromEntries(
+ ['key', 'fill', 'rim'].map((role) => [
+ role,
+ Object.freeze({
+ color: defaultPresentation[role].color,
+ intensity: defaultPresentation[role].intensity,
+ position: defaultPresentation[role].position,
+ }),
+ ]),
+ ),
+});
+
+/**
+ * Ceiling on views per request. One render target is pooled per view at each
+ * size, and the caller pays for every extra render, so this is a real resource
+ * bound rather than a formality. The engine caps its own grid at 9 cells; the
+ * headroom is for a caller that wants a few diagnostic angles alongside.
+ */
+let ctx = null;
+
+/**
+ * Render sizes a caller may ask for. Pools are keyed by size, hold MSAA targets,
+ * and are never evicted — so a free 64..2048 range would let a caller mint ~1985
+ * of them (hundreds of MB apiece at the top end) and exhaust VRAM on a warm
+ * worker. Requests snap UP to the next allowed size, so a caller always gets at
+ * least the detail it asked for. Add a rung only if a real consumer needs it.
+ */
+export const ALLOWED_RENDER_SIZES = Object.freeze([128, 256, 384, 512, 768, 1024, 2048]);
+
+/** Snap to the smallest allowed size that is >= requested (largest if beyond). */
+export function snapRenderSize(requested) {
+ const n = Number.isFinite(requested) ? requested : 384;
+ return ALLOWED_RENDER_SIZES.find((s) => s >= n) ?? ALLOWED_RENDER_SIZES.at(-1);
+}
+
+const _rtPools = new Map();
+function rtPool(size, count) {
+ const pool = _rtPools.get(size) ?? [];
+ while (pool.length < count)
+ pool.push(new THREE.RenderTarget(size, size, { depthBuffer: true, samples: 4 }));
+ _rtPools.set(size, pool);
+ return pool.slice(0, count);
+}
+
+export async function initRenderer(opts = {}) {
+ if (ctx) return ctx;
+ const gpuState = await acquireGpu(opts);
+ const fakeCanvas = {
+ width: 4,
+ height: 4,
+ style: {},
+ addEventListener() {},
+ removeEventListener() {},
+ dispatchEvent() {},
+ getContext() {
+ throw new Error('default canvas context requested — RT-only expectation violated');
+ },
+ };
+ const renderer = new THREE.WebGPURenderer({
+ canvas: fakeCanvas,
+ device: gpuState.device,
+ antialias: false,
+ samples: 4,
+ outputBufferType: THREE.HalfFloatType,
+ });
+ await renderer.init();
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+ renderer.toneMappingExposure = PRESENTATION_EXPOSURE;
+
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ const environments = new Map(
+ PRESENTATION_PRESET_IDS.map((id) => {
+ const preset = getPresentationPreset(id);
+ return [id, pmrem.fromScene(new RoomEnvironment(), preset.environment.sigma).texture];
+ }),
+ );
+ const environment = environments.get(PRESENTATION_PROFILE_ID);
+
+ const loader = new GLTFLoader();
+ ctx = { renderer, environment, environments, loader, gpuState, device: gpuState.device };
+ return ctx;
+}
+
+function toDataTextures(root) {
+ root.traverse((o) => {
+ for (const mat of Array.isArray(o.material) ? o.material : o.material ? [o.material] : []) {
+ for (const slot of [
+ 'map',
+ 'normalMap',
+ 'roughnessMap',
+ 'metalnessMap',
+ 'aoMap',
+ 'emissiveMap',
+ ]) {
+ const tex = mat[slot];
+ if (tex?.image?.data && !tex.isDataTexture) {
+ const dt = new THREE.DataTexture(
+ tex.image.data,
+ tex.image.width,
+ tex.image.height,
+ THREE.RGBAFormat,
+ );
+ dt.colorSpace = tex.colorSpace;
+ dt.flipY = tex.flipY;
+ dt.wrapS = tex.wrapS;
+ dt.wrapT = tex.wrapT;
+ dt.magFilter = tex.magFilter;
+ dt.minFilter = THREE.LinearMipmapLinearFilter;
+ dt.generateMipmaps = true;
+ dt.needsUpdate = true;
+ mat[slot] = dt;
+ mat.needsUpdate = true;
+ }
+ }
+ }
+ });
+}
+
+/**
+ * Release the GPU resources this request's parse allocated. `ctx.environment` is
+ * seeded into the visited set because it is shared across every request and
+ * disposing it would break every later render; pooled render targets are never
+ * reached from here for the same reason. three removes its own dispose listener
+ * on the first call, so re-disposing a shared texture is a no-op.
+ */
+function disposeGltf(gltf) {
+ const seen = new Set(ctx?.environments?.values() ?? [ctx?.environment]);
+ const dispose = (r) => {
+ if (!r || seen.has(r)) return;
+ seen.add(r);
+ r.dispose();
+ };
+ for (const root of gltf.scenes?.length ? gltf.scenes : [gltf.scene]) {
+ root?.traverse((o) => {
+ dispose(o.geometry);
+ for (const mat of Array.isArray(o.material) ? o.material : o.material ? [o.material] : []) {
+ if (seen.has(mat)) continue;
+ for (const v of Object.values(mat)) if (v?.isTexture) dispose(v);
+ dispose(mat);
+ }
+ });
+ }
+}
+
+/**
+ * Preset filter name -> three constant. The schema owns the names because it validates
+ * them; this owns the constants because it is the module that imports three.
+ *
+ * The two have to cover each other, so that is checked here rather than remembered: a
+ * name the validator accepts and this map lacks would set `shadowMap.type` to undefined
+ * at render time, which is not a crash -- just a quietly different image. Note the
+ * comparison is against undefined, since BasicShadowMap is 0.
+ */
+const SHADOW_MAP_TYPES = {
+ basic: THREE.BasicShadowMap,
+ pcf: THREE.PCFShadowMap,
+ vsm: THREE.VSMShadowMap,
+};
+for (const name of SHADOW_FILTERS) {
+ if (SHADOW_MAP_TYPES[name] === undefined) {
+ throw new Error(`presentation preset shadow filter '${name}' has no three constant`);
+ }
+}
+
+function applyPresentationPreset(renderer, scene, root, preset, environment) {
+ renderer.toneMappingExposure = preset.exposure;
+ renderer.shadowMap.enabled = preset.shadows.enabled;
+ if (preset.shadows.enabled) renderer.shadowMap.type = SHADOW_MAP_TYPES[preset.shadows.type];
+ scene.background = new THREE.Color(preset.background);
+ scene.environment = environment;
+
+ const ambient = preset.ambient;
+ scene.add(new THREE.HemisphereLight(ambient.sky, ambient.ground, ambient.intensity));
+ for (const role of ['sun', 'key', 'fill', 'rim']) {
+ const lightSpec = preset[role];
+ if (!lightSpec.enabled) continue;
+ const light = new THREE.DirectionalLight(lightSpec.color, lightSpec.intensity);
+ light.position.set(...lightSpec.position);
+ light.castShadow = preset.shadows.enabled && lightSpec.castsShadow;
+ if (light.castShadow) {
+ light.shadow.mapSize.set(...preset.shadows.mapSize);
+ light.shadow.bias = preset.shadows.bias;
+ light.shadow.normalBias = preset.shadows.normalBias;
+ light.shadow.radius = preset.shadows.radius;
+ }
+ scene.add(light);
+ }
+ if (preset.shadows.enabled) {
+ root.traverse((object) => {
+ if (!object.isMesh) return;
+ object.castShadow = true;
+ object.receiveShadow = true;
+ });
+ }
+}
+
+/**
+ * Camera for one view. The fit itself lives in `framing.mjs`, which is pure
+ * arithmetic and therefore testable without a GPU; see the note there for why
+ * the old `max(sizes) * 0.72` had to go.
+ */
+function orthoCam(center, min, max, dir) {
+ const half = orthoHalfExtent(min, max, dir);
+ const { distance, far } = orthoDepth(min, max, half);
+ const cam = new THREE.OrthographicCamera(-half, half, half, -half, 0.01, far);
+ cam.position.copy(
+ center.clone().add(new THREE.Vector3(...dir).normalize().multiplyScalar(distance)),
+ );
+ cam.lookAt(center);
+ cam.updateMatrixWorld();
+ return cam;
+}
+
+function exactPerspectiveCam(spec) {
+ const cam =
+ spec.projection === 'orthographic'
+ ? new THREE.OrthographicCamera(
+ -spec.halfHeight * spec.aspect,
+ spec.halfHeight * spec.aspect,
+ spec.halfHeight,
+ -spec.halfHeight,
+ spec.near,
+ spec.far,
+ )
+ : new THREE.PerspectiveCamera(spec.fovDeg, spec.aspect, spec.near, spec.far);
+ cam.position.set(...spec.position);
+ cam.up.set(...spec.up);
+ cam.lookAt(new THREE.Vector3(...spec.target));
+ cam.updateProjectionMatrix();
+ cam.updateMatrixWorld(true);
+ return cam;
+}
+
+async function readPng(renderer, rt, w, h) {
+ const pixels = await renderer.readRenderTargetPixelsAsync(rt, 0, 0, w, h);
+ const png = new PNG({ width: w, height: h });
+ packRgbaReadback(pixels, w, h).copy(png.data);
+ // Fast encode: deflate 1 + no row filtering is ~10x quicker than the adaptive
+ // default and consumers read pixels, not bytes (image tokens scale with
+ // dimensions, not file size).
+ return PNG.sync.write(png, { deflateLevel: 1, filterType: 0 });
+}
+
+/**
+ * Render a GLB into PNG views.
+ * @param {Buffer} glbBytes
+ * @param {{size?: number, viewDirs?: number[][], beautySize?: number, background?: string,
+ * cameras?: object[], width?: number, height?: number, lightingPresetId?: string}} opts
+ * @returns {Promise<{views: Buffer[], beauty: Buffer|null, timings: object,
+ * cameras?: object[], width?: number, height?: number, lightingPresetId?: string}>}
+ */
+export async function renderGlb(glbBytes, opts = {}) {
+ const { renderer, environments, loader } = await initRenderer();
+ const renderMode = validateRenderMode({
+ cameras: opts.cameras,
+ width: opts.width,
+ height: opts.height,
+ lighting_preset_id: opts.lightingPresetId,
+ views: opts.viewDirs,
+ size: opts.size,
+ beauty_size: opts.beautySize,
+ background: opts.background,
+ });
+ // Snapped, not clamped: pooled render targets are keyed by size and never
+ // evicted, so an unbounded key space is a caller-controlled VRAM leak. The
+ // beauty target below is allocated per request and disposed, so it keeps a
+ // plain clamp — it has no pool to poison.
+ const size = renderMode.mode === 'legacy' ? snapRenderSize(renderMode.size ?? 384) : null;
+ const beautySize =
+ renderMode.mode === 'legacy' && renderMode.beautySize
+ ? Math.min(Math.max(renderMode.beautySize, 128), 4096)
+ : null;
+ const viewDirs = renderMode.mode === 'legacy' ? renderMode.viewDirs : null;
+ const presentationPresetId =
+ renderMode.mode === 'camera' ? renderMode.lightingPresetId : PRESENTATION_PROFILE_ID;
+ const presentation = getPresentationPreset(presentationPresetId);
+
+ const t0 = performance.now();
+ const ab = glbBytes.buffer.slice(glbBytes.byteOffset, glbBytes.byteOffset + glbBytes.byteLength);
+ const gltf = await new Promise((res, rej) => loader.parse(ab, '', res, rej));
+ let scene = null;
+ const requestTargets = [];
+ try {
+ toDataTextures(gltf.scene);
+ const tLoad = performance.now();
+
+ scene = new THREE.Scene();
+ applyPresentationPreset(
+ renderer,
+ scene,
+ gltf.scene,
+ presentation,
+ environments.get(presentationPresetId),
+ );
+ // Legacy callers retain their historical escape hatch. Exact camera mode is
+ // preset-ID-only and validateRenderMode rejects a background field.
+ if (renderMode.mode === 'legacy' && opts.background !== undefined) {
+ scene.background = new THREE.Color(opts.background);
+ }
+ scene.add(gltf.scene);
+
+ if (renderMode.mode === 'camera') {
+ // Exact milestone targets are deliberately request-owned and rectangular;
+ // unlike the bounded square legacy pool, no camera dimensions survive the
+ // request. Submit every camera first, then read back in request order.
+ for (const camera of renderMode.cameras) {
+ const target = new THREE.RenderTarget(renderMode.width, renderMode.height, {
+ depthBuffer: true,
+ samples: 4,
+ });
+ requestTargets.push(target);
+ renderDisplayTarget(renderer, scene, exactPerspectiveCam(camera), target);
+ }
+ const views = [];
+ for (const target of requestTargets) {
+ views.push(await readPng(renderer, target, renderMode.width, renderMode.height));
+ }
+ const tEnd = performance.now();
+ return {
+ views,
+ beauty: null,
+ cameras: renderMode.cameras,
+ width: renderMode.width,
+ height: renderMode.height,
+ lightingPresetId: renderMode.lightingPresetId,
+ timings: {
+ loadMs: +(tLoad - t0).toFixed(1),
+ viewsMs: +(tEnd - tLoad).toFixed(1),
+ beautyMs: 0,
+ totalMs: +(tEnd - t0).toFixed(1),
+ },
+ };
+ }
+
+ const box = new THREE.Box3().setFromObject(gltf.scene);
+ const center = box.getCenter(new THREE.Vector3());
+ const sizes = box.getSize(new THREE.Vector3());
+ const boxMin = [box.min.x, box.min.y, box.min.z];
+ const boxMax = [box.max.x, box.max.y, box.max.z];
+
+ // One RT per view, pooled across requests (alloc is pure overhead). Submit
+ // every render first, then read back — a mid-loop readback forces a full GPU
+ // sync per view.
+ const rts = rtPool(size, viewDirs.length);
+ viewDirs.forEach((dir, i) => {
+ renderDisplayTarget(renderer, scene, orthoCam(center, boxMin, boxMax, dir), rts[i]);
+ });
+ const views = [];
+ for (const vrt of rts) {
+ views.push(await readPng(renderer, vrt, size, size));
+ }
+ const tViews = performance.now();
+
+ let beauty = null;
+ if (beautySize) {
const rtB = new THREE.RenderTarget(beautySize, beautySize, { depthBuffer: true, samples: 4 });
requestTargets.push(rtB);
- renderDisplayTarget(renderer, scene, exactPerspectiveCam(beautyCameraSpec(center.toArray(), sizes.length() * 0.62 + 1e-3)), rtB);
- beauty = await readPng(renderer, rtB, beautySize, beautySize);
- }
- const tEnd = performance.now();
-
- return {
- views,
- beauty,
- timings: {
- loadMs: +(tLoad - t0).toFixed(1),
- viewsMs: +(tViews - tLoad).toFixed(1),
- beautyMs: beauty ? +(tEnd - tViews).toFixed(1) : 0,
- totalMs: +(tEnd - t0).toFixed(1),
- },
- };
- } finally {
- // Every request parses its own copy and toDataTextures uploads fresh GPU
- // textures for it; a warm worker that skips this accumulates every asset it
- // has ever rendered. Readback is complete by here, so nothing in flight can
- // still reference what we release. Runs on the throwing path too.
- //
- // Swallowed deliberately: this runs after the response value is built, so
- // letting cleanup throw would turn a completed render into a 500. A leak is
- // the better failure than losing work already paid for on the GPU.
- try {
- renderer.setRenderTarget(null);
- for (const target of requestTargets) target.dispose();
- scene?.clear();
- disposeGltf(gltf);
- } catch (e) {
- console.warn(JSON.stringify({ evt: 'dispose-failed', error: String(e?.message ?? e) }));
- }
- }
-}
+ renderDisplayTarget(
+ renderer,
+ scene,
+ exactPerspectiveCam(beautyCameraSpec(center.toArray(), sizes.length() * 0.62 + 1e-3)),
+ rtB,
+ );
+ beauty = await readPng(renderer, rtB, beautySize, beautySize);
+ }
+ const tEnd = performance.now();
+
+ return {
+ views,
+ beauty,
+ timings: {
+ loadMs: +(tLoad - t0).toFixed(1),
+ viewsMs: +(tViews - tLoad).toFixed(1),
+ beautyMs: beauty ? +(tEnd - tViews).toFixed(1) : 0,
+ totalMs: +(tEnd - t0).toFixed(1),
+ },
+ };
+ } finally {
+ // Every request parses its own copy and toDataTextures uploads fresh GPU
+ // textures for it; a warm worker that skips this accumulates every asset it
+ // has ever rendered. Readback is complete by here, so nothing in flight can
+ // still reference what we release. Runs on the throwing path too.
+ //
+ // Swallowed deliberately: this runs after the response value is built, so
+ // letting cleanup throw would turn a completed render into a 500. A leak is
+ // the better failure than losing work already paid for on the GPU.
+ try {
+ renderer.setRenderTarget(null);
+ for (const target of requestTargets) target.dispose();
+ scene?.clear();
+ disposeGltf(gltf);
+ } catch (e) {
+ console.warn(JSON.stringify({ evt: 'dispose-failed', error: String(e?.message ?? e) }));
+ }
+ }
+}
diff --git a/render-service/src/server.mjs b/render-service/src/server.mjs
index 8907467f..2355d23e 100644
--- a/render-service/src/server.mjs
+++ b/render-service/src/server.mjs
@@ -1,280 +1,306 @@
-// HTTP surface. Contract (plan B2):
-// GET /health, /ping -> 200 {ok, rendererId, adapter, capabilities, authRequired}
-// (never 503: a software or absent adapter aborts boot below,
-// so a listening server always implies a hardware adapter)
-// POST /render legacy: {glb_base64, input_glb_sha256?, size?, views?, beauty_size?, background?}
-// POST /render camera: {glb_base64, input_glb_sha256?, cameras, width, height,
-// lighting_preset_id?}
-// -> 200 legacy response unchanged, or exact camera
-// receipt metadata + ordered output identities
-// (`input_glb_sha256` opts into an additive,
-// hash-verified material-fidelity receipt)
-// -> 400 on a malformed/over-long views[] (max 12).
-// Exactly one PNG comes back per requested view,
-// in request order — the caller composites a grid
-// whose shape it chose from that length, so this
-// rejects rather than truncating.
-// POST /bake -> 501 (texture bakes are a later workstream)
-// Auth: $RENDER_SERVICE_TOKEN on POST routes (required if set; boot warns loudly
-// when unset), supplied as either `x-render-token: <token>` or
-// `Authorization: Bearer <token>`. The custom header exists because RunPod's
-// load-balancer gateway consumes Authorization for its own edge API-key auth, so
-// gateway callers can never deliver an app-layer bearer token through it.
-// Renders are serialized: one GPU, one queue.
-import { createServer } from 'node:http';
-import {
- PRESENTATION_PROFILE_ID,
- initRenderer,
- renderGlb,
-} from './renderer.mjs';
-import { acquireGpu } from './gpu.mjs';
-import { buildHealthDocument } from './health-contract.mjs';
-import {createRendererCaptureIdentity} from './cache-identity.mjs';
-import {
- buildRenderFidelityV1,
- buildRenderOperationalEvidenceV1,
- createSerialRenderQueue,
- httpRenderOutcomeCode,
- outputSetSha256,
- sha256,
- validateInputGlbIdentity,
- validateRenderMode,
-} from './contract.mjs';
-
-const PROCESS_STARTED_AT = performance.now();
-const PORT = Number(process.env.PORT ?? 8000);
-// Unset binds every interface, which is what a container deployment needs and is
-// the long-standing default here. A service started FOR the user -- by the MCP
-// server's on-demand start -- passes 127.0.0.1 instead, because choosing on
-// somebody's behalf to put a renderer on their LAN is not ours to choose.
-const HOST = process.env.HOST || undefined;
-const TOKEN = process.env.RENDER_SERVICE_TOKEN ?? '';
-
-const MAX_BODY = 96 * 1024 * 1024; // 64MB base64 ≈ 48MB GLB, plus JSON overhead
-const MAX_GLB = 48 * 1024 * 1024;
-
-// Boot assertion: a software adapter must prevent the service from starting at all,
-// so a driver regression yields a service that will not boot rather than one that
-// silently renders everything on CPU.
-let gpuState;
-try {
- gpuState = await acquireGpu();
- await initRenderer();
-} catch (e) {
- console.error(`FATAL: ${e.message}`);
- process.exit(1);
-}
-gpuState.captureIdentity=createRendererCaptureIdentity(gpuState);
-console.log(`adapter: ${JSON.stringify(gpuState.summary)}`);
-console.log(`rendererId: ${gpuState.rendererId}`);
-if (!TOKEN) console.warn('WARNING: RENDER_SERVICE_TOKEN unset — POST routes are UNAUTHENTICATED');
-
-const renderQueue = createSerialRenderQueue({ processStartedAt: PROCESS_STARTED_AT });
-
-function readBody(req) {
- return new Promise((resolve, reject) => {
- const chunks = [];
- let total = 0;
- req.on('data', (c) => {
- total += c.length;
- if (total > MAX_BODY) { reject(Object.assign(new Error('body too large'), { status: 413 })); req.destroy(); return; }
- chunks.push(c);
- });
- req.on('end', () => resolve(Buffer.concat(chunks)));
- req.on('error', reject);
- });
-}
-
-function send(res, status, obj) {
- const body = JSON.stringify(obj);
- res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) });
- res.end(body);
-}
-
-const server = createServer(async (req, res) => {
- const started = performance.now();
- // Accumulated across the handler and emitted exactly once by done(). Only
- // names and sizes go in here — never a token, a header value, or GLB bytes.
- // Path only, never the query string: nothing here accepts a token as a query
- // parameter, but logging the raw URL would make any future one a disclosure.
- const log = {
- method: req.method,
- path: String(req.url ?? '').split('?')[0].slice(0, 200),
- auth: 'not-required',
- };
- const done = (status, obj) => {
- send(res, status, obj);
- const outcomeCode = httpRenderOutcomeCode({
- method: log.method,
- path: log.path,
- status,
- });
- console.log(JSON.stringify({
- evt: 'request',
- ...log,
- outcomeCode,
- status,
- ...(status >= 400 && obj?.error ? { error: obj.error } : {}),
- ms: +(performance.now() - started).toFixed(1),
- }));
- };
- try {
- // /ping: RunPod load-balancer health convention (200 = healthy). The boot
- // assertion guarantees a listening server implies a hardware adapter.
- if (req.method === 'GET' && (req.url === '/health' || req.url === '/ping')) {
- // Capability advertisement, not decoration: a GitHub-build endpoint carries
- // no commit stamp, so this is the only way a caller can tell WHICH build is
- // live before depending on a feature. The pure builder is contract-tested
- // without booting a GPU and advertises every registry ID explicitly.
- return done(200, buildHealthDocument(gpuState, Boolean(TOKEN)));
- }
- if (req.method === 'POST' && (req.url === '/render' || req.url === '/bake')) {
- if (TOKEN) {
- const auth = req.headers.authorization ?? '';
- const custom = req.headers['x-render-token'] ?? '';
- if (auth !== `Bearer ${TOKEN}` && custom !== TOKEN) {
- log.auth = 'rejected';
- return done(401, { ok: false, error: 'unauthorized' });
- }
- // Which header carried it, never the value: the gateway strips
- // Authorization, so this distinguishes a gateway caller from a direct one.
- log.auth = 'ok';
- log.authVia = custom === TOKEN ? 'x-render-token' : 'authorization';
- } else {
- log.auth = 'disabled';
- }
- if (req.url === '/bake') return done(501, { ok: false, error: 'bake not implemented yet' });
-
- const raw = await readBody(req);
- log.bodyBytes = raw.length;
- let body;
- try { body = JSON.parse(raw.toString('utf8')); } catch { return done(400, { ok: false, error: 'invalid JSON' }); }
- if (!body || typeof body !== 'object' || Array.isArray(body)) {
- return done(400, { ok: false, error: 'JSON body must be an object' });
- }
- if (typeof body.glb_base64 !== 'string' || !body.glb_base64) {
- return done(400, { ok: false, error: 'glb_base64 (string) required' });
- }
- const glb = Buffer.from(body.glb_base64, 'base64');
- log.glbBytes = glb.length;
- if (glb.length < 20 || glb.readUInt32LE(0) !== 0x46546c67) {
- return done(400, { ok: false, error: 'not a GLB (bad magic)' });
- }
- if (glb.length > MAX_GLB) return done(413, { ok: false, error: 'GLB too large' });
- // New fidelity-aware callers assert the identity they sent. Legacy callers
- // omit it and retain their exact historical response shape.
- let inputGlbSha256;
- try { inputGlbSha256 = validateInputGlbIdentity(glb, body.input_glb_sha256); }
- catch (e) { return done(e.status ?? 400, { ok: false, error: String(e.message ?? e) }); }
- const fidelityRequested = body.input_glb_sha256 !== undefined;
- log.inputGlbSha256 = inputGlbSha256;
- // Validated BEFORE the queue: malformed exact cameras or legacy views are
- // immediate 400s, not GPU-queue work. renderGlb validates again for direct callers.
- let renderMode;
- try { renderMode = validateRenderMode(body); }
- catch (e) { return done(e.status ?? 400, { ok: false, error: String(e.message ?? e) }); }
- log.renderMode = renderMode.mode;
- if (renderMode.mode === 'camera') {
- log.camerasRequested = renderMode.cameras.length;
- log.width = renderMode.width;
- log.height = renderMode.height;
- log.totalPixels = renderMode.totalPixels;
- log.lightingPresetId = renderMode.lightingPresetId;
- log.backend = gpuState.backend;
- log.rendererId = gpuState.rendererId;
- } else {
- log.viewsRequested = renderMode.viewDirs.length;
- }
-
- const t0 = performance.now();
- const queued = await renderQueue.enqueue(async (operationalStart) => {
- log.renderOperationalStart = operationalStart;
- return {
- operationalStart,
- result: await renderGlb(glb, renderMode.mode === 'camera'
- ? {
- cameras: renderMode.cameras,
- width: renderMode.width,
- height: renderMode.height,
- lightingPresetId: renderMode.lightingPresetId,
- background: renderMode.background,
- }
- : {
- size: renderMode.size,
- viewDirs: renderMode.viewDirs,
- beautySize: renderMode.beautySize,
- background: renderMode.background,
- }),
- };
- });
- const result = queued.result;
- const timings = {
- ...result.timings,
- queueWaitMs: +queued.operationalStart.queueWaitMs.toFixed(1),
- queueAndTotalMs: +(performance.now() - t0).toFixed(1),
- };
- log.views = result.views.length;
- log.beauty = Boolean(result.beauty);
- log.timings = timings;
- const viewSha256 = result.views.map(sha256);
- const outputSetHash = outputSetSha256(result.views);
- if (renderMode.mode === 'camera') log.outputSetSha256 = outputSetHash;
- const appliedPresentationProfile = result.lightingPresetId ?? PRESENTATION_PROFILE_ID;
- const fidelity = fidelityRequested
- ? buildRenderFidelityV1({
- rendererId: gpuState.rendererId,
- inputGlbSha256,
- presentationProfile: appliedPresentationProfile,
- renderMode,
- resolvedCameras: result.cameras ?? [],
- timings,
- })
- : undefined;
- const operationalEvidence = buildRenderOperationalEvidenceV1({
- outcomeCode: 'gpu_success',
- ...queued.operationalStart,
- });
- log.operationalEvidence = operationalEvidence;
- delete log.renderOperationalStart;
- return done(200, {
- ok: true,
- rendererId: gpuState.rendererId,
- presentationProfile: appliedPresentationProfile,
- timings,
- views: result.views.map((b) => b.toString('base64')),
- ...(result.beauty ? { beauty: result.beauty.toString('base64') } : {}),
- ...(fidelity ? { inputGlbSha256, fidelity, operationalEvidence } : {}),
- ...(renderMode.mode === 'camera' ? {
- backend: gpuState.backend,
- cameras: result.cameras,
- width: result.width,
- height: result.height,
- lightingPresetId: result.lightingPresetId,
- viewSha256,
- outputSetSha256: outputSetHash,
- cameraReceipts: result.cameras.map((camera, index) => ({
- index,
- camera,
- width: result.width,
- height: result.height,
- outputSha256: viewSha256[index],
- })),
- } : {}),
- });
- }
- done(404, { ok: false, error: 'not found' });
- } catch (e) {
- if (log.renderOperationalStart && !log.operationalEvidence) {
- try {
- log.operationalEvidence = buildRenderOperationalEvidenceV1({
- outcomeCode: 'render_failed',
- ...log.renderOperationalStart,
- });
- } catch { /* never mask the original render failure with metrics evidence */ }
- delete log.renderOperationalStart;
- }
- done(e.status ?? 500, { ok: false, error: String(e.message ?? e) });
- }
-});
-
-server.listen(PORT, HOST, () => console.log(`kiln-render-service listening on ${HOST ?? '*'}:${PORT}`));
+// HTTP surface. Contract (plan B2):
+// GET /health, /ping -> 200 {ok, rendererId, adapter, capabilities, authRequired}
+// (never 503: a software or absent adapter aborts boot below,
+// so a listening server always implies a hardware adapter)
+// POST /render legacy: {glb_base64, input_glb_sha256?, size?, views?, beauty_size?, background?}
+// POST /render camera: {glb_base64, input_glb_sha256?, cameras, width, height,
+// lighting_preset_id?}
+// -> 200 legacy response unchanged, or exact camera
+// receipt metadata + ordered output identities
+// (`input_glb_sha256` opts into an additive,
+// hash-verified material-fidelity receipt)
+// -> 400 on a malformed/over-long views[] (max 12).
+// Exactly one PNG comes back per requested view,
+// in request order — the caller composites a grid
+// whose shape it chose from that length, so this
+// rejects rather than truncating.
+// POST /bake -> 501 (texture bakes are a later workstream)
+// Auth: $RENDER_SERVICE_TOKEN on POST routes (required if set; boot warns loudly
+// when unset), supplied as either `x-render-token: <token>` or
+// `Authorization: Bearer <token>`. The custom header exists because RunPod's
+// load-balancer gateway consumes Authorization for its own edge API-key auth, so
+// gateway callers can never deliver an app-layer bearer token through it.
+// Renders are serialized: one GPU, one queue.
+import { createServer } from 'node:http';
+import { PRESENTATION_PROFILE_ID, initRenderer, renderGlb } from './renderer.mjs';
+import { acquireGpu } from './gpu.mjs';
+import { buildHealthDocument } from './health-contract.mjs';
+import { createRendererCaptureIdentity } from './cache-identity.mjs';
+import {
+ buildRenderFidelityV1,
+ buildRenderOperationalEvidenceV1,
+ createSerialRenderQueue,
+ httpRenderOutcomeCode,
+ outputSetSha256,
+ sha256,
+ validateInputGlbIdentity,
+ validateRenderMode,
+} from './contract.mjs';
+
+const PROCESS_STARTED_AT = performance.now();
+const PORT = Number(process.env.PORT ?? 8000);
+// Unset binds every interface, which is what a container deployment needs and is
+// the long-standing default here. A service started FOR the user -- by the MCP
+// server's on-demand start -- passes 127.0.0.1 instead, because choosing on
+// somebody's behalf to put a renderer on their LAN is not ours to choose.
+const HOST = process.env.HOST || undefined;
+const TOKEN = process.env.RENDER_SERVICE_TOKEN ?? '';
+
+const MAX_BODY = 96 * 1024 * 1024; // 64MB base64 ≈ 48MB GLB, plus JSON overhead
+const MAX_GLB = 48 * 1024 * 1024;
+
+// Boot assertion: a software adapter must prevent the service from starting at all,
+// so a driver regression yields a service that will not boot rather than one that
+// silently renders everything on CPU.
+let gpuState;
+try {
+ gpuState = await acquireGpu();
+ await initRenderer();
+} catch (e) {
+ console.error(`FATAL: ${e.message}`);
+ process.exit(1);
+}
+gpuState.captureIdentity = createRendererCaptureIdentity(gpuState);
+console.log(`adapter: ${JSON.stringify(gpuState.summary)}`);
+console.log(`rendererId: ${gpuState.rendererId}`);
+if (!TOKEN) console.warn('WARNING: RENDER_SERVICE_TOKEN unset — POST routes are UNAUTHENTICATED');
+
+const renderQueue = createSerialRenderQueue({ processStartedAt: PROCESS_STARTED_AT });
+
+function readBody(req) {
+ return new Promise((resolve, reject) => {
+ const chunks = [];
+ let total = 0;
+ req.on('data', (c) => {
+ total += c.length;
+ if (total > MAX_BODY) {
+ reject(Object.assign(new Error('body too large'), { status: 413 }));
+ req.destroy();
+ return;
+ }
+ chunks.push(c);
+ });
+ req.on('end', () => resolve(Buffer.concat(chunks)));
+ req.on('error', reject);
+ });
+}
+
+function send(res, status, obj) {
+ const body = JSON.stringify(obj);
+ res.writeHead(status, {
+ 'content-type': 'application/json',
+ 'content-length': Buffer.byteLength(body),
+ });
+ res.end(body);
+}
+
+const server = createServer(async (req, res) => {
+ const started = performance.now();
+ // Accumulated across the handler and emitted exactly once by done(). Only
+ // names and sizes go in here — never a token, a header value, or GLB bytes.
+ // Path only, never the query string: nothing here accepts a token as a query
+ // parameter, but logging the raw URL would make any future one a disclosure.
+ const log = {
+ method: req.method,
+ path: String(req.url ?? '')
+ .split('?')[0]
+ .slice(0, 200),
+ auth: 'not-required',
+ };
+ const done = (status, obj) => {
+ send(res, status, obj);
+ const outcomeCode = httpRenderOutcomeCode({
+ method: log.method,
+ path: log.path,
+ status,
+ });
+ console.log(
+ JSON.stringify({
+ evt: 'request',
+ ...log,
+ outcomeCode,
+ status,
+ ...(status >= 400 && obj?.error ? { error: obj.error } : {}),
+ ms: +(performance.now() - started).toFixed(1),
+ }),
+ );
+ };
+ try {
+ // /ping: RunPod load-balancer health convention (200 = healthy). The boot
+ // assertion guarantees a listening server implies a hardware adapter.
+ if (req.method === 'GET' && (req.url === '/health' || req.url === '/ping')) {
+ // Capability advertisement, not decoration: a GitHub-build endpoint carries
+ // no commit stamp, so this is the only way a caller can tell WHICH build is
+ // live before depending on a feature. The pure builder is contract-tested
+ // without booting a GPU and advertises every registry ID explicitly.
+ return done(200, buildHealthDocument(gpuState, Boolean(TOKEN)));
+ }
+ if (req.method === 'POST' && (req.url === '/render' || req.url === '/bake')) {
+ if (TOKEN) {
+ const auth = req.headers.authorization ?? '';
+ const custom = req.headers['x-render-token'] ?? '';
+ if (auth !== `Bearer ${TOKEN}` && custom !== TOKEN) {
+ log.auth = 'rejected';
+ return done(401, { ok: false, error: 'unauthorized' });
+ }
+ // Which header carried it, never the value: the gateway strips
+ // Authorization, so this distinguishes a gateway caller from a direct one.
+ log.auth = 'ok';
+ log.authVia = custom === TOKEN ? 'x-render-token' : 'authorization';
+ } else {
+ log.auth = 'disabled';
+ }
+ if (req.url === '/bake') return done(501, { ok: false, error: 'bake not implemented yet' });
+
+ const raw = await readBody(req);
+ log.bodyBytes = raw.length;
+ let body;
+ try {
+ body = JSON.parse(raw.toString('utf8'));
+ } catch {
+ return done(400, { ok: false, error: 'invalid JSON' });
+ }
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
+ return done(400, { ok: false, error: 'JSON body must be an object' });
+ }
+ if (typeof body.glb_base64 !== 'string' || !body.glb_base64) {
+ return done(400, { ok: false, error: 'glb_base64 (string) required' });
+ }
+ const glb = Buffer.from(body.glb_base64, 'base64');
+ log.glbBytes = glb.length;
+ if (glb.length < 20 || glb.readUInt32LE(0) !== 0x46546c67) {
+ return done(400, { ok: false, error: 'not a GLB (bad magic)' });
+ }
+ if (glb.length > MAX_GLB) return done(413, { ok: false, error: 'GLB too large' });
+ // New fidelity-aware callers assert the identity they sent. Legacy callers
+ // omit it and retain their exact historical response shape.
+ let inputGlbSha256;
+ try {
+ inputGlbSha256 = validateInputGlbIdentity(glb, body.input_glb_sha256);
+ } catch (e) {
+ return done(e.status ?? 400, { ok: false, error: String(e.message ?? e) });
+ }
+ const fidelityRequested = body.input_glb_sha256 !== undefined;
+ log.inputGlbSha256 = inputGlbSha256;
+ // Validated BEFORE the queue: malformed exact cameras or legacy views are
+ // immediate 400s, not GPU-queue work. renderGlb validates again for direct callers.
+ let renderMode;
+ try {
+ renderMode = validateRenderMode(body);
+ } catch (e) {
+ return done(e.status ?? 400, { ok: false, error: String(e.message ?? e) });
+ }
+ log.renderMode = renderMode.mode;
+ if (renderMode.mode === 'camera') {
+ log.camerasRequested = renderMode.cameras.length;
+ log.width = renderMode.width;
+ log.height = renderMode.height;
+ log.totalPixels = renderMode.totalPixels;
+ log.lightingPresetId = renderMode.lightingPresetId;
+ log.backend = gpuState.backend;
+ log.rendererId = gpuState.rendererId;
+ } else {
+ log.viewsRequested = renderMode.viewDirs.length;
+ }
+
+ const t0 = performance.now();
+ const queued = await renderQueue.enqueue(async (operationalStart) => {
+ log.renderOperationalStart = operationalStart;
+ return {
+ operationalStart,
+ result: await renderGlb(
+ glb,
+ renderMode.mode === 'camera'
+ ? {
+ cameras: renderMode.cameras,
+ width: renderMode.width,
+ height: renderMode.height,
+ lightingPresetId: renderMode.lightingPresetId,
+ background: renderMode.background,
+ }
+ : {
+ size: renderMode.size,
+ viewDirs: renderMode.viewDirs,
+ beautySize: renderMode.beautySize,
+ background: renderMode.background,
+ },
+ ),
+ };
+ });
+ const result = queued.result;
+ const timings = {
+ ...result.timings,
+ queueWaitMs: +queued.operationalStart.queueWaitMs.toFixed(1),
+ queueAndTotalMs: +(performance.now() - t0).toFixed(1),
+ };
+ log.views = result.views.length;
+ log.beauty = Boolean(result.beauty);
+ log.timings = timings;
+ const viewSha256 = result.views.map(sha256);
+ const outputSetHash = outputSetSha256(result.views);
+ if (renderMode.mode === 'camera') log.outputSetSha256 = outputSetHash;
+ const appliedPresentationProfile = result.lightingPresetId ?? PRESENTATION_PROFILE_ID;
+ const fidelity = fidelityRequested
+ ? buildRenderFidelityV1({
+ rendererId: gpuState.rendererId,
+ inputGlbSha256,
+ presentationProfile: appliedPresentationProfile,
+ renderMode,
+ resolvedCameras: result.cameras ?? [],
+ timings,
+ })
+ : undefined;
+ const operationalEvidence = buildRenderOperationalEvidenceV1({
+ outcomeCode: 'gpu_success',
+ ...queued.operationalStart,
+ });
+ log.operationalEvidence = operationalEvidence;
+ delete log.renderOperationalStart;
+ return done(200, {
+ ok: true,
+ rendererId: gpuState.rendererId,
+ presentationProfile: appliedPresentationProfile,
+ timings,
+ views: result.views.map((b) => b.toString('base64')),
+ ...(result.beauty ? { beauty: result.beauty.toString('base64') } : {}),
+ ...(fidelity ? { inputGlbSha256, fidelity, operationalEvidence } : {}),
+ ...(renderMode.mode === 'camera'
+ ? {
+ backend: gpuState.backend,
+ cameras: result.cameras,
+ width: result.width,
+ height: result.height,
+ lightingPresetId: result.lightingPresetId,
+ viewSha256,
+ outputSetSha256: outputSetHash,
+ cameraReceipts: result.cameras.map((camera, index) => ({
+ index,
+ camera,
+ width: result.width,
+ height: result.height,
+ outputSha256: viewSha256[index],
+ })),
+ }
+ : {}),
+ });
+ }
+ done(404, { ok: false, error: 'not found' });
+ } catch (e) {
+ if (log.renderOperationalStart && !log.operationalEvidence) {
+ try {
+ log.operationalEvidence = buildRenderOperationalEvidenceV1({
+ outcomeCode: 'render_failed',
+ ...log.renderOperationalStart,
+ });
+ } catch {
+ /* never mask the original render failure with metrics evidence */
+ }
+ delete log.renderOperationalStart;
+ }
+ done(e.status ?? 500, { ok: false, error: String(e.message ?? e) });
+ }
+});
+
+server.listen(PORT, HOST, () =>
+ console.log(`kiln-render-service listening on ${HOST ?? '*'}:${PORT}`),
+);
diff --git a/render-service/test/asset-camera.test.mjs b/render-service/test/asset-camera.test.mjs
index 163b84c6..7b50a60e 100644
--- a/render-service/test/asset-camera.test.mjs
+++ b/render-service/test/asset-camera.test.mjs
@@ -1,5 +1,36 @@
-import {test} from 'node:test';import assert from 'node:assert/strict';import {validateCameraMode} from '../src/contract.mjs';
-const camera={version:'kiln.camera.v1',projection:'orthographic',position:[3,2,4],target:[0,0,0],up:[0,1,0],halfHeight:2,aspect:1,near:.1,far:100};
-test('versioned orthographic cameras retain exact framing',()=>{const result=validateCameraMode({cameras:[camera],width:128,height:128});assert.deepEqual(result.cameras,[camera]);assert.throws(()=>validateCameraMode({cameras:[{...camera,halfHeight:0}],width:128,height:128}),/halfHeight/);});
-import {buildRenderFidelityV1} from '../src/contract.mjs';
-test('orthographic service receipt retains projection and half-height',()=>{const parsed=validateCameraMode({cameras:[camera],width:128,height:128});const receipt=buildRenderFidelityV1({rendererId:'gpu:test',inputGlbSha256:`sha256:${'a'.repeat(64)}`,presentationProfile:parsed.lightingPresetId,renderMode:{mode:'camera',...parsed},resolvedCameras:parsed.cameras,timings:{totalMs:1,queueAndTotalMs:1}});assert.equal(receipt.resolvedCameras[0].halfHeight,2);assert.equal(receipt.resolvedCameras[0].projection,'orthographic');});
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { validateCameraMode } from '../src/contract.mjs';
+const camera = {
+ version: 'kiln.camera.v1',
+ projection: 'orthographic',
+ position: [3, 2, 4],
+ target: [0, 0, 0],
+ up: [0, 1, 0],
+ halfHeight: 2,
+ aspect: 1,
+ near: 0.1,
+ far: 100,
+};
+test('versioned orthographic cameras retain exact framing', () => {
+ const result = validateCameraMode({ cameras: [camera], width: 128, height: 128 });
+ assert.deepEqual(result.cameras, [camera]);
+ assert.throws(
+ () => validateCameraMode({ cameras: [{ ...camera, halfHeight: 0 }], width: 128, height: 128 }),
+ /halfHeight/,
+ );
+});
+import { buildRenderFidelityV1 } from '../src/contract.mjs';
+test('orthographic service receipt retains projection and half-height', () => {
+ const parsed = validateCameraMode({ cameras: [camera], width: 128, height: 128 });
+ const receipt = buildRenderFidelityV1({
+ rendererId: 'gpu:test',
+ inputGlbSha256: `sha256:${'a'.repeat(64)}`,
+ presentationProfile: parsed.lightingPresetId,
+ renderMode: { mode: 'camera', ...parsed },
+ resolvedCameras: parsed.cameras,
+ timings: { totalMs: 1, queueAndTotalMs: 1 },
+ });
+ assert.equal(receipt.resolvedCameras[0].halfHeight, 2);
+ assert.equal(receipt.resolvedCameras[0].projection, 'orthographic');
+});
diff --git a/render-service/test/beauty-camera.test.mjs b/render-service/test/beauty-camera.test.mjs
index e5b5cca8..c9e19f7f 100644
--- a/render-service/test/beauty-camera.test.mjs
+++ b/render-service/test/beauty-camera.test.mjs
@@ -1,2 +1,30 @@
-import {test} from 'node:test';import assert from 'node:assert/strict';import * as THREE from 'three/webgpu';import {beautyCameraSpec} from '../src/framing.mjs';
-test('legacy beauty camera frames a translated sphere without near/far clipping',()=>{for(const radius of [.001,1,100]){const center=[12,-7,32],spec=beautyCameraSpec(center,radius);const camera=new THREE.PerspectiveCamera(spec.fovDeg,spec.aspect,spec.near,spec.far);camera.position.fromArray(spec.position);camera.up.fromArray(spec.up);camera.lookAt(...spec.target);camera.updateMatrixWorld(true);for(let lat=0;lat<=12;lat++)for(let lon=0;lon<24;lon++){const theta=lat*Math.PI/12,phi=lon*Math.PI/12;const p=new THREE.Vector3(center[0]+radius*Math.sin(theta)*Math.cos(phi),center[1]+radius*Math.cos(theta),center[2]+radius*Math.sin(theta)*Math.sin(phi)).project(camera);assert(Math.abs(p.x)<1&&Math.abs(p.y)<1&&p.z>-1&&p.z<1,'sphere must stay in frame')}assert.deepEqual(spec.target,center)}});
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import * as THREE from 'three/webgpu';
+import { beautyCameraSpec } from '../src/framing.mjs';
+test('legacy beauty camera frames a translated sphere without near/far clipping', () => {
+ for (const radius of [0.001, 1, 100]) {
+ const center = [12, -7, 32],
+ spec = beautyCameraSpec(center, radius);
+ const camera = new THREE.PerspectiveCamera(spec.fovDeg, spec.aspect, spec.near, spec.far);
+ camera.position.fromArray(spec.position);
+ camera.up.fromArray(spec.up);
+ camera.lookAt(...spec.target);
+ camera.updateMatrixWorld(true);
+ for (let lat = 0; lat <= 12; lat++)
+ for (let lon = 0; lon < 24; lon++) {
+ const theta = (lat * Math.PI) / 12,
+ phi = (lon * Math.PI) / 12;
+ const p = new THREE.Vector3(
+ center[0] + radius * Math.sin(theta) * Math.cos(phi),
+ center[1] + radius * Math.cos(theta),
+ center[2] + radius * Math.sin(theta) * Math.sin(phi),
+ ).project(camera);
+ assert(
+ Math.abs(p.x) < 1 && Math.abs(p.y) < 1 && p.z > -1 && p.z < 1,
+ 'sphere must stay in frame',
+ );
+ }
+ assert.deepEqual(spec.target, center);
+ }
+});
diff --git a/render-service/test/cache-identity.test.mjs b/render-service/test/cache-identity.test.mjs
index c58010d1..17edf509 100644
--- a/render-service/test/cache-identity.test.mjs
+++ b/render-service/test/cache-identity.test.mjs
@@ -1,2 +1,24 @@
-import {test} from 'node:test';import assert from 'node:assert/strict';import {mkdtempSync,writeFileSync,rmSync} from 'node:fs';import {tmpdir} from 'node:os';import {join,resolve,sep} from 'node:path';import {fingerprintRendererInputs} from '../src/cache-identity.mjs';
-test('renderer fingerprint changes with source, installed runtime bytes, and adapter',()=>{const dir=mkdtempSync(join(tmpdir(),'kiln-render-id-'));try{writeFileSync(join(dir,'renderer.mjs'),'one');const state={rendererId:'gpu',backend:'d3d12',summary:{device:'one'}};const first=fingerprintRendererInputs([dir],state);assert.equal(first,fingerprintRendererInputs([dir],state));writeFileSync(join(dir,'renderer.mjs'),'two');assert.notEqual(first,fingerprintRendererInputs([dir],state));assert.notEqual(fingerprintRendererInputs([dir],state),fingerprintRendererInputs([dir],{...state,summary:{device:'two'}}));}finally{assert.ok(resolve(dir).startsWith(resolve(tmpdir())+sep));rmSync(dir,{recursive:true,force:true});}});
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve, sep } from 'node:path';
+import { fingerprintRendererInputs } from '../src/cache-identity.mjs';
+test('renderer fingerprint changes with source, installed runtime bytes, and adapter', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'kiln-render-id-'));
+ try {
+ writeFileSync(join(dir, 'renderer.mjs'), 'one');
+ const state = { rendererId: 'gpu', backend: 'd3d12', summary: { device: 'one' } };
+ const first = fingerprintRendererInputs([dir], state);
+ assert.equal(first, fingerprintRendererInputs([dir], state));
+ writeFileSync(join(dir, 'renderer.mjs'), 'two');
+ assert.notEqual(first, fingerprintRendererInputs([dir], state));
+ assert.notEqual(
+ fingerprintRendererInputs([dir], state),
+ fingerprintRendererInputs([dir], { ...state, summary: { device: 'two' } }),
+ );
+ } finally {
+ assert.ok(resolve(dir).startsWith(resolve(tmpdir()) + sep));
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/render-service/test/contract.test.mjs b/render-service/test/contract.test.mjs
index e9dfd372..e36d2997 100644
--- a/render-service/test/contract.test.mjs
+++ b/render-service/test/contract.test.mjs
@@ -54,7 +54,10 @@ describe('provider-free render contract', () => {
parsed.viewDirs[0][0] = 99;
assert.equal(validateViewDirs(undefined)[0][0], 1);
- const requested = [[1, 0, 0], [0, 0, -1]];
+ const requested = [
+ [1, 0, 0],
+ [0, 0, -1],
+ ];
const directions = validateViewDirs(requested);
assert.deepEqual(directions, requested);
assert.notEqual(directions, requested);
@@ -74,12 +77,17 @@ describe('provider-free render contract', () => {
});
assert.notEqual(parsed.cameras, body.cameras);
assert.notEqual(parsed.cameras[0].position, body.cameras[0].position);
- assert.equal(validateRenderMode({ ...body, lighting_preset_id: undefined }).lightingPresetId,
- SUPPORTED_LIGHTING_PRESET_ID);
- assert.equal(validateRenderMode({
- ...body,
- input_glb_sha256: `sha256:${'a'.repeat(64)}`,
- }).mode, 'camera');
+ assert.equal(
+ validateRenderMode({ ...body, lighting_preset_id: undefined }).lightingPresetId,
+ SUPPORTED_LIGHTING_PRESET_ID,
+ );
+ assert.equal(
+ validateRenderMode({
+ ...body,
+ input_glb_sha256: `sha256:${'a'.repeat(64)}`,
+ }).mode,
+ 'camera',
+ );
});
it('rejects mixed legacy and exact selectors in either direction', () => {
@@ -87,26 +95,44 @@ describe('provider-free render contract', () => {
throws400(() => validateRenderMode({ ...exactBody(), ...legacy }), /mutually exclusive/);
}
throws400(() => validateRenderMode({ ...exactBody(), mystery_option: true }), /unknown/);
- throws400(() => validateRenderMode({ ...exactBody(), background: '#000000' }), /cannot override/);
- for (const cameraOnly of [{ width: 1 }, { height: 1 }, { lighting_preset_id: SUPPORTED_LIGHTING_PRESET_ID }]) {
+ throws400(
+ () => validateRenderMode({ ...exactBody(), background: '#000000' }),
+ /cannot override/,
+ );
+ for (const cameraOnly of [
+ { width: 1 },
+ { height: 1 },
+ { lighting_preset_id: SUPPORTED_LIGHTING_PRESET_ID },
+ ]) {
throws400(() => validateRenderMode(cameraOnly), /require cameras/);
}
});
it('bounds dimensions, camera count, and total transient pixels', () => {
throws400(() => validateCameraMode({ cameras: [], width: 1, height: 1 }), /1\.\.12/);
- throws400(() => validateCameraMode({
- cameras: Array.from({ length: MAX_CAMERAS + 1 }, () => camera({ aspect: 1 })),
- width: 1,
- height: 1,
- }), /1\.\.12/);
+ throws400(
+ () =>
+ validateCameraMode({
+ cameras: Array.from({ length: MAX_CAMERAS + 1 }, () => camera({ aspect: 1 })),
+ width: 1,
+ height: 1,
+ }),
+ /1\.\.12/,
+ );
throws400(() => validateCameraMode({ cameras: [camera()], width: 0, height: 720 }), /width/);
- throws400(() => validateCameraMode({ cameras: [camera()], width: 1280, height: 4097 }), /height/);
- throws400(() => validateCameraMode({
- cameras: [camera({ aspect: 1 }), camera({ aspect: 1 })],
- width: 4096,
- height: 4096,
- }), /total pixels/);
+ throws400(
+ () => validateCameraMode({ cameras: [camera()], width: 1280, height: 4097 }),
+ /height/,
+ );
+ throws400(
+ () =>
+ validateCameraMode({
+ cameras: [camera({ aspect: 1 }), camera({ aspect: 1 })],
+ width: 4096,
+ height: 4096,
+ }),
+ /total pixels/,
+ );
const boundary = validateCameraMode({
cameras: [camera({ aspect: 1 })],
width: 4096,
@@ -117,16 +143,37 @@ describe('provider-free render contract', () => {
it('fails closed on malformed or ambiguous perspective cameras', () => {
const base = { cameras: [camera()], width: 1280, height: 720 };
- throws400(() => validateCameraMode({ ...base, cameras: [{ ...camera(), surprise: true }] }), /unknown/);
- throws400(() => validateCameraMode({ ...base, cameras: [camera({ position: [0, 0] })] }), /position/);
- throws400(() => validateCameraMode({ ...base, cameras: [camera({ target: [12, 8, 15] })] }), /differ/);
- throws400(() => validateCameraMode({ ...base, cameras: [camera({ up: [0, 0, 0] })] }), /non-zero/);
- throws400(() => validateCameraMode({ ...base, cameras: [camera({ up: [12, 7, 15] })] }), /collinear/);
+ throws400(
+ () => validateCameraMode({ ...base, cameras: [{ ...camera(), surprise: true }] }),
+ /unknown/,
+ );
+ throws400(
+ () => validateCameraMode({ ...base, cameras: [camera({ position: [0, 0] })] }),
+ /position/,
+ );
+ throws400(
+ () => validateCameraMode({ ...base, cameras: [camera({ target: [12, 8, 15] })] }),
+ /differ/,
+ );
+ throws400(
+ () => validateCameraMode({ ...base, cameras: [camera({ up: [0, 0, 0] })] }),
+ /non-zero/,
+ );
+ throws400(
+ () => validateCameraMode({ ...base, cameras: [camera({ up: [12, 7, 15] })] }),
+ /collinear/,
+ );
throws400(() => validateCameraMode({ ...base, cameras: [camera({ fovDeg: 180 })] }), /fovDeg/);
throws400(() => validateCameraMode({ ...base, cameras: [camera({ near: 0 })] }), /near/);
throws400(() => validateCameraMode({ ...base, cameras: [camera({ far: 0.05 })] }), /far/);
- throws400(() => validateCameraMode({ ...base, cameras: [camera({ aspect: 1 })] }), /width\/height/);
- throws400(() => validateCameraMode({ ...base, lightingPresetId: 'dramatic-night-v1' }), /neutral-studio-v1/);
+ throws400(
+ () => validateCameraMode({ ...base, cameras: [camera({ aspect: 1 })] }),
+ /width\/height/,
+ );
+ throws400(
+ () => validateCameraMode({ ...base, lightingPresetId: 'dramatic-night-v1' }),
+ /neutral-studio-v1/,
+ );
});
it('binds ordered output identity without pretending it is a composite hash', () => {
@@ -135,7 +182,10 @@ describe('provider-free render contract', () => {
assert.match(sha256(first), /^sha256:[0-9a-f]{64}$/);
assert.equal(outputSetSha256([first, second]), outputSetSha256([first, second]));
assert.notEqual(outputSetSha256([first, second]), outputSetSha256([second, first]));
- assert.notEqual(outputSetSha256([first, second]), outputSetSha256([Buffer.concat([first, second])]));
+ assert.notEqual(
+ outputSetSha256([first, second]),
+ outputSetSha256([Buffer.concat([first, second])]),
+ );
});
it('computes the exact input GLB identity and fails closed on a claimed mismatch', () => {
@@ -216,10 +266,11 @@ describe('provider-free render contract', () => {
/presentationProfile must be one of: neutral-studio-v1, gallery-studio-v1/,
);
throws400(
- () => buildRenderFidelityV1({
- ...common,
- resolvedCameras: [camera({ position: [99, 8, 15] })],
- }),
+ () =>
+ buildRenderFidelityV1({
+ ...common,
+ resolvedCameras: [camera({ position: [99, 8, 15] })],
+ }),
/resolved cameras do not match/,
);
throws400(
@@ -231,17 +282,19 @@ describe('provider-free render contract', () => {
/timings.secretMs is unknown/,
);
throws400(
- () => buildRenderFidelityV1({
- ...common,
- timings: { totalMs: 10, queueAndTotalMs: 9 },
- }),
+ () =>
+ buildRenderFidelityV1({
+ ...common,
+ timings: { totalMs: 10, queueAndTotalMs: 9 },
+ }),
/queueAndTotalMs must be at least totalMs/,
);
throws400(
- () => buildRenderFidelityV1({
- ...common,
- timings: { totalMs: 10, queueWaitMs: 13, queueAndTotalMs: 12 },
- }),
+ () =>
+ buildRenderFidelityV1({
+ ...common,
+ timings: { totalMs: 10, queueWaitMs: 13, queueAndTotalMs: 12 },
+ }),
/queueWaitMs must not exceed queueAndTotalMs/,
);
});
@@ -271,14 +324,38 @@ describe('provider-free render contract', () => {
'route_not_found',
'render_failed',
]);
- assert.equal(httpRenderOutcomeCode({ method: 'GET', path: '/health', status: 200 }), 'health_ok');
- assert.equal(httpRenderOutcomeCode({ method: 'POST', path: '/render', status: 200 }), 'gpu_success');
- assert.equal(httpRenderOutcomeCode({ method: 'POST', path: '/render', status: 401 }), 'auth_rejected');
- assert.equal(httpRenderOutcomeCode({ method: 'POST', path: '/render', status: 400 }), 'request_rejected');
- assert.equal(httpRenderOutcomeCode({ method: 'POST', path: '/render', status: 413 }), 'request_rejected');
- assert.equal(httpRenderOutcomeCode({ method: 'POST', path: '/bake', status: 501 }), 'not_implemented');
- assert.equal(httpRenderOutcomeCode({ method: 'GET', path: '/missing', status: 404 }), 'route_not_found');
- assert.equal(httpRenderOutcomeCode({ method: 'POST', path: '/render', status: 500 }), 'render_failed');
+ assert.equal(
+ httpRenderOutcomeCode({ method: 'GET', path: '/health', status: 200 }),
+ 'health_ok',
+ );
+ assert.equal(
+ httpRenderOutcomeCode({ method: 'POST', path: '/render', status: 200 }),
+ 'gpu_success',
+ );
+ assert.equal(
+ httpRenderOutcomeCode({ method: 'POST', path: '/render', status: 401 }),
+ 'auth_rejected',
+ );
+ assert.equal(
+ httpRenderOutcomeCode({ method: 'POST', path: '/render', status: 400 }),
+ 'request_rejected',
+ );
+ assert.equal(
+ httpRenderOutcomeCode({ method: 'POST', path: '/render', status: 413 }),
+ 'request_rejected',
+ );
+ assert.equal(
+ httpRenderOutcomeCode({ method: 'POST', path: '/bake', status: 501 }),
+ 'not_implemented',
+ );
+ assert.equal(
+ httpRenderOutcomeCode({ method: 'GET', path: '/missing', status: 404 }),
+ 'route_not_found',
+ );
+ assert.equal(
+ httpRenderOutcomeCode({ method: 'POST', path: '/render', status: 500 }),
+ 'render_failed',
+ );
});
it('builds bounded queue/concurrency evidence with only stable fields', () => {
@@ -375,7 +452,9 @@ describe('provider-free render contract', () => {
let now = 100;
const queue = createSerialRenderQueue({ now: () => now, processStartedAt: 0 });
let releaseFirst;
- const firstGate = new Promise((resolve) => { releaseFirst = resolve; });
+ const firstGate = new Promise((resolve) => {
+ releaseFirst = resolve;
+ });
const starts = [];
const first = queue.enqueue(async (start) => {
starts.push(start);
@@ -415,7 +494,12 @@ describe('provider-free render contract', () => {
it('serial queue settles a failed render and still starts the next job warm', async () => {
let now = 10;
const queue = createSerialRenderQueue({ now: () => now, processStartedAt: 0 });
- await assert.rejects(queue.enqueue(async () => { throw new Error('device lost'); }), /device lost/);
+ await assert.rejects(
+ queue.enqueue(async () => {
+ throw new Error('device lost');
+ }),
+ /device lost/,
+ );
now = 20;
const next = await queue.enqueue(async (start) => start);
assert.deepEqual(next, {
diff --git a/render-service/test/display-output-conformance.mjs b/render-service/test/display-output-conformance.mjs
index e26059b5..e92a6e12 100644
--- a/render-service/test/display-output-conformance.mjs
+++ b/render-service/test/display-output-conformance.mjs
@@ -9,37 +9,120 @@ import { packRgbaReadback } from '../src/readback.mjs';
import { markGpuShutdown } from '../src/gpu.mjs';
const out = new URL('../../tmp/display-output-proof/', import.meta.url);
await mkdir(out, { recursive: true });
-const colors = [[.04,.04,.04],[.18,.18,.18],[.5,.5,.5],[1,1,1],[2,2,2],[4,4,4],[.8,.05,.02],[.03,.6,.05],[.02,.04,.8]];
-const mul = (m,c) => m.map(row => row.reduce((s,v,i) => s+v*c[i],0));
+const colors = [
+ [0.04, 0.04, 0.04],
+ [0.18, 0.18, 0.18],
+ [0.5, 0.5, 0.5],
+ [1, 1, 1],
+ [2, 2, 2],
+ [4, 4, 4],
+ [0.8, 0.05, 0.02],
+ [0.03, 0.6, 0.05],
+ [0.02, 0.04, 0.8],
+];
+const mul = (m, c) => m.map((row) => row.reduce((s, v, i) => s + v * c[i], 0));
function expected(c, exposure) {
- const input=mul([[.59719,.35458,.04823],[.076,.90834,.01566],[.0284,.13383,.83777]],c.map(v=>v*exposure/.6));
- const fit=input.map(v=>(v*(v+.0245786)-.000090537)/(v*(v+.432951)*.983729+.238081));
- const linear=mul([[1.60475,-.53108,-.07367],[-.10208,1.10813,-.00605],[-.00327,-.07276,1.07602]],fit).map(v=>Math.max(0,Math.min(1,v)));
- return linear.map(v=>Math.round(255*(v<=.0031308?12.92*v:1.055*v**(1/2.4)-.055)));
+ const input = mul(
+ [
+ [0.59719, 0.35458, 0.04823],
+ [0.076, 0.90834, 0.01566],
+ [0.0284, 0.13383, 0.83777],
+ ],
+ c.map((v) => (v * exposure) / 0.6),
+ );
+ const fit = input.map(
+ (v) => (v * (v + 0.0245786) - 0.000090537) / (v * (v + 0.432951) * 0.983729 + 0.238081),
+ );
+ const linear = mul(
+ [
+ [1.60475, -0.53108, -0.07367],
+ [-0.10208, 1.10813, -0.00605],
+ [-0.00327, -0.07276, 1.07602],
+ ],
+ fit,
+ ).map((v) => Math.max(0, Math.min(1, v)));
+ return linear.map((v) =>
+ Math.round(255 * (v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055)),
+ );
+}
+const { renderer, gpuState } = await initRenderer();
+const scene = new THREE.Scene();
+scene.background = new THREE.Color(0);
+const geometry = new THREE.PlaneGeometry(0.96, 0.96);
+colors.forEach((c, i) => {
+ const material = new THREE.MeshBasicMaterial({
+ color: new THREE.Color().setRGB(...c, THREE.LinearSRGBColorSpace),
+ });
+ const mesh = new THREE.Mesh(geometry, material);
+ mesh.position.set((i % 3) - 1, 1 - Math.floor(i / 3), 0);
+ scene.add(mesh);
+});
+const camera = new THREE.OrthographicCamera(-1.5, 1.5, 1.5, -1.5, 0.1, 10);
+camera.position.z = 3;
+camera.lookAt(0, 0, 0);
+const target = new THREE.RenderTarget(270, 270, { samples: 4 });
+async function read(name) {
+ const data = packRgbaReadback(
+ await renderer.readRenderTargetPixelsAsync(target, 0, 0, 270, 270),
+ 270,
+ 270,
+ );
+ const png = new PNG({ width: 270, height: 270 });
+ data.copy(png.data);
+ await writeFile(new URL(`${name}.png`, out), PNG.sync.write(png));
+ return colors.map((_, i) => {
+ const at = ((Math.floor(i / 3) * 90 + 45) * 270 + (i % 3) * 90 + 45) * 4;
+ return [...data.subarray(at, at + 3)];
+ });
}
-const {renderer,gpuState}=await initRenderer();
-const scene=new THREE.Scene();scene.background=new THREE.Color(0);
-const geometry=new THREE.PlaneGeometry(.96,.96);
-colors.forEach((c,i)=>{const material=new THREE.MeshBasicMaterial({color:new THREE.Color().setRGB(...c,THREE.LinearSRGBColorSpace)});const mesh=new THREE.Mesh(geometry,material);mesh.position.set(i%3-1,1-Math.floor(i/3),0);scene.add(mesh)});
-const camera=new THREE.OrthographicCamera(-1.5,1.5,1.5,-1.5,.1,10);camera.position.z=3;camera.lookAt(0,0,0);
-const target=new THREE.RenderTarget(270,270,{samples:4});
-async function read(name){const data=packRgbaReadback(await renderer.readRenderTargetPixelsAsync(target,0,0,270,270),270,270);const png=new PNG({width:270,height:270});data.copy(png.data);await writeFile(new URL(name+'.png',out),PNG.sync.write(png));return colors.map((_,i)=>{const at=((Math.floor(i/3)*90+45)*270+i%3*90+45)*4;return [...data.subarray(at,at+3)]})}
try {
- renderer.toneMappingExposure=1.38;
- renderer.setRenderTarget(target);renderer.render(scene,camera);renderer.setRenderTarget(null);
- const legacy=await read('legacy-linear-clipped');
- renderDisplayTarget(renderer,scene,camera,target);
- const corrected=await read('display-aces-srgb'),reference=colors.map(c=>expected(c,1.38));
- for(let i=0;i<colors.length;i++)for(let j=0;j<3;j++)assert(Math.abs(corrected[i][j]-reference[i][j])<=2,JSON.stringify({patch:i,actual:corrected[i],reference:reference[i]}));
- assert.deepEqual(legacy[3],[255,255,255]);assert.deepEqual(legacy[5],[255,255,255]);
- assert(corrected[3][0]<corrected[4][0]&&corrected[4][0]<corrected[5][0]);
- renderer.toneMappingExposure=.7;renderDisplayTarget(renderer,scene,camera,target);
- const lower=await read('display-lower-exposure');
- for(let i=0;i<colors.length;i++)for(let j=0;j<3;j++)assert(Math.abs(lower[i][j]-expected(colors[i],.7)[j])<=2);
- assert(lower[1][0]<corrected[1][0]);
- const receipt={status:'passed',rendererId:gpuState.rendererId,inputLinearColors:colors,legacy,corrected,expected:reference,lowerExposure:lower,toleranceBytes:2,checks:['HDR whites1/2/4 remain distinguishable','neutral/color patches match ACES+exposure+sRGB','exposure changes actual output','unaligned270px readback retains rows']};
- await writeFile(new URL('receipt.json',out),JSON.stringify(receipt,null,2));console.log(JSON.stringify(receipt));
+ renderer.toneMappingExposure = 1.38;
+ renderer.setRenderTarget(target);
+ renderer.render(scene, camera);
+ renderer.setRenderTarget(null);
+ const legacy = await read('legacy-linear-clipped');
+ renderDisplayTarget(renderer, scene, camera, target);
+ const corrected = await read('display-aces-srgb'),
+ reference = colors.map((c) => expected(c, 1.38));
+ for (let i = 0; i < colors.length; i++)
+ for (let j = 0; j < 3; j++)
+ assert(
+ Math.abs(corrected[i][j] - reference[i][j]) <= 2,
+ JSON.stringify({ patch: i, actual: corrected[i], reference: reference[i] }),
+ );
+ assert.deepEqual(legacy[3], [255, 255, 255]);
+ assert.deepEqual(legacy[5], [255, 255, 255]);
+ assert(corrected[3][0] < corrected[4][0] && corrected[4][0] < corrected[5][0]);
+ renderer.toneMappingExposure = 0.7;
+ renderDisplayTarget(renderer, scene, camera, target);
+ const lower = await read('display-lower-exposure');
+ for (let i = 0; i < colors.length; i++)
+ for (let j = 0; j < 3; j++) assert(Math.abs(lower[i][j] - expected(colors[i], 0.7)[j]) <= 2);
+ assert(lower[1][0] < corrected[1][0]);
+ const receipt = {
+ status: 'passed',
+ rendererId: gpuState.rendererId,
+ inputLinearColors: colors,
+ legacy,
+ corrected,
+ expected: reference,
+ lowerExposure: lower,
+ toleranceBytes: 2,
+ checks: [
+ 'HDR whites1/2/4 remain distinguishable',
+ 'neutral/color patches match ACES+exposure+sRGB',
+ 'exposure changes actual output',
+ 'unaligned270px readback retains rows',
+ ],
+ };
+ await writeFile(new URL('receipt.json', out), JSON.stringify(receipt, null, 2));
+ console.log(JSON.stringify(receipt));
} finally {
- markGpuShutdown();target.dispose();geometry.dispose();for(const mesh of scene.children)mesh.material?.dispose();renderer.dispose();gpuState.device.destroy();
+ markGpuShutdown();
+ target.dispose();
+ geometry.dispose();
+ for (const mesh of scene.children) mesh.material?.dispose();
+ renderer.dispose();
+ gpuState.device.destroy();
}
process.exit(0);
diff --git a/render-service/test/display-output.test.mjs b/render-service/test/display-output.test.mjs
index acaad5c8..8400d35c 100644
--- a/render-service/test/display-output.test.mjs
+++ b/render-service/test/display-output.test.mjs
@@ -1,13 +1,55 @@
import assert from 'node:assert/strict';
-import {test} from 'node:test';
+import { test } from 'node:test';
import * as THREE from 'three/webgpu';
-import {renderDisplayTarget} from '../src/display-output.mjs';
-function fixture(){const canvas={width:4,height:4,style:{},addEventListener(){},removeEventListener(){},getContext(){throw Error('No GPU needed')}};const renderer=new THREE.WebGPURenderer({canvas,outputBufferType:THREE.HalfFloatType});renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.outputColorSpace=THREE.SRGBColorSpace;const target=new THREE.RenderTarget(16,8);return{renderer,target};}
-test('PNG output invokes the actual Three HDR framebuffer/display-transform path',()=>{
- const {renderer,target}=fixture();let observed;
- renderer.render=()=>{observed={target:renderer.getRenderTarget(),output:renderer.getOutputRenderTarget(),needsHdr:renderer.needsFrameBufferTarget,toneMapping:renderer.currentToneMapping,colorSpace:renderer.currentColorSpace,bufferType:renderer.getOutputBufferType()}};
- renderDisplayTarget(renderer,{}, {},target);
- assert.equal(observed.target,null,'must permit Three internal HDR framebuffer pass');assert.equal(observed.output,target);assert.equal(observed.needsHdr,true);assert.equal(observed.toneMapping,THREE.ACESFilmicToneMapping);assert.equal(observed.colorSpace,THREE.SRGBColorSpace);assert.equal(observed.bufferType,THREE.HalfFloatType);
- assert.equal(renderer.getRenderTarget(),null);assert.equal(renderer.getOutputRenderTarget(),null);
+import { renderDisplayTarget } from '../src/display-output.mjs';
+function fixture() {
+ const canvas = {
+ width: 4,
+ height: 4,
+ style: {},
+ addEventListener() {},
+ removeEventListener() {},
+ getContext() {
+ throw Error('No GPU needed');
+ },
+ };
+ const renderer = new THREE.WebGPURenderer({ canvas, outputBufferType: THREE.HalfFloatType });
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+ const target = new THREE.RenderTarget(16, 8);
+ return { renderer, target };
+}
+test('PNG output invokes the actual Three HDR framebuffer/display-transform path', () => {
+ const { renderer, target } = fixture();
+ let observed;
+ renderer.render = () => {
+ observed = {
+ target: renderer.getRenderTarget(),
+ output: renderer.getOutputRenderTarget(),
+ needsHdr: renderer.needsFrameBufferTarget,
+ toneMapping: renderer.currentToneMapping,
+ colorSpace: renderer.currentColorSpace,
+ bufferType: renderer.getOutputBufferType(),
+ };
+ };
+ renderDisplayTarget(renderer, {}, {}, target);
+ assert.equal(observed.target, null, 'must permit Three internal HDR framebuffer pass');
+ assert.equal(observed.output, target);
+ assert.equal(observed.needsHdr, true);
+ assert.equal(observed.toneMapping, THREE.ACESFilmicToneMapping);
+ assert.equal(observed.colorSpace, THREE.SRGBColorSpace);
+ assert.equal(observed.bufferType, THREE.HalfFloatType);
+ assert.equal(renderer.getRenderTarget(), null);
+ assert.equal(renderer.getOutputRenderTarget(), null);
+});
+test('a failed view restores prior public renderer targets', () => {
+ const { renderer, target } = fixture();
+ const previous = new THREE.RenderTarget(4, 4);
+ renderer.setOutputRenderTarget(previous);
+ renderer.render = () => {
+ throw Error('draw failed');
+ };
+ assert.throws(() => renderDisplayTarget(renderer, {}, {}, target), /draw failed/);
+ assert.equal(renderer.getRenderTarget(), null);
+ assert.equal(renderer.getOutputRenderTarget(), previous);
});
-test('a failed view restores prior public renderer targets',()=>{const {renderer,target}=fixture();const previous=new THREE.RenderTarget(4,4);renderer.setOutputRenderTarget(previous);renderer.render=()=>{throw Error('draw failed')};assert.throws(()=>renderDisplayTarget(renderer,{}, {},target),/draw failed/);assert.equal(renderer.getRenderTarget(),null);assert.equal(renderer.getOutputRenderTarget(),previous)});
diff --git a/render-service/test/gallery-presentation.test.mjs b/render-service/test/gallery-presentation.test.mjs
index 89b29d1b..2301b6f3 100644
--- a/render-service/test/gallery-presentation.test.mjs
+++ b/render-service/test/gallery-presentation.test.mjs
@@ -1,12 +1,20 @@
import assert from 'node:assert/strict';
-import {test} from 'node:test';
-import {getPresentationPreset,DEFAULT_PRESENTATION_PRESET_ID} from '../src/presentation-presets.mjs';
-test('gallery profile changes gallery exposure and backdrop and leaves default studio unchanged',()=>{
- const original=getPresentationPreset('neutral-studio-v1');
- const gallery=getPresentationPreset('gallery-studio-v1');
- assert.ok(gallery,'gallery profile must be selectable');
- assert.equal(DEFAULT_PRESENTATION_PRESET_ID,'neutral-studio-v1');
- assert.equal(original.exposure,1.38);
- assert.deepEqual(gallery,{...original,id:'gallery-studio-v1',exposure:0.9,background:'#747474'});
- assert.ok(Object.isFrozen(gallery));
+import { test } from 'node:test';
+import {
+ getPresentationPreset,
+ DEFAULT_PRESENTATION_PRESET_ID,
+} from '../src/presentation-presets.mjs';
+test('gallery profile changes gallery exposure and backdrop and leaves default studio unchanged', () => {
+ const original = getPresentationPreset('neutral-studio-v1');
+ const gallery = getPresentationPreset('gallery-studio-v1');
+ assert.ok(gallery, 'gallery profile must be selectable');
+ assert.equal(DEFAULT_PRESENTATION_PRESET_ID, 'neutral-studio-v1');
+ assert.equal(original.exposure, 1.38);
+ assert.deepEqual(gallery, {
+ ...original,
+ id: 'gallery-studio-v1',
+ exposure: 0.9,
+ background: '#747474',
+ });
+ assert.ok(Object.isFrozen(gallery));
});
diff --git a/render-service/test/generate-material-fixture.mjs b/render-service/test/generate-material-fixture.mjs
index 575f82c2..def01aad 100644
--- a/render-service/test/generate-material-fixture.mjs
+++ b/render-service/test/generate-material-fixture.mjs
@@ -39,15 +39,15 @@ function pngBytes(pixel) {
}
function sourceImages() {
- const checker = (x, y) => ((Math.floor(x / 4) + Math.floor(y / 4)) % 2) === 0;
+ const checker = (x, y) => (Math.floor(x / 4) + Math.floor(y / 4)) % 2 === 0;
return [
{
name: 'AlbedoChecker',
- bytes: pngBytes((x, y) => checker(x, y) ? [245, 245, 245, 255] : [18, 18, 18, 255]),
+ bytes: pngBytes((x, y) => (checker(x, y) ? [245, 245, 245, 255] : [18, 18, 18, 255])),
},
{
name: 'NormalSplit',
- bytes: pngBytes((x) => x < IMAGE_SIZE / 2 ? [32, 128, 224, 255] : [224, 128, 224, 255]),
+ bytes: pngBytes((x) => (x < IMAGE_SIZE / 2 ? [32, 128, 224, 255] : [224, 128, 224, 255])),
},
{
name: 'SharedOrm',
@@ -60,11 +60,11 @@ function sourceImages() {
},
{
name: 'EmissiveChecker',
- bytes: pngBytes((x, y) => checker(x, y) ? [255, 32, 8, 255] : [0, 0, 0, 255]),
+ bytes: pngBytes((x, y) => (checker(x, y) ? [255, 32, 8, 255] : [0, 0, 0, 255])),
},
{
name: 'AlphaChecker',
- bytes: pngBytes((x, y) => checker(x, y) ? [32, 255, 64, 255] : [255, 32, 192, 0]),
+ bytes: pngBytes((x, y) => (checker(x, y) ? [32, 255, 64, 255] : [255, 32, 192, 0])),
},
];
}
@@ -75,10 +75,10 @@ function align4(value) {
function panelRegion([x, y], insetWorld = 0.18) {
const half = PANEL_SIZE / 2 - insetWorld;
- const tanHalf = Math.tan(CAMERA.fovDeg * Math.PI / 360);
+ const tanHalf = Math.tan((CAMERA.fovDeg * Math.PI) / 360);
const project = (worldX, worldY) => ({
- x: WIDTH * (1 + worldX / (10 * tanHalf * CAMERA.aspect)) / 2,
- y: HEIGHT * (1 - worldY / (10 * tanHalf)) / 2,
+ x: (WIDTH * (1 + worldX / (10 * tanHalf * CAMERA.aspect))) / 2,
+ y: (HEIGHT * (1 - worldY / (10 * tanHalf))) / 2,
});
const topLeft = project(x - half, y + half);
const bottomRight = project(x + half, y - half);
@@ -102,13 +102,17 @@ function appendBuffer(parts, bufferViews, bytes, extra = {}) {
function floatBuffer(values) {
const bytes = Buffer.alloc(values.length * 4);
- values.forEach((value, index) => bytes.writeFloatLE(value, index * 4));
+ values.forEach((value, index) => {
+ bytes.writeFloatLE(value, index * 4);
+ });
return bytes;
}
function uint16Buffer(values) {
const bytes = Buffer.alloc(values.length * 2);
- values.forEach((value, index) => bytes.writeUInt16LE(value, index * 2));
+ values.forEach((value, index) => {
+ bytes.writeUInt16LE(value, index * 2);
+ });
return bytes;
}
@@ -137,22 +141,33 @@ function encodeGlb(json, bin) {
export function buildMaterialChannelsFixture() {
const parts = [];
const bufferViews = [];
- const positionView = appendBuffer(parts, bufferViews, floatBuffer([
- -0.9, -0.9, 0, 0.9, -0.9, 0, 0.9, 0.9, 0, -0.9, 0.9, 0,
- ]), { target: 34962 });
- const normalView = appendBuffer(parts, bufferViews, floatBuffer([
- 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,
- ]), { target: 34962 });
- const tangentView = appendBuffer(parts, bufferViews, floatBuffer([
- 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1,
- ]), { target: 34962 });
- const uv0View = appendBuffer(parts, bufferViews, floatBuffer([
- 0, 1, 1, 1, 1, 0, 0, 0,
- ]), { target: 34962 });
- const uv1View = appendBuffer(parts, bufferViews, floatBuffer([
- 0, 1, 1, 1, 1, 0, 0, 0,
- ]), { target: 34962 });
- const indexView = appendBuffer(parts, bufferViews, uint16Buffer([0, 1, 2, 0, 2, 3]), { target: 34963 });
+ const positionView = appendBuffer(
+ parts,
+ bufferViews,
+ floatBuffer([-0.9, -0.9, 0, 0.9, -0.9, 0, 0.9, 0.9, 0, -0.9, 0.9, 0]),
+ { target: 34962 },
+ );
+ const normalView = appendBuffer(
+ parts,
+ bufferViews,
+ floatBuffer([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
+ { target: 34962 },
+ );
+ const tangentView = appendBuffer(
+ parts,
+ bufferViews,
+ floatBuffer([1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1]),
+ { target: 34962 },
+ );
+ const uv0View = appendBuffer(parts, bufferViews, floatBuffer([0, 1, 1, 1, 1, 0, 0, 0]), {
+ target: 34962,
+ });
+ const uv1View = appendBuffer(parts, bufferViews, floatBuffer([0, 1, 1, 1, 1, 0, 0, 0]), {
+ target: 34962,
+ });
+ const indexView = appendBuffer(parts, bufferViews, uint16Buffer([0, 1, 2, 0, 2, 3]), {
+ target: 34963,
+ });
const images = sourceImages();
const imageJson = images.map((image) => ({
@@ -177,16 +192,27 @@ export function buildMaterialChannelsFixture() {
mesh: index,
translation: PANEL_CENTERS[name],
})),
- meshes: materialNames.map((name, index) => ({ name: `${name}Mesh`, primitives: [primitive(index)] })),
+ meshes: materialNames.map((name, index) => ({
+ name: `${name}Mesh`,
+ primitives: [primitive(index)],
+ })),
materials: [
{
name: 'AlbedoChecker',
- pbrMetallicRoughness: { baseColorTexture: { index: 0 }, metallicFactor: 0, roughnessFactor: 1 },
+ pbrMetallicRoughness: {
+ baseColorTexture: { index: 0 },
+ metallicFactor: 0,
+ roughnessFactor: 1,
+ },
doubleSided: true,
},
{
name: 'NormalResponse',
- pbrMetallicRoughness: { baseColorFactor: [0.62, 0.62, 0.62, 1], metallicFactor: 0, roughnessFactor: 0.7 },
+ pbrMetallicRoughness: {
+ baseColorFactor: [0.62, 0.62, 0.62, 1],
+ metallicFactor: 0,
+ roughnessFactor: 0.7,
+ },
normalTexture: { index: 1, scale: 1 },
doubleSided: true,
},
@@ -203,20 +229,32 @@ export function buildMaterialChannelsFixture() {
},
{
name: 'AoResponse',
- pbrMetallicRoughness: { baseColorFactor: [0.72, 0.72, 0.72, 1], metallicFactor: 0, roughnessFactor: 0.9 },
+ pbrMetallicRoughness: {
+ baseColorFactor: [0.72, 0.72, 0.72, 1],
+ metallicFactor: 0,
+ roughnessFactor: 0.9,
+ },
occlusionTexture: { index: 2, strength: 1 },
doubleSided: true,
},
{
name: 'EmissiveResponse',
- pbrMetallicRoughness: { baseColorFactor: [0.01, 0.01, 0.01, 1], metallicFactor: 0, roughnessFactor: 1 },
+ pbrMetallicRoughness: {
+ baseColorFactor: [0.01, 0.01, 0.01, 1],
+ metallicFactor: 0,
+ roughnessFactor: 1,
+ },
emissiveTexture: { index: 3 },
emissiveFactor: [1, 1, 1],
doubleSided: true,
},
{
name: 'AlphaResponse',
- pbrMetallicRoughness: { baseColorTexture: { index: 4 }, metallicFactor: 0, roughnessFactor: 0.8 },
+ pbrMetallicRoughness: {
+ baseColorTexture: { index: 4 },
+ metallicFactor: 0,
+ roughnessFactor: 0.8,
+ },
alphaMode: 'MASK',
alphaCutoff: 0.5,
doubleSided: true,
@@ -228,7 +266,14 @@ export function buildMaterialChannelsFixture() {
buffers: [{ byteLength: bin.length }],
bufferViews,
accessors: [
- { bufferView: positionView, componentType: 5126, count: 4, type: 'VEC3', min: [-0.9, -0.9, 0], max: [0.9, 0.9, 0] },
+ {
+ bufferView: positionView,
+ componentType: 5126,
+ count: 4,
+ type: 'VEC3',
+ min: [-0.9, -0.9, 0],
+ max: [0.9, 0.9, 0],
+ },
{ bufferView: normalView, componentType: 5126, count: 4, type: 'VEC3' },
{ bufferView: tangentView, componentType: 5126, count: 4, type: 'VEC4' },
{ bufferView: uv0View, componentType: 5126, count: 4, type: 'VEC2' },
@@ -247,7 +292,9 @@ export function buildMaterialChannelsFixture() {
lightingPresetId: 'neutral-studio-v1',
cameras: [CAMERA],
},
- regions: Object.fromEntries(Object.entries(PANEL_CENTERS).map(([name, center]) => [name, panelRegion(center)])),
+ regions: Object.fromEntries(
+ Object.entries(PANEL_CENTERS).map(([name, center]) => [name, panelRegion(center)]),
+ ),
};
return { glb, manifest };
}
@@ -257,8 +304,14 @@ async function main() {
const { glb, manifest } = buildMaterialChannelsFixture();
await mkdir(outputDir, { recursive: true });
await writeFile(resolve(outputDir, 'material-channels-v1.glb'), glb);
- await writeFile(resolve(outputDir, 'material-channels-v1.manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
- process.stdout.write(`wrote material-channels-v1.glb (${glb.length} bytes, ${manifest.glbSha256})\n`);
+ await writeFile(
+ resolve(outputDir, 'material-channels-v1.manifest.json'),
+ `${JSON.stringify(manifest, null, 2)}\n`,
+ );
+ process.stdout.write(
+ `wrote material-channels-v1.glb (${glb.length} bytes, ${manifest.glbSha256})\n`,
+ );
}
-if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) await main();
+if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url)
+ await main();
diff --git a/render-service/test/material-conformance.mjs b/render-service/test/material-conformance.mjs
index c4404890..d65147c8 100644
--- a/render-service/test/material-conformance.mjs
+++ b/render-service/test/material-conformance.mjs
@@ -7,7 +7,8 @@ import { PNG } from 'pngjs';
const fixtureUrl = new URL('./fixtures/material-channels-v1.glb', import.meta.url);
const manifestUrl = new URL('./fixtures/material-channels-v1.manifest.json', import.meta.url);
-const noHardware = /(?:no webgpu adapter|no usable .*device|software adapter refused|couldn(?:'|’)t find a suitable webgpu backend|requestadapter.*(?:failed|null)|(?:vulkan|d3d12|metal).*(?:unavailable|not found|failed to init))/i;
+const noHardware =
+ /(?:no webgpu adapter|no usable .*device|software adapter refused|couldn(?:'|’)t find a suitable webgpu backend|requestadapter.*(?:failed|null)|(?:vulkan|d3d12|metal).*(?:unavailable|not found|failed to init))/i;
// A fixture with embedded PNG buffer views has no reason to cross a network
// boundary. Fail closed if a loader regression ever attempts to do so.
@@ -33,7 +34,9 @@ Object.defineProperty(globalThis, 'fetch', {
// The exemption is a hole in a guard, so prove the guard is still closed around
// it before rendering anything through it.
await globalThis.fetch('https://example.invalid/texture.png').then(
- () => { throw new Error('network guard is open: an https fetch was permitted'); },
+ () => {
+ throw new Error('network guard is open: an https fetch was permitted');
+ },
(error) => {
if (!/network disabled/.test(String(error?.message ?? error)))
throw new Error(`network guard failed for an unexpected reason: ${error}`);
@@ -93,7 +96,10 @@ function colorDistance(a, b) {
}
async function main() {
- const [glb, manifestText] = await Promise.all([readFile(fixtureUrl), readFile(manifestUrl, 'utf8')]);
+ const [glb, manifestText] = await Promise.all([
+ readFile(fixtureUrl),
+ readFile(manifestUrl, 'utf8'),
+ ]);
const manifest = JSON.parse(manifestText);
let rendered;
try {
@@ -107,7 +113,9 @@ async function main() {
} catch (error) {
const message = String(error?.message ?? error);
if (noHardware.test(message)) {
- process.stdout.write(`SKIP material GPU conformance: no usable hardware WebGPU adapter (${message})\n`);
+ process.stdout.write(
+ `SKIP material GPU conformance: no usable hardware WebGPU adapter (${message})\n`,
+ );
process.exit(0);
}
throw error;
@@ -118,13 +126,14 @@ async function main() {
assert.equal(png.width, manifest.render.width);
assert.equal(png.height, manifest.render.height);
const region = (name) => manifest.regions[name];
- const stats = Object.fromEntries(Object.entries(manifest.regions).map(([name, box]) => [
- name,
- summarize(pixelsIn(png, box)),
- ]));
+ const stats = Object.fromEntries(
+ Object.entries(manifest.regions).map(([name, box]) => [name, summarize(pixelsIn(png, box))]),
+ );
- assert.ok(stats.AlbedoChecker.lumaSpread >= 45,
- `albedo checker did not modulate base color: ${stats.AlbedoChecker.lumaSpread}`);
+ assert.ok(
+ stats.AlbedoChecker.lumaSpread >= 45,
+ `albedo checker did not modulate base color: ${stats.AlbedoChecker.lumaSpread}`,
+ );
// This threshold is measured, and it was previously a guess that had never run:
// the albedo assertion above always failed first, so nothing below it was ever
@@ -142,11 +151,15 @@ async function main() {
// fixture would buy headroom and is the better instrument, but it would change
// what this file conforms -- the default tool rig.
const normalDelta = lumaDelta(halves(png, region('NormalResponse')));
- assert.ok(normalDelta >= 1,
- `normal map halves did not change lighting response: ${normalDelta.toFixed(1)}`);
+ assert.ok(
+ normalDelta >= 1,
+ `normal map halves did not change lighting response: ${normalDelta.toFixed(1)}`,
+ );
- assert.ok(stats.SharedOrmResponse.lumaSpread >= 5,
- `shared ORM channels did not change material response: ${stats.SharedOrmResponse.lumaSpread}`);
+ assert.ok(
+ stats.SharedOrmResponse.lumaSpread >= 5,
+ `shared ORM channels did not change material response: ${stats.SharedOrmResponse.lumaSpread}`,
+ );
const aoDelta = lumaDelta(halves(png, region('AoResponse')));
assert.ok(aoDelta >= 5, `AO red channel did not occlude one half: ${aoDelta.toFixed(1)}`);
@@ -154,30 +167,56 @@ async function main() {
const emissivePixels = pixelsIn(png, region('EmissiveResponse'));
const emissive = summarize(emissivePixels);
assert.ok(emissive.lumaSpread >= 30, `emissive checker response is flat: ${emissive.lumaSpread}`);
- assert.ok(percentile(emissivePixels.map((pixel) => pixel[0]), 0.9) >=
- percentile(emissivePixels.map((pixel) => pixel[1]), 0.9) + 35,
- 'emissive red channel is not visibly dominant');
+ assert.ok(
+ percentile(
+ emissivePixels.map((pixel) => pixel[0]),
+ 0.9,
+ ) >=
+ percentile(
+ emissivePixels.map((pixel) => pixel[1]),
+ 0.9,
+ ) +
+ 35,
+ 'emissive red channel is not visibly dominant',
+ );
const backgroundSamples = [
[png.data[0], png.data[1], png.data[2]],
- (() => { const i = (png.width - 1) * 4; return [png.data[i], png.data[i + 1], png.data[i + 2]]; })(),
- (() => { const i = ((png.height - 1) * png.width) * 4; return [png.data[i], png.data[i + 1], png.data[i + 2]]; })(),
- (() => { const i = (png.width * png.height - 1) * 4; return [png.data[i], png.data[i + 1], png.data[i + 2]]; })(),
+ (() => {
+ const i = (png.width - 1) * 4;
+ return [png.data[i], png.data[i + 1], png.data[i + 2]];
+ })(),
+ (() => {
+ const i = (png.height - 1) * png.width * 4;
+ return [png.data[i], png.data[i + 1], png.data[i + 2]];
+ })(),
+ (() => {
+ const i = (png.width * png.height - 1) * 4;
+ return [png.data[i], png.data[i + 1], png.data[i + 2]];
+ })(),
];
- const background = [0, 1, 2].map((channel) => mean(backgroundSamples.map((pixel) => pixel[channel])));
+ const background = [0, 1, 2].map((channel) =>
+ mean(backgroundSamples.map((pixel) => pixel[channel])),
+ );
const alphaPixels = pixelsIn(png, region('AlphaResponse'));
- const backgroundFraction = alphaPixels.filter((pixel) => colorDistance(pixel, background) <= 8).length / alphaPixels.length;
- assert.ok(backgroundFraction >= 0.2 && backgroundFraction <= 0.8,
- `alpha mask must expose both material and background: ${(backgroundFraction * 100).toFixed(1)}% background`);
-
- process.stdout.write(`${JSON.stringify({
- result: 'PASS',
- fixtureId: manifest.fixtureId,
- normalHalfLumaDelta: +normalDelta.toFixed(1),
- aoHalfLumaDelta: +aoDelta.toFixed(1),
- alphaBackgroundFraction: +backgroundFraction.toFixed(3),
- regions: stats,
- })}\n`);
+ const backgroundFraction =
+ alphaPixels.filter((pixel) => colorDistance(pixel, background) <= 8).length /
+ alphaPixels.length;
+ assert.ok(
+ backgroundFraction >= 0.2 && backgroundFraction <= 0.8,
+ `alpha mask must expose both material and background: ${(backgroundFraction * 100).toFixed(1)}% background`,
+ );
+
+ process.stdout.write(
+ `${JSON.stringify({
+ result: 'PASS',
+ fixtureId: manifest.fixtureId,
+ normalHalfLumaDelta: +normalDelta.toFixed(1),
+ aoHalfLumaDelta: +aoDelta.toFixed(1),
+ alphaBackgroundFraction: +backgroundFraction.toFixed(3),
+ regions: stats,
+ })}\n`,
+ );
process.exit(0);
}
diff --git a/render-service/test/material-fixture.test.mjs b/render-service/test/material-fixture.test.mjs
index e769d932..a8091070 100644
--- a/render-service/test/material-fixture.test.mjs
+++ b/render-service/test/material-fixture.test.mjs
@@ -7,7 +7,8 @@ import { buildMaterialChannelsFixture } from './generate-material-fixture.mjs';
const fixtureUrl = new URL('./fixtures/material-channels-v1.glb', import.meta.url);
const manifestUrl = new URL('./fixtures/material-channels-v1.manifest.json', import.meta.url);
-const MATERIAL_CHANNELS_V1_SHA256 = 'sha256:8ef3e9e5f28303639fc1d28c8648dda2494aed4c11b74ad17cb30b7726a59a9e';
+const MATERIAL_CHANNELS_V1_SHA256 =
+ 'sha256:8ef3e9e5f28303639fc1d28c8648dda2494aed4c11b74ad17cb30b7726a59a9e';
function sha256(bytes) {
return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
@@ -19,7 +20,12 @@ function parseGlb(bytes) {
assert.equal(bytes.readUInt32LE(8), bytes.length, 'GLB declared length');
const jsonLength = bytes.readUInt32LE(12);
assert.equal(bytes.readUInt32LE(16), 0x4e4f534a, 'JSON chunk type');
- const json = JSON.parse(bytes.subarray(20, 20 + jsonLength).toString('utf8').trim());
+ const json = JSON.parse(
+ bytes
+ .subarray(20, 20 + jsonLength)
+ .toString('utf8')
+ .trim(),
+ );
const binHeader = 20 + jsonLength;
assert.equal(bytes.readUInt32LE(binHeader + 4), 0x004e4942, 'BIN chunk type');
const binLength = bytes.readUInt32LE(binHeader);
@@ -54,7 +60,9 @@ describe('material channel conformance fixture', () => {
it('embeds every required PNG and binds every PBR channel explicitly', async () => {
const glb = parseGlb(await readFile(fixtureUrl));
- const byName = Object.fromEntries(glb.json.materials.map((material) => [material.name, material]));
+ const byName = Object.fromEntries(
+ glb.json.materials.map((material) => [material.name, material]),
+ );
const albedo = byName.AlbedoChecker;
const normal = byName.NormalResponse;
const orm = byName.SharedOrmResponse;
@@ -93,10 +101,9 @@ describe('material channel conformance fixture', () => {
it('pins high-contrast source pixels for each statistical GPU assertion', async () => {
const glb = parseGlb(await readFile(fixtureUrl));
- const decoded = Object.fromEntries(glb.json.images.map((image) => [
- image.name,
- PNG.sync.read(imageBytes(glb, image)),
- ]));
+ const decoded = Object.fromEntries(
+ glb.json.images.map((image) => [image.name, PNG.sync.read(imageBytes(glb, image))]),
+ );
assert.deepEqual(channelRange(decoded.AlbedoChecker, 0), { min: 18, max: 245 });
assert.deepEqual(channelRange(decoded.NormalSplit, 0), { min: 32, max: 224 });
assert.deepEqual(channelRange(decoded.SharedOrm, 0), { min: 32, max: 255 });
diff --git a/render-service/test/presentation-presets.test.mjs b/render-service/test/presentation-presets.test.mjs
index e402791b..13ad6701 100644
--- a/render-service/test/presentation-presets.test.mjs
+++ b/render-service/test/presentation-presets.test.mjs
@@ -47,9 +47,27 @@ describe('versioned presentation preset registry', () => {
exposure: 1.38,
ambient: { type: 'hemisphere', sky: 0xffffff, ground: 0x6f7888, intensity: 2 },
sun: { enabled: false },
- key: { enabled: true, color: 0xffffff, intensity: 3, position: [4, 7, 5], castsShadow: false },
- fill: { enabled: true, color: 0xdce8ff, intensity: 1.8, position: [-4, 3, 2], castsShadow: false },
- rim: { enabled: true, color: 0xffead6, intensity: 1.2, position: [-2, 5, -5], castsShadow: false },
+ key: {
+ enabled: true,
+ color: 0xffffff,
+ intensity: 3,
+ position: [4, 7, 5],
+ castsShadow: false,
+ },
+ fill: {
+ enabled: true,
+ color: 0xdce8ff,
+ intensity: 1.8,
+ position: [-4, 3, 2],
+ castsShadow: false,
+ },
+ rim: {
+ enabled: true,
+ color: 0xffead6,
+ intensity: 1.2,
+ position: [-2, 5, -5],
+ castsShadow: false,
+ },
shadows: {
enabled: false,
type: 'pcf',
@@ -83,33 +101,61 @@ describe('versioned presentation preset registry', () => {
assert.equal(isPresentationPresetId('neutral-studio-v1'), true);
assert.equal(isPresentationPresetId('dramatic-night-v1'), false);
assert.equal(getPresentationPreset('dramatic-night-v1'), undefined);
- assert.throws(() => validateRenderMode({
- cameras: [camera], width: 512, height: 512, lighting_preset_id: 'dramatic-night-v1',
- }), (error) => error?.status === 400 && /neutral-studio-v1/.test(error.message));
+ assert.throws(
+ () =>
+ validateRenderMode({
+ cameras: [camera],
+ width: 512,
+ height: 512,
+ lighting_preset_id: 'dramatic-night-v1',
+ }),
+ (error) => error?.status === 400 && /neutral-studio-v1/.test(error.message),
+ );
for (const nonId of [null, { exposure: 2 }, ['neutral-studio-v1']]) {
- assert.throws(() => validateRenderMode({
- cameras: [camera], width: 512, height: 512, lighting_preset_id: nonId,
- }), (error) => error?.status === 400 && /neutral-studio-v1/.test(error.message));
+ assert.throws(
+ () =>
+ validateRenderMode({
+ cameras: [camera],
+ width: 512,
+ height: 512,
+ lighting_preset_id: nonId,
+ }),
+ (error) => error?.status === 400 && /neutral-studio-v1/.test(error.message),
+ );
}
const renderMode = validateRenderMode({ cameras: [camera], width: 512, height: 512 });
- assert.throws(() => buildRenderFidelityV1({
- rendererId: 'dawn-vulkan:test',
- inputGlbSha256: sha256(Buffer.from('glb')),
- presentationProfile: 'dramatic-night-v1',
- renderMode,
- resolvedCameras: renderMode.cameras,
- timings: { totalMs: 1 },
- }), (error) => error?.status === 400 && /neutral-studio-v1/.test(error.message));
+ assert.throws(
+ () =>
+ buildRenderFidelityV1({
+ rendererId: 'dawn-vulkan:test',
+ inputGlbSha256: sha256(Buffer.from('glb')),
+ presentationProfile: 'dramatic-night-v1',
+ renderMode,
+ resolvedCameras: renderMode.cameras,
+ timings: { totalMs: 1 },
+ }),
+ (error) => error?.status === 400 && /neutral-studio-v1/.test(error.message),
+ );
});
it('advertises every registry ID through provider-free health contract data', () => {
- assert.deepEqual(PRESENTATION_PRESET_CAPABILITIES, ['render.profile.neutral-studio-v1', 'render.profile.gallery-studio-v1']);
- assert.ok(PRESENTATION_PRESET_CAPABILITIES.every((capability) => RENDER_CAPABILITIES.includes(capability)));
- const health = buildHealthDocument({
- rendererId: 'dawn-vulkan:test',
- backend: 'vulkan',
- summary: { vendor: 'test' },
- }, true);
+ assert.deepEqual(PRESENTATION_PRESET_CAPABILITIES, [
+ 'render.profile.neutral-studio-v1',
+ 'render.profile.gallery-studio-v1',
+ ]);
+ assert.ok(
+ PRESENTATION_PRESET_CAPABILITIES.every((capability) =>
+ RENDER_CAPABILITIES.includes(capability),
+ ),
+ );
+ const health = buildHealthDocument(
+ {
+ rendererId: 'dawn-vulkan:test',
+ backend: 'vulkan',
+ summary: { vendor: 'test' },
+ },
+ true,
+ );
assert.equal(health.presentationProfile, 'neutral-studio-v1');
assert.deepEqual(health.lightingPresetIds, ['neutral-studio-v1', 'gallery-studio-v1']);
assert.notEqual(health.lightingPresetIds, PRESENTATION_PRESET_IDS);
diff --git a/render-service/test/readback.test.mjs b/render-service/test/readback.test.mjs
index fac354f2..da2c700b 100644
--- a/render-service/test/readback.test.mjs
+++ b/render-service/test/readback.test.mjs
@@ -1,3 +1,21 @@
-import {test} from 'node:test';import assert from 'node:assert/strict';import {packRgbaReadback} from '../src/readback.mjs';
-test('1200-wide GPU rows discard 256-byte alignment padding and preserve every row',()=>{const width=1200,height=3,row=width*4,stride=Math.ceil(row/256)*256;const input=new Uint8Array((height-1)*stride+row).fill(255);for(let y=0;y<height;y++)input.fill(y+1,y*stride,y*stride+row);const output=packRgbaReadback(input,width,height);assert.equal(output.length,row*height);for(let y=0;y<height;y++)assert.ok(output.subarray(y*row,(y+1)*row).every(v=>v===y+1));});
-test('aligned and already packed arrays retain exact pixels and respect byte offsets',()=>{const backing=new Uint8Array(1024*2*4+16).fill(7);const input=backing.subarray(8,-8);assert.deepEqual(packRgbaReadback(input,1024,2),Buffer.from(input));assert.throws(()=>packRgbaReadback(new Uint8Array(2),1200,2),/readback/);});
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { packRgbaReadback } from '../src/readback.mjs';
+test('1200-wide GPU rows discard 256-byte alignment padding and preserve every row', () => {
+ const width = 1200,
+ height = 3,
+ row = width * 4,
+ stride = Math.ceil(row / 256) * 256;
+ const input = new Uint8Array((height - 1) * stride + row).fill(255);
+ for (let y = 0; y < height; y++) input.fill(y + 1, y * stride, y * stride + row);
+ const output = packRgbaReadback(input, width, height);
+ assert.equal(output.length, row * height);
+ for (let y = 0; y < height; y++)
+ assert.ok(output.subarray(y * row, (y + 1) * row).every((v) => v === y + 1));
+});
+test('aligned and already packed arrays retain exact pixels and respect byte offsets', () => {
+ const backing = new Uint8Array(1024 * 2 * 4 + 16).fill(7);
+ const input = backing.subarray(8, -8);
+ assert.deepEqual(packRgbaReadback(input, 1024, 2), Buffer.from(input));
+ assert.throws(() => packRgbaReadback(new Uint8Array(2), 1200, 2), /readback/);
+});
diff --git a/render-service/test/smoke.mjs b/render-service/test/smoke.mjs
index a423c3f2..eeb315e8 100644
--- a/render-service/test/smoke.mjs
+++ b/render-service/test/smoke.mjs
@@ -19,7 +19,7 @@ await new Promise((r) => setTimeout(r, 300));
const base = `http://127.0.0.1:${PORT}`;
let failures = 0;
const check = (name, cond, extra = '') => {
- console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ' ' + extra : ''}`);
+ console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` ${extra}` : ''}`);
if (!cond) failures++;
};
@@ -29,7 +29,9 @@ const check = (name, cond, extra = '') => {
async function capturingLog(fn) {
const lines = [];
const real = console.log;
- console.log = (...args) => { lines.push(args.join(' ')); };
+ console.log = (...args) => {
+ lines.push(args.join(' '));
+ };
try {
const value = await fn();
return { value, lines, text: lines.join('\n') };
@@ -38,9 +40,16 @@ async function capturingLog(fn) {
}
}
-const requestLines = (lines) => lines
- .map((l) => { try { return JSON.parse(l); } catch { return null; } })
- .filter((o) => o?.evt === 'request');
+const requestLines = (lines) =>
+ lines
+ .map((l) => {
+ try {
+ return JSON.parse(l);
+ } catch {
+ return null;
+ }
+ })
+ .filter((o) => o?.evt === 'request');
const health = await (await fetch(`${base}/health`)).json();
check('health ok', health.ok === true, health.rendererId);
@@ -59,7 +68,8 @@ check(
// is that every advertised preset is backed by a declared capability.
health.lightingPresetIds.includes('neutral-studio-v1') &&
health.lightingPresetIds.every((id) => health.capabilities.includes(`render.profile.${id}`)) &&
- typeof health.backend === 'string' && health.backend.length > 0 &&
+ typeof health.backend === 'string' &&
+ health.backend.length > 0 &&
health.presentationProfile === 'neutral-studio-v1' &&
health.authRequired === true,
JSON.stringify(health.capabilities),
@@ -71,18 +81,26 @@ check('unauthenticated render rejected', noAuth.status === 401);
// The gateway path cannot use Authorization (RunPod consumes it at the edge),
// so the custom header must authenticate on its own.
const customHeader = await fetch(`${base}/render`, {
- method: 'POST', headers: { 'x-render-token': TOKEN }, body: 'nope',
+ method: 'POST',
+ headers: { 'x-render-token': TOKEN },
+ body: 'nope',
});
check('x-render-token accepted (reaches body validation)', customHeader.status === 400);
-const wrongCustom = await capturingLog(() => fetch(`${base}/render`, {
- method: 'POST', headers: { 'x-render-token': 'wrong-token' }, body: '{}',
-}));
+const wrongCustom = await capturingLog(() =>
+ fetch(`${base}/render`, {
+ method: 'POST',
+ headers: { 'x-render-token': 'wrong-token' },
+ body: '{}',
+ }),
+);
check('wrong x-render-token rejected', wrongCustom.value.status === 401);
const rejectedLine = requestLines(wrongCustom.lines)[0];
check(
'rejected auth is logged as such',
- rejectedLine?.status === 401 && rejectedLine?.auth === 'rejected' && rejectedLine?.path === '/render',
+ rejectedLine?.status === 401 &&
+ rejectedLine?.auth === 'rejected' &&
+ rejectedLine?.path === '/render',
JSON.stringify(rejectedLine),
);
check(
@@ -91,29 +109,40 @@ check(
);
const badJson = await fetch(`${base}/render`, {
- method: 'POST', headers: { authorization: `Bearer ${TOKEN}` }, body: 'nope',
+ method: 'POST',
+ headers: { authorization: `Bearer ${TOKEN}` },
+ body: 'nope',
});
check('invalid JSON rejected', badJson.status === 400);
const badGlb = await fetch(`${base}/render`, {
- method: 'POST', headers: { authorization: `Bearer ${TOKEN}` },
+ method: 'POST',
+ headers: { authorization: `Bearer ${TOKEN}` },
body: JSON.stringify({ glb_base64: Buffer.from('not a glb').toString('base64') }),
});
check('bad GLB magic rejected', badGlb.status === 400);
const glb = readFileSync(glbPath);
const t0 = performance.now();
-const rendered = await capturingLog(async () => (await fetch(`${base}/render`, {
- method: 'POST', headers: { authorization: `Bearer ${TOKEN}` },
- body: JSON.stringify({ glb_base64: glb.toString('base64'), size: 384, beauty_size: 1024 }),
-})).json());
+const rendered = await capturingLog(async () =>
+ (
+ await fetch(`${base}/render`, {
+ method: 'POST',
+ headers: { authorization: `Bearer ${TOKEN}` },
+ body: JSON.stringify({ glb_base64: glb.toString('base64'), size: 384, beauty_size: 1024 }),
+ })
+ ).json(),
+);
const r = rendered.value;
const wallMs = (performance.now() - t0).toFixed(1);
check('render ok', r.ok === true);
check('six views', Array.isArray(r.views) && r.views.length === 6);
check('rendererId present', typeof r.rendererId === 'string' && r.rendererId.startsWith('dawn-'));
-check('render reports the fixed presentation profile', r.presentationProfile === 'neutral-studio-v1');
+check(
+ 'render reports the fixed presentation profile',
+ r.presentationProfile === 'neutral-studio-v1',
+);
const png0 = Buffer.from(r.views?.[0] ?? '', 'base64');
check('view is PNG', png0[0] === 0x89 && png0[1] === 0x50, `${png0.length}B`);
const decodedView0 = PNG.sync.read(png0);
@@ -138,19 +167,26 @@ check(
);
check(
'log line carries method/path/status/auth',
- renderLine?.method === 'POST' && renderLine?.path === '/render' &&
- renderLine?.status === 200 && renderLine?.auth === 'ok' &&
+ renderLine?.method === 'POST' &&
+ renderLine?.path === '/render' &&
+ renderLine?.status === 200 &&
+ renderLine?.auth === 'ok' &&
renderLine?.authVia === 'authorization',
);
check(
'log line carries byte counts and timings',
- renderLine?.glbBytes === glb.length && renderLine?.bodyBytes > glb.length &&
- renderLine?.views === 6 && renderLine?.beauty === true &&
- typeof renderLine?.timings?.totalMs === 'number' && renderLine?.ms > 0,
+ renderLine?.glbBytes === glb.length &&
+ renderLine?.bodyBytes > glb.length &&
+ renderLine?.views === 6 &&
+ renderLine?.beauty === true &&
+ typeof renderLine?.timings?.totalMs === 'number' &&
+ renderLine?.ms > 0,
`glbBytes=${renderLine?.glbBytes} ms=${renderLine?.ms}`,
);
-check('no token or GLB payload in the log line', !rendered.text.includes(TOKEN) &&
- !rendered.text.includes(glb.toString('base64').slice(0, 32)));
+check(
+ 'no token or GLB payload in the log line',
+ !rendered.text.includes(TOKEN) && !rendered.text.includes(glb.toString('base64').slice(0, 32)),
+);
const out = join(here, 'out');
mkdirSync(out, { recursive: true });
@@ -170,17 +206,35 @@ const { renderer } = await initRenderer();
// this baseline isolates exactly what a request allocates and must give back.
const mem1 = { ...renderer.info.memory };
const t1 = performance.now();
-const r2 = await (await fetch(`${base}/render`, {
- method: 'POST', headers: { 'x-render-token': TOKEN },
- body: JSON.stringify({ glb_base64: glb.toString('base64'), size: 384, beauty_size: 1024 }),
-})).json();
-check('warm render ok', r2.ok === true, `wall=${(performance.now() - t1).toFixed(1)}ms gpu=${JSON.stringify(r2.timings)}`);
-check('repeat render matches first view count', r2.views?.length === r.views?.length, `${r2.views?.length} vs ${r.views?.length}`);
+const r2 = await (
+ await fetch(`${base}/render`, {
+ method: 'POST',
+ headers: { 'x-render-token': TOKEN },
+ body: JSON.stringify({ glb_base64: glb.toString('base64'), size: 384, beauty_size: 1024 }),
+ })
+).json();
+check(
+ 'warm render ok',
+ r2.ok === true,
+ `wall=${(performance.now() - t1).toFixed(1)}ms gpu=${JSON.stringify(r2.timings)}`,
+);
+check(
+ 'repeat render matches first view count',
+ r2.views?.length === r.views?.length,
+ `${r2.views?.length} vs ${r.views?.length}`,
+);
const png0b = Buffer.from(r2.views?.[0] ?? '', 'base64');
const beautyB = Buffer.from(r2.beauty ?? '', 'base64');
-check('repeat render still produces PNGs', png0b[0] === 0x89 && png0b[1] === 0x50 &&
- beautyB[0] === 0x89 && beautyB[1] === 0x50, `${png0b.length}B ${beautyB.length}B`);
-check('repeat render byte-identical to first', png0b.equals(png0), `${png0.length}B vs ${png0b.length}B`);
+check(
+ 'repeat render still produces PNGs',
+ png0b[0] === 0x89 && png0b[1] === 0x50 && beautyB[0] === 0x89 && beautyB[1] === 0x50,
+ `${png0b.length}B ${beautyB.length}B`,
+);
+check(
+ 'repeat render byte-identical to first',
+ png0b.equals(png0),
+ `${png0.length}B vs ${png0b.length}B`,
+);
const mem2 = renderer.info.memory;
const grew = (k) => mem2[k] - mem1[k];
@@ -216,22 +270,45 @@ check(
const { validateViewDirs, MAX_VIEW_DIRS } = await import('../src/renderer.mjs');
const nineDirs = [
- [1, 0, 0], [0, 0, 1], [-1, 0, 0], [0, 0, -1], [0, 1, 0.001],
- [0.7, 0.5, 0.7], [0, -1, 0.001], [-0.7, 0.5, -0.7], [0.7, -0.35, 0.7],
+ [1, 0, 0],
+ [0, 0, 1],
+ [-1, 0, 0],
+ [0, 0, -1],
+ [0, 1, 0.001],
+ [0.7, 0.5, 0.7],
+ [0, -1, 0.001],
+ [-0.7, 0.5, -0.7],
+ [0.7, -0.35, 0.7],
];
-const nine = await (await fetch(`${base}/render`, {
- method: 'POST', headers: { 'x-render-token': TOKEN },
- body: JSON.stringify({ glb_base64: glb.toString('base64'), size: 128, views: nineDirs }),
-})).json();
-check('nine requested views produce nine PNGs', nine.ok === true && nine.views?.length === 9,
- `${nine.views?.length ?? nine.error}`);
+const nine = await (
+ await fetch(`${base}/render`, {
+ method: 'POST',
+ headers: { 'x-render-token': TOKEN },
+ body: JSON.stringify({ glb_base64: glb.toString('base64'), size: 128, views: nineDirs }),
+ })
+).json();
+check(
+ 'nine requested views produce nine PNGs',
+ nine.ok === true && nine.views?.length === 9,
+ `${nine.views?.length ?? nine.error}`,
+);
-const one = await (await fetch(`${base}/render`, {
- method: 'POST', headers: { 'x-render-token': TOKEN },
- body: JSON.stringify({ glb_base64: glb.toString('base64'), size: 128, views: [[0.7, 0.5, 0.7]] }),
-})).json();
-check('a single requested view produces a single PNG', one.ok === true && one.views?.length === 1,
- `${one.views?.length ?? one.error}`);
+const one = await (
+ await fetch(`${base}/render`, {
+ method: 'POST',
+ headers: { 'x-render-token': TOKEN },
+ body: JSON.stringify({
+ glb_base64: glb.toString('base64'),
+ size: 128,
+ views: [[0.7, 0.5, 0.7]],
+ }),
+ })
+).json();
+check(
+ 'a single requested view produces a single PNG',
+ one.ok === true && one.views?.length === 1,
+ `${one.views?.length ?? one.error}`,
+);
const exactCamera = {
position: [4, 3, 6],
@@ -243,103 +320,161 @@ const exactCamera = {
far: 100,
};
const cameraMemBefore = { ...renderer.info.memory };
-const cameraRendered = await capturingLog(async () => (await fetch(`${base}/render`, {
- method: 'POST', headers: { 'x-render-token': TOKEN },
- body: JSON.stringify({
- glb_base64: glb.toString('base64'),
- cameras: [exactCamera],
- width: 320,
- height: 180,
- lighting_preset_id: 'neutral-studio-v1',
- }),
-})).json());
+const cameraRendered = await capturingLog(async () =>
+ (
+ await fetch(`${base}/render`, {
+ method: 'POST',
+ headers: { 'x-render-token': TOKEN },
+ body: JSON.stringify({
+ glb_base64: glb.toString('base64'),
+ cameras: [exactCamera],
+ width: 320,
+ height: 180,
+ lighting_preset_id: 'neutral-studio-v1',
+ }),
+ })
+ ).json(),
+);
const cameraResult = cameraRendered.value;
const cameraPng = PNG.sync.read(Buffer.from(cameraResult.views?.[0] ?? '', 'base64'));
-check('exact perspective camera render returns its rectangular PNG',
+check(
+ 'exact perspective camera render returns its rectangular PNG',
cameraResult.ok === true && cameraPng.width === 320 && cameraPng.height === 180,
- `${cameraPng.width}x${cameraPng.height}`);
-check('camera response echoes actual renderer provenance and exact transport',
- cameraResult.rendererId === health.rendererId && cameraResult.backend === health.backend &&
+ `${cameraPng.width}x${cameraPng.height}`,
+);
+check(
+ 'camera response echoes actual renderer provenance and exact transport',
+ cameraResult.rendererId === health.rendererId &&
+ cameraResult.backend === health.backend &&
cameraResult.presentationProfile === 'neutral-studio-v1' &&
cameraResult.lightingPresetId === 'neutral-studio-v1' &&
- cameraResult.width === 320 && cameraResult.height === 180 &&
- JSON.stringify(cameraResult.cameras) === JSON.stringify([exactCamera]));
-check('camera response binds each output and the ordered output set',
+ cameraResult.width === 320 &&
+ cameraResult.height === 180 &&
+ JSON.stringify(cameraResult.cameras) === JSON.stringify([exactCamera]),
+);
+check(
+ 'camera response binds each output and the ordered output set',
/^sha256:[0-9a-f]{64}$/.test(cameraResult.viewSha256?.[0] ?? '') &&
/^sha256:[0-9a-f]{64}$/.test(cameraResult.outputSetSha256 ?? '') &&
cameraResult.cameraReceipts?.[0]?.outputSha256 === cameraResult.viewSha256[0] &&
- cameraResult.cameraReceipts?.[0]?.width === 320 && cameraResult.cameraReceipts?.[0]?.height === 180);
+ cameraResult.cameraReceipts?.[0]?.width === 320 &&
+ cameraResult.cameraReceipts?.[0]?.height === 180,
+);
const cameraMemAfter = renderer.info.memory;
-check('camera targets are request-owned and disposed after readback',
+check(
+ 'camera targets are request-owned and disposed after readback',
cameraMemAfter.textures <= cameraMemBefore.textures &&
cameraMemAfter.texturesSize <= cameraMemBefore.texturesSize,
`textures ${cameraMemBefore.textures}->${cameraMemAfter.textures} ` +
- `bytes ${cameraMemBefore.texturesSize}->${cameraMemAfter.texturesSize}`);
+ `bytes ${cameraMemBefore.texturesSize}->${cameraMemAfter.texturesSize}`,
+);
const cameraLine = requestLines(cameraRendered.lines)[0];
-check('camera log carries bounded dimensions/profile/output identity without payloads',
- cameraLine?.renderMode === 'camera' && cameraLine?.camerasRequested === 1 &&
- cameraLine?.width === 320 && cameraLine?.height === 180 &&
+check(
+ 'camera log carries bounded dimensions/profile/output identity without payloads',
+ cameraLine?.renderMode === 'camera' &&
+ cameraLine?.camerasRequested === 1 &&
+ cameraLine?.width === 320 &&
+ cameraLine?.height === 180 &&
cameraLine?.lightingPresetId === 'neutral-studio-v1' &&
- cameraLine?.backend === health.backend && cameraLine?.rendererId === health.rendererId &&
+ cameraLine?.backend === health.backend &&
+ cameraLine?.rendererId === health.rendererId &&
cameraLine?.outputSetSha256 === cameraResult.outputSetSha256 &&
- !cameraRendered.text.includes(glb.toString('base64').slice(0, 32)));
+ !cameraRendered.text.includes(glb.toString('base64').slice(0, 32)),
+);
const mixedMode = await fetch(`${base}/render`, {
- method: 'POST', headers: { 'x-render-token': TOKEN },
+ method: 'POST',
+ headers: { 'x-render-token': TOKEN },
body: JSON.stringify({
glb_base64: glb.toString('base64'),
- cameras: [exactCamera], width: 320, height: 180, size: 320,
+ cameras: [exactCamera],
+ width: 320,
+ height: 180,
+ size: 320,
}),
});
check('camera mode rejects legacy square sizing before queueing', mixedMode.status === 400);
const unsupportedLight = await fetch(`${base}/render`, {
- method: 'POST', headers: { 'x-render-token': TOKEN },
+ method: 'POST',
+ headers: { 'x-render-token': TOKEN },
body: JSON.stringify({
glb_base64: glb.toString('base64'),
- cameras: [exactCamera], width: 320, height: 180,
+ cameras: [exactCamera],
+ width: 320,
+ height: 180,
lighting_preset_id: 'dramatic-night-v1',
}),
});
check('camera mode rejects unsupported lighting identities', unsupportedLight.status === 400);
const overriddenBackground = await fetch(`${base}/render`, {
- method: 'POST', headers: { 'x-render-token': TOKEN },
+ method: 'POST',
+ headers: { 'x-render-token': TOKEN },
body: JSON.stringify({
glb_base64: glb.toString('base64'),
- cameras: [exactCamera], width: 320, height: 180,
+ cameras: [exactCamera],
+ width: 320,
+ height: 180,
background: '#000000',
}),
});
-check('camera mode rejects background overrides that would falsify its profile',
- overriddenBackground.status === 400);
+check(
+ 'camera mode rejects background overrides that would falsify its profile',
+ overriddenBackground.status === 400,
+);
const tooMany = await fetch(`${base}/render`, {
- method: 'POST', headers: { 'x-render-token': TOKEN },
+ method: 'POST',
+ headers: { 'x-render-token': TOKEN },
body: JSON.stringify({
glb_base64: glb.toString('base64'),
views: Array.from({ length: MAX_VIEW_DIRS + 1 }, () => [1, 0, 0]),
}),
});
const tooManyBody = await tooMany.json();
-check('an over-long views list is rejected, not truncated',
- tooMany.status === 400 && /maximum is 12/.test(tooManyBody.error ?? ''), tooManyBody.error);
+check(
+ 'an over-long views list is rejected, not truncated',
+ tooMany.status === 400 && /maximum is 12/.test(tooManyBody.error ?? ''),
+ tooManyBody.error,
+);
const malformed = await fetch(`${base}/render`, {
- method: 'POST', headers: { 'x-render-token': TOKEN },
+ method: 'POST',
+ headers: { 'x-render-token': TOKEN },
body: JSON.stringify({ glb_base64: glb.toString('base64'), views: [['a', 'b', 'c']] }),
});
-check('a malformed view vector is rejected before it becomes a NaN camera',
- malformed.status === 400, `status ${malformed.status}`);
+check(
+ 'a malformed view vector is rejected before it becomes a NaN camera',
+ malformed.status === 400,
+ `status ${malformed.status}`,
+);
-const threw = (v) => { try { validateViewDirs(v); return false; } catch { return true; } };
-check('validateViewDirs defaults on undefined and on an empty list',
- validateViewDirs(undefined).length === 6 && validateViewDirs([]).length === 6);
-check('validateViewDirs returns a valid list unchanged (no truncation, no reorder)',
- JSON.stringify(validateViewDirs(nineDirs)) === JSON.stringify(nineDirs));
-check('validateViewDirs rejects the shapes that render as plausible nonsense',
- threw('nope') && threw([[1, 0]]) && threw([[1, 0, 0, 0]]) && threw([[1, Number.NaN, 0]]) &&
- threw([[0, 0, 0]]) && threw(Array.from({ length: MAX_VIEW_DIRS + 1 }, () => [1, 0, 0])));
+const threw = (v) => {
+ try {
+ validateViewDirs(v);
+ return false;
+ } catch {
+ return true;
+ }
+};
+check(
+ 'validateViewDirs defaults on undefined and on an empty list',
+ validateViewDirs(undefined).length === 6 && validateViewDirs([]).length === 6,
+);
+check(
+ 'validateViewDirs returns a valid list unchanged (no truncation, no reorder)',
+ JSON.stringify(validateViewDirs(nineDirs)) === JSON.stringify(nineDirs),
+);
+check(
+ 'validateViewDirs rejects the shapes that render as plausible nonsense',
+ threw('nope') &&
+ threw([[1, 0]]) &&
+ threw([[1, 0, 0, 0]]) &&
+ threw([[1, Number.NaN, 0]]) &&
+ threw([[0, 0, 0]]) &&
+ threw(Array.from({ length: MAX_VIEW_DIRS + 1 }, () => [1, 0, 0])),
+);
// Device-loss policy. Real loss cannot be injected through Dawn's Node binding,
// so assert the decision itself; markGpuShutdown mutates module state, hence last.
@@ -347,7 +482,10 @@ const { shouldExitOnDeviceLost, markGpuShutdown } = await import('../src/gpu.mjs
check('lost device exits the worker', shouldExitOnDeviceLost({ reason: 'unknown' }) === true);
check('our own destroy is not a fault', shouldExitOnDeviceLost({ reason: 'destroyed' }) === false);
markGpuShutdown();
-check('loss during shutdown is not a fault', shouldExitOnDeviceLost({ reason: 'unknown' }) === false);
+check(
+ 'loss during shutdown is not a fault',
+ shouldExitOnDeviceLost({ reason: 'unknown' }) === false,
+);
console.log(failures ? `\n${failures} FAILURES` : '\nALL PASS');
process.exit(failures ? 1 : 0);
diff --git a/scripts/reliability.test.mjs b/scripts/reliability.test.mjs
index 6ca0fd19..47d8bed6 100644
--- a/scripts/reliability.test.mjs
+++ b/scripts/reliability.test.mjs
@@ -84,6 +84,13 @@ describe('repository reliability contracts', () => {
// ledger 14.4 with what taking them costs.
expect(biome.files.includes).toContain('scripts/check-*.mjs');
expect(biome.files.includes).toContain('scripts/**/*.test.mjs');
+ // render-service joined the surface once its sources stopped being CRLF. It is
+ // a shipped subsystem with 37 tests in CI, so it belongs here; what kept it out
+ // was a `.gitattributes` `-text` line freezing an inconsistent line-ending mix.
+ expect(biome.files.includes).toContain('render-service/src/**/*.mjs');
+ expect(biome.files.includes).toContain('render-service/test/**/*.mjs');
+ // And the attribute must stay gone, or the next edit reintroduces the mix.
+ expect(await readText('.gitattributes')).not.toContain('render-service/src/** -text');
// Views must be byte-reproducible: a runner that happens to reach a GPU render
// service must not be able to change what the golden-image tests compare.