Skip to content

3D engine that AI agents drive

Add ID mattes to render jobs and pass compositing helpers (#1962)

Nguyen Xuan Anbcdc980d1775
diff --git a/changes/1962.md b/changes/1962.md
new file mode 100644
index 00000000..6a659ffe
--- /dev/null
+++ b/changes/1962.md
@@ -0,0 +1 @@
+- Render jobs take `settings.mattes` to write one ID matte PNG per part or material, and `src/pass-compositing.js` adds Z combine and alpha-over of pass pixels (#1962)
diff --git a/changes/1962.size.md b/changes/1962.size.md
new file mode 100644
index 00000000..8c91a908
--- /dev/null
+++ b/changes/1962.size.md
@@ -0,0 +1,2 @@
+- tool-total: settings.mattes lets an agent ask a render job for a part or material matte by name; without it the agent would have to decode the 24-bit object ID pass and match Cryptomatte hashes itself.
+- tool:scene_render_submit: the same field, a list of up to 8 { object } or { material } entries, 262 bytes; the details live in docs and scene_capabilities.
diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.md
index 3d13b4fe..c936a48e 100644
--- a/docs/agent-render-jobs.md
+++ b/docs/agent-render-jobs.md
@@ -159,6 +159,30 @@ Videos hold the lit image only.
A seek to any frame gives the same pixels: a job samples each frame from its time and keeps no state between frames.
`npm run smoke:render-passes` proves it through MCP: it renders eight stills with every pass, then renders frame 3 again as an image in a different order of seeks and compares the bytes of the lit image and all five passes.
+### ID mattes {since 0.22.0}
+
+`settings.mattes` on an `image` or `stills` job writes one gray PNG per entry next to the lit image: `render-matte-<n>.png` (`frame-N-matte-<n>.png` for stills), where `<n>` is the entry's position. A pixel is white where the named part is drawn and black elsewhere.
+
+```json
+{ "kind": "image", "width": 1280, "height": 720, "mattes": [{ "object": "hero" }, { "material": "stone" }] }
+```
+
+Each entry names exactly one `object` (a part name from `metrics.objectNames`) or one `material` (a name from `metrics.cryptomatte.materials`), up to 8 entries and 120 characters a name. An object matte is read from the exact 24-bit object ID, so a part that other parts overlap still gets its own clean edge. A material matte is read from the `cryptomatte` pass, whose hash has 255 values: two materials can share one, and then `metrics.mattes[n].sharedWith` lists the other names and the matte holds both. A name the scene does not have fails the job with the list of names it does have.
+`metrics.mattes` holds `{ object, partIds, coveragePixels }` or `{ material, sharedWith?, coveragePixels }` for each entry, from the last frame. Mattes are 8-bit PNG: they need `format` png, no `multilayer` and no `renderer`, and they cost about one extra pass each in the job estimate.
+
+### Combining pass pixels
+
+`src/pass-compositing.js` holds the pixel steps that put passes together. They work on plain RGBA8 buffers (top row first, up to 3840x2160) with integer math, so the same input gives the same bytes on every machine, and each throws an error that says which buffer to pass instead.
+
+| Function | Result |
+| --- | --- |
+| `zCombine({ width, height, colorA, depthA, colorB, depthB })` | Per pixel, the colour and depth of the nearer input; a tie keeps A. Returns `{ color, depth, nearest }`. `depthMetresFromPass` reads a depth pass into the metres these take, and a background pixel reads `Infinity`, so it never wins. |
+| `alphaOver({ width, height, foreground, background })` | The foreground over the background, straight alpha in and out, each channel rounded to the nearest byte. |
+| `objectIdMatte`, `cryptomatteMatte` | The 0 or 255 masks behind `settings.mattes`, from an object ID pass or from the red (object) or green (material) channel of a Cryptomatte pass. |
+| `applyMatteAsAlpha({ width, height, color, mask })` | A colour buffer with the mask as its alpha: the cut-out of a part, ready for `alphaOver`. |
+
+These are library functions for scripts and addons; no MCP tool combines passes yet, and `scene_render_submit` reads no image from disk.
+
## Output options: transparent, 16-bit PNG, EXR, region and 60 fps
### A transparent frame sequence {since 0.21.0}
diff --git a/package.json b/package.json
index b9ee49bd..e45f3a17 100644
--- a/package.json
+++ b/package.json
@@ -206,6 +206,7 @@
"smoke:agent-texture-sequence": "node scripts/smoke-agent-texture-sequence.mjs",
"smoke:agent-texture-sequence-streamed": "node scripts/smoke-agent-texture-sequence-streamed.mjs",
"smoke:render-passes": "node scripts/smoke-render-passes.mjs",
+ "smoke:pass-mattes": "node scripts/smoke-pass-mattes.mjs",
"smoke:wireframe-pass": "node scripts/smoke-wireframe-pass.mjs",
"smoke:object-motion-blur": "node scripts/smoke-object-motion-blur.mjs",
"smoke:path-tracer": "node scripts/smoke-path-tracer.mjs",
diff --git a/scripts/agent-render-budget.mjs b/scripts/agent-render-budget.mjs
index a0878a44..c8fd3f62 100644
--- a/scripts/agent-render-budget.mjs
+++ b/scripts/agent-render-budget.mjs
@@ -18,7 +18,7 @@ export const RASTER_SCALE_STEPS = Object.freeze([1, 0.75, 0.5, 0.25]);
/** A candidate must be expected to finish within this share of the time budget, because the estimate is only good to a few tens of percent. */
export const TIME_HEADROOM = 0.85;
const MINIMUM_SIDE = 64;
-const TRACER_BLOCKERS = ['passes', 'transparent', 'region', 'multilayer'];
+const TRACER_BLOCKERS = ['passes', 'mattes', 'transparent', 'region', 'multilayer'];
function limitedNumber(value, name) {
const { minimum, maximum } = BUDGET_LIMITS[name];
diff --git a/scripts/agent-render-estimate.mjs b/scripts/agent-render-estimate.mjs
index 3f473190..58513aa1 100644
--- a/scripts/agent-render-estimate.mjs
+++ b/scripts/agent-render-estimate.mjs
@@ -99,7 +99,7 @@ function rasterFrameSeconds({ size, settings }) {
const drawSeconds = COST_MODEL.drawFrameSeconds + settings.width * settings.height * COST_MODEL.drawSecondsPerPixel
+ size.triangles * COST_MODEL.drawSecondsPerTriangle + size.assetParts * COST_MODEL.drawSecondsPerAssetPart + size.lights * COST_MODEL.drawSecondsPerLight;
const outputSeconds = settings.kind === 'video' ? COST_MODEL.videoEncodeSeconds : COST_MODEL.imageCaptureSeconds;
- return drawSeconds * (1 + (settings.passes?.length ?? 0) * COST_MODEL.passFactor) + outputSeconds;
+ return drawSeconds * (1 + ((settings.passes?.length ?? 0) + (settings.mattes?.length ?? 0)) * COST_MODEL.passFactor) + outputSeconds;
}
function peakMemoryMiB({ size, settings }) {
diff --git a/scripts/agent-render-jobs.mjs b/scripts/agent-render-jobs.mjs
index 1063b68e..ae1f4fc2 100644
--- a/scripts/agent-render-jobs.mjs
+++ b/scripts/agent-render-jobs.mjs
@@ -109,7 +109,7 @@ export function normalizeJobSettings(input, clips, recipe) {
}
function settingsFrom(input, clips = [], recipe) {
- objectKeys(input, ['kind', 'width', 'height', 'fps', 'duration', 'animation', 'motion', 'rendererTime', 'passes', 'renderer', 'timeline', 'audio', 'encoder', 'transparent', 'format', 'multilayer', 'region', 'quality', 'stillCount'], 'settings');
+ objectKeys(input, ['kind', 'width', 'height', 'fps', 'duration', 'animation', 'motion', 'rendererTime', 'passes', 'renderer', 'timeline', 'audio', 'encoder', 'transparent', 'format', 'multilayer', 'region', 'quality', 'stillCount', 'mattes'], 'settings');
if (!['image', 'stills', 'video'].includes(input.kind)) throw new TypeError('kind must be image, stills or video.');
const largeFrame = input.kind === 'image';
const maximumSide = largeFrame ? MAXIMUM_JOB_SIDE : MAXIMUM_SEQUENCE_JOB_SIDE;
@@ -138,6 +138,7 @@ function settingsFrom(input, clips = [], recipe) {
if (framesAsked !== undefined) result.stillCount = framesAsked;
if (input.passes !== undefined) result.passes = passesFrom(input.passes, input.kind);
if (input.renderer !== undefined) result.renderer = rendererFrom(input.renderer, input.passes);
+ if (input.mattes !== undefined) result.mattes = mattesFrom(input);
Object.assign(result, outputOptionsFrom(input, result));
if (input.quality !== undefined) result.quality = qualityFrom(input.quality, result.renderer);
const lastSampleTime = input.kind === 'image' ? 0 : input.kind === 'stills' ? duration : (frameCount - 1) / fps;
@@ -301,13 +302,34 @@ function passesFrom(passes, kind) {
return [...passes];
}
-/** Every artifact filename of a job, lit image first and then each requested pass, frame by frame. */
-export function artifactNames(kind, passes = [], format = 'png', multilayer = false, stillCount = 8) {
+const MAXIMUM_MATTES = 8;
+const MAXIMUM_MATTE_NAME_LENGTH = 120;
+
+/** The ID mattes of a job: each names one object (part) or one material, and writes one gray PNG per frame. */
+function mattesFrom(input) {
+ const { mattes, kind, renderer, format, multilayer } = input;
+ if (kind === 'video') throw new RangeError('mattes need kind image or stills; a video holds the lit image only.');
+ if (renderer !== undefined) throw new RangeError('mattes cannot combine with renderer: the path tracer has no object ID or Cryptomatte pass. Leave renderer out.');
+ if (format !== undefined && format !== 'png') throw new RangeError('mattes are 8-bit PNG files: leave format out or use png.');
+ if (multilayer) throw new RangeError('mattes cannot combine with multilayer. Leave multilayer out.');
+ if (!Array.isArray(mattes) || mattes.length < 1 || mattes.length > MAXIMUM_MATTES) throw new TypeError(`mattes must list 1 to ${MAXIMUM_MATTES} entries, each { object: "<part name>" } or { material: "<material name>" }.`);
+ return mattes.map((matte, index) => {
+ objectKeys(matte, ['object', 'material'], `mattes[${index}]`);
+ const kindsGiven = ['object', 'material'].filter(key => matte[key] !== undefined);
+ if (kindsGiven.length !== 1) throw new TypeError(`mattes[${index}] needs exactly one of object or material. Pass { object: "<part name>" } or { material: "<material name>" }.`);
+ const name = matte[kindsGiven[0]];
+ if (typeof name !== 'string' || name.length < 1 || name.length > MAXIMUM_MATTE_NAME_LENGTH) throw new TypeError(`mattes[${index}].${kindsGiven[0]} must be a name of 1 to ${MAXIMUM_MATTE_NAME_LENGTH} characters. scene_render_result metrics.objectNames and metrics.cryptomatte list the names of a render.`);
+ return { [kindsGiven[0]]: name };
+ });
+}
+
+/** Every artifact filename of a job, lit image first and then each requested pass and matte, frame by frame. */
+export function artifactNames(kind, passes = [], format = 'png', multilayer = false, stillCount = 8, mattes = []) {
if (kind === 'video') return ['render.mp4'];
const extension = format === 'exr' ? 'exr' : 'png';
const stems = kind === 'image' ? ['render'] : Array.from({ length: stillCount }, (_, index) => `frame-${index}`);
if (multilayer) return stems.map(stem => `${stem}.${extension}`);
- return stems.flatMap(stem => [`${stem}.${extension}`, ...passes.map(pass => `${stem}-${pass}.${extension}`)]);
+ return stems.flatMap(stem => [`${stem}.${extension}`, ...passes.map(pass => `${stem}-${pass}.${extension}`), ...mattes.map((_, index) => `${stem}-matte-${index}.png`)]);
}
function artifactMimeType(settings) {
@@ -348,7 +370,7 @@ function artifactByteLimit(settings, limits) {
function allowedFile(name) {
const passNames = RENDER_PASS_NAMES.join('|');
- const artifact = new RegExp(`^(?:render\\.(?:png|mp4|exr)|(?:render|frame-\\d{1,3})(?:-(?:${passNames}))?\\.(?:png|exr))(?:\\.partial)?$`);
+ const artifact = new RegExp(`^(?:render\\.(?:png|mp4|exr)|(?:render|frame-\\d{1,3})(?:-(?:${passNames}|matte-[0-7]))?\\.(?:png|exr))(?:\\.partial)?$`);
return INTERNAL_FILES.has(name) || artifact.test(name);
}
@@ -836,7 +858,7 @@ export async function createAgentRenderJobs({ root, run, acquireGpu, limits: inp
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, settings.multilayer, settings.frameCount);
+ const namesAllowed = artifactNames(settings.kind, settings.passes, settings.format, settings.multilayer, settings.frameCount, settings.mattes);
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) {
@@ -919,7 +941,7 @@ export async function createAgentRenderJobs({ root, run, acquireGpu, limits: inp
record.state = 'finalizing';
await persist(job);
objectKeys(completed, ['artifacts', 'metrics'], 'runner result');
- const expected = artifactNames(record.settings.kind, record.settings.passes, record.settings.format, record.settings.multilayer, record.settings.frameCount);
+ const expected = artifactNames(record.settings.kind, record.settings.passes, record.settings.format, record.settings.multilayer, record.settings.frameCount, record.settings.mattes);
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-render-quality.mjs b/scripts/agent-render-quality.mjs
index 2c10db04..d00829b7 100644
--- a/scripts/agent-render-quality.mjs
+++ b/scripts/agent-render-quality.mjs
@@ -20,7 +20,7 @@ export const FINAL_TIER_RENDERER = Object.freeze({ type: 'pathTracer', samples:
import { PATH_TRACER_JOB_LIMITS } from '../src/path-tracer-capabilities.js';
-const PATH_TRACER_ONLY_LIT_PNG = ['passes', 'transparent', 'region', 'multilayer'];
+const PATH_TRACER_ONLY_LIT_PNG = ['passes', 'mattes', 'transparent', 'region', 'multilayer'];
export function parseQuality(value) {
if (!QUALITY_TIERS.includes(value)) throw new TypeError(`quality must be one of ${QUALITY_TIERS.join(', ')}.`);
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index a6a70d34..2587595e 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -44,6 +44,7 @@ import { RENDER_QUALITY_NOTE, applyQuality, tierReport } from './agent-render-qu
import { RENDER_BUDGET_NOTE, chooseBudgetSettings, parseBudget } from './agent-render-budget.mjs';
import { RENDER_ESTIMATE_NOTE, estimateRenderJob, historyWithJob, parseHistory, pathTraceTriangleProblem, renderReport, sceneSizeFrom } from './agent-render-estimate.mjs';
import { objectIdMetrics } from './agent-object-id-metrics.mjs';
+import { renderJobMattes } from './job-mattes.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';
@@ -860,7 +861,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
await jobPage.setViewportSize({ width, height });
session = await jobPage.context().newCDPSession(jobPage);
const region = settings.region;
- if (settings.format && settings.format !== 'png') await jobPage.evaluate(prepareInput => window.__agentPreview.prepareFloatOutput(prepareInput), { sessionId: jobId });
+ if ((settings.format && settings.format !== 'png') || settings.mattes) await jobPage.evaluate(prepareInput => window.__agentPreview.prepareFloatOutput(prepareInput), { sessionId: jobId });
if (settings.passes?.includes('wireframe')) await jobPage.evaluate(prepareInput => window.__agentPreview.prepareWireframe(prepareInput), { sessionId: jobId });
// A memory budget can shrink the frame below the size the region was chosen for.
if (region && (region.x + region.width > width || region.y + region.height > height)) {
@@ -1102,6 +1103,15 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
Object.assign(metrics, objectIdMetrics(passInfo));
}
}
+ if (settings.mattes) {
+ const mattes = await renderJobMattes({ mattes: settings.mattes, renderPass: async pass => {
+ const info = await jobPage.evaluate(input => window.__agentPreview.frame(input),
+ { ...frameInput, floatOutput: false, pass, passDepthRange: RENDER_PASS_DEPTH_RANGE, passFloat: true });
+ return { info, ...(await readFloatPass(pass)) };
+ } });
+ for (const [index, matte] of mattes.entries()) await writeArtifact(`${stem}-matte-${index}.png`, matte.bytes);
+ metrics.mattes = mattes.map(matte => matte.metric);
+ }
}
}
await recordPeakMemory();
diff --git a/scripts/job-mattes.mjs b/scripts/job-mattes.mjs
new file mode 100644
index 00000000..aa5a02f3
--- /dev/null
+++ b/scripts/job-mattes.mjs
@@ -0,0 +1,68 @@
+import { encodePng } from '../src/export-png.js';
+import { cryptomatteByte, cryptomatteMatte, floatPassToBytes, matteToGrayRgba, objectIdMatte } from '../src/pass-compositing.js';
+
+// The ID mattes of a render job (settings.mattes): one gray PNG per matte, white where the named part or material is drawn.
+// Parts come from the exact 24-bit object ID pass, materials from the Cryptomatte pass (an 8-bit hash that two names can share).
+
+const NAMES_IN_ERROR = 20;
+
+function nameList(names) {
+ const shown = names.slice(0, NAMES_IN_ERROR).join(', ');
+ return names.length > NAMES_IN_ERROR ? `${shown}, and ${names.length - NAMES_IN_ERROR} more` : shown;
+}
+
+function coverageOf(mask) {
+ let covered = 0;
+ for (const value of mask) if (value) covered++;
+ return covered;
+}
+
+function objectMatte({ target, index, objectPass }) {
+ const ids = [];
+ objectPass.info.objectNames.forEach((name, position) => { if (name === target) ids.push(position + 1); });
+ if (ids.length === 0) {
+ throw new Error(`mattes[${index}]: no part named "${target}" in this scene. Pass one of: ${nameList(objectPass.info.objectNames)}.`);
+ }
+ const mask = objectIdMatte({ pixels: objectPass.bytes, width: objectPass.width, height: objectPass.height, ids });
+ return { mask, metric: { object: target, partIds: ids } };
+}
+
+function materialMatte({ target, index, cryptomattePass }) {
+ const { materials } = cryptomattePass.info.cryptomatte;
+ const entry = materials[target];
+ if (!entry) {
+ throw new Error(`mattes[${index}]: no material named "${target}" in this scene. Pass one of: ${nameList(Object.keys(materials))}.`);
+ }
+ const mask = cryptomatteMatte({ pixels: cryptomattePass.bytes, width: cryptomattePass.width, height: cryptomattePass.height, channel: 'material', value: entry.value });
+ const sharedWith = Object.entries(materials)
+ .filter(([name, other]) => name !== target && cryptomatteByte(other.value) === cryptomatteByte(entry.value))
+ .map(([name]) => name);
+ return { mask, metric: { material: target, ...(sharedWith.length ? { sharedWith } : {}) } };
+}
+
+/**
+ * Renders the passes the mattes need through `renderPass(name)` (which returns `{ info, pixels, width, height }`, the pass info and the
+ * float readback of the frame) and returns `[{ bytes, metric }]` in the order of `mattes`: the PNG file and what to report in the job metrics.
+ */
+export async function renderJobMattes({ mattes, renderPass }) {
+ const passes = new Map();
+ async function passBytes(name) {
+ if (!passes.has(name)) {
+ const pass = await renderPass(name);
+ passes.set(name, { info: pass.info, width: pass.width, height: pass.height, bytes: floatPassToBytes(pass) });
+ }
+ return passes.get(name);
+ }
+ const results = [];
+ for (const [index, matte] of mattes.entries()) {
+ const built = matte.object !== undefined
+ ? objectMatte({ target: matte.object, index, objectPass: await passBytes('objectId') })
+ : materialMatte({ target: matte.material, index, cryptomattePass: await passBytes('cryptomatte') });
+ const { width, height } = passes.get(matte.object !== undefined ? 'objectId' : 'cryptomatte');
+ results.push({
+ bytes: encodePng(matteToGrayRgba(built.mask), width, height),
+ metric: { ...built.metric, coveragePixels: coverageOf(built.mask) },
+ });
+ }
+ return results;
+}
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index d1e9bbe2..58062561 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -878,6 +878,7 @@ const renderSettings = z.strictObject({
audio: z.strictObject({ file: z.string().max(68), offset: z.number().min(0).max(3600).optional(), track: z.enum(['aac', 'pcm']).optional() }).optional().describe('Video only: a file in the --audio folder, mixed in from offset seconds.'),
encoder: z.enum(VIDEO_ENCODERS).optional().describe('Video only: cpu (default) or nvenc.'),
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.'),
+ mattes: z.array(z.strictObject({ object: z.string().max(120).optional(), material: z.string().max(120).optional() })).max(8).optional().describe('One ID matte PNG per part or material; see jobs.'),
stillCount: z.number().int().min(2).max(MAXIMUM_STILLS_FRAMES).optional(),
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).'),
diff --git a/scripts/smoke-pass-mattes.mjs b/scripts/smoke-pass-mattes.mjs
new file mode 100644
index 00000000..36176b31
--- /dev/null
+++ b/scripts/smoke-pass-mattes.mjs
@@ -0,0 +1,148 @@
+// Proves ID mattes through the real MCP runtime: a render job with settings.mattes writes one gray PNG per matte, white exactly
+// where the object ID pass shows the named part (and where the Cryptomatte pass shows the named material), and refuses an unknown name.
+import assert from 'node:assert/strict';
+import { mkdtemp, readFile } from 'node:fs/promises';
+import { tmpdir, constants, setPriority } from 'node:os';
+import { join, resolve } from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import { inflateSync } from 'node:zlib';
+import { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const directory = await mkdtemp(join(tmpdir(), 'crucible-mcp-mattes-'));
+const cli = resolve(process.argv[2] ?? 'bin/crucible-mcp.mjs');
+const backend = process.argv[3] ?? 'cpu';
+const transport = new StdioClientTransport({ command: process.execPath,
+ args: [cli, '--backend', backend, '--memory', '128', '--jobs', join(directory, 'jobs')], cwd: directory, stderr: 'pipe' });
+let diagnostics = '';
+transport.stderr.on('data', bytes => { diagnostics = (diagnostics + bytes).slice(-8192); });
+const client = new Client({ name: 'crucible-mattes-proof', version: '1' });
+const SIZE = 160;
+
+async function call(name, argumentsValue = {}, timeout = 60000) {
+ return client.callTool({ name, arguments: argumentsValue }, { timeout });
+}
+
+async function finished(jobId) {
+ const deadline = Date.now() + 120000;
+ while (Date.now() < deadline) {
+ const record = (await call('scene_render_status', { jobId })).structuredContent;
+ if (['completed', 'cancelled', 'failed'].includes(record.state)) return record;
+ await delay(100);
+ }
+ throw new Error('Job did not finish within 120 seconds.');
+}
+
+function paeth(left, up, upLeft) {
+ const estimate = left + up - upLeft;
+ const toLeft = Math.abs(estimate - left);
+ const toUp = Math.abs(estimate - up);
+ const toUpLeft = Math.abs(estimate - upLeft);
+ if (toLeft <= toUp && toLeft <= toUpLeft) return left;
+ return toUp <= toUpLeft ? up : upLeft;
+}
+
+// Reads an 8-bit RGB or RGBA PNG, the only kind these jobs write.
+function decodePng(bytes) {
+ let offset = 8;
+ let header = null;
+ const chunks = [];
+ while (offset < bytes.length) {
+ const length = bytes.readUInt32BE(offset);
+ const type = bytes.toString('latin1', offset + 4, offset + 8);
+ const data = bytes.subarray(offset + 8, offset + 8 + length);
+ if (type === 'IHDR') header = { width: data.readUInt32BE(0), height: data.readUInt32BE(4), colorType: data[9] };
+ if (type === 'IDAT') chunks.push(data);
+ offset += 12 + length;
+ }
+ const channels = header.colorType === 6 ? 4 : 3;
+ const stride = header.width * channels;
+ const raw = inflateSync(Buffer.concat(chunks));
+ const pixels = Buffer.alloc(stride * header.height);
+ for (let row = 0; row < header.height; row++) {
+ const filter = raw[row * (stride + 1)];
+ for (let column = 0; column < stride; column++) {
+ const value = raw[row * (stride + 1) + 1 + column];
+ const left = column >= channels ? pixels[row * stride + column - channels] : 0;
+ const up = row > 0 ? pixels[(row - 1) * stride + column] : 0;
+ const upLeft = row > 0 && column >= channels ? pixels[(row - 1) * stride + column - channels] : 0;
+ pixels[row * stride + column] = (value + [0, left, up, (left + up) >> 1, paeth(left, up, upLeft)][filter]) & 255;
+ }
+ }
+ return { channels, pixels, pixelCount: header.width * header.height };
+}
+
+function recipe() {
+ return {
+ format: 'crucible.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box' }, { id: 'sphere', type: 'sphere', segments: 24, rings: 16 }],
+ materials: [
+ { id: 'red', color: [0.8, 0.1, 0.1], roughness: 0.6 },
+ { id: 'glow', color: [0.1, 0.3, 0.9], emission: 2 },
+ ],
+ nodes: [
+ { id: 'floor', geometry: 'box', material: 'red', translation: [0, -0.1, 0], scale: [12, 0.2, 12] },
+ { id: 'near-ball', geometry: 'sphere', material: 'glow', translation: [-0.6, 0.5, 1.5], scale: [1, 1, 1] },
+ { id: 'far-block', geometry: 'box', material: 'red', translation: [1.4, 0.5, -3], scale: [1, 1, 1] },
+ ],
+ environment: { ground: false },
+ camera: { eye: [0, 1.6, 6], target: [0, 0.5, 0], fov: 40 },
+ };
+}
+
+async function runJob(sessionId, settings) {
+ const submitted = await call('scene_render_submit', { sessionId, expectedRevision: 0, settings });
+ if (submitted.isError) return { error: submitted.content.find(item => item.type === 'text').text };
+ const record = await finished(submitted.structuredContent.jobId);
+ if (record.state === 'failed') return { error: record.reason };
+ assert.equal(record.state, 'completed', record.reason);
+ const result = (await call('scene_render_result', { jobId: submitted.structuredContent.jobId, response_format: 'detailed' })).structuredContent;
+ const files = new Map();
+ for (const artifact of result.artifacts) files.set(artifact.path.split(/[\\/]/).pop(), await readFile(artifact.path));
+ await call('scene_render_release', { jobId: submitted.structuredContent.jobId });
+ return { files, metrics: result.metrics ?? record.metrics };
+}
+
+function whitePixels(png) {
+ let count = 0;
+ for (let offset = 0; offset < png.pixels.length; offset += png.channels) if (png.pixels[offset] === 255) count++;
+ return count;
+}
+
+try {
+ await client.connect(transport);
+ const created = (await call('scene_create', { recipe: recipe() }, 180000)).structuredContent;
+ const sessionId = created.sessionId;
+ const first = await runJob(sessionId, { kind: 'image', width: SIZE, height: SIZE, passes: ['objectId'],
+ mattes: [{ object: 'near-ball' }, { object: 'far-block' }, { material: 'glow' }] });
+ assert.equal(first.error, undefined, first.error);
+ const { files, metrics } = first;
+ assert.deepEqual([...files.keys()].sort(), ['render-matte-0.png', 'render-matte-1.png', 'render-matte-2.png', 'render-objectId.png', 'render.png']);
+ const ids = decodePng(files.get('render-objectId.png'));
+ const idOf = name => metrics.objectNames.indexOf(name) + 1;
+ const expectedCoverage = name => {
+ let count = 0;
+ for (let offset = 0; offset < ids.pixels.length; offset += ids.channels) {
+ if (ids.pixels[offset] + ids.pixels[offset + 1] * 256 + ids.pixels[offset + 2] * 65536 === idOf(name)) count++;
+ }
+ return count;
+ };
+ const ball = decodePng(files.get('render-matte-0.png'));
+ const block = decodePng(files.get('render-matte-1.png'));
+ const glow = decodePng(files.get('render-matte-2.png'));
+ assert.ok(whitePixels(ball) > 200, 'the near ball must cover pixels');
+ assert.equal(whitePixels(ball), expectedCoverage('near-ball'), 'object matte equals the object ID pass');
+ assert.equal(whitePixels(block), expectedCoverage('far-block'));
+ assert.deepEqual(glow.pixels, ball.pixels, 'the glow material is only on the near ball');
+ assert.deepEqual(metrics.mattes.map(matte => matte.coveragePixels), [whitePixels(ball), whitePixels(block), whitePixels(glow)]);
+
+ const refused = await runJob(sessionId, { kind: 'image', width: SIZE, height: SIZE, mattes: [{ object: 'chair' }] });
+ assert.match(refused.error ?? "", /no part named "chair" in this scene. Pass one of: .*near-ball/);
+ console.log(`pass mattes smoke passed on ${backend}: ball ${whitePixels(ball)} px, block ${whitePixels(block)} px of ${ball.pixelCount}`);
+} catch (error) {
+ console.error(diagnostics);
+ throw error;
+} finally {
+ await client.close();
+}
diff --git a/src/pass-compositing.js b/src/pass-compositing.js
new file mode 100644
index 00000000..db3a0022
--- /dev/null
+++ b/src/pass-compositing.js
@@ -0,0 +1,175 @@
+// Compositing of render pass pixels on plain buffers: Z combine by depth, alpha-over, and Cryptomatte-style ID mattes.
+// Everything works on whole bytes with integer math, so one input gives the same output bytes on every machine.
+// Colour and mask buffers are RGBA8, top row first. A render job reads its passes back bottom row first as floats;
+// `floatPassToBytes` turns that readback into the same RGBA8 layout.
+
+/** Largest frame a compositing call accepts, the largest frame a render job writes. */
+export const MAXIMUM_COMPOSITE_PIXELS = 3840 * 2160;
+/** Furthest value of a depth pass step: the background reads this step and never wins a Z combine. */
+export const DEPTH_BACKGROUND_STEP = 65535;
+
+function requireFrameSize(width, height) {
+ for (const [name, value] of [['width', width], ['height', height]]) {
+ if (!Number.isInteger(value) || value < 1) throw new RangeError(`${name} must be a whole number of pixels, 1 or more. Pass the frame size the buffers were rendered at.`);
+ }
+ if (width * height > MAXIMUM_COMPOSITE_PIXELS) throw new RangeError(`A frame holds at most ${MAXIMUM_COMPOSITE_PIXELS} pixels (3840x2160). Composite a smaller region.`);
+}
+
+function requireBytes(name, buffer, expectedLength) {
+ if (!(buffer instanceof Uint8Array || buffer instanceof Uint8ClampedArray)) throw new TypeError(`${name} must be a Uint8Array of RGBA bytes (4 per pixel).`);
+ if (buffer.length !== expectedLength) throw new RangeError(`${name} holds ${buffer.length} bytes but the frame needs ${expectedLength} (width x height x 4). Pass a buffer rendered at the same size.`);
+}
+
+function requireDepths(name, depths, pixelCount) {
+ if (!(depths instanceof Float32Array || depths instanceof Float64Array)) throw new TypeError(`${name} must be a Float32Array of metres, one per pixel. Use depthMetresFromPass to read a depth pass.`);
+ if (depths.length !== pixelCount) throw new RangeError(`${name} holds ${depths.length} values but the frame has ${pixelCount} pixels. Pass a depth buffer rendered at the same size.`);
+ for (let index = 0; index < depths.length; index++) {
+ if (Number.isNaN(depths[index])) throw new RangeError(`${name} has NaN at pixel ${index}. Use Infinity for a pixel with no surface.`);
+ }
+}
+
+/**
+ * Metres per pixel from an RGBA8 depth pass (high byte in red, low byte in green, as the depth pass is written).
+ * A background pixel (the far step) reads Infinity, so it loses every Z combine.
+ */
+export function depthMetresFromPass({ pixels, width, height, depthRange = 100 }) {
+ requireFrameSize(width, height);
+ requireBytes('pixels', pixels, width * height * 4);
+ if (!(depthRange > 0) || !Number.isFinite(depthRange)) throw new RangeError('depthRange must be a positive number of metres. The depth pass spans 100 m by default.');
+ const metres = new Float32Array(width * height);
+ for (let index = 0; index < metres.length; index++) {
+ const step = pixels[index * 4] * 256 + pixels[index * 4 + 1];
+ metres[index] = step >= DEPTH_BACKGROUND_STEP ? Infinity : Math.fround(step / DEPTH_BACKGROUND_STEP * depthRange);
+ }
+ return metres;
+}
+
+/**
+ * Z combine: for each pixel the colour and depth of the nearer input win. A tie keeps input A.
+ * Returns `{ color, depth, nearest }` where `nearest` is 0 where A won and 1 where B won.
+ */
+export function zCombine({ width, height, colorA, depthA, colorB, depthB }) {
+ requireFrameSize(width, height);
+ const pixelCount = width * height;
+ requireBytes('colorA', colorA, pixelCount * 4);
+ requireBytes('colorB', colorB, pixelCount * 4);
+ requireDepths('depthA', depthA, pixelCount);
+ requireDepths('depthB', depthB, pixelCount);
+ const color = new Uint8Array(pixelCount * 4);
+ const depth = new Float32Array(pixelCount);
+ const nearest = new Uint8Array(pixelCount);
+ for (let index = 0; index < pixelCount; index++) {
+ const useB = depthB[index] < depthA[index];
+ const source = useB ? colorB : colorA;
+ color.set(source.subarray(index * 4, index * 4 + 4), index * 4);
+ depth[index] = useB ? depthB[index] : depthA[index];
+ nearest[index] = useB ? 1 : 0;
+ }
+ return { color, depth, nearest };
+}
+
+function roundedDivide(numerator, denominator) {
+ return Math.floor((2 * numerator + denominator) / (2 * denominator));
+}
+
+/**
+ * Alpha-over of `foreground` onto `background`, both RGBA8 with straight (not premultiplied) alpha, result straight alpha:
+ * out alpha = fa + ba (1 - fa), out colour = (fc fa + bc ba (1 - fa)) / out alpha. Rounded to the nearest byte.
+ */
+export function alphaOver({ width, height, foreground, background }) {
+ requireFrameSize(width, height);
+ const pixelCount = width * height;
+ requireBytes('foreground', foreground, pixelCount * 4);
+ requireBytes('background', background, pixelCount * 4);
+ const result = new Uint8Array(pixelCount * 4);
+ for (let index = 0; index < pixelCount; index++) {
+ const offset = index * 4;
+ const foregroundAlpha = foreground[offset + 3];
+ const backgroundAlpha = background[offset + 3];
+ const backgroundWeight = backgroundAlpha * (255 - foregroundAlpha);
+ const foregroundWeight = foregroundAlpha * 255;
+ const alphaScaled = foregroundWeight + backgroundWeight;
+ if (alphaScaled === 0) continue;
+ for (let channel = 0; channel < 3; channel++) {
+ const numerator = foreground[offset + channel] * foregroundWeight + background[offset + channel] * backgroundWeight;
+ result[offset + channel] = roundedDivide(numerator, alphaScaled);
+ }
+ result[offset + 3] = roundedDivide(alphaScaled, 255);
+ }
+ return result;
+}
+
+/** The RGBA8 pixels (top row first) of a float pass readback (RGBA, bottom row first, 0..1 per channel). */
+export function floatPassToBytes({ pixels, width, height }) {
+ requireFrameSize(width, height);
+ if (!(pixels instanceof Float32Array) || pixels.length !== width * height * 4) throw new RangeError('pixels must be the Float32Array readback of a pass, width x height x 4 values.');
+ const bytes = new Uint8Array(pixels.length);
+ const rowValues = width * 4;
+ for (let row = 0; row < height; row++) {
+ const sourceStart = (height - 1 - row) * rowValues;
+ for (let index = 0; index < rowValues; index++) {
+ bytes[row * rowValues + index] = Math.round(Math.min(1, Math.max(0, pixels[sourceStart + index])) * 255);
+ }
+ }
+ return bytes;
+}
+
+/** The byte a Cryptomatte value (0..1) is stored as in an 8-bit pass. */
+export function cryptomatteByte(value) {
+ return Math.round(Math.min(1, Math.max(0, value)) * 255);
+}
+
+/** A 0 or 255 mask of the pixels of an RGBA8 object ID pass (24-bit ID in red, green, blue) whose ID is in `ids`. */
+export function objectIdMatte({ pixels, width, height, ids }) {
+ requireFrameSize(width, height);
+ requireBytes('pixels', pixels, width * height * 4);
+ const wanted = new Set(ids ?? []);
+ if (wanted.size < 1 || [...wanted].some(id => !Number.isInteger(id) || id < 1 || id > 0xffffff)) {
+ throw new RangeError('ids must list one or more object IDs from 1 to 16777215. Read them from metrics.objectNames (ID 1 is the first name).');
+ }
+ const mask = new Uint8Array(width * height);
+ for (let index = 0; index < mask.length; index++) {
+ const id = pixels[index * 4] + pixels[index * 4 + 1] * 256 + pixels[index * 4 + 2] * 65536;
+ if (wanted.has(id)) mask[index] = 255;
+ }
+ return mask;
+}
+
+/**
+ * A 0 or 255 mask of the surface pixels of an RGBA8 Cryptomatte pass whose object (`channel: 'object'`, red) or
+ * material (`channel: 'material'`, green) byte equals the byte of `value`. Coverage in blue must be set, so the background never matches.
+ * Hashes are 8-bit, so two names can share a byte: `sharedWith` in the job metrics lists them.
+ */
+export function cryptomatteMatte({ pixels, width, height, channel, value }) {
+ requireFrameSize(width, height);
+ requireBytes('pixels', pixels, width * height * 4);
+ if (channel !== 'object' && channel !== 'material') throw new TypeError("channel must be 'object' or 'material'. Pass 'object' for the red hash and 'material' for the green hash.");
+ if (!(value >= 0 && value <= 1)) throw new RangeError('value must be the Cryptomatte value of the name, 0 to 1. Read it from metrics.cryptomatte.');
+ const wantedByte = cryptomatteByte(value);
+ const channelOffset = channel === 'object' ? 0 : 1;
+ const mask = new Uint8Array(width * height);
+ for (let index = 0; index < mask.length; index++) {
+ if (pixels[index * 4 + 2] > 0 && pixels[index * 4 + channelOffset] === wantedByte) mask[index] = 255;
+ }
+ return mask;
+}
+
+/** A 0/255 mask as gray RGBA8 with full alpha, ready for the PNG encoder. */
+export function matteToGrayRgba(mask) {
+ const rgba = new Uint8Array(mask.length * 4);
+ for (let index = 0; index < mask.length; index++) {
+ rgba.fill(mask[index], index * 4, index * 4 + 3);
+ rgba[index * 4 + 3] = 255;
+ }
+ return rgba;
+}
+
+/** The same colour buffer with a mask as its alpha channel: the cut-out of the masked part, ready for alphaOver. */
+export function applyMatteAsAlpha({ width, height, color, mask }) {
+ requireFrameSize(width, height);
+ requireBytes('color', color, width * height * 4);
+ if (!(mask instanceof Uint8Array) || mask.length !== width * height) throw new RangeError('mask must be a Uint8Array with one byte per pixel at the same size as color.');
+ const result = new Uint8Array(color);
+ for (let index = 0; index < mask.length; index++) result[index * 4 + 3] = Math.floor(color[index * 4 + 3] * mask[index] / 255);
+ return result;
+}
diff --git a/tests/pass-compositing.test.js b/tests/pass-compositing.test.js
new file mode 100644
index 00000000..8382e288
--- /dev/null
+++ b/tests/pass-compositing.test.js
@@ -0,0 +1,162 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import {
+ alphaOver, applyMatteAsAlpha, cryptomatteByte, cryptomatteMatte, depthMetresFromPass, floatPassToBytes, matteToGrayRgba, objectIdMatte, zCombine,
+} from '../src/pass-compositing.js';
+import { cryptomatteValue } from '../src/render-passes.js';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { artifactNames, createAgentRenderJobs, normalizeJobSettings } from '../scripts/agent-render-jobs.mjs';
+import { renderJobMattes } from '../scripts/job-mattes.mjs';
+import { encodePng } from '../src/export-png.js';
+
+const rgba = (...pixels) => Uint8Array.from(pixels.flat());
+
+test('zCombine keeps the nearer pixel, the first input on a tie, and never a background pixel', () => {
+ const colorA = rgba([255, 0, 0, 255], [255, 0, 0, 255], [255, 0, 0, 255], [255, 0, 0, 255]);
+ const colorB = rgba([0, 0, 255, 255], [0, 0, 255, 255], [0, 0, 255, 255], [0, 0, 255, 255]);
+ const depthA = Float32Array.from([2, 2, 5, Infinity]);
+ const depthB = Float32Array.from([3, 2, 1, Infinity]);
+ const result = zCombine({ width: 2, height: 2, colorA, depthA, colorB, depthB });
+ assert.deepEqual([...result.nearest], [0, 0, 1, 0]);
+ assert.deepEqual([...result.depth], [2, 2, 1, Infinity]);
+ assert.deepEqual([...result.color], [255, 0, 0, 255, 255, 0, 0, 255, 0, 0, 255, 255, 255, 0, 0, 255]);
+});
+
+test('depthMetresFromPass reads the 16-bit step over the range and sends the background to Infinity', () => {
+ const pixels = rgba([0, 0, 0, 255], [128, 0, 0, 255], [255, 255, 0, 255], [0, 1, 0, 255]);
+ const metres = depthMetresFromPass({ pixels, width: 2, height: 2 });
+ assert.equal(metres[0], 0);
+ assert.equal(metres[1], Math.fround(32768 / 65535 * 100));
+ assert.equal(metres[2], Infinity);
+ assert.equal(metres[3], Math.fround(1 / 65535 * 100));
+ assert.equal(depthMetresFromPass({ pixels, width: 2, height: 2, depthRange: 10 })[1], Math.fround(32768 / 65535 * 10));
+});
+
+test('alphaOver composites straight-alpha pixels byte for byte', () => {
+ const foreground = rgba([255, 0, 0, 128], [10, 20, 30, 0], [200, 100, 50, 255], [90, 90, 90, 0]);
+ const background = rgba([0, 0, 255, 255], [1, 2, 3, 255], [9, 9, 9, 9], [5, 5, 5, 0]);
+ const result = alphaOver({ width: 2, height: 2, foreground, background });
+ assert.deepEqual([...result], [128, 0, 127, 255, 1, 2, 3, 255, 200, 100, 50, 255, 0, 0, 0, 0]);
+ // A half-transparent foreground over a transparent background keeps its own colour and alpha.
+ const onNothing = alphaOver({ width: 1, height: 1, foreground: rgba([255, 0, 0, 128]), background: rgba([0, 0, 0, 0]) });
+ assert.deepEqual([...onNothing], [255, 0, 0, 128]);
+ // Over with itself is repeatable: same bytes on every call.
+ assert.deepEqual([...alphaOver({ width: 2, height: 2, foreground, background })], [...result]);
+});
+
+test('floatPassToBytes flips the bottom-first readback and rounds to bytes', () => {
+ const readback = Float32Array.from([
+ 0, 0, 1, 1, 1, 1, 1, 1, // bottom row
+ 1, 0, 0, 1, 0.5, 0.5, 0.5, 1, // top row
+ ]);
+ assert.deepEqual([...floatPassToBytes({ pixels: readback, width: 2, height: 2 })],
+ [255, 0, 0, 255, 128, 128, 128, 255, 0, 0, 255, 255, 255, 255, 255, 255]);
+});
+
+test('objectIdMatte selects 24-bit IDs and rejects an empty or invalid list', () => {
+ const pixels = rgba([1, 0, 0, 255], [2, 0, 0, 255], [0, 1, 0, 255], [0, 0, 0, 255]);
+ assert.deepEqual([...objectIdMatte({ pixels, width: 2, height: 2, ids: [2, 256] })], [0, 255, 255, 0]);
+ assert.throws(() => objectIdMatte({ pixels, width: 2, height: 2, ids: [] }), /object IDs from 1/);
+ assert.throws(() => objectIdMatte({ pixels, width: 2, height: 2, ids: [0] }), /object IDs from 1/);
+});
+
+test('cryptomatteMatte matches the hash byte of one channel and never the background', () => {
+ const heroByte = cryptomatteByte(cryptomatteValue(1));
+ const stoneByte = cryptomatteByte(cryptomatteValue(2));
+ assert.notEqual(heroByte, stoneByte);
+ const pixels = rgba([heroByte, stoneByte, 255, 255], [stoneByte, heroByte, 255, 255], [heroByte, heroByte, 0, 255], [0, 0, 0, 255]);
+ assert.deepEqual([...cryptomatteMatte({ pixels, width: 2, height: 2, channel: 'object', value: cryptomatteValue(1) })], [255, 0, 0, 0]);
+ assert.deepEqual([...cryptomatteMatte({ pixels, width: 2, height: 2, channel: 'material', value: cryptomatteValue(1) })], [0, 255, 0, 0]);
+ assert.throws(() => cryptomatteMatte({ pixels, width: 2, height: 2, channel: 'both', value: 0.5 }), /'object' or 'material'/);
+ assert.throws(() => cryptomatteMatte({ pixels, width: 2, height: 2, channel: 'object', value: 2 }), /metrics.cryptomatte/);
+});
+
+test('a matte turns a colour buffer into an alpha-over cut-out', () => {
+ const color = rgba([10, 20, 30, 255], [40, 50, 60, 255]);
+ const mask = Uint8Array.from([255, 0]);
+ const cutout = applyMatteAsAlpha({ width: 2, height: 1, color, mask });
+ assert.deepEqual([...cutout], [10, 20, 30, 255, 40, 50, 60, 0]);
+ assert.deepEqual([...matteToGrayRgba(mask)], [255, 255, 255, 255, 0, 0, 0, 255]);
+});
+
+test('compositing rejects mismatched sizes with what to pass instead', () => {
+ const small = new Uint8Array(4);
+ assert.throws(() => alphaOver({ width: 2, height: 2, foreground: small, background: small }), /needs 16 \(width x height x 4\)/);
+ assert.throws(() => alphaOver({ width: 0, height: 2, foreground: small, background: small }), /frame size/);
+ assert.throws(() => alphaOver({ width: 4000, height: 4000, foreground: small, background: small }), /3840x2160/);
+ assert.throws(() => alphaOver({ width: 1, height: 1, foreground: [1, 2, 3, 4], background: small }), /Uint8Array/);
+ assert.throws(() => zCombine({ width: 1, height: 1, colorA: small, colorB: small, depthA: Float32Array.of(NaN), depthB: Float32Array.of(1) }), /NaN.*Infinity/);
+ assert.throws(() => zCombine({ width: 1, height: 1, colorA: small, colorB: small, depthA: Float32Array.of(1, 2), depthB: Float32Array.of(1) }), /same size/);
+});
+
+test('renderJobMattes builds one PNG per matte from the object and cryptomatte passes', async () => {
+ const heroValue = cryptomatteValue(1);
+ const stoneValue = cryptomatteValue(2);
+ const cryptomatte = { objects: { hero: { id: 1, value: heroValue }, floor: { id: 2, value: stoneValue } },
+ materials: { steel: { id: 1, value: heroValue }, stone: { id: 2, value: stoneValue } } };
+ // Bottom row first: the top row of the picture is [hero, floor], the bottom row [floor, background].
+ const objectIds = Float32Array.from([2 / 255, 0, 0, 1, 0, 0, 0, 1, 1 / 255, 0, 0, 1, 2 / 255, 0, 0, 1]);
+ const crypto = Float32Array.from([stoneValue, stoneValue, 1, 1, 0, 0, 0, 1, heroValue, heroValue, 1, 1, stoneValue, stoneValue, 1, 1]);
+ const seen = [];
+ const renderPass = async name => {
+ seen.push(name);
+ return name === 'objectId'
+ ? { info: { objectNames: ['hero', 'floor'] }, pixels: objectIds, width: 2, height: 2 }
+ : { info: { cryptomatte }, pixels: crypto, width: 2, height: 2 };
+ };
+ const results = await renderJobMattes({ mattes: [{ object: 'hero' }, { object: 'floor' }, { material: 'stone' }], renderPass });
+ assert.deepEqual(seen, ['objectId', 'cryptomatte'], 'each pass renders once');
+ assert.deepEqual([...results[0].bytes], [...encodePng(matteToGrayRgba(Uint8Array.from([255, 0, 0, 0])), 2, 2)]);
+ assert.deepEqual([...results[1].bytes], [...encodePng(matteToGrayRgba(Uint8Array.from([0, 255, 255, 0])), 2, 2)]);
+ assert.deepEqual([...results[2].bytes], [...encodePng(matteToGrayRgba(Uint8Array.from([0, 255, 255, 0])), 2, 2)]);
+ assert.deepEqual(results.map(result => result.metric.coveragePixels), [1, 2, 2]);
+ assert.deepEqual(results[0].metric.partIds, [1]);
+ await assert.rejects(renderJobMattes({ mattes: [{ object: 'chair' }], renderPass }), /no part named "chair".*hero, floor/);
+ await assert.rejects(renderJobMattes({ mattes: [{ material: 'glass' }], renderPass }), /no material named "glass".*steel, stone/);
+});
+
+test('settings.mattes is validated and adds one file per matte and frame', () => {
+ const recipe = { format: 'fixture' };
+ const base = { kind: 'image', width: 64, height: 64 };
+ const settings = normalizeJobSettings({ ...base, passes: ['depth'], mattes: [{ object: 'hero' }, { material: 'stone' }] }, [], recipe);
+ assert.deepEqual(settings.mattes, [{ object: 'hero' }, { material: 'stone' }]);
+ assert.deepEqual(artifactNames('image', ['depth'], 'png', false, 8, settings.mattes), ['render.png', 'render-depth.png', 'render-matte-0.png', 'render-matte-1.png']);
+ assert.deepEqual(artifactNames('stills', [], 'png', false, 2, [{ object: 'a' }]), ['frame-0.png', 'frame-0-matte-0.png', 'frame-1.png', 'frame-1-matte-0.png']);
+ assert.deepEqual(artifactNames('image', ['depth']), ['render.png', 'render-depth.png']);
+ const rejected = (mattes, extra, pattern) => assert.throws(() => normalizeJobSettings({ ...base, ...extra, mattes }, [], recipe), pattern);
+ rejected([], {}, /1 to 8 entries/);
+ rejected(Array.from({ length: 9 }, () => ({ object: 'a' })), {}, /1 to 8 entries/);
+ rejected([{}], {}, /exactly one of object or material/);
+ rejected([{ object: 'a', material: 'b' }], {}, /exactly one of object or material/);
+ rejected([{ object: '' }], {}, /1 to 120 characters/);
+ rejected([{ object: 'a'.repeat(121) }], {}, /1 to 120 characters/);
+ rejected([{ part: 'a' }], {}, /Unknown mattes\[0\] field: part/);
+ rejected([{ object: 'a' }], { kind: 'video', fps: 24, duration: 1 }, /image or stills/);
+ rejected([{ object: 'a' }], { format: 'exr' }, /8-bit PNG/);
+ rejected([{ object: 'a' }], { renderer: { type: 'pathTracer' } }, /cannot combine with renderer/);
+});
+
+test('a job with mattes publishes every matte file through the job store', async context => {
+ const root = await mkdtemp(join(tmpdir(), 'crucible-mattes-'));
+ context.after(() => rm(root, { recursive: true, force: true }));
+ const run = async ({ directory, settings }) => {
+ const artifacts = [];
+ for (const filename of artifactNames(settings.kind, settings.passes, settings.format, settings.multilayer, settings.frameCount, settings.mattes)) {
+ await writeFile(join(directory, `${filename}.partial`), Buffer.from(filename));
+ artifacts.push({ temporary: `${filename}.partial`, filename, mimeType: 'image/png' });
+ }
+ return { artifacts, metrics: {} };
+ };
+ const limits = { maxOutputBytes: 1024 ** 2, maxFrameBytes: 128, maxStoreBytes: 8 * 1024 ** 2, cleanupMs: 100 };
+ const controller = await createAgentRenderJobs({ root, limits, run });
+ const submitted = await controller.submit({ sourceRevision: 0, snapshot: { recipe: { format: 'fixture' } },
+ settings: { kind: 'stills', width: 64, height: 64, stillCount: 2, mattes: [{ object: 'a' }, { material: 'b' }] } });
+ while (controller.status(submitted.jobId).state !== 'completed') await new Promise(resolve => setTimeout(resolve, 2));
+ assert.deepEqual(controller.status(submitted.jobId).artifacts.map(artifact => artifact.filename),
+ ['frame-0.png', 'frame-0-matte-0.png', 'frame-0-matte-1.png', 'frame-1.png', 'frame-1-matte-0.png', 'frame-1-matte-1.png']);
+ await controller.release(submitted.jobId);
+ await controller.close();
+});