3D engine that AI agents drive
Add position, velocity, UV, cryptomatte, AOV and multilayer passes (#706) (#741)
Nguyen Xuan An063dd1313770
diff --git a/changes/706.md b/changes/706.mdnew file mode 100644index 00000000..569ee154--- /dev/null+++ b/changes/706.md@@ -0,0 +1 @@+- Add `position`, `velocity`, `uv`, `transmission`, `volume`, `environment`, `cryptomatte` and `aov` render passes (`material.aov` and material graph `aov` outputs), plus `multilayer: true` OpenEXR render jobs (#706).diff --git a/changes/706.size.md b/changes/706.size.mdnew file mode 100644index 00000000..164313a6--- /dev/null+++ b/changes/706.size.md@@ -0,0 +1,12 @@+- entry:core: 69 B gzip for passSupport.bindFrame, passSupport.drawsInPass and passSupport.drawBatch hooks plus aov/aovMap/transmissionMap batch separation in groupParts (#706).+- entry:core+lazy: 69 B gzip for the same passSupport hooks and batch separation in renderer.js (#706).+- entry:render-passes: 8118 B gzip for position, velocity, UV, transmission, volume, environment, cryptomatte (FNV-1a manifest + float IDs) and AOV render passes (#706).+- scene:gltf-box: 73 B gzip for the passSupport hooks and batch separation in renderer.js (#706).+- scene:gltf-box+lazy: 73 B gzip for the passSupport hooks and batch separation in renderer.js (#706).+- scene:agent-scene: 230 B gzip for material.aov validation, aovMap pattern field, material graph aov output and RENDER_PASS_NAMES (#706).+- scene:agent-scene+lazy: 292 B gzip for material.aov validation, aovMap pattern field, material graph aov output and RENDER_PASS_NAMES (#706).+- goal:lit-box: 63 B gzip for the passSupport hooks and batch separation in renderer.js (#706).+- goal:gltf-box: 73 B gzip for the passSupport hooks and batch separation in renderer.js (#706).+- goal:agent-scene: 230 B gzip for material.aov validation, aovMap pattern field, material graph aov output and RENDER_PASS_NAMES (#706).+- tool-total: 214 B for material.aov and render settings passes/multilayer schemas on scene_render_submit (#706).+- tool:scene_render_submit: 214 B for the 8 new pass names and multilayer EXR option (#706).diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.mdindex 64e633e6..eb5ca96e 100644--- a/docs/agent-render-jobs.md+++ b/docs/agent-render-jobs.md@@ -105,7 +105,7 @@ and a click placed on a cut in a WAV lands on the decoded cut frame within a fra## Render passes-`image` and `stills` jobs accept `settings.passes`, a list of `albedo`, `normal`, `emission`, `depth`, `objectId`, `diffuse`, `glossy`, `shadow`, `ao` and `mist`.+`image` and `stills` jobs accept `settings.passes`, a list of `albedo`, `normal`, `emission`, `depth`, `objectId`, `diffuse`, `glossy`, `shadow`, `ao`, `mist`, `position`, `velocity`, `uv`, `transmission`, `volume`, `environment`, `cryptomatte` and `aov`.Each frame writes its lit image and then one PNG per pass: `render.png` and `render-<pass>.png` for an image, `frame-N.png` and `frame-N-<pass>.png` for stills.Passes are raw data at the lit image's size: no tone mapping, grading, bloom, depth of field or antialiasing, so values stay exact at silhouettes.Only opaque and cutout geometry appears. Liquid, foam and blended parts, the sky and the environment background do not.@@ -122,6 +122,14 @@ Only opaque and cutout geometry appears. Liquid, foam and blended parts, the sky| `shadow` | Sun shadow visibility, 1 lit and 0 shadowed. Background 1 || `ao` | Ambient occlusion the shader applies (occlusion map, vertex sky visibility, room term). Background 1 || `mist` | Fog amount `1 - exp(-distance * fogDensity)`. Background 1 |+| `position` | World-space XYZ in metres (float in `exr`, mapped over `±100 m` into `0..1` in `png` and `png16`). Background 0 |+| `velocity` | Screen-space motion vector `(dx, dy)` in normalized screen coordinates from camera and object motion (signed in `exr`, `vel * 0.5 + 0.5` in `png` and `png16`). Background 0 |+| `uv` | Primary texture coordinate `(U, V)` in red and green (`U, V` channels in `exr`). Background 0 |+| `transmission` | Transmitted light for materials with `transmission > 0`, scaled by `transmissionMap`. Background 0 |+| `volume` | Volumetric / fog scattering contribution along the view ray. Background 0 |+| `environment` | Image-based / sky environment lighting contribution times exposure. Background 0 |+| `cryptomatte` | Deterministic float hash per object in red, per material in green and coverage `1` in blue (`metrics.cryptomatte` holds the `{ objects, materials }` manifest). Background 0 |+| `aov` | Custom material AOV from `material.aov` (`0..1` scalar or RGB) and/or a material graph's `aov` output. Background 0 |The lighting passes hold linear values above 1, so write them as `exr` (a `png` or `png16` file clamps at 1). They add back to the lit image: `diffuse + glossy + emission * exposure` is the radiance before fog, and with an open world the lit image is that radiance mixed toward the fog colour by `mist`, then tone mapped. `tests/lighting-passes.test.js` checks the sum against the beauty frame (mean difference under 1.5 display levels, under 2% of samples off by more than 4). Not covered: unlit parts, the editor floor, parts that a probe or irradiance grid changes after the sky term, and anything the lit image adds after the shader (bloom, grading, depth of field).@@ -140,6 +148,7 @@ Four optional settings, each off by default. A job without them writes the same| --- | --- || `transparent: true` | `image` and `stills`: the lit image keeps alpha (a PNG of colour type 6). The sky, the environment background and the automatic ground are not drawn, so give the scene its own ground or a `shadowCatcher` node (see `renderFlags` in `scene_capabilities`). Volume fog is refused. Passes ignore it. || `format` | `image` and `stills`: `png` (8-bit, default), `png16` or `exr`. The lit image is drawn into a half-float target and read back, so the file holds the same graded display colour as the 8-bit PNG (within one 8-bit step) with 16-bit steps. |+| `multilayer: true` | With `format: "exr"` and `passes`: writes one OpenEXR file per frame (`render.exr` or `frame-N.exr`) containing `Combined.R/G/B(/A)` and `<pass>.<channel>` for every requested pass (`depth.Z`, `objectId.id`, `position.X/Y/Z`, `velocity.X/Y`, `uv.U/V`, `<pass>.R/G/B`). || `region: { x, y, width, height }` | Pixels from the top left, each side at least 16. The frame is rendered whole and the crop is kept, so the look is the same as the full frame. Works for `image`, `stills` and `video` (a video region has even sides). Not with `renderer`. || `fps` | Up to 60 for video, within the 900 frame limit. |diff --git a/docs/parity.md b/docs/parity.mdindex 474190e7..5ed10b01 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -210,7 +210,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Rendering > Shader Nodes > Group | missing | No node graph. | | #50 || Rendering > Color Management | partial | View transforms `aces` (default), `agx` and `neutral` (Khronos PBR Neutral) in the rasterizer and the path tracer, and `.cube` look LUTs or four named looks; grading as before. Neutral matches Blender 5.2 within 0.01 on a ramp, AgX within 0.026 (a fit of Blender 5.2's AgX LUT; saturated colour is the part that is off). No choice of working color space or display device; no Filmic or Standard. | [view transforms](../tests/view-transform.test.js), [effects](../tests/effects.test.js) | AgX looks || Rendering > Freestyle | partial | `environment.lines` draws silhouette, boundary and crease lines in screen space, and `polylines` draws screen-width lines in the world. There are no line sets, styles or strokes along curves. Outline width is 1.65 px at 960x540 and 1.60 px at 3840x2160 for a requested 2 px, against 1.73 px in Freestyle ([comparison](line-art.md)). | [line-art](../tests/line-art.test.js), [guide](line-art.md), [reference script](../bench/reference/line-art.mjs) | |-| Rendering > View Layers & Passes | partial | Render jobs write albedo, normal, emission, depth, object ID and the lighting passes diffuse, glossy, shadow, ao and mist as PNG, PNG16 or EXR files; diffuse + glossy + emission add back to the lit image. There are no view layers, no cryptomatte, and no transmission or volume passes. | [render-passes](../tests/render-passes.test.js), [lighting-passes](../tests/lighting-passes.test.js) | #54, #601 |+| Rendering > View Layers & Passes | partial | Render jobs write albedo, normal, emission, depth, object ID, the lighting passes diffuse, glossy, shadow, ao, mist, transmission, volume and environment, and the auxiliary passes position, velocity, uv, cryptomatte (with object and material manifests in job metrics) and aov (from `material.aov` or a material graph's `aov` output) as PNG, PNG16, single-pass EXR or multilayer EXR (`multilayer: true`, packing `Combined` and `<pass>.<channel>` into one `.exr` per frame). There are no view layers or per-layer collection overrides. | [render-passes](../tests/render-passes.test.js), [lighting-passes](../tests/lighting-passes.test.js) | #54, #601, #706 || Rendering > Render Output > Output Properties | partial | PNG and MP4, frame rate, duration (to 60 s) and size, and a CPU or NVENC encoder. There is no stereo or metadata. | [agent-render-jobs](../tests/agent-render-jobs.test.js) | #60 || Rendering > Render Output > Audio Rendering | partial | A video job mixes one local WAV, MP3, OGG or FLAC file with an offset and reports measured sync. No several tracks, mixing, gain or generated sound. | [film-timeline](../tests/film-timeline.test.js), `npm run smoke:film-timeline` | #60 || Rendering > Render Output > Rendering Animations | done | Snapshot render jobs with progress, cancel and verified output. | [agent-render-jobs](../tests/agent-render-jobs.test.js) | |diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex 5787eb8c..90febd7d 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -290,8 +290,8 @@ function draw(record, time = 0, camera = record.scene.camera, frameOptions = {})if (objectMotion) {// Object motion blur reads each pixel's part from the object ID pass, drawn first; the lit frame then smears along each part's motion.const { installObjectMotionBlur, packObjectMotion } = agentSceneModule('objectMotionBlur');- installObjectMotionBlur(record.renderer);- record.renderer.render({ ...frame, pass: 'objectId', previousCamera: undefined });+ if (!frame.pass) installObjectMotionBlur(record.renderer);+ if (!frame.pass) record.renderer.render({ ...frame, pass: 'objectId', previousCamera: undefined });frame.objectMotion = packObjectMotion(record.renderer, objectMotion.current, objectMotion.previous);}record.renderer.render(frame);@@ -429,8 +429,8 @@ function withCameraOverrides(camera, overrides) {}// The camera at the start of the shutter interval, sampled from time so the same seek always gives the same blur.-function previousCameraFor(record, motionTime) {- const shutter = record.scene.effects.motionBlur.shutter;+function previousCameraFor(record, motionTime, forVelocity = false) {+ const shutter = record.scene.effects.motionBlur.shutter || (forVelocity ? 1 / 24 : 0);if (shutter <= 0 || motionTime === undefined || record.asset) return undefined;record.scene.sampleMotion(Math.max(0, motionTime - shutter));const previousCamera = record.scene.camera;@@ -440,9 +440,10 @@ function previousCameraFor(record, motionTime) {// The parts' world matrices now and at the start of the shutter, sampled from time like the previous camera. Only a scene that// asks for object blur (and has motion to sample) pays for it; an imported asset animates by skin, which this does not follow.-function objectMotionFor(record, motionTime) {- const { shutter, objects } = record.scene.effects.motionBlur;- if (!(shutter > 0 && objects > 0) || motionTime === undefined || record.asset) return undefined;+function objectMotionFor(record, motionTime, forVelocity = false) {+ const { shutter: blurShutter, objects } = record.scene.effects.motionBlur;+ const shutter = blurShutter || (forVelocity ? 1 / 24 : 0);+ if (!(shutter > 0 && (objects > 0 || forVelocity)) || motionTime === undefined || record.asset) return undefined;const { sampleWorldMatrices } = agentSceneModule('objectMotionBlur');const current = sampleWorldMatrices(record.scene.parts);record.scene.sampleMotion(Math.max(0, motionTime - shutter));@@ -814,9 +815,10 @@ window.__agentPreview = {record.scene.sampleMotion(motionTime);}const shotCamera = cameraOverrides ? withCameraOverrides(record.scene.camera, cameraOverrides) : undefined;- const sampledPreviousCamera = pass ? undefined : previousCameraFor(record, motionTime);+ const forVelocity = pass === 'velocity';+ const sampledPreviousCamera = (!pass || forVelocity) ? previousCameraFor(record, motionTime, forVelocity) : undefined;const previousCamera = sampledPreviousCamera && cameraOverrides ? withCameraOverrides(sampledPreviousCamera, cameraOverrides) : sampledPreviousCamera;- const objectMotion = pass ? undefined : objectMotionFor(record, motionTime);+ const objectMotion = (!pass || forVelocity) ? objectMotionFor(record, motionTime, forVelocity) : undefined;const exposure = record.scene.effects.exposure * brightness;const shotEffects = depthOfFieldOverrides? { ...record.scene.effects, depthOfField: { ...record.scene.effects.depthOfField, ...depthOfFieldOverrides } }@@ -827,7 +829,9 @@ window.__agentPreview = {// The first lit frame of a job is checked; a pass or a fade has no exposure to judge.const checkLitFrame = diagnose && !pass && !floatOutput && brightness === 1;const info = renderInfo(record.renderer, pass ? [] : viewProblems(record, shotCamera ?? record.scene.camera, checkLitFrame ? record.scene.effects.exposure : undefined));- return pass === 'objectId' ? { ...info, objectNames: record.renderer.passSupport.objectNames() } : info;+ return pass === 'objectId' ? { ...info, objectNames: record.renderer.passSupport.objectNames() }+ : pass === 'cryptomatte' ? { ...info, cryptomatte: record.renderer.passSupport.cryptomatteManifest() }+ : info;},// Reads the last frame as RGBA float32, rows bottom to top, cropped to `region` (pixels from the top left): the lit image// when it was drawn with floatOutput, a pass when it was drawn with passFloat. Base64 of the float bytes.diff --git a/scripts/agent-render-jobs.mjs b/scripts/agent-render-jobs.mjsindex 53b62827..c869c762 100644--- a/scripts/agent-render-jobs.mjs+++ b/scripts/agent-render-jobs.mjs@@ -85,7 +85,7 @@ function jsonCopy(value, maximum = MAXIMUM_JSON_BYTES) {}function settingsFrom(input, clips, recipe) {- objectKeys(input, ['kind', 'width', 'height', 'fps', 'duration', 'animation', 'motion', 'rendererTime', 'passes', 'renderer', 'timeline', 'audio', 'encoder', 'transparent', 'format', 'region'], 'settings');+ objectKeys(input, ['kind', 'width', 'height', 'fps', 'duration', 'animation', 'motion', 'rendererTime', 'passes', 'renderer', 'timeline', 'audio', 'encoder', 'transparent', 'format', 'multilayer', 'region'], 'settings');if (!['image', 'stills', 'video'].includes(input.kind)) throw new TypeError('kind must be image, stills or video.');const width = boundedNumber(input.width, 64, MAXIMUM_JOB_SIDE, 'width', true);const height = boundedNumber(input.height, 64, MAXIMUM_JOB_SIDE, 'height', true);@@ -151,7 +151,7 @@ function settingsFrom(input, clips, recipe) {}/** The optional transparent, format and region settings, kept only when they differ from the defaults so old records read the same. */-function outputOptionsFrom(input, { kind, width, height, renderer }) {+function outputOptionsFrom(input, { kind, width, height, renderer, passes }) {const options = {};const tracerNote = 'The path tracer writes an opaque 8-bit PNG of the whole frame.';if (input.transparent !== undefined) {@@ -166,6 +166,11 @@ function outputOptionsFrom(input, { kind, width, height, renderer }) {if (input.format !== 'png' && renderer) throw new RangeError(`format cannot combine with renderer. ${tracerNote}`);if (input.format !== 'png') options.format = input.format;}+ if (input.multilayer !== undefined) {+ if (typeof input.multilayer !== 'boolean') throw new TypeError('multilayer must be boolean.');+ if (input.multilayer && (input.format !== 'exr' || !passes)) throw new RangeError('multilayer requires format exr and passes.');+ if (input.multilayer) options.multilayer = true;+ }if (input.region !== undefined) {objectKeys(input.region, ['x', 'y', 'width', 'height'], 'region');if (renderer) throw new RangeError(`region cannot combine with renderer. ${tracerNote}`);@@ -231,10 +236,11 @@ function passesFrom(passes, kind) {}/** Every artifact filename of a job, lit image first and then each requested pass, frame by frame. */-export function artifactNames(kind, passes = [], format = 'png') {+export function artifactNames(kind, passes = [], format = 'png', multilayer = false) {if (kind === 'video') return ['render.mp4'];const extension = format === 'exr' ? 'exr' : 'png';const stems = kind === 'image' ? ['render'] : Array.from({ length: 8 }, (_, index) => `frame-${index}`);+ if (multilayer) return stems.map(stem => `${stem}.${extension}`);return stems.flatMap(stem => [`${stem}.${extension}`, ...passes.map(pass => `${stem}-${pass}.${extension}`)]);}@@ -462,7 +468,7 @@ export async function createAgentRenderJobs({ root, run, limits: inputLimits = {boundedNumber(record.progress.maximumPendingFrames, 0, 1, 'persisted pending frames', true);if (record.metrics !== undefined) record.metrics = jsonCopy(record.metrics, 65536);if (record.reason !== undefined && (typeof record.reason !== 'string' || record.reason.length > 2048)) throw new Error('Invalid persisted job reason.');- const namesAllowed = artifactNames(settings.kind, settings.passes, settings.format);+ const namesAllowed = artifactNames(settings.kind, settings.passes, settings.format, settings.multilayer);if (!Array.isArray(record.artifacts) || record.artifacts.length > namesAllowed.length) throw new Error('Invalid persisted artifacts.');const seen = new Set();for (const artifact of record.artifacts) {@@ -526,7 +532,7 @@ export async function createAgentRenderJobs({ root, run, limits: inputLimits = {record.state = 'finalizing';await persist(job);objectKeys(completed, ['artifacts', 'metrics'], 'runner result');- const expected = artifactNames(record.settings.kind, record.settings.passes, record.settings.format);+ const expected = artifactNames(record.settings.kind, record.settings.passes, record.settings.format, record.settings.multilayer);if (!Array.isArray(completed.artifacts) || completed.artifacts.length !== expected.length) throw new Error('Runner did not return the required fixed artifacts.');const directory = await directoryFor(record.jobId);const metrics = jsonCopy(completed.metrics ?? {}, 65536);diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjsindex ce189280..78abf08a 100644--- a/scripts/agent-runtime.mjs+++ b/scripts/agent-runtime.mjs@@ -23,7 +23,7 @@ import { sequenceFrameIds } from '../src/agent-texture-sequence.js';import { catalogLookReferences, BUNDLED_ENVIRONMENT_NAMES, BUNDLED_CUBE_LOOK_NAMES } from '../src/look-catalog.js';import { TEXTURE_SEQUENCE_CAPABILITIES } from '../src/texture-sequence-limits.js';import { createAgentRenderJobs, EXPORT_DIRECTORY_NAME, HIGH_PRECISION_FRAME_FACTOR } from './agent-render-jobs.mjs';-import { encodeRenderOutput } from './render-output-encoders.mjs';+import { encodeRenderOutput, encodeMultilayerExr } from './render-output-encoders.mjs';import { createFrameEncoder } from './frame-encoder.mjs';import { DEFAULT_PAGE_ENCODER_QUANTIZER, createFrameReceiver, startVideoEncoderInPage } from './gpu-frame-reader.mjs';import { audioInputArguments, createAudioLibrary, measureStreamSeconds } from './job-audio.mjs';@@ -583,6 +583,13 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browreturn captureBytes;}// 16-bit PNG and EXR come from a float readback of the same frame (or of its pass), encoded here.+ async function readFloatPass(pass) {+ const read = await jobPage.evaluate(readInput => window.__agentPreview.readFloat(readInput),+ { sessionId: jobId, source: pass ? 'pass' : 'frame', ...(region ? { region } : {}) });+ const readBytes = Buffer.from(read.data, 'base64');+ const pixels = new Float32Array(readBytes.buffer.slice(readBytes.byteOffset, readBytes.byteOffset + readBytes.length));+ return { pixels, width: read.width, height: read.height };+ }async function captureHighPrecisionBytes(pass) {const captureStarted = performance.now();const read = await jobPage.evaluate(readInput => window.__agentPreview.readFloat(readInput),@@ -600,18 +607,39 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browawait writeFile(join(directory, `${filename}.partial`), artifactBytes, { flag: 'wx' });artifacts.push({ temporary: `${filename}.partial`, filename, mimeType: artifactMimeType });}- const bytes = highPrecision ? await captureHighPrecisionBytes(undefined) : await captureFrameBytes();+ const bytes = settings.multilayer ? undefined : (highPrecision ? await captureHighPrecisionBytes(undefined) : await captureFrameBytes());if (encoder) {if (bytes) await encoder.writeFrame(bytes);}else {const stem = settings.kind === 'image' ? 'render' : `frame-${frame}`;+ if (settings.multilayer) {+ const captureStarted = performance.now();+ const beautyRead = await readFloatPass(undefined);+ const passPixels = {};+ for (const pass of settings.passes ?? []) {+ const passInfo = await jobPage.evaluate(input => window.__agentPreview.frame(input),+ { ...frameInput, floatOutput: false, pass, passDepthRange: RENDER_PASS_DEPTH_RANGE, passFloat: true });+ passPixels[pass] = (await readFloatPass(pass)).pixels;+ if (pass === 'depth') metrics.depthRangeMetres = RENDER_PASS_DEPTH_RANGE;+ if (pass === 'objectId') {+ metrics.objectNames = passInfo.objectNames.slice(0, MAXIMUM_OBJECT_NAMES);+ metrics.objectNamesTruncated = passInfo.objectNames.length > MAXIMUM_OBJECT_NAMES;+ }+ if (pass === 'cryptomatte') metrics.cryptomatte = passInfo.cryptomatte;+ }+ const encodedBytes = encodeMultilayerExr({ width: beautyRead.width, height: beautyRead.height, beauty: beautyRead.pixels, passes: passPixels, hasAlpha: settings.transparent === true, depthRange: RENDER_PASS_DEPTH_RANGE });+ metrics.captureSeconds += (performance.now() - captureStarted) / 1000;+ if (encodedBytes.length > MAXIMUM_JOB_FRAME_BYTES * HIGH_PRECISION_FRAME_FACTOR) throw new Error('Rendered frame exceeded the high-precision size limit.');+ await writeArtifact(`${stem}.exr`, encodedBytes);+ } else {await writeArtifact(`${stem}.${artifactExtension}`, bytes);// Passes follow the lit image of the same instant, so each seek yields every file for that frame.for (const pass of settings.passes ?? []) {const passInfo = await jobPage.evaluate(input => window.__agentPreview.frame(input),{ ...frameInput, floatOutput: false, pass, passDepthRange: RENDER_PASS_DEPTH_RANGE, ...(highPrecision ? { passFloat: true } : {}) });await writeArtifact(`${stem}-${pass}.${artifactExtension}`, highPrecision ? await captureHighPrecisionBytes(pass) : await captureFrameBytes());+ if (pass === 'cryptomatte') metrics.cryptomatte = passInfo.cryptomatte;if (pass === 'depth') metrics.depthRangeMetres = RENDER_PASS_DEPTH_RANGE;if (pass === 'objectId') {metrics.objectNames = passInfo.objectNames.slice(0, MAXIMUM_OBJECT_NAMES);@@ -619,6 +647,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow}}}+ }metrics.peakNodeBytes = Math.max(metrics.peakNodeBytes, process.memoryUsage().rss);const heap = await session.send('Runtime.getHeapUsage');metrics.peakBrowserHeap = Math.max(metrics.peakBrowserHeap, heap.usedSize);diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex e411cf84..f42918ba 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -162,6 +162,7 @@ const materialFields = {opacity: unit.optional().describe('Surface opacity. Any value below one draws the material blended (glass, windows, visors).'),alphaMode: z.enum(['opaque', 'blend']).optional().describe('blend draws after opaque geometry, sorted back to front.'),doubleSided: z.boolean().optional().describe('Draw and light both faces (thin sheets, leaves, cloth).'),+ aov: z.union([unit, color]).optional(),};const materialTag = z.enum(['surface', 'unlit', 'liquid', 'foam', 'foliage', 'grass', 'water']).optional().describe('Surface kind; liquid, foam, foliage, grass and water change how it renders: see scene_capabilities materialTags and water.');const materialCore = coreOf(materialFields, ['color', 'metallic', 'roughness', 'emission', 'opacity']);@@ -760,6 +761,7 @@ const renderSettings = z.strictObject({passes: z.array(z.enum(RENDER_PASS_NAMES)).min(1).max(RENDER_PASS_NAMES.length).optional().describe('image and stills: also write a raw PNG per pass; opaque geometry only.'),transparent: z.boolean().optional().describe('image and stills: lit image with alpha; no sky, auto ground or volume fog.'),format: z.enum(RENDER_OUTPUT_FORMATS).optional().describe('image and stills: png (default), png16 or exr (depth in metres).'),+ multilayer: z.boolean().optional().describe('With format exr and passes: pack Combined and every pass into one EXR per frame.'),region: z.strictObject({ x: z.number().int().min(0), y: z.number().int().min(0), width: z.number().int().min(16), height: z.number().int().min(16) }).optional().describe('Pixels to keep from the top left. Not with renderer.'),}).describe('Snapshot render: one PNG, eight evenly spaced PNGs, or H.264 MP4 (even dimensions). Defaults: 24 fps, one second. motion.start plays recipe tracks, animation an imported clip, both layer. Omitted motion holds time zero.');const readOnly = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };diff --git a/scripts/render-output-encoders.mjs b/scripts/render-output-encoders.mjsindex 1bce1264..edc9b54f 100644--- a/scripts/render-output-encoders.mjs+++ b/scripts/render-output-encoders.mjs@@ -195,7 +195,7 @@ function objectIdentifier(pixels, offset) {return byteOf(pixels[offset]) + byteOf(pixels[offset + 1]) * 256 + byteOf(pixels[offset + 2]) * 65536;}-function encodeExrPass({ pixels, width, height, pass, hasAlpha, depthRange }) {+function exrChannelsForPass({ pixels, width, height, pass, hasAlpha, depthRange, prefix = '' }) {if (pass === 'depth' || pass === 'objectId') {const values = new Float32Array(width * height);for (let row = 0; row < height; row++) {@@ -205,15 +205,32 @@ function encodeExrPass({ pixels, width, height, pass, hasAlpha, depthRange }) {values[row * width + column] = pass === 'depth' ? depthSteps(pixels, offset) / 65535 * depthRange : objectIdentifier(pixels, offset);}}- return encodeExr(width, height, [{ name: pass === 'depth' ? 'Z' : 'id', type: 'float', values }]);+ return [{ name: `${prefix}${pass === 'depth' ? 'Z' : 'id'}`, type: 'float', values }];}const [red, green, blue, alpha] = planes(pixels, width, height, [0, 1, 2, 3]);- const channels = [{ name: 'R', type: 'half', values: red }, { name: 'G', type: 'half', values: green }, { name: 'B', type: 'half', values: blue }];- if (hasAlpha) channels.push({ name: 'A', type: 'half', values: alpha });+ if (pass === 'uv') return [{ name: `${prefix}U`, type: 'half', values: red }, { name: `${prefix}V`, type: 'half', values: green }];+ if (pass === 'velocity') return [{ name: `${prefix}X`, type: 'half', values: red }, { name: `${prefix}Y`, type: 'half', values: green }];+ if (pass === 'position') return [{ name: `${prefix}X`, type: 'float', values: red }, { name: `${prefix}Y`, type: 'float', values: green }, { name: `${prefix}Z`, type: 'float', values: blue }];+ const channels = [{ name: `${prefix}R`, type: 'half', values: red }, { name: `${prefix}G`, type: 'half', values: green }, { name: `${prefix}B`, type: 'half', values: blue }];+ if (hasAlpha) channels.push({ name: `${prefix}A`, type: 'half', values: alpha });+ return channels;+}++function encodeExrPass(options) {+ return encodeExr(options.width, options.height, exrChannelsForPass(options));+}++export function encodeMultilayerExr({ width, height, beauty, passes = {}, hasAlpha = false, depthRange = 100 }) {+ if (beauty.length !== width * height * 4) throw new RangeError('The beauty pixel count does not match the image size.');+ const channels = [...exrChannelsForPass({ pixels: beauty, width, height, pass: undefined, hasAlpha, depthRange, prefix: 'Combined.' })];+ for (const [pass, pixels] of Object.entries(passes)) {+ if (pixels.length !== width * height * 4) throw new RangeError(`The ${pass} pixel count does not match the image size.`);+ channels.push(...exrChannelsForPass({ pixels, width, height, pass, hasAlpha: false, depthRange, prefix: `${pass}.` }));+ }return encodeExr(width, height, channels);}-function encodePng16Pass({ pixels, width, height, pass, hasAlpha }) {+function encodePng16Pass({ pixels, width, height, pass, hasAlpha, depthRange = 100 }) {const pixelCount = width * height;if (pass === 'depth' || pass === 'objectId') {const samples = new Uint16Array(pixelCount);@@ -236,7 +253,13 @@ function encodePng16Pass({ pixels, width, height, pass, hasAlpha }) {const alpha = pixels[offset + 3];// The lit frame is premultiplied by alpha; a PNG stores straight colour.const scale = hasAlpha && alpha > 0 ? 1 / alpha : 1;- for (let component = 0; component < 3; component++) samples[target + component] = toSixteenBits(pixels[offset + component] * scale);+ for (let component = 0; component < 3; component++) {+ const raw = pixels[offset + component];+ const mapped = pass === 'position' ? raw / depthRange * 0.5 + 0.5+ : pass === 'velocity' ? (component < 2 ? raw * 0.5 + 0.5 : 0)+ : raw * scale;+ samples[target + component] = toSixteenBits(mapped);+ }if (hasAlpha) samples[target + 3] = toSixteenBits(alpha);}}diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex fff33f69..94d7e460 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -50,7 +50,7 @@ export const MATERIAL_PATTERN_TYPES =Object.freeze(['noise', 'wood', 'planks', 'export const MAX_MATERIAL_PATTERNS = 16;// A material graph bakes to textures on the CPU and never becomes shader text. Its node and depth limits are the field// expression limits; maxWork is work units per pixel times pixels, so a costly graph needs a smaller texture.-export const MATERIAL_GRAPH_OUTPUTS = Object.freeze(['color', 'roughness', 'metallic', 'emission', 'height', 'opacity', 'clearcoat', 'transmission']);+export const MATERIAL_GRAPH_OUTPUTS = Object.freeze(['color', 'roughness', 'metallic', 'emission', 'height', 'opacity', 'clearcoat', 'transmission', 'aov']);export const MATERIAL_GRAPH_OPERATORS = Object.freeze(['uv', 'vec', 'ramp', 'noise', 'voronoi', 'wave', 'checker', 'gradient','add', 'sub', 'mul', 'div', 'min', 'max', 'pow', 'abs', 'floor', 'fract', 'sqrt', 'invert', 'clamp', 'smoothstep', 'mix',@@ -69,7 +69,7 @@ export const CURVE_TEXT_DETAILS = Object.freeze({});export const MATERIAL_MAPPINGS = Object.freeze(['box', 'uv']);export const MATERIAL_GRAPH_NODES = Object.freeze({- outputs: 'color (linear RGB; a number is grey), roughness, metallic, emission (defaults to 1), height (normal map), opacity (alpha), clearcoat, transmission (masks).',+ outputs: 'color (linear RGB; a number is grey), roughness, metallic, emission (defaults to 1), height (normal map), opacity (alpha), clearcoat, transmission (masks), aov (linear RGB or scalar).',textures: Object.freeze({noise: '{"noise":{"scale":8,"seed":1,"octaves":4}}',voronoi: '{"voronoi":{"scale":6,"output":"distance"|"edge"|"cell"}}',@@ -94,7 +94,7 @@ export const DEFAULT_LIGHTING_SETUP = 'daylight';export const DEFAULT_AMBIENT_OCCLUSION = 0;// Render passes a render job can write next to the lit image (see RENDER_PASS_MODES in renderer.js, which must list the same names).-export const RENDER_PASS_NAMES = Object.freeze(['albedo', 'normal', 'emission', 'depth', 'objectId', 'diffuse', 'glossy', 'shadow', 'ao', 'mist']);+export const RENDER_PASS_NAMES = Object.freeze(['albedo', 'normal', 'emission', 'depth', 'objectId', 'diffuse', 'glossy', 'shadow', 'ao', 'mist', 'position', 'velocity', 'uv', 'transmission', 'volume', 'environment', 'cryptomatte', 'aov']);// Video encoders a render job can choose (nvenc is h264_nvenc and fails the job when the GPU or ffmpeg lacks it), the// longest video, and the audio file names a job may mix in from the --audio folder: one path segment with a known// extension, no drive or protocol syntax.@@ -180,9 +180,9 @@ export const MESH_SCULPT_NOTES = Object.freeze({export const AGENT_SCENE_CAPABILITIES = Object.freeze({format: '67js.scene', schemaVersion: 1,geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'cone', 'icoSphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'grid', 'plane', 'circle', 'line', 'terrain', 'mesh']),- camera: 'eye, target, up, near, far, then fov (vertical degrees) or focalLength (mm, with sensorWidth mm, 36; not both). projection orthographic with orthoScale (view height in m, default 4). shift [x, y] moves the frame by a fraction of its size. fStop (0.7-64) turns on depth of field focused on target; 1.4 or lower is full blur; effects.depthOfField.blur must stay 0. Orthographic and shifted cameras use the rasterizer, not the path tracer.',+ camera: 'eye, target, up, near, far, then fov (vertical degrees) or focalLength (mm, with sensorWidth mm, 36; not both). projection orthographic with orthoScale (view height in m, default 4). shift [x, y] moves the frame by a fraction of its size. fStop (0.7-64) turns on depth of field focused on target; 1.4 or lower is full blur; effects.depthOfField.blur must stay 0. Orthographic/shifted cameras use the rasterizer.',terrain: 'One mesh, x and z from -size/2 to size/2, hills about y = 0. size 40 m (1-2000), resolution 64 cells (2-256), seed 1, amplitude 1 m (0-200), holes up to 16 of {center:[x,z],radius}, no surface inside; radius a few cells or more.',- placedAssets: 'Node field asset:{id,materials?,clip?,drive?} turns a group node into a catalog GLB (id from asset_catalog). Its transform places it. materials:[{name,color,metallic,roughness,opacity,emission,emissiveColor}] override source materials by name. clip:{index,start=0,speed=1,loop=true} plays that clip from scene time start; set-motion tracks move the node and scene time seeks the clip. drive:{path | legs, cruiseSpeed | speed, wheels, lights} drives a car along a path in the placement frame (docs/vehicle.md). At most 512 placements, 16 assets, 16 animated.',+ placedAssets: 'Node field asset:{id,materials?,clip?,drive?} turns a group node into a catalog GLB (id from asset_catalog). Its transform places it. materials:[{name,color,metallic,roughness,opacity,emission,emissiveColor}] override source materials by name. clip:{index,start=0,speed=1,loop=true} plays that clip from scene time start; set-motion tracks move the node and scene time seeks the clip. drive:{path | legs, cruiseSpeed | speed, wheels, lights} drives a car along a path in the placement frame (docs/vehicle.md). Max 512 placements, 16 assets, 16 animated.',navigation: 'scene_inspect path:{ground,from:[x,z],to:[x,z]} returns a route over the ground node around its holes, steep slopes and the nodes in avoid:[ids] (box footprints), as keyframes [{time,value:[x,y,z]}] for a translation track with interpolation LINEAR. radius 0.3 m; maxSlope 40 degrees; cellSize defaults to radius; seconds or speed (1.4 m/s); lift adds y.',meshEdits: Object.freeze({ operations: Object.freeze(Object.keys(MESH_EDIT_OPERATIONS)), maxEdits: MAX_MESH_EDITS }),meshStack: Object.freeze({ operations: STACK_OPERATIONS, maxNodes: MAX_STACK_NODES }),@@ -216,7 +216,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({alphaModes: RECIPE_ALPHA_MODES,materialPatterns: MATERIAL_PATTERN_TYPES, maxMaterialPatterns: MAX_MATERIAL_PATTERNS,materialMappings: MATERIAL_MAPPINGS,- renderPasses: Object.freeze({ names: RENDER_PASS_NAMES, files: 'render-<pass>.png or frame-N-<pass>.png, raw and unantialiased; opaque and cutout geometry only', depth: `16 bits in red and green over ${RENDER_PASS_DEPTH_RANGE} m`, objectId: '24 bits in RGB; the job result lists the part names' }),+ renderPasses: Object.freeze({ names: RENDER_PASS_NAMES, files: 'render-<pass>.png/.exr or frame-N-<pass>.png/.exr (multilayer: true packs all into render.exr)', depth: `16 bits in red and green over ${RENDER_PASS_DEPTH_RANGE} m`, objectId: '24 bits in RGB; metrics.objectNames lists parts', cryptomatte: 'R object hash, G material hash, B coverage; metrics.cryptomatte holds manifests', aov: 'material.aov or pattern.graph.aov linear RGB' }),// Recipe timeline (src/film-timeline.js), rendered with settings.timeline; the rest is in docs/agent-render-jobs.md.filmTimeline: Object.freeze({maxShots: 64, maxTotalSeconds: 60, maxShotSeconds: 30,diff --git a/src/agent-scene.js b/src/agent-scene.jsindex c4962d3e..864ca4aa 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -30,8 +30,8 @@ const CAMERA_DEFAULTS = Object.freeze({ eye: [4, 3, 5], target: [0, 0, 0], up: [const RENDER_FLAG_FIELDS = ['visible', 'castShadow', 'receiveShadow', 'holdout', 'shadowCatcher'];const PART_FLAG_FIELDS = RENDER_FLAG_FIELDS.slice(1);const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material', 'skin', 'relations', 'asset', 'vegetation', 'decal', 'depthLayer', 'blend', ...RENDER_FLAG_FIELDS];-const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', 'map', 'subsurface', 'snippet', 'waterPreset', 'absorption', 'turbidity', ...MATERIAL_LAYER_FIELDS];-const PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'emissiveMap', 'layerMaps', 'transmissionMap', 'boxMapScale', 'boxMapAxis'];+const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', 'map', 'subsurface', 'snippet', 'waterPreset', 'absorption', 'turbidity', 'aov', ...MATERIAL_LAYER_FIELDS];+const PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'emissiveMap', 'layerMaps', 'transmissionMap', 'aovMap', 'boxMapScale', 'boxMapAxis'];const CAMERA_FIELDS = [...Object.keys(CAMERA_DEFAULTS), ...CAMERA_LENS_FIELDS];const LOOK_OPERATION_FIELDS = Object.freeze({'set-environment': 'environment',@@ -264,6 +264,13 @@ function materialFrom(value) {throw invalidField('emissiveColor', result.emissiveColor, 'three numbers of 0 or more, such as [1, 0.5, 0.2]');}}+ if (value.aov !== undefined) {+ const aov = typeof value.aov === 'number' ? [finite(value.aov, 'aov'), value.aov, value.aov] : vector(value.aov, 3, 'aov');+ if (aov.some(component => component < 0 || component > 1)) {+ throw invalidField('aov', value.aov, 'a number or three numbers from 0 to 1, such as [1, 0.5, 0]');+ }+ result.aov = aov;+ }copyMaterialLayers(value, result);if (agentSceneModuleLoaded('worldMaterials')) {agentSceneModule('worldMaterials').copyWaterFields(value, result, vector);@@ -875,7 +882,7 @@ function batchSignature(material) {function materialHandle(snapshot, sequence) {const holder = { snapshot, sequence };const output = {};- for (const field of ['tag', ...MATERIAL_FIELDS]) {+ for (const field of ['id', 'tag', ...MATERIAL_FIELDS]) {Object.defineProperty(output, field, {enumerable: true,configurable: true,@@ -898,7 +905,7 @@ function materialHandle(snapshot, sequence) {}function immutableMaterial(snapshot) {- for (const field of ['color', 'emissiveColor', 'absorption']) {+ for (const field of ['color', 'emissiveColor', 'absorption', 'aov']) {if (snapshot[field]) {Object.freeze(snapshot[field]);}diff --git a/src/lighting-pass-shader.js b/src/lighting-pass-shader.jsindex 8970df22..0e6f1e6f 100644--- a/src/lighting-pass-shader.js+++ b/src/lighting-pass-shader.js@@ -1,24 +1,65 @@import { registerShaderFeatureCode } from './shader-registry.js';-// The GLSL of the lighting render passes (diffuse, glossy, shadow, ao, mist), spliced into the main fragment shader by the-// `lightingPass` feature. render-passes.js imports this file, so only a renderer that installs render passes carries it, and-// only a frame that asks for a lighting pass compiles it in. Modes 6 to 10 of renderPassMode, see RENDER_PASS_MODES.-//-// glossyLight collects every specular term: each light's lobe inside illuminate, and the sky or environment reflection. The-// environment term is the same function with a black surface colour, which removes its diffuse half. Diffuse is the rest of-// the lit radiance without emission, so diffuse + glossy + emission is the radiance before fog by construction.+// The GLSL of the lighting and auxiliary render passes (modes 6 to 18 of renderPassMode, see RENDER_PASS_MODES), spliced into+// the main fragment shader by the `lightingPass` feature. render-passes.js imports this file, so only a renderer that installs+// render passes carries it, and only a frame that asks for one of these passes compiles it in.registerShaderFeatureCode('lightingPass', {declarations: `#define USES_LIGHTING_PASS (renderPassMode > 5.5)vec3 glossyLight = vec3(0.0);+vec3 environmentLight = vec3(0.0);+uniform float passFloatOutput;+uniform mat4 passCurrentViewProjection;+uniform mat4 passPreviousViewProjection;+uniform mat4 passObjectDeltas[8];+uniform float passVolumeDensity;+uniform vec3 passVolumeColor;+uniform float passMaterialIds[32];+uniform float passTransmission;+uniform vec3 passMaterialAov;+uniform float hasPassAuxMap;+float cryptoHash(float id) {+ uint h = uint(id + 0.5) * 0x9e3779b9u;+ h ^= h >> 16u;+ h *= 0x85ebca6bu;+ h ^= h >> 13u;+ return float((h % 255u) + 1u) / 255.0;+}`,illuminateSpecular: ' if (USES_LIGHTING_PASS) glossyLight += specular * radiance * normalLight;\n',- probeReflection: ' if (USES_LIGHTING_PASS && ENVIRONMENT_ENABLED) glossyLight += environmentLighting(normal, specularNormal, baseReflectance, viewDirection, reflected, vec3(0.0), metallic, roughness, occlusion, ambientIntensity, skyReflection);\n',- probeSurroundings: ' if (USES_LIGHTING_PASS) glossyLight += surroundings * reflectance * skyReflection * (1.0 - roughness * 0.55) * mix(1.0, 0.5 * daylight, worldMode) * occlusion * ambientIntensity;\n',+ probeReflection: ` if (USES_LIGHTING_PASS && ENVIRONMENT_ENABLED) {+ glossyLight += environmentLighting(normal, specularNormal, baseReflectance, viewDirection, reflected, vec3(0.0), metallic, roughness, occlusion, ambientIntensity, skyReflection);+ environmentLight = environmentLighting(normal, specularNormal, baseReflectance, viewDirection, reflected, color, metallic, roughness, occlusion, ambientIntensity, skyReflection);+ }+`,+ probeSurroundings: ` if (USES_LIGHTING_PASS) {+ vec3 envSpecular = surroundings * reflectance * skyReflection * (1.0 - roughness * 0.55) * mix(1.0, 0.5 * daylight, worldMode) * occlusion * ambientIntensity;+ glossyLight += envSpecular;+ environmentLight = envSpecular + color * (1.0 - metallic) * mix(vec3(0.16, 0.20, 0.22), vec3(0.19, 0.25, 0.30) * max(daylight, 0.08), worldMode) * (0.45 + 0.55 * max(normal.y, 0.0)) * occlusion * ambientIntensity;+ }+`,worldFinal: ` if (USES_LIGHTING_PASS) {float mist = 1.0 - exp(-length(worldPosition - eye) * fogDensity);+ int instanceIndex = int(instanceEmission.w + 0.5);+ vec4 currentClip = passCurrentViewProjection * vec4(worldPosition, 1.0);+ vec2 currentScreen = currentClip.xy / max(currentClip.w, 1e-6) * 0.5 + 0.5;+ vec4 prevClip = passPreviousViewProjection * (passObjectDeltas[min(instanceIndex, 7)] * vec4(worldPosition, 1.0));+ vec2 prevScreen = prevClip.w > 0.0 ? prevClip.xy / prevClip.w * 0.5 + 0.5 : currentScreen;+ vec2 vel = currentScreen - prevScreen;+ vec2 uvCoord = max(textureUV, vec2(0.0));+ vec4 auxSample = hasPassAuxMap > 0.5 ? (BOX_MAPPED ? sampleBox(emissiveMap) : texture(emissiveMap, textureUV)) : vec4(1.0);vec3 passValue = renderPassMode < 6.5 ? (radiance - glossyLight - emission) * exposure: renderPassMode < 7.5 ? glossyLight * exposure- : vec3(renderPassMode < 8.5 ? visibility : renderPassMode < 9.5 ? occlusion : mist);+ : renderPassMode < 8.5 ? vec3(visibility)+ : renderPassMode < 9.5 ? vec3(occlusion)+ : renderPassMode < 10.5 ? vec3(mist)+ : renderPassMode < 11.5 ? (passFloatOutput > 0.5 ? worldPosition : clamp(worldPosition / renderPassDepthRange * 0.5 + 0.5, 0.0, 1.0))+ : renderPassMode < 12.5 ? (passFloatOutput > 0.5 ? vec3(vel, 0.0) : vec3(clamp(vel * 0.5 + 0.5, 0.0, 1.0), 0.0))+ : renderPassMode < 13.5 ? (passFloatOutput > 0.5 ? vec3(uvCoord, 0.0) : vec3(clamp(fract(uvCoord), 0.0, 1.0), 0.0))+ : renderPassMode < 14.5 ? (1.0 - reflectance) * passTransmission * auxSample.r * ((radiance - glossyLight - emission) + color * ambientIntensity * 0.5) * exposure+ : renderPassMode < 15.5 ? passVolumeColor * (1.0 - exp(-length(worldPosition - eye) * passVolumeDensity)) * exposure+ : renderPassMode < 16.5 ? environmentLight * exposure+ : renderPassMode < 17.5 ? vec3(cryptoHash(renderPassObjectBase + instanceEmission.w + 1.0), cryptoHash(passMaterialIds[min(instanceIndex, 31)]), 1.0)+ : passMaterialAov * auxSample.rgb;outputColor = vec4(passValue, 1.0);return;}diff --git a/src/material-graph.js b/src/material-graph.jsindex 71b1c9bd..d7cd8237 100644--- a/src/material-graph.js+++ b/src/material-graph.js@@ -529,13 +529,14 @@ function writeColor(data, offset, channels) {export function bakeMaterialGraph(graph, { resolution, bump }) {const compiled = compileMaterialGraph(graph);checkMaterialGraphWork(compiled, resolution);- const { color, roughness, metallic, emission, height, opacity, clearcoat, transmission } = compiled.outputs;+ const { color, roughness, metallic, emission, height, opacity, clearcoat, transmission, aov } = compiled.outputs;const pixelCount = resolution * resolution;// Opacity travels in the alpha of the base texture, so an opacity-only graph still gets a (white) base texture.const colorData = color || opacity ? new Uint8ClampedArray(pixelCount * 4).fill(255) : null;const clearcoatData = clearcoat ? new Uint8ClampedArray(pixelCount * 4) : null;const transmissionData = transmission ? new Uint8ClampedArray(pixelCount * 4) : null;const emissionData = emission ? new Uint8ClampedArray(pixelCount * 4) : null;+ const aovData = aov ? new Uint8ClampedArray(pixelCount * 4) : null;const surfaceData = roughness || metallic ? new Uint8ClampedArray(pixelCount * 4) : null;for (let row = 0; row < resolution; row++) {for (let column = 0; column < resolution; column++) {@@ -548,6 +549,11 @@ export function bakeMaterialGraph(graph, { resolution, bump }) {if (clearcoat) writeMask(clearcoatData, offset, clearcoat.evaluate(u, v));if (transmission) writeMask(transmissionData, offset, transmission.evaluate(u, v));if (emission) writeColor(emissionData, offset, sampleChannels(emission, u, v));+ if (aov) {+ const channels = sampleChannels(aov, u, v);+ for (let channel = 0; channel < 3; channel++) aovData[offset + channel] = unitByte(channels[channel]);+ aovData[offset + 3] = 255;+ }if (surfaceData) {surfaceData[offset] = 255;surfaceData[offset + 1] = roughness ? Math.round(clampUnit(finiteOrZero(roughness.evaluate(u, v))) * 255) : 255;@@ -564,6 +570,7 @@ export function bakeMaterialGraph(graph, { resolution, bump }) {// The rasterizer binds clearcoatTexture from layerMaps; transmission has no layer slot, so the tracer reads transmissionMap.layerMaps: clearcoatData ? { clearcoatTexture: descriptor(clearcoatData, 'linear') } : undefined,transmissionMap: descriptor(transmissionData, 'linear'),+ aovMap: descriptor(aovData, 'linear'),normalMap: descriptor(height ? normalMapFromHeightFunction((u, v) => finiteOrZero(height.evaluate(u, v)), resolution, bump) : null, 'linear'),};}diff --git a/src/render-passes.js b/src/render-passes.jsindex 1747bd97..6223cd3d 100644--- a/src/render-passes.js+++ b/src/render-passes.js@@ -1,17 +1,42 @@+import { mat4 } from 'gl-matrix';+import { applyProjection } from './camera.js';import { compileProgram, fullscreenVertex } from './gl-program.js';import './lighting-pass-shader.js';-// Render passes draw raw material data (albedo, normal, emission, depth, object ID) instead of the lit image.-// The shader branch lives in the main fragment shader behind the `renderPass` feature, which compiles on the first-// pass request; this addon owns the rest: the target, the copy to the canvas and the object ID table.+// Render passes draw raw material data or isolated lighting/auxiliary terms instead of the lit beauty image.+// The shader branches live in the main fragment shader behind `renderPass` and `lightingPass`, which compile on the first+// pass request; this addon owns the target, the copy to the canvas, the per-pass uniforms and the Cryptomatte manifest./** The shader's `renderPassMode` for each pass name. agent-scene-capabilities.js lists the same names. */-export const RENDER_PASS_MODES = Object.freeze({ albedo: 1, normal: 2, emission: 3, depth: 4, objectId: 5, diffuse: 6, glossy: 7, shadow: 8, ao: 9, mist: 10 });+export const RENDER_PASS_MODES = Object.freeze({+ albedo: 1, normal: 2, emission: 3, depth: 4, objectId: 5,+ diffuse: 6, glossy: 7, shadow: 8, ao: 9, mist: 10,+ position: 11, velocity: 12, uv: 13, transmission: 14, volume: 15, environment: 16, cryptomatte: 17, aov: 18,+});// Background pixels: depth reads as the far limit, and shadow, ao and mist as open sky (one); every other pass reads zero, and object ID zero means no object.const PASS_BACKGROUNDS = Object.freeze({ depth: [1, 1, 0, 1], shadow: [1, 1, 1, 1], ao: [1, 1, 1, 1], mist: [1, 1, 1, 1] });-// Modes above this one run the lit shader (lighting-pass-shader.js) and write one lighting term: linear, scaled by exposure.+// Modes above this one run the lit shader (lighting-pass-shader.js).const LAST_RAW_PASS_MODE = 5;const DEFAULT_BACKGROUND = Object.freeze([0, 0, 0, 1]);+const IDENTITY_MAT4 = mat4.create();++/** Deterministic non-zero float ID in [1/255, 1] for Cryptomatte object/material IDs, matching cryptoHash() in GLSL. */+export function cryptomatteValue(id) {+ let hash = Math.imul(id >>> 0, 0x9e3779b9) >>> 0;+ hash = (hash ^ (hash >>> 16)) >>> 0;+ hash = Math.imul(hash, 0x85ebca6b) >>> 0;+ hash = (hash ^ (hash >>> 13)) >>> 0;+ return ((hash % 255) + 1) / 255;+}++/** Deterministic 8-hex-character FNV-1a manifest hash for a Cryptomatte object or material name. */+export function cryptomatteHashHex(name) {+ let hash = 0x811c9dc5;+ for (let index = 0; index < name.length; index++) {+ hash = Math.imul(hash ^ name.charCodeAt(index), 0x01000193) >>> 0;+ }+ return hash.toString(16).padStart(8, '0');+}// Copies a pass texture to the canvas byte for byte: one texel per pixel, no filtering, no grading.const passCopyFragment = `#version 300 es@@ -44,14 +69,38 @@ function createPassTarget(context, width, height, float = false) {/*** Lets `renderer.render({ ...camera, pass })` draw one pass. Passes draw without multisampling into their own target,- * so object IDs and normals stay exact at silhouettes. Only opaque and cutout parts appear. `passDepthRange` is the- * number of metres that depth values 0 to 65535 span (default 100).+ * so object IDs and normals stay exact at silhouettes. Only opaque and cutout parts appear (plus transmissive parts in+ * the `transmission` pass). `passDepthRange` is the number of metres that depth values 0 to 65535 span (default 100).*/export function installRenderPasses(renderer) {if (renderer.passSupport) return renderer;let target = null;let copyProgram = null;let copyTextureUniform = null;+ let cachedProgram = null;+ let passUniforms = null;+ let frameMaterials = null;+ const deltaBuffer = new Float32Array(8 * 16);+ const materialIdBuffer = new Float32Array(32);++ function uniformsFor(program) {+ if (cachedProgram === program && passUniforms) return passUniforms;+ const context = renderer.context;+ cachedProgram = program;+ passUniforms = {+ passFloatOutput: context.getUniformLocation(program, 'passFloatOutput'),+ passCurrentViewProjection: context.getUniformLocation(program, 'passCurrentViewProjection'),+ passPreviousViewProjection: context.getUniformLocation(program, 'passPreviousViewProjection'),+ passObjectDeltas: context.getUniformLocation(program, 'passObjectDeltas[0]'),+ passVolumeDensity: context.getUniformLocation(program, 'passVolumeDensity'),+ passVolumeColor: context.getUniformLocation(program, 'passVolumeColor'),+ passMaterialIds: context.getUniformLocation(program, 'passMaterialIds[0]'),+ passTransmission: context.getUniformLocation(program, 'passTransmission'),+ passMaterialAov: context.getUniformLocation(program, 'passMaterialAov'),+ hasPassAuxMap: context.getUniformLocation(program, 'hasPassAuxMap'),+ };+ return passUniforms;+ }function releaseTargets(context) {if (!target) return;@@ -66,6 +115,8 @@ export function installRenderPasses(renderer) {releaseTargets(context);if (copyProgram) context.deleteProgram(copyProgram);copyProgram = null;+ cachedProgram = null;+ passUniforms = null;}function prepare(frame) {@@ -105,11 +156,111 @@ export function installRenderPasses(renderer) {context.drawArrays(context.TRIANGLES, 0, 3);}+ function drawsInPass(batch, passMode) {+ return renderer.drawsInOpaqueLoop(batch) || (passMode === RENDER_PASS_MODES.transmission && batch.layerState[9] > 0);+ }+// Part names by object ID minus one, in the order the object ID pass numbers them (draw order, grouped by geometry).function objectNames() {return renderer.batches.filter(batch => renderer.drawsInOpaqueLoop(batch)).flatMap(batch => batch.parts.map(part => part.name));}+ function materialTable() {+ const table = new Map();+ for (const batch of renderer.batches) {+ if (!renderer.drawsInOpaqueLoop(batch)) continue;+ for (const part of batch.parts) {+ const material = part.material;+ const key = material.id ?? material.name ?? material;+ if (!table.has(key)) {+ const id = table.size + 1;+ const name = typeof key === 'string' ? key : `material-${id}`;+ table.set(key, { id, name });+ }+ }+ }+ return table;+ }++ function cryptomatteManifest() {+ const objects = Object.fromEntries(objectNames().map((name, index) => [name, { id: index + 1, hash: cryptomatteHashHex(name), value: cryptomatteValue(index + 1) }]));+ const materials = Object.fromEntries([...materialTable().values()].map(({ id, name }) => [name, { id, hash: cryptomatteHashHex(name), value: cryptomatteValue(id) }]));+ return { objects, materials };+ }++ function previousViewProjectionFor(frame) {+ if (frame.previousViewProjection) return frame.previousViewProjection;+ if (!frame.previousCamera) return renderer.viewProjection;+ const aspect = renderer.canvas.width / renderer.canvas.height;+ const camera = frame.previousCamera;+ const view = mat4.lookAt(mat4.create(), camera.eye, camera.target ?? [0, 1.2, 0], camera.up ?? [0, 1, 0]);+ const projection = applyProjection(mat4.create(), camera, aspect);+ return mat4.multiply(mat4.create(), projection, view);+ }++ function bindFrame(frame, environment, volume) {+ const context = renderer.context;+ const uniforms = uniformsFor(renderer.program);+ const density = volume.density > 0 ? volume.density : (environment.fogDensity ?? 0.006);+ const color = volume.density > 0 ? volume.color : (environment.fogColor ?? [0.35, 0.43, 0.43]);+ context.uniform1f(uniforms.passFloatOutput, frame.passFloat ? 1 : 0);+ context.uniformMatrix4fv(uniforms.passCurrentViewProjection, false, renderer.viewProjection);+ context.uniformMatrix4fv(uniforms.passPreviousViewProjection, false, previousViewProjectionFor(frame));+ context.uniform1f(uniforms.passVolumeDensity, density);+ context.uniform3fv(uniforms.passVolumeColor, color);+ frameMaterials = materialTable();+ }++ function drawBatch(batch, passMode, frame, objectBase) {+ const materials = frameMaterials ?? materialTable();+ const context = renderer.context;+ const uniforms = uniformsFor(renderer.program);+ const count = Math.min(batch.parts.length, 8);+ for (let index = 0; index < 8; index++) {+ const slot = deltaBuffer.subarray(index * 16, (index + 1) * 16);+ if (index < count && frame.objectMotion?.matrices) {+ const motionIndex = (objectBase + index) * 16;+ if (motionIndex + 16 <= frame.objectMotion.matrices.length) {+ slot.set(frame.objectMotion.matrices.subarray(motionIndex, motionIndex + 16));+ continue;+ }+ }+ if (index < count && frame.previousMatrices) {+ const name = batch.parts[index].name;+ const previous = frame.previousMatrices instanceof Map ? frame.previousMatrices.get(name) : frame.previousMatrices[name];+ const inverse = mat4.create();+ if (previous && mat4.invert(inverse, batch.parts[index].matrix)) {+ mat4.multiply(slot, previous, inverse);+ continue;+ }+ }+ slot.set(IDENTITY_MAT4);+ }+ context.uniformMatrix4fv(uniforms.passObjectDeltas, false, deltaBuffer);+ materialIdBuffer.fill(1);+ for (let index = 0; index < Math.min(batch.parts.length, 32); index++) {+ const material = batch.parts[index].material;+ materialIdBuffer[index] = materials.get(material.id ?? material.name ?? material)?.id ?? 1;+ }+ context.uniform1fv(uniforms.passMaterialIds, materialIdBuffer);+ context.uniform1f(uniforms.passTransmission, batch.layerState[9] ?? 0);+ const firstMaterial = batch.parts[0].material;+ const aov = firstMaterial.aov ?? (firstMaterial.aovMap ? [1, 1, 1] : [0, 0, 0]);+ context.uniform3f(uniforms.passMaterialAov, aov[0], aov[1], aov[2]);+ const auxDescriptor = passMode === RENDER_PASS_MODES.aov ? firstMaterial.aovMap+ : passMode === RENDER_PASS_MODES.transmission ? firstMaterial.transmissionMap+ : null;+ context.uniform1f(uniforms.hasPassAuxMap, auxDescriptor ? 1 : 0);+ const savedEmissiveTexture = batch.textures[4];+ if (auxDescriptor) batch.textures[4] = renderer.createTexture(auxDescriptor);+ try {+ const culled = passMode !== RENDER_PASS_MODES.objectId && passMode !== RENDER_PASS_MODES.cryptomatte;+ renderer.drawAlphaBatch(batch, true, culled);+ } finally {+ batch.textures[4] = savedEmissiveTexture;+ }+ }+renderer.passSupport = {prepare,get framebuffer() { return target.framebuffer; },@@ -117,7 +268,11 @@ export function installRenderPasses(renderer) {get texture() { return target.texture; },background: pass => PASS_BACKGROUNDS[pass] ?? DEFAULT_BACKGROUND,copyToCanvas,+ drawsInPass,+ bindFrame,+ drawBatch,objectNames,+ cryptomatteManifest,releaseTargets,dispose,};diff --git a/src/renderer.js b/src/renderer.jsindex 3e6a7e6e..9f8558dd 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -418,7 +418,7 @@ export function groupParts(parts, batching = true) {const key = batching ? part.geometry : part;if (!groups.has(key)) groups.set(key, new Map());let maps = groups.get(key);- for (const value of [...materialMapState(part.material), ...materialLayerState(part.material), part.skin ?? null, part.material.snippet, part.crowd ?? null, part.morph ?? null, castsShadow(part), receivesShadow(part), compositeModeOf(part), depthLayerOf(part), renderPass(part.material), part.lods ?? null, part.shadowLods ?? null, isMirroredMatrix(part.matrix), ...materialAlphaState(part.material)]) {+ for (const value of [...materialMapState(part.material), ...materialLayerState(part.material), part.skin ?? null, part.material.snippet, part.crowd ?? null, part.morph ?? null, castsShadow(part), receivesShadow(part), compositeModeOf(part), depthLayerOf(part), renderPass(part.material), part.lods ?? null, part.shadowLods ?? null, isMirroredMatrix(part.matrix), ...materialAlphaState(part.material), part.material.aovMap ?? null, part.material.transmissionMap ?? null, ...(part.material.aov ?? ZERO_VECTOR)]) {if (!maps.has(value)) maps.set(value, new Map());maps = maps.get(value);}@@ -2311,15 +2311,17 @@ export class Renderer67 {this.applyEnvironmentUniforms(environmentMap);context.uniform1f(this.uniforms.renderPassMode, passMode);context.uniform1f(this.uniforms.renderPassDepthRange, frame.passDepthRange ?? 100);+ if (passMode > 5) this.passSupport.bindFrame(frame, environment, volume);let objectBase = 0;for (const batch of this.batches) {if (this.benchmark) {this.drawBatch(batch, true);- } else if (this.drawsInOpaqueLoop(batch) && !(mirrorTarget && batch.mapState[20])) {+ } else if ((passMode > 5 ? this.passSupport.drawsInPass(batch, passMode) : this.drawsInOpaqueLoop(batch)) && !(mirrorTarget && batch.mapState[20])) {context.uniform1f(this.uniforms.renderPassObjectBase, objectBase);objectBase += batch.instanceCount;// Object IDs are the instance ordinal, which culling and level selection renumber, so that pass draws every instance.- this.drawAlphaBatch(batch, true, passMode !== OBJECT_ID_PASS_MODE);+ if (passMode > 5) this.passSupport.drawBatch(batch, passMode, frame, objectBase - batch.instanceCount);+ else this.drawAlphaBatch(batch, true, passMode !== OBJECT_ID_PASS_MODE);}}this.applyDepthLayer(0);diff --git a/tests/lighting-passes.test.js b/tests/lighting-passes.test.jsindex fff97879..7cd04014 100644--- a/tests/lighting-passes.test.js+++ b/tests/lighting-passes.test.js@@ -1,4 +1,5 @@-// Lighting render passes (issue 601) drawn for real: diffuse + glossy + emission add back to the beauty frame, and shadow, ao and mist read sensibly.+// Lighting and auxiliary render passes (issues 601 and 706) drawn for real: diffuse + glossy + emission add back to the+// beauty frame, and shadow, ao, mist, position, velocity, uv, transmission, volume, environment, cryptomatte and aov read accurately.// It draws in headless Chrome (SwiftShader, no GPU) from the Vite dev server, and skips when Chrome cannot start.import test from 'node:test';import assert from 'node:assert/strict';@@ -23,12 +24,10 @@ async function startServer(port) {return server;}---// Draws the beauty frame and every lighting pass of a floor with a shiny, an emissive and a rough box above it.-async function drawFrames(page, withEnvironment) {- const task = async (useEnvironment) => {- const { box } = await import('/src/geometry.js');+// Draws the beauty frame and every lighting and auxiliary pass of a floor with a shiny, a rough/emissive and a glass box.+async function drawFrames(page) {+ const task = async () => {+ const { box, sphere } = await import('/src/geometry.js');const { Renderer67 } = await import('/src/renderer.js');const { installRenderPasses } = await import('/src/render-passes.js');const { readFloatPixels } = await import('/src/float-output.js');@@ -41,11 +40,12 @@ async function drawFrames(page, withEnvironment) {copy.height = 64;const copyContext = copy.getContext('2d', { willReadFrequently: true });const geometry = box(0, 1);+ const uvSphere = sphere(16, 12);const scaled = (sx, sy, sz, x, y, z) => new Float32Array([sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, sz, 0, x, y, z, 1]);const parts = [- { name: 'floor', geometry, matrix: scaled(8, 0.2, 8, 0, -0.1, 0), material: { tag: 'surface', color: [0.25, 0.25, 0.25], metallic: 0, roughness: 0.7, emission: 0 } },- { name: 'shiny', geometry, matrix: scaled(1.2, 1.2, 1.2, -1.5, 1, 0), material: { tag: 'surface', color: [0.9, 0.2, 0.2], metallic: 0.8, roughness: 0.25, emission: 0 } },- { name: 'rough', geometry, matrix: scaled(1.2, 1.2, 1.2, 1.5, 1, 0), material: { tag: 'surface', color: [0.2, 0.5, 0.9], metallic: 0, roughness: 0.6, emission: 0.15 } },+ { name: 'floor', geometry, matrix: scaled(8, 0.2, 8, 0, -0.1, 0), material: { id: 'floor-mat', tag: 'surface', color: [0.25, 0.25, 0.25], metallic: 0, roughness: 0.7, emission: 0, aov: [0.1, 0.2, 0.3] } },+ { name: 'shiny', geometry: uvSphere, matrix: scaled(0.8, 0.8, 0.8, -1.5, 1, 0), material: { id: 'shiny-mat', tag: 'surface', color: [0.9, 0.2, 0.2], metallic: 0.8, roughness: 0.25, emission: 0, aov: [0.8, 0.25, 0.5] } },+ { name: 'rough', geometry: uvSphere, matrix: scaled(0.8, 0.8, 0.8, 1.5, 1, 0), material: { id: 'rough-mat', tag: 'surface', color: [0.2, 0.5, 0.9], metallic: 0, roughness: 0.6, emission: 0.15, aov: [0.2, 0.9, 0.4] } },];const renderer = installRenderPasses(new Renderer67(canvas, parts, { ground: false, samples: 1, pixelRatio: 1 }));const size = renderer.canvas.width;@@ -56,13 +56,31 @@ async function drawFrames(page, withEnvironment) {copyContext.drawImage(canvas, 0, 0, size, size);const beauty = Array.from(copyContext.getImageData(0, 0, size, size).data);const passes = {};- for (const pass of ['diffuse', 'glossy', 'emission', 'shadow', 'ao', 'mist', 'albedo']) {+ for (const pass of ['diffuse', 'glossy', 'emission', 'shadow', 'ao', 'mist', 'albedo', 'position', 'velocity', 'uv', 'volume', 'environment', 'cryptomatte', 'aov', 'objectId']) {renderer.render({ ...camera, pass, passFloat: true });passes[pass] = Array.from(readFloatPixels(renderer.context, renderer.passSupport.framebuffer, size, size));}- return { beauty, passes, size };+ // Render velocity with a moved camera and moved shiny box:+ renderer.render({+ ...camera,+ pass: 'velocity',+ passFloat: true,+ previousCamera: { eye: [0.8, 5, 7], target: [0, 0.6, 0] },+ previousMatrices: { shiny: scaled(1.2, 1.2, 1.2, -2.2, 1, 0) },+ });+ const movedVelocity = Array.from(readFloatPixels(renderer.context, renderer.passSupport.framebuffer, size, size));+ const manifest = renderer.passSupport.cryptomatteManifest();++ // Also test transmission pass on a transmissive glass part:+ const glassRenderer = installRenderPasses(new Renderer67(canvas, [+ ...parts,+ { name: 'glass', geometry, matrix: scaled(1.4, 1.4, 1.4, 0, 1.2, 2.0), material: { id: 'glass-mat', tag: 'surface', color: [0.8, 0.95, 1.0], metallic: 0, roughness: 0.1, emission: 0, transmission: 0.85 } },+ ], { ground: false, samples: 1, pixelRatio: 1 }));+ glassRenderer.render({ ...camera, pass: 'transmission', passFloat: true });+ const transmission = Array.from(readFloatPixels(glassRenderer.context, glassRenderer.passSupport.framebuffer, size, size));+ return { beauty, passes, movedVelocity, manifest, transmission, size };};- return page.evaluate(task, withEnvironment);+ return page.evaluate(task);}// The renderer's tone map and gamma, for the lit radiance that the passes add back up to.@@ -71,7 +89,7 @@ function display(value) {return Math.round(255 * mapped ** (1 / 2.2));}-test('diffuse + glossy + emission match the beauty frame, and shadow, ao and mist read as light terms', async (context) => {+test('diffuse + glossy + emission match the beauty frame, and auxiliary passes read exact values', async (context) => {let chromium;try {({ chromium } = await import('playwright'));@@ -84,19 +102,28 @@ test('diffuse + glossy + emission match the beauty frame, and shadow, ao and mislet browser;try {try {- browser = await chromium.launch({ headless: true, args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'] });+ const launchArgs = ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'];+ browser = await chromium.launch({ headless: true, args: launchArgs }).catch(() => chromium.launch({ headless: true, channel: 'chrome', args: launchArgs }));} catch (error) {context.skip(`Chrome did not start: ${error.message.split('\n')[0]}`);return;}const page = await browser.newPage({ viewport: { width: 64, height: 64 } });await page.goto(`http://127.0.0.1:${port}/`);- const { beauty, passes, size: SIZE } = await drawFrames(page, false);+ const { beauty, passes, movedVelocity, manifest, transmission, size: SIZE } = await drawFrames(page);let compared = 0;let totalError = 0;let largeErrors = 0;let glossyEnergy = 0;let shadowed = 0;+ let environmentEnergy = 0;+ let volumeEnergy = 0;+ let uvPositive = 0;+ let leftPositions = 0;+ let rightPositions = 0;+ let cryptoMatched = 0;+ let aovMatched = 0;+ let movingPixels = 0;for (let row = 0; row < SIZE; row++) {for (let column = 0; column < SIZE; column++) {const beautyIndex = (row * SIZE + column) * 4;@@ -111,14 +138,40 @@ test('diffuse + glossy + emission match the beauty frame, and shadow, ao and miscompared++;}glossyEnergy += passes.glossy[passIndex];+ environmentEnergy += passes.environment[passIndex] + passes.environment[passIndex + 1] + passes.environment[passIndex + 2];+ volumeEnergy += passes.volume[passIndex] + passes.volume[passIndex + 1] + passes.volume[passIndex + 2];if (passes.shadow[passIndex] < 0.5) shadowed++;+ if (passes.uv[passIndex] > 0.01 || passes.uv[passIndex + 1] > 0.01) uvPositive++;+ assert.ok(Math.abs(passes.velocity[passIndex]) < 1e-4 && Math.abs(passes.velocity[passIndex + 1]) < 1e-4, 'still frame has zero velocity');+ if (Math.hypot(movedVelocity[passIndex], movedVelocity[passIndex + 1]) > 0.01) movingPixels++;+ const objectId = Math.round(passes.objectId[passIndex] * 255);+ if (objectId === 2) {+ // shiny box sits around x = -1.5+ if (passes.position[passIndex] < -0.5) leftPositions++;+ if (Math.abs(passes.cryptomatte[passIndex] - manifest.objects.shiny.value) < 0.01+ && Math.abs(passes.cryptomatte[passIndex + 1] - manifest.materials['shiny-mat'].value) < 0.01+ && Math.abs(passes.cryptomatte[passIndex + 2] - 1) < 0.01) cryptoMatched++;+ if (Math.abs(passes.aov[passIndex] - 0.8) < 0.02 && Math.abs(passes.aov[passIndex + 1] - 0.25) < 0.02) aovMatched++;+ } else if (objectId === 3) {+ // rough box sits around x = +1.5+ if (passes.position[passIndex] > 0.5) rightPositions++;+ }}}assert.ok(compared > 3000, `the frame has ${compared} lit samples`);assert.ok(totalError / compared < 1.5, `mean difference ${totalError / compared} display levels`);assert.ok(largeErrors / compared < 0.02, `${largeErrors} of ${compared} samples differ by more than 4 levels`);assert.ok(glossyEnergy > 1, 'the glossy pass holds light');+ assert.ok(environmentEnergy > 1, 'the environment pass holds IBL/sky light');+ assert.ok(volumeEnergy > 0.1, 'the volume pass holds fog scattering');assert.ok(shadowed > 20, `the shadow pass marks ${shadowed} shadowed pixels`);+ assert.ok(uvPositive > 50, `the uv pass writes UVs on ${uvPositive} pixels`);+ assert.ok(leftPositions > 40 && rightPositions > 40, `position pass separates -X (${leftPositions}) and +X (${rightPositions})`);+ assert.ok(cryptoMatched > 40, `cryptomatte matches manifest on ${cryptoMatched} shiny pixels`);+ assert.ok(aovMatched > 40, `aov pass matches material.aov on ${aovMatched} shiny pixels`);+ assert.ok(movingPixels > 500, `velocity pass records motion on ${movingPixels} pixels`);+ const transmissionEnergy = transmission.reduce((sum, value, index) => (index % 4 < 3 ? sum + value : sum), 0);+ assert.ok(transmissionEnergy > 1, `transmission pass holds transmitted light (${transmissionEnergy})`);for (const name of ['shadow', 'ao', 'mist']) {for (let index = 0; index < passes[name].length; index += 4) {assert.ok(passes[name][index] >= 0 && passes[name][index] <= 1.001, `${name} stays between zero and one`);diff --git a/tests/render-passes.test.js b/tests/render-passes.test.jsindex 18aa5d3f..855c79c1 100644--- a/tests/render-passes.test.js+++ b/tests/render-passes.test.js@@ -5,22 +5,26 @@ import test from 'node:test';import assert from 'node:assert/strict';import { resolveEffects } from '../src/effects.js';import { normalizeAgentLook } from '../src/agent-look.js';-import { RENDER_PASS_MODES, installRenderPasses } from '../src/render-passes.js';+import { RENDER_PASS_MODES, installRenderPasses, cryptomatteValue, cryptomatteHashHex } from '../src/render-passes.js';import { createFragmentShader } from '../src/shaders.js';import { RENDER_PASS_NAMES } from '../src/agent-scene-capabilities.js';import { installCameraEffects, depthOfFieldFragment, motionBlurFragment } from '../src/camera-effects.js';import { createAgentRenderJobs, artifactNames } from '../scripts/agent-render-jobs.mjs';+import { encodeRenderOutput, encodeMultilayerExr } from '../scripts/render-output-encoders.mjs';+import { createAgentScene, loadAllAgentSceneModules } from '../src/agent-scene.js';+import { bakeMaterialGraph } from '../src/material-graph.js';const limits = { maxOutputBytes: 1024, maxFrameBytes: 128, maxStoreBytes: 1024 ** 2, cleanupMs: 100 };test('capabilities and the renderer list the same passes in the same order', () => {assert.deepEqual(Object.keys(RENDER_PASS_MODES), [...RENDER_PASS_NAMES]);- assert.deepEqual(Object.values(RENDER_PASS_MODES), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);+ assert.deepEqual(Object.values(RENDER_PASS_MODES), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]);});test('the pass branch of the main shader is compiled out unless a pass is requested', () => {assert.match(createFragmentShader([]), /#define USES_RENDER_PASS false/);assert.match(createFragmentShader(['renderPass']), /#define USES_RENDER_PASS \(renderPassMode > 0\.5 && renderPassMode < 5\.5\)/);+ assert.match(createFragmentShader(['renderPass', 'lightingPass']), /cryptoHash/);});test('camera effects default off, validate ranges and survive look normalization', () => {@@ -51,33 +55,213 @@ test('installing camera effects adds two stages once and costs nothing until a ffor (const source of [depthOfFieldFragment, motionBlurFragment]) assert.doesNotMatch(source, /rand\(|Math\.random|time/);});-test('render passes need the addon, reject unknown names and touch no GL until asked', () => {- const unusedContext = new Proxy({}, { get() { throw new Error('The GL context was touched.'); } });- const renderer = { passSupport: null, context: unusedContext, canvas: { width: 8, height: 8 }, benchmark: false };+test('render passes need the addon, reject unknown names and bind per-pass uniforms and manifests', () => {+ const calls = [];+ const context = {+ VERTEX_SHADER: 1, FRAGMENT_SHADER: 2, COMPILE_STATUS: 3, LINK_STATUS: 4,+ TEXTURE_2D: 5, RGBA16F: 6, RGBA8: 7, RGBA: 8, HALF_FLOAT: 9, UNSIGNED_BYTE: 10,+ TEXTURE_MIN_FILTER: 11, TEXTURE_MAG_FILTER: 12, NEAREST: 13, RENDERBUFFER: 14,+ DEPTH_COMPONENT24: 15, FRAMEBUFFER: 16, COLOR_ATTACHMENT0: 17, DEPTH_ATTACHMENT: 18,+ FRAMEBUFFER_COMPLETE: 19, DEPTH_TEST: 20, CULL_FACE: 21, TEXTURE0: 22, TRIANGLES: 23,+ getExtension: () => ({}),+ createShader: () => ({}),+ shaderSource: () => {},+ compileShader: () => {},+ getShaderParameter: () => true,+ deleteShader: () => {},+ createProgram: () => ({}),+ attachShader: () => {},+ linkProgram: () => {},+ getProgramParameter: () => true,+ getProgramInfoLog: () => '',+ getShaderInfoLog: () => '',+ deleteProgram: () => {},+ getUniformLocation: (_program, name) => name,+ createTexture: () => ({ kind: 'tex' }),+ bindTexture: () => {},+ texImage2D: () => {},+ texParameteri: () => {},+ createRenderbuffer: () => ({ kind: 'rb' }),+ bindRenderbuffer: () => {},+ renderbufferStorage: () => {},+ createFramebuffer: () => ({ kind: 'fb' }),+ bindFramebuffer: () => {},+ framebufferTexture2D: () => {},+ framebufferRenderbuffer: () => {},+ checkFramebufferStatus: () => 19,+ deleteTexture: () => {},+ deleteRenderbuffer: () => {},+ deleteFramebuffer: () => {},+ viewport: () => {},+ disable: () => {},+ bindVertexArray: () => {},+ useProgram: () => {},+ activeTexture: () => {},+ uniform1i: (loc, val) => calls.push([loc, val]),+ uniform1f: (loc, val) => calls.push([loc, val]),+ uniform1fv: (loc, val) => calls.push([loc, val.length]),+ uniform3f: (loc, x, y, z) => calls.push([loc, [x, y, z]]),+ uniform3fv: (loc, val) => calls.push([loc, val]),+ uniformMatrix4fv: (loc, _transpose, val) => calls.push([loc, val.length]),+ drawArrays: () => calls.push(['drawArrays']),+ };+ const drawn = [];+ const batchOpaque = {+ parts: [+ { name: 'hero', matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), material: { id: 'steel', aov: [0.2, 0.4, 0.6], aovMap: { id: 'aov-tex' } } },+ { name: 'floor', matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), material: { name: 'stone' } },+ ],+ layerState: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],+ textures: ['t0', 't1', 't2', 't3', 't4'],+ };+ const batchGlass = {+ parts: [{ name: 'glass', matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), material: { transmissionMap: { id: 'trans-tex' } } }],+ layerState: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0.85],+ textures: ['g0', 'g1', 'g2', 'g3', 'g4'],+ };+ const renderer = {+ passSupport: null,+ context,+ canvas: { width: 8, height: 8 },+ benchmark: false,+ program: {},+ viewProjection: new Float32Array(16),+ renderTargets: { record: () => {}, release: () => {} },+ requireFeatureNames: () => {},+ drawsInOpaqueLoop: batch => batch === batchOpaque,+ createTexture: desc => desc,+ drawAlphaBatch: (batch, _tex, culled) => drawn.push({ batch, tex4: batch.textures[4], culled }),+ batches: [batchOpaque, batchGlass],+ };installRenderPasses(installRenderPasses(renderer));assert.ok(renderer.passSupport);assert.throws(() => renderer.passSupport.prepare({ pass: 'beauty' }), /Unknown render pass/);assert.throws(() => renderer.passSupport.prepare({ pass: 'depth', passDepthRange: 0 }), /depth range/);assert.deepEqual(renderer.passSupport.background('depth'), [1, 1, 0, 1]);assert.deepEqual(renderer.passSupport.background('objectId'), [0, 0, 0, 1]);+ const manifest = renderer.passSupport.cryptomatteManifest();+ assert.deepEqual(Object.keys(manifest.objects), ['hero', 'floor']);+ assert.deepEqual(Object.keys(manifest.materials), ['steel', 'stone']);+ assert.equal(manifest.objects.hero.value, cryptomatteValue(1));+ assert.equal(manifest.objects.hero.hash, cryptomatteHashHex('hero'));+ assert.equal(manifest.materials.stone.value, cryptomatteValue(2));+ assert.equal(renderer.passSupport.drawsInPass(batchGlass, RENDER_PASS_MODES.albedo), false);+ assert.equal(renderer.passSupport.drawsInPass(batchGlass, RENDER_PASS_MODES.transmission), true);++ assert.equal(renderer.passSupport.prepare({ pass: 'aov', passFloat: true }), RENDER_PASS_MODES.aov);+ assert.ok(renderer.passSupport.framebuffer);+ assert.ok(renderer.passSupport.texture);+ renderer.passSupport.bindFrame(+ { passFloat: true, previousCamera: { eye: [1, 2, 5], target: [0, 0, 0] } },+ { fogDensity: 0.01, fogColor: [0.3, 0.4, 0.5] },+ { density: 0, color: [0, 0, 0] },+ );+ renderer.passSupport.drawBatch(+ batchOpaque,+ RENDER_PASS_MODES.aov,+ { previousMatrices: { hero: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1]) } },+ 0,+ );+ assert.equal(drawn.at(-1).tex4.id, 'aov-tex');+ assert.equal(batchOpaque.textures[4], 't4');+ renderer.passSupport.drawBatch(+ batchGlass,+ RENDER_PASS_MODES.transmission,+ { objectMotion: { matrices: new Float32Array(32) } },+ 0,+ );+ assert.equal(drawn.at(-1).tex4.id, 'trans-tex');+ assert.equal(batchGlass.textures[4], 'g4');+ renderer.passSupport.copyToCanvas();+ assert.equal(renderer.passSupport.prepare({ pass: 'cryptomatte', passFloat: false }), RENDER_PASS_MODES.cryptomatte);+ renderer.passSupport.dispose(context);});-test('artifact names list the lit image and each pass per frame', () => {+test('materials accept scalar or RGB aov values and material graphs bake aovMap descriptors', async () => {+ await loadAllAgentSceneModules();+ const scene = createAgentScene({+ format: '67js.scene',+ schemaVersion: 1,+ geometries: [{ id: 'cube', type: 'box' }],+ materials: [+ { id: 'scalar-aov', color: [0.5, 0.5, 0.5], aov: 0.75 },+ { id: 'rgb-aov', color: [0.5, 0.5, 0.5], aov: [0.2, 0.4, 0.8] },+ ],+ nodes: [+ { id: 'a', geometry: 'cube', material: 'scalar-aov' },+ { id: 'b', geometry: 'cube', material: 'rgb-aov', translation: [2, 0, 0] },+ ],+ });+ assert.deepEqual(scene.parts[0].material.aov, [0.75, 0.75, 0.75]);+ assert.deepEqual(scene.parts[1].material.aov, [0.2, 0.4, 0.8]);+ assert.equal(scene.parts[0].material.id, 'scalar-aov');+ assert.throws(() => createAgentScene({+ format: '67js.scene',+ schemaVersion: 1,+ geometries: [{ id: 'cube', type: 'box' }],+ materials: [{ id: 'bad', aov: [1.5, 0, 0] }],+ nodes: [],+ }), /aov/);+ const baked = bakeMaterialGraph({+ color: [0.5, 0.5, 0.5],+ aov: { checker: { count: 2 } },+ }, { resolution: 64, bump: 1 });+ assert.ok(baked.aovMap);+ assert.equal(baked.aovMap.colorSpace, 'linear');+ assert.equal(baked.aovMap.image.width, 64);+});++test('artifact names and multilayer EXR encoders cover new passes and multilayer jobs', () => {assert.deepEqual(artifactNames('image'), ['render.png']);assert.deepEqual(artifactNames('image', ['depth', 'objectId']), ['render.png', 'render-depth.png', 'render-objectId.png']);+ assert.deepEqual(artifactNames('image', ['depth', 'position', 'cryptomatte'], 'exr', true), ['render.exr']);+ assert.deepEqual(artifactNames('stills', ['depth', 'uv'], 'exr', true).length, 8);assert.equal(artifactNames('stills', ['normal']).length, 16);assert.ok(artifactNames('stills', ['normal']).includes('frame-7-normal.png'));assert.deepEqual(artifactNames('video'), ['render.mp4']);++ const pixels = new Float32Array([+ 1.5, -2.0, 3.25, 1,+ 0.25, 0.75, 0.5, 1,+ -0.1, 0.2, 0, 1,+ 0.8, 0.4, 1, 1,+ ]);+ for (const pass of ['position', 'velocity', 'uv', 'cryptomatte', 'aov']) {+ const exr = encodeRenderOutput({ format: 'exr', pixels, width: 2, height: 2, pass });+ assert.equal(exr[0], 0x76);+ const png16 = encodeRenderOutput({ format: 'png16', pixels, width: 2, height: 2, pass });+ assert.equal(png16[0], 0x89);+ }+ const multi = encodeMultilayerExr({+ width: 2,+ height: 2,+ beauty: pixels,+ passes: {+ position: pixels,+ velocity: pixels,+ uv: pixels,+ depth: new Float32Array(16),+ objectId: new Float32Array(16),+ cryptomatte: pixels,+ aov: pixels,+ },+ hasAlpha: true,+ });+ const headerText = multi.subarray(0, 512).toString('latin1');+ for (const channelName of ['Combined.R', 'Combined.A', 'position.X', 'position.Z', 'velocity.X', 'uv.U', 'depth.Z', 'objectId.id', 'cryptomatte.R', 'aov.G']) {+ assert.ok(headerText.includes(channelName), `multilayer EXR header includes ${channelName}`);+ }});-test('a job with passes publishes every pass file and rejects bad pass requests', async context => {+test('a job with passes or multilayer EXR publishes every expected file and rejects bad pass requests', async context => {const root = await mkdtemp(join(tmpdir(), '67js-render-passes-'));context.after(() => rm(root, { recursive: true, force: true }));const run = async ({ directory, settings }) => {const artifacts = [];- for (const filename of artifactNames(settings.kind, settings.passes)) {+ const mimeType = settings.format === 'exr' ? 'image/x-exr' : 'image/png';+ for (const filename of artifactNames(settings.kind, settings.passes, settings.format, settings.multilayer)) {await writeFile(join(directory, `${filename}.partial`), Buffer.from(filename));- artifacts.push({ temporary: `${filename}.partial`, filename, mimeType: 'image/png' });+ artifacts.push({ temporary: `${filename}.partial`, filename, mimeType });}return { artifacts, metrics: {} };};@@ -89,6 +273,20 @@ test('a job with passes publishes every pass file and rejects bad pass requests'assert.deepEqual(record.artifacts.map(artifact => artifact.filename), ['render.png', 'render-depth.png', 'render-albedo.png']);assert.deepEqual(record.settings.passes, ['depth', 'albedo']);await controller.release(submitted.jobId);++ const multiSubmitted = await controller.submit({+ sourceRevision: 0,+ snapshot,+ settings: { kind: 'image', width: 64, height: 64, format: 'exr', multilayer: true, passes: ['position', 'velocity', 'uv', 'cryptomatte', 'aov'] },+ });+ while (controller.status(multiSubmitted.jobId).state !== 'completed') await new Promise(resolve => setTimeout(resolve, 2));+ const multiRecord = controller.status(multiSubmitted.jobId);+ assert.deepEqual(multiRecord.artifacts.map(artifact => artifact.filename), ['render.exr']);+ assert.equal(multiRecord.settings.multilayer, true);+ await controller.release(multiSubmitted.jobId);++ await assert.rejects(controller.submit({ sourceRevision: 0, snapshot, settings: { kind: 'image', width: 64, height: 64, multilayer: true, passes: ['depth'] } }), /multilayer requires format exr/);+ await assert.rejects(controller.submit({ sourceRevision: 0, snapshot, settings: { kind: 'image', width: 64, height: 64, format: 'exr', multilayer: true } }), /multilayer requires format exr and passes/);for (const passes of [['mystery'], ['depth', 'depth'], [], 'depth']) {await assert.rejects(controller.submit({ sourceRevision: 0, snapshot, settings: { kind: 'image', width: 64, height: 64, passes } }), /pass/i);}