Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Let a render job pick its settings from a time and memory budget (#904)

Nguyen Xuan Andb69b21419d5
diff --git a/changes/904.md b/changes/904.md
new file mode 100644
index 00000000..4da42612
--- /dev/null
+++ b/changes/904.md
@@ -0,0 +1 @@
+- `scene_render_submit` takes `settings.budget` (`secondsPerFrame` or `framesPerSecond`, optional `memoryMiB`), picks the path tracer samples or the raster frame size whose estimate fits, and returns what it picked and why (#904)
diff --git a/changes/904.size.md b/changes/904.size.md
new file mode 100644
index 00000000..5e3b0d6c
--- /dev/null
+++ b/changes/904.size.md
@@ -0,0 +1,2 @@
+- tool-total: the `budget` field of scene_render_submit settings (273 bytes) lets an agent give a time and memory limit instead of tuning renderer, samples and size by hand; the detail sits in scene_capabilities jobs
+- tool:scene_render_submit: the same `budget` field, three optional numbers and one short description
diff --git a/docs/mcp.md b/docs/mcp.md
index 58392305..c9b50362 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -202,6 +202,14 @@ When a job completes, `scene_render_result` has `metrics.report`, one record of
Limits of the estimate: it covers a job's own time, not the wait for a busy machine; memory is the sampled Node RSS plus the browser JS heap, which is a lower bound for GPU memory; path tracer estimates assume the CPU or GPU backend named in the settings, and a native tracer that cannot run falls back (see `fallbacks`).
+### Render budget
+
+`settings.budget` lets a job choose its own renderer and size from what you can spend: `{ "secondsPerFrame": 2 }` for an offline render, `{ "framesPerSecond": 30 }` for a realtime preview, and optionally `"memoryMiB"` (64 to 65536) as a cap on the estimated peak memory. Give exactly one of `secondsPerFrame` (0.001 to 3600) and `framesPerSecond` (0.01 to 240). `width` and `height` stay the largest frame you want; `renderer` must be left out, because the budget picks it. A job that cannot go through the path tracer (`passes`, `transparent`, `region`, `multilayer`, a `format` other than png) only considers raster.
+
+The runtime estimates these candidates with the cost model above (history correction included), best looking first, and takes the first one that fits: the path tracer at 256, 64 and 16 samples with the wavelet denoiser at full size on the runtime's backend, then the raster renderer at full size, 0.75, 0.5 and 0.25 scale (sides rounded, even for video, at least 64). The ladder is the whole choice for now: named quality tiers are a later slice of #904. A candidate fits when its estimated seconds per frame (the whole job divided by its frames, so scene build time counts) is at most 85% of the budget, because the estimate is only good to a few tens of percent, and its estimated peak memory is within `memoryMiB`. The same scene, budget and history always give the same pick.
+
+`scene_render_submit` returns `budget` beside `estimate`: `requested`, `picked` (label, size, renderer or `raster`, expected seconds per frame and memory), `fits`, `reason` (which better candidate was too expensive, or why nothing fits) and `considered`, every candidate with its expected cost. When nothing fits, the cheapest candidate runs anyway and `fits` is false; raise the budget or shorten the job. `scripts/measure-render-budget.mjs` submits tight, middle, loose and 30 fps budgets on two scenes and prints what each picked beside the measured time.
+
### Response format
`scene_review`, `scene_render_status`, `scene_render_result` and `scene_capabilities` take `response_format`: `concise` or `detailed`.
diff --git a/scripts/agent-render-budget.mjs b/scripts/agent-render-budget.mjs
new file mode 100644
index 00000000..f96578ea
--- /dev/null
+++ b/scripts/agent-render-budget.mjs
@@ -0,0 +1,119 @@
+// Picks a render job's settings from a budget instead of by hand. The candidates run from the best looking to the cheapest; the
+// first one whose estimate fits the budget wins. Nothing here renders: it asks agent-render-estimate.mjs what each candidate
+// would cost, so the same scene, budget and history always give the same pick.
+
+/** What scene_capabilities topic jobs says about the budget. The details are in docs/mcp.md. */
+export const RENDER_BUDGET_NOTE = 'settings.budget { secondsPerFrame | framesPerSecond, memoryMiB? } replaces hand-picked renderer settings: width and height become the largest frame, and the job takes the best candidate whose estimate fits (path tracer at 256, 64 or 16 samples, then raster at scale 1, 0.75, 0.5, 0.25). Time is the whole job divided by its frames, and a pick is expected to use at most 85% of it. submit returns budget { picked, fits, reason, considered }; when nothing fits the cheapest candidate runs and fits is false.';
+
+export const BUDGET_LIMITS = Object.freeze({
+ secondsPerFrame: Object.freeze({ minimum: 0.001, maximum: 3600 }),
+ framesPerSecond: Object.freeze({ minimum: 0.01, maximum: 240 }),
+ memoryMiB: Object.freeze({ minimum: 64, maximum: 65536 }),
+});
+
+/** Quality order, best first. A path tracer candidate keeps the frame size; a raster candidate shrinks it. */
+export const PATH_TRACER_SAMPLE_STEPS = Object.freeze([256, 64, 16]);
+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'];
+
+function limitedNumber(value, name) {
+ const { minimum, maximum } = BUDGET_LIMITS[name];
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum) {
+ throw new RangeError(`budget.${name} must be a number from ${minimum} to ${maximum}.`);
+ }
+ return value;
+}
+
+/** The budget as { secondsPerFrame, memoryMiB? }; a frame rate is turned into seconds per frame. Throws with what to pass instead. */
+export function parseBudget(input) {
+ if (input === null || typeof input !== 'object' || Array.isArray(input)) {
+ throw new TypeError('budget must be an object such as { "secondsPerFrame": 2 } or { "framesPerSecond": 30, "memoryMiB": 1024 }.');
+ }
+ const unknown = Object.keys(input).filter(name => !(name in BUDGET_LIMITS));
+ if (unknown.length) throw new TypeError(`budget has no field ${unknown.join(', ')}. Use secondsPerFrame or framesPerSecond, and optionally memoryMiB.`);
+ const hasSeconds = input.secondsPerFrame !== undefined;
+ const hasRate = input.framesPerSecond !== undefined;
+ if (hasSeconds === hasRate) throw new TypeError('budget needs exactly one of secondsPerFrame (offline renders) or framesPerSecond (realtime previews).');
+ const secondsPerFrame = hasSeconds ? limitedNumber(input.secondsPerFrame, 'secondsPerFrame') : 1 / limitedNumber(input.framesPerSecond, 'framesPerSecond');
+ const budget = { secondsPerFrame };
+ if (hasRate) budget.framesPerSecond = input.framesPerSecond;
+ if (input.memoryMiB !== undefined) budget.memoryMiB = limitedNumber(input.memoryMiB, 'memoryMiB');
+ return budget;
+}
+
+function scaledSide(side, scale, even) {
+ const unit = even ? 2 : 1;
+ return Math.max(MINIMUM_SIDE, Math.round((side * scale) / unit) * unit);
+}
+
+/** Raw job settings (what the caller would have written by hand) for each candidate, best first, with a label. */
+export function budgetCandidates(base, tracerBackend) {
+ const candidates = [];
+ const tracerAllowed = !TRACER_BLOCKERS.some(name => base[name]) && !(base.format && base.format !== 'png');
+ if (tracerAllowed) {
+ for (const samples of PATH_TRACER_SAMPLE_STEPS) {
+ candidates.push({ label: `path tracer, ${samples} samples, full size`, settings: { ...base, renderer: { type: 'pathTracer', backend: tracerBackend, samples, denoise: 'wavelet' } } });
+ }
+ }
+ const even = base.kind === 'video';
+ for (const scale of RASTER_SCALE_STEPS) {
+ const width = scaledSide(base.width, scale, even);
+ const height = scaledSide(base.height, scale, even);
+ candidates.push({ label: `raster, ${scale === 1 ? 'full size' : `${scale} scale`}`, settings: { ...base, width, height } });
+ }
+ return candidates;
+}
+
+function cost(estimate) {
+ return { seconds: estimate.seconds, peakMemoryMiB: estimate.peakMemoryMiB };
+}
+
+/**
+ * Chooses among the candidates. `estimateOf(rawSettings)` returns an estimate for a candidate; `frameCount` turns its seconds into seconds per frame. The result holds the settings to
+ * submit and the report of the choice: what was picked, whether it fits, why, and what each candidate was expected to cost.
+ */
+export function chooseBudgetSettings({ base, budget, tracerBackend, frameCount, estimateOf }) {
+ const considered = budgetCandidates(base, tracerBackend).map(candidate => {
+ const estimate = estimateOf(candidate.settings);
+ return { ...candidate, estimate, secondsPerFrame: round(estimate.seconds / frameCount, 3) };
+ });
+ const fits = candidate => candidate.secondsPerFrame <= budget.secondsPerFrame * TIME_HEADROOM && (budget.memoryMiB === undefined || candidate.estimate.peakMemoryMiB <= budget.memoryMiB);
+ const fitting = considered.find(fits);
+ const cheapest = [...considered].sort((first, second) => first.secondsPerFrame - second.secondsPerFrame || first.estimate.peakMemoryMiB - second.estimate.peakMemoryMiB)[0];
+ const picked = fitting ?? cheapest;
+ const { settings, label } = picked;
+ const requested = { secondsPerFrame: round(budget.secondsPerFrame, 4) };
+ if (budget.framesPerSecond !== undefined) requested.framesPerSecond = budget.framesPerSecond;
+ if (budget.memoryMiB !== undefined) requested.memoryMiB = budget.memoryMiB;
+ return {
+ settings,
+ report: {
+ requested,
+ picked: { label, width: settings.width, height: settings.height, renderer: settings.renderer ? { backend: settings.renderer.backend, samples: settings.renderer.samples, denoise: settings.renderer.denoise } : 'raster', expected: { ...cost(picked.estimate), secondsPerFrame: picked.secondsPerFrame } },
+ fits: Boolean(fitting),
+ reason: fitting ? reasonForFit(picked, considered, budget) : reasonForMiss(picked, budget),
+ considered: considered.map(candidate => ({ label: candidate.label, secondsPerFrame: candidate.secondsPerFrame, peakMemoryMiB: candidate.estimate.peakMemoryMiB, fits: fits(candidate) })),
+ },
+ };
+}
+
+function round(value, digits) {
+ const scale = 10 ** digits;
+ return Math.round(value * scale) / scale;
+}
+
+function reasonForFit(picked, considered, budget) {
+ const better = considered.slice(0, considered.indexOf(picked));
+ if (!better.length) return `The best candidate fits: about ${picked.secondsPerFrame} s per frame and ${picked.estimate.peakMemoryMiB} MiB.`;
+ const next = better[better.length - 1];
+ const over = next.secondsPerFrame > budget.secondsPerFrame * TIME_HEADROOM ? `${next.label} needs about ${next.secondsPerFrame} s per frame against ${round(budget.secondsPerFrame * TIME_HEADROOM, 4)} s` : `${next.label} needs about ${next.estimate.peakMemoryMiB} MiB against ${budget.memoryMiB} MiB`;
+ return `${over}, so ${picked.label} is the best that fits.`;
+}
+
+function reasonForMiss(picked, budget) {
+ return `Nothing fits: the cheapest candidate, ${picked.label}, needs about ${picked.secondsPerFrame} s per frame and ${picked.estimate.peakMemoryMiB} MiB against ${round(budget.secondsPerFrame, 4)} s${budget.memoryMiB === undefined ? '' : ` and ${budget.memoryMiB} MiB`}. It runs anyway; raise the budget or shorten the job.`;
+}
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index 98e4b359..5861629a 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -32,6 +32,7 @@ import { TEXTURE_SEQUENCE_CAPABILITIES } from '../src/texture-sequence-limits.js
import { writeWebBuild } from './web-export.mjs';
import { gameAssetIds } from '../src/game-assets.js';
import { createAgentRenderJobs, EXPORT_DIRECTORY_NAME, HIGH_PRECISION_FRAME_FACTOR, RENDER_HISTORY_FILE, normalizeJobSettings } from './agent-render-jobs.mjs';
+import { RENDER_BUDGET_NOTE, chooseBudgetSettings, parseBudget } from './agent-render-budget.mjs';
import { RENDER_ESTIMATE_NOTE, estimateRenderJob, historyWithJob, parseHistory, renderReport, sceneSizeFrom } from './agent-render-estimate.mjs';
import { encodeRenderOutput, encodeMultilayerExr } from './render-output-encoders.mjs';
import { createFrameEncoder } from './frame-encoder.mjs';
@@ -896,7 +897,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
maximumFileBytes: MAXIMUM_PACK_FILE_BYTES, maximumJsonBytes: MAXIMUM_PACK_JSON_BYTES, maximumItemsPerKind: MAXIMUM_PACK_ITEMS_PER_KIND,
use: 'scene_asset_catalog lists packs: name, version, license, author, description and item ids. GLBs, images, looks and environments carry assetId values that work in scene_create_asset, look, hdri and texture fields. Materials and recipes are read with scene_asset_catalog { pack, material } or { pack, recipe }: pass a recipe to scene_create, and a material as a materials entry or a scene_apply set-material. Packs are installed by the user (unzip into the --packs folder); a tool call never downloads one. Invalid packs are skipped and listed under packs.rejected with the reason.',
},
- jobs: { configured: Boolean(jobRoot), kinds: ['image', 'stills', 'video'], passes: RENDER_PASS_NAMES, pathTracer: PATH_TRACER_CAPABILITIES, maximumActiveJobs: 1, estimate: RENDER_ESTIMATE_NOTE,
+ jobs: { configured: Boolean(jobRoot), kinds: ['image', 'stills', 'video'], passes: RENDER_PASS_NAMES, pathTracer: PATH_TRACER_CAPABILITIES, maximumActiveJobs: 1, estimate: RENDER_ESTIMATE_NOTE, budget: RENDER_BUDGET_NOTE,
maximumWidth: MAXIMUM_JOB_SIDE, maximumHeight: MAXIMUM_JOB_SIDE, maximumPixels: MAXIMUM_JOB_PIXELS,
maximumDuration: MAXIMUM_VIDEO_SECONDS, maximumFps: 30, maximumFrames: 900, maximumStills: 8,
encoder: 'H.264', encoders: VIDEO_ENCODERS, audio: Boolean(audioRoot), timeline: true, previewSuspendedDuringJob: true,
@@ -1260,12 +1261,23 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
try {
// The estimate is made before the job exists, because the job suspends the scene and starts at once.
const size = sceneSizeFrom(await invoke('inspect', { sessionId, limit: Math.max(1, snapshot.recipe.nodes?.length ?? 1) }), snapshot.recipe);
- const estimate = estimateRenderJob({ size, settings: normalizeJobSettings(settings, snapshot.clips, snapshot.recipe), backend, memoryBudgetMiB: memory, history: await readRenderHistory(), gpuTracerWarm });
+ const history = await readRenderHistory();
+ const estimateOf = rawSettings => estimateRenderJob({ size, settings: normalizeJobSettings(rawSettings, snapshot.clips, snapshot.recipe), backend, memoryBudgetMiB: memory, history, gpuTracerWarm });
+ let jobSettings = settings;
+ let budgetReport;
+ if (settings?.budget !== undefined) {
+ const { budget: budgetInput, ...base } = settings;
+ if (base.renderer !== undefined) throw new TypeError('budget picks the renderer: leave settings.renderer out, or leave settings.budget out to choose it yourself.');
+ const budget = parseBudget(budgetInput);
+ const frameCount = normalizeJobSettings(base, snapshot.clips, snapshot.recipe).frameCount;
+ ({ settings: jobSettings, report: budgetReport } = chooseBudgetSettings({ base, budget, tracerBackend: backend === 'cpu' ? 'cpu' : 'gpu', frameCount, estimateOf }));
+ }
+ const estimate = estimateOf(jobSettings);
estimateForNextJob = estimate;
try {
const submitted = await controller.submit({ sessionId, sourceRevision: snapshot.sourceRevision,
- snapshot: { recipe: snapshot.recipe, clips: snapshot.clips, ...(assetBytes ? { assetBytes } : {}) }, settings });
- return { ...submitted, estimate };
+ snapshot: { recipe: snapshot.recipe, clips: snapshot.clips, ...(assetBytes ? { assetBytes } : {}) }, settings: jobSettings });
+ return { ...submitted, estimate, ...(budgetReport ? { budget: budgetReport } : {}) };
} catch (error) {
if (estimateForNextJob === estimate) estimateForNextJob = undefined;
throw error;
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 8e0e8a2d..ec19cbf5 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -791,6 +791,7 @@ const renderSettings = z.strictObject({
motion: z.strictObject({ start: z.number().min(0).max(3600).optional() }).optional(),
rendererTime: z.strictObject({ start: z.number().min(0).max(3600).optional(), rate: z.number().min(-16).max(16).optional() }).optional(),
renderer: z.looseObject({ type: z.literal('pathTracer'), backend: z.enum(['cpu', 'gpu', 'native']).optional() }).meta({ description: 'Path tracer. Also samples, bounces, denoise, seed, maxSeconds, noiseThreshold: scene_capabilities pathTracer.' }).pipe(z.strictObject({ type: z.literal('pathTracer'), backend: z.enum(['cpu', 'gpu', 'native']).optional(), samples: z.number().optional(), bounces: z.number().optional(), denoise: z.union([z.boolean(), z.enum(['wavelet', 'oidn', 'none'])]).optional(), seed: z.number().optional(), maxSeconds: z.number().optional(), noiseThreshold: z.number().optional() })).optional(),
+ budget: z.strictObject({ secondsPerFrame: z.number().optional(), framesPerSecond: z.number().optional(), memoryMiB: z.number().optional() }).optional().describe('Pick renderer, samples and size to fit; not with renderer. scene_capabilities jobs.'),
timeline: z.strictObject({ start: z.number().min(0).max(60).optional() }).optional().describe('Play the recipe timeline from start (default 0); it owns the motion clock, so leave motion and animation out.'),
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.'),
diff --git a/scripts/measure-render-budget.mjs b/scripts/measure-render-budget.mjs
new file mode 100644
index 00000000..35a9f464
--- /dev/null
+++ b/scripts/measure-render-budget.mjs
@@ -0,0 +1,98 @@
+// Checks that a render budget picks settings that meet it. Builds a small and a medium scene, submits a still with a tight, a
+// middle and a loose budget through the MCP runtime, and prints what each budget picked beside the measured time per frame.
+// node scripts/measure-render-budget.mjs [--backend gpu|cpu] [--json]
+// On a shared machine run it through your GPU job lock, so it waits for a free card.
+import { mkdtemp } 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 { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const backendArgument = process.argv.indexOf('--backend');
+const backend = backendArgument > 0 ? process.argv[backendArgument + 1] : 'gpu';
+const printJson = process.argv.includes('--json');
+
+const SCENES = [
+ { name: 'small', spheres: 3, segments: 16, rings: 10, pointLights: 1 },
+ { name: 'medium', spheres: 120, segments: 32, rings: 20, pointLights: 4 },
+];
+const BUDGETS = [
+ { label: 'tight', budget: { secondsPerFrame: 0.8 } },
+ { label: 'middle', budget: { secondsPerFrame: 6 } },
+ { label: 'loose', budget: { secondsPerFrame: 40 } },
+ { label: 'realtime', budget: { framesPerSecond: 30 }, frame: { kind: 'video', width: 480, height: 270, fps: 30, duration: 2 } },
+];
+const FRAME = { kind: 'image', width: 480, height: 270 };
+
+function recipeFor({ spheres, segments, rings, pointLights }) {
+ const columns = Math.ceil(Math.sqrt(spheres));
+ const nodes = [{ id: 'floor', geometry: 'box', material: 'matte', translation: [0, -0.1, 0], scale: [columns * 1.2 + 4, 0.2, columns * 1.2 + 4] }];
+ for (let index = 0; index < spheres; index++) {
+ const column = index % columns;
+ const row = Math.floor(index / columns);
+ nodes.push({ id: `ball-${index}`, geometry: 'sphere', material: index % 2 ? 'matte' : 'glow', translation: [(column - columns / 2) * 1.2, 0.5, (row - columns / 2) * 1.2], scale: [0.5, 0.5, 0.5] });
+ }
+ const span = columns * 0.6 + 4;
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box' }, { id: 'sphere', type: 'sphere', segments, rings }],
+ materials: [{ id: 'matte', color: [0.7, 0.7, 0.7], roughness: 0.6 }, { id: 'glow', color: [0.1, 0.3, 0.9], emission: 1 }],
+ nodes,
+ environment: { pointLights: Array.from({ length: pointLights }, (_, index) => ({ position: [index - pointLights / 2, 3, 2], intensity: 20, color: [1, 1, 1] })) },
+ camera: { eye: [0, span * 0.5, span], target: [0, 0, 0], fov: 40 },
+ };
+}
+
+const directory = await mkdtemp(join(tmpdir(), '67js-budget-'));
+const transport = new StdioClientTransport({ command: process.execPath,
+ args: [resolve('bin/67js-mcp.mjs'), '--backend', backend, '--memory', '256', '--jobs', join(directory, 'jobs')], cwd: directory, stderr: 'pipe' });
+const client = new Client({ name: '67js-budget-measure', version: '1' });
+
+async function call(name, argumentsValue = {}, timeout = 120000) {
+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout });
+ if (result.isError) throw new Error(result.content?.find(item => item.type === 'text')?.text);
+ return result;
+}
+
+async function untilFinished(jobId) {
+ const deadline = Date.now() + 300000;
+ 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 300 seconds.');
+}
+
+const rows = [];
+try {
+ await client.connect(transport, { timeout: 240000 });
+ for (const scene of SCENES) {
+ const created = (await call('scene_create', { recipe: recipeFor(scene) }, 300000)).structuredContent;
+ for (const { label, budget, frame = FRAME } of BUDGETS) {
+ try {
+ const submitted = (await call('scene_render_submit', { sessionId: created.sessionId, expectedRevision: created.revision ?? 0, settings: { ...frame, budget } })).structuredContent;
+ const record = await untilFinished(submitted.jobId);
+ const result = record.state === 'completed' ? (await call('scene_render_result', { jobId: submitted.jobId, response_format: 'detailed' })).structuredContent : undefined;
+ rows.push({ scene: scene.name, label, budget, limit: submitted.budget.requested.secondsPerFrame, picked: submitted.budget.picked, fits: submitted.budget.fits, reason: submitted.budget.reason, state: record.state, measured: result?.metrics?.report?.measured });
+ if (result) await call('scene_render_release', { jobId: submitted.jobId });
+ } catch (error) {
+ rows.push({ scene: scene.name, label, budget, state: 'error', reason: error.message });
+ }
+ }
+ await call('scene_dispose', { sessionId: created.sessionId });
+ }
+} finally {
+ await client.close();
+}
+
+if (printJson) console.log(JSON.stringify(rows, null, 2));
+console.log('| scene | budget s/frame | picked | size | expected s | measured s | meets | says fits |');
+console.log('| --- | --- | --- | --- | --- | --- | --- | --- |');
+for (const row of rows) {
+ const measuredSeconds = row.measured?.secondsPerFrame;
+ const meets = measuredSeconds === undefined ? row.state : measuredSeconds <= row.limit ? 'yes' : 'no';
+ console.log(`| ${row.scene} | ${row.limit} (${row.label}) | ${row.picked?.label ?? row.reason} | ${row.picked ? `${row.picked.width}x${row.picked.height}` : '-'} | ${row.picked?.expected.secondsPerFrame ?? '-'} | ${measuredSeconds ?? '-'} | ${meets} | ${row.fits ?? '-'} |`);
+}
diff --git a/tests/agent-runtime.test.js b/tests/agent-runtime.test.js
index d89efbc8..d0e94369 100644
--- a/tests/agent-runtime.test.js
+++ b/tests/agent-runtime.test.js
@@ -17,6 +17,7 @@ import { VEGETATION_CAPABILITY_NOTE } from '../src/agent-vegetation-notes.js';
import { CROWD_CAPABILITY_NOTE } from '../src/agent-crowd-notes.js';
import { SETTLE_CAPABILITY_NOTE } from '../src/settle-notes.js';
import { RENDER_ESTIMATE_NOTE, estimateRenderJob, historyWithJob, parseHistory, renderReport, sceneSizeFrom } from '../scripts/agent-render-estimate.mjs';
+import { RENDER_BUDGET_NOTE, chooseBudgetSettings, parseBudget } from '../scripts/agent-render-budget.mjs';
import { GAME_CAPABILITIES } from '../src/game-setup-notes.js';
import { USER_PASS_CAPABILITIES } from '../src/user-pass.js';
import { MESH_BLEND_CAPABILITIES } from '../src/mesh-blend.js';
@@ -132,7 +133,7 @@ async function reviewRuntimeHarness({ failShot, blockShot = false, oversize = fa
audioInputArguments, createAudioLibrary, measureStreamSeconds, filmTimelineDuration, filmTimelineShotStarts, sampleFilmTimeline, normalizeReview, REVIEW_LIMITS, isPreviewHost, BRANCH_LIMITS, validateBranchName, sessionProblem, SCENE_STORE_LIMITS,
runAnnotateSession: async () => ({ outcome: 'timeout' }), openInDefaultBrowser: async () => {}, ANNOTATE_LIMITS,
...packLimits, createPackRegistry,
- sampleBrowserHeap, exceedsMemoryGuard, RENDER_ESTIMATE_NOTE, estimateRenderJob, historyWithJob, parseHistory, renderReport, sceneSizeFrom, RENDER_HISTORY_FILE, normalizeJobSettings,
+ sampleBrowserHeap, exceedsMemoryGuard, RENDER_BUDGET_NOTE, chooseBudgetSettings, parseBudget, RENDER_ESTIMATE_NOTE, estimateRenderJob, historyWithJob, parseHistory, renderReport, sceneSizeFrom, RENDER_HISTORY_FILE, normalizeJobSettings,
chromium: { launch: async () => browser }, URL, Buffer, process, performance, clearTimeout,
runtimeOptions, mkdir, rm, join, isAbsolute, fileURLToPath, writeWebBuild, EXPORT_DIRECTORY_NAME, createAgentRenderJobs: async () => ({ list: () => [], close: async () => {} }), ...contextOverrides,
setTimeout: (callback, delay) => { deadlines.push(delay); return setTimeout(callback, delay); },
diff --git a/tests/render-budget.test.js b/tests/render-budget.test.js
new file mode 100644
index 00000000..4a84336b
--- /dev/null
+++ b/tests/render-budget.test.js
@@ -0,0 +1,79 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { normalizeJobSettings } from '../scripts/agent-render-jobs.mjs';
+import { estimateRenderJob } from '../scripts/agent-render-estimate.mjs';
+import { budgetCandidates, chooseBudgetSettings, parseBudget } from '../scripts/agent-render-budget.mjs';
+
+const recipe = { format: '67js.scene' };
+const size = { parts: 40, assetParts: 0, triangles: 60000, materials: 4, textures: 0, lights: 3 };
+const base = { kind: 'image', width: 1280, height: 720 };
+
+function choose(budget, overrides = {}, history = []) {
+ const input = { ...base, ...overrides };
+ const frameCount = normalizeJobSettings(input, [], recipe).frameCount;
+ const estimateOf = raw => estimateRenderJob({ size, settings: normalizeJobSettings(raw, [], recipe), backend: 'gpu', memoryBudgetMiB: 192, history });
+ return chooseBudgetSettings({ base: input, budget: parseBudget(budget), tracerBackend: 'gpu', frameCount, estimateOf });
+}
+
+test('a frame rate becomes seconds per frame and bad budgets say what to pass', () => {
+ assert.equal(parseBudget({ framesPerSecond: 30 }).secondsPerFrame, 1 / 30);
+ assert.deepEqual(parseBudget({ secondsPerFrame: 2, memoryMiB: 512 }), { secondsPerFrame: 2, memoryMiB: 512 });
+ assert.throws(() => parseBudget({}), /exactly one of secondsPerFrame/);
+ assert.throws(() => parseBudget({ secondsPerFrame: 1, framesPerSecond: 30 }), /exactly one of secondsPerFrame/);
+ assert.throws(() => parseBudget({ secondsPerFrame: -1 }), /budget.secondsPerFrame must be a number from 0.001 to 3600/);
+ assert.throws(() => parseBudget({ framesPerSecond: 1000 }), /budget.framesPerSecond must be a number from 0.01 to 240/);
+ assert.throws(() => parseBudget({ secondsPerFrame: 1, memoryMiB: 8 }), /budget.memoryMiB must be a number from 64/);
+ assert.throws(() => parseBudget({ secondsPerFrame: 1, fps: 30 }), /no field fps/);
+ assert.throws(() => parseBudget('fast'), /budget must be an object/);
+});
+
+test('candidates run from the path tracer to a small raster frame, and shrink only the raster ones', () => {
+ const labels = budgetCandidates({ ...base }, 'gpu').map(candidate => candidate.label);
+ assert.deepEqual(labels, ['path tracer, 256 samples, full size', 'path tracer, 64 samples, full size', 'path tracer, 16 samples, full size', 'raster, full size', 'raster, 0.75 scale', 'raster, 0.5 scale', 'raster, 0.25 scale']);
+ const raster = budgetCandidates({ ...base }, 'gpu').filter(candidate => !candidate.settings.renderer);
+ assert.deepEqual(raster.map(candidate => candidate.settings.width), [1280, 960, 640, 320]);
+});
+
+test('a job that a path tracer cannot write keeps to raster, and video sides stay even', () => {
+ const withPasses = budgetCandidates({ ...base, passes: ['depth'] }, 'gpu');
+ assert.ok(withPasses.every(candidate => !candidate.settings.renderer));
+ const video = budgetCandidates({ kind: 'video', width: 854, height: 480 }, 'cpu').filter(candidate => !candidate.settings.renderer);
+ assert.ok(video.every(candidate => candidate.settings.width % 2 === 0 && candidate.settings.height % 2 === 0));
+});
+
+test('a loose budget picks the path tracer and a tight one picks a smaller raster frame', () => {
+ const loose = choose({ secondsPerFrame: 600 });
+ assert.equal(loose.report.fits, true);
+ assert.equal(loose.settings.renderer.samples, 256);
+ const tight = choose({ framesPerSecond: 45 }, { kind: 'video', fps: 45, duration: 10 });
+ assert.equal(tight.settings.renderer, undefined);
+ assert.equal(tight.report.fits, true);
+ assert.ok(tight.report.picked.expected.secondsPerFrame <= 1 / 45);
+ assert.match(tight.report.reason, /needs about .* so raster/);
+});
+
+test('a memory cap rules out candidates that need more', () => {
+ const capped = choose({ secondsPerFrame: 600, memoryMiB: 100 });
+ assert.equal(capped.report.fits, false);
+ assert.match(capped.report.reason, /Nothing fits: .* 100 MiB/);
+});
+
+test('when nothing fits the cheapest candidate is picked and the result says so', () => {
+ const nothing = choose({ secondsPerFrame: 0.001 });
+ assert.equal(nothing.report.fits, false);
+ assert.equal(nothing.report.picked.label, 'raster, 0.25 scale');
+ assert.match(nothing.report.reason, /^Nothing fits: the cheapest candidate, raster, 0.25 scale/);
+ assert.equal(nothing.report.considered.length, 7);
+ assert.ok(nothing.report.considered.every(candidate => candidate.fits === false));
+});
+
+test('the same scene, budget and history give the same pick', () => {
+ const history = [
+ { kind: 'raster-image-gpu', estimatedSeconds: 1, measuredSeconds: 2, estimatedPeakMemoryMiB: 200, measuredPeakMemoryMiB: 220 },
+ { kind: 'raster-image-gpu', estimatedSeconds: 1, measuredSeconds: 2, estimatedPeakMemoryMiB: 200, measuredPeakMemoryMiB: 220 },
+ ];
+ assert.deepEqual(choose({ secondsPerFrame: 1 }, {}, history), choose({ secondsPerFrame: 1 }, {}, history));
+ const corrected = choose({ secondsPerFrame: 1 }, {}, history).report.considered.find(candidate => candidate.label === 'raster, full size');
+ const plain = choose({ secondsPerFrame: 1 }).report.considered.find(candidate => candidate.label === 'raster, full size');
+ assert.ok(corrected.secondsPerFrame > plain.secondsPerFrame);
+});