Skip to content

armgit / kiln

Public Imported from GitHub
0

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

feat(render): route in-loop views through the GPU port (#19)

Matthew Kissingerfb6c0e9e0eab
diff --git a/AGENTS.md b/AGENTS.md
index 9e88d386..3f73fc32 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -20,6 +20,21 @@ the single owner of the deadline, renderer/PNG validation, grid composition, and
fallback. Do not duplicate that degrade policy in a host or introduce network/service knowledge into
the deterministic engine paths.
+The port is injected twice, for different jobs, and their deadlines must stay separate. The host
+calls it once after the loop for the artifact sheet, where nothing is blocked and a long deadline is
+correct. `KilnToolContext.viewRenderPort` injects it into `kiln_render` for the IN-LOOP grid, where a
+slow render blocks the agent mid-thought — that deadline is its own per-call argument and belongs far
+lower. Never collapse the two onto one value. Routing there is conditional on
+`sceneNeedsPbrShading(root)`: bound texture or `metalness > 0`, never material type, because
+`gameMaterial` and `pbrMaterial` both construct a `MeshStandardMaterial` and are indistinguishable
+after construction. Who drew a grid is reported through the context's `onViewsRendered` callback, not
+the tool result, so the cached tool definition stays byte-identical.
+
+`src/views/renderer-id.ts` runs `readFileSync` at MODULE LOAD. Reach `CPU_RASTER_RENDERER_ID` through
+the lazy `await import('../views')` that render paths already use; a static import puts a `node:fs`
+edge, evaluated at import time, into a graph deliberately kept free of node-only dependencies. No test
+catches this.
+
Prompt-cache transports are deliberately different. Native Anthropic and Bedrock adapters consume a
system `[TextBlock, CachePointBlock]`; OpenRouter-hosted Anthropic keeps plain system text and receives
top-level `cache_control: { type: 'ephemeral' }` because its Vercel bridge drops cache-point blocks.
diff --git a/src/__tests__/material-resources.test.ts b/src/__tests__/material-resources.test.ts
index 53fff3ab..25b4d182 100644
--- a/src/__tests__/material-resources.test.ts
+++ b/src/__tests__/material-resources.test.ts
@@ -3,11 +3,13 @@ import * as THREE from 'three';
import { applyMaterialRecipeV1 } from '../material-recipe-runtime';
import { createMaterialRecipeRequestV1 } from '../material-recipes';
+import { gameMaterial } from '../primitives';
import {
ApprovedTextureResourceCache,
collectMaterialResourceProvenance,
loadLegacyTextureSource,
readMaterialResourceProvenance,
+ sceneNeedsPbrShading,
} from '../material-resources';
describe('MAT-016 approved resource boundary', () => {
@@ -87,3 +89,44 @@ describe('MAT-017 content cache and provenance', () => {
expect(collectMaterialResourceProvenance(root)).toEqual(applied.provenance.resources);
});
});
+
+describe('sceneNeedsPbrShading', () => {
+ test('untextured gameMaterial (metalness 0 default) does not need PBR shading', () => {
+ const root = new THREE.Group();
+ root.add(new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), gameMaterial('#8080ff')));
+ expect(sceneNeedsPbrShading(root)).toBe(false);
+ });
+
+ test('an empty scene does not need PBR shading', () => {
+ expect(sceneNeedsPbrShading(new THREE.Group())).toBe(false);
+ });
+
+ test('metalness > 0 with no bound texture still needs PBR shading (untextured chrome/brass)', () => {
+ const root = new THREE.Group();
+ root.add(
+ new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), gameMaterial('#c0c0c0', { metalness: 0.6 })),
+ );
+ expect(sceneNeedsPbrShading(root)).toBe(true);
+ });
+
+ const TEXTURE_SLOTS = [
+ 'map',
+ 'normalMap',
+ 'roughnessMap',
+ 'metalnessMap',
+ 'emissiveMap',
+ 'aoMap',
+ ] as const;
+
+ for (const slot of TEXTURE_SLOTS) {
+ test(`a bound ${slot} needs PBR shading`, () => {
+ const material = gameMaterial('#ffffff') as unknown as Record<string, THREE.Texture>;
+ material[slot] = new THREE.Texture();
+ const root = new THREE.Group();
+ root.add(
+ new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), material as unknown as THREE.Material),
+ );
+ expect(sceneNeedsPbrShading(root)).toBe(true);
+ });
+ }
+});
diff --git a/src/agent/generate.ts b/src/agent/generate.ts
index 64fed817..8be4a541 100644
--- a/src/agent/generate.ts
+++ b/src/agent/generate.ts
@@ -212,7 +212,17 @@ export async function generateKilnCodeAgent(opts: {
export const DEFAULT_VIEW_RENDER_TIMEOUT_MS = 8000;
export type PortViewsOutcome =
- | { ok: true; png: Buffer; rendererId: string; capture: CaptureShape }
+ | {
+ ok: true;
+ png: Buffer;
+ rendererId: string;
+ capture: CaptureShape;
+ /** Pixel dimensions of the composited grid — the same `width`/`height` the
+ * CPU path reports alongside its grid, additive here so a caller never has
+ * to decode the PNG to learn them. */
+ width: number;
+ height: number;
+ }
| { ok: false; reason: string };
/**
@@ -301,7 +311,14 @@ export async function captureViewsViaPort(
// Degrade stays reportable through `renderDegraded` / `viewsRendererId`,
// which is a structured field rather than a visual tell.
const grid = compositeViewPngGrid(result.viewsPng, resolved.cols, views);
- return { ok: true, png: grid.png, rendererId: result.rendererId, capture: shape };
+ return {
+ ok: true,
+ png: grid.png,
+ rendererId: result.rendererId,
+ capture: shape,
+ width: grid.width,
+ height: grid.height,
+ };
} catch (err) {
return { ok: false, reason: err instanceof Error ? err.message : String(err) };
} finally {
diff --git a/src/material-resources.ts b/src/material-resources.ts
index d1b3ffb0..4a56aff4 100644
--- a/src/material-resources.ts
+++ b/src/material-resources.ts
@@ -431,6 +431,47 @@ const materialTextures = (material: THREE.Material): THREE.Texture[] => {
];
};
+/**
+ * Does this scene contain anything a flat-shaded raster cannot honestly show?
+ *
+ * The question a caller actually wants answered is "is `gameMaterial` enough here,
+ * or did the author reach for PBR", and that is NOT recoverable from the material
+ * type: `gameMaterial` and `pbrMaterial` both construct a `MeshStandardMaterial`,
+ * so after construction they are the same object shape. Two signals survive, and
+ * this checks both:
+ *
+ * 1. A bound texture in any of the six slots. Same six {@link materialTextures}
+ * reads, and the same duck-typed `.isTexture` — the sandbox is a different
+ * module realm, so `instanceof THREE.Texture` is always false here.
+ * 2. `metalness > 0`. `gameMaterial` defaults it to 0 and a flat-shaded raster
+ * is at its most wrong exactly on metal, so an untextured chrome or brass
+ * surface has to count even though no texture is bound. Roughness is NOT a
+ * signal: `gameMaterial` sets it by default, so it says nothing about intent.
+ *
+ * Deterministic and read-only: a pure traversal of already-executed scene state,
+ * no clock, no randomness, safe to call from a render path.
+ */
+export function sceneNeedsPbrShading(root: THREE.Object3D): boolean {
+ let needs = false;
+ root.traverse((node) => {
+ if (needs) return;
+ const material = (node as THREE.Mesh).material;
+ const materials = Array.isArray(material) ? material : material ? [material] : [];
+ for (const item of materials) {
+ if (materialTextures(item).length > 0) {
+ needs = true;
+ return;
+ }
+ const metalness = (item as THREE.MeshStandardMaterial).metalness;
+ if (typeof metalness === 'number' && metalness > 0) {
+ needs = true;
+ return;
+ }
+ }
+ });
+ return needs;
+}
+
/** Deterministic scene-side provenance hook for render/wire/provenance integration. */
export function collectMaterialResourceProvenance(
root: THREE.Object3D,
diff --git a/src/tools/__tests__/registry-render-views-port.test.ts b/src/tools/__tests__/registry-render-views-port.test.ts
new file mode 100644
index 00000000..17ae7aa1
--- /dev/null
+++ b/src/tools/__tests__/registry-render-views-port.test.ts
@@ -0,0 +1,243 @@
+/**
+ * In-loop GPU view-render port routing inside `runRenderViews` (the unified
+ * kiln_render tool, `createKilnRenderViewsDef`).
+ *
+ * `sceneNeedsPbrShading` decides whether a scene needs the GPU port at all
+ * (untextured, non-metal geometry never pays the round trip);
+ * `captureViewsViaPort` (../../agent/generate) is the single owner of the port
+ * call, its deadline, and its degrade policy; the CPU rasterizer is always the
+ * fallback — absent port, false predicate, or any port failure. Follows the
+ * port-stubbing pattern in ../../agent/generate.test.ts:260-288.
+ */
+import { describe, expect, test } from 'bun:test';
+
+import {
+ createKilnRenderViewsDef,
+ type InLoopViewRender,
+ type KilnRenderViewsResult,
+ type KilnToolContext,
+} from '../registry';
+import type { PbrRenderPort, PbrRenderRequest } from '../../composer/render-port';
+import {
+ CPU_RASTER_RENDERER_ID,
+ SIX_VIEWS,
+ compositeViewPngGrid,
+ encodePng,
+ renderViewGrid,
+} from '../../views';
+import { executeKilnCode } from '../../render';
+
+const UNTEXTURED_CODE = `
+const meta = { name: 'plain-box', category: 'prop' };
+function build() {
+ const root = createRoot('Root');
+ createPart('Body', boxGeo(1, 1, 1), gameMaterial('#8080ff'), { parent: root });
+ return root;
+}
+`;
+
+// A real, QA-decodable DataTexture (8-bit RGBA, srgb) — an empty `new
+// THREE.Texture()` has no pixel payload and gets blocked by
+// MAT_TEXTURE_DECODE_FAILED before routing is ever reached.
+const TEXTURED_CODE = `
+const meta = { name: 'textured-box', category: 'prop' };
+function build() {
+ const root = createRoot('Root');
+ const mat = gameMaterial('#ffffff');
+ const size = 8;
+ const data = new Uint8Array(size * size * 4);
+ for (let i = 0; i < size * size; i++) {
+ data[i * 4] = 200;
+ data[i * 4 + 1] = 100;
+ data[i * 4 + 2] = 50;
+ data[i * 4 + 3] = 255;
+ }
+ const tex = new THREE.DataTexture(data, size, size, THREE.RGBAFormat, THREE.UnsignedByteType);
+ tex.needsUpdate = true;
+ tex.colorSpace = THREE.SRGBColorSpace;
+ mat.map = tex;
+ createPart('Body', boxGeo(1, 1, 1), mat, { parent: root });
+ return root;
+}
+`;
+
+const METAL_CODE = `
+const meta = { name: 'metal-box', category: 'prop' };
+function build() {
+ const root = createRoot('Root');
+ createPart('Body', boxGeo(1, 1, 1), gameMaterial('#c0c0c0', { metalness: 0.6 }), { parent: root });
+ return root;
+}
+`;
+
+/** 6 solid-color per-view PNGs at the CPU path's default 384px cell size, so a
+ * GPU-composited grid is byte-comparable to what the CPU path would produce
+ * for the same view count/columns. */
+function stubViewPngs(size = 384): Uint8Array[] {
+ return Array.from({ length: 6 }, (_, i) => {
+ const rgb = new Uint8Array(size * size * 3);
+ for (let p = 0; p < size * size; p++) rgb[p * 3] = 20 + i * 30;
+ return new Uint8Array(encodePng(rgb, size, size));
+ });
+}
+
+describe('kiln_render in-loop GPU port routing', () => {
+ test('no port injected: CPU raster runs, onViewsRendered reports cpu-raster:* and degraded:false', async () => {
+ const events: InLoopViewRender[] = [];
+ const def = createKilnRenderViewsDef({ onViewsRendered: (e) => events.push(e) });
+ const out = (await def.run({ code: UNTEXTURED_CODE })) as KilnRenderViewsResult;
+
+ expect(out.ok).toBe(true);
+ expect(out.pngBase64).toBeDefined();
+ expect(events).toHaveLength(1);
+ expect(events[0]!.renderer).toBe(CPU_RASTER_RENDERER_ID);
+ expect(events[0]!.renderer).toMatch(/^cpu-raster:/);
+ expect(events[0]!.degraded).toBe(false);
+ expect(events[0]!.neededPbr).toBe(false);
+ });
+
+ test('port injected + untextured metalness-0 scene: port is never called, CPU still draws', async () => {
+ const events: InLoopViewRender[] = [];
+ const requests: PbrRenderRequest[] = [];
+ const port: PbrRenderPort = async (req) => {
+ requests.push(req);
+ return { ok: true, rendererId: 'gpu:test', viewsPng: stubViewPngs() };
+ };
+ const def = createKilnRenderViewsDef({
+ viewRenderPort: port,
+ onViewsRendered: (e) => events.push(e),
+ });
+ const out = (await def.run({ code: UNTEXTURED_CODE })) as KilnRenderViewsResult;
+
+ expect(out.ok).toBe(true);
+ expect(requests).toHaveLength(0);
+ expect(events).toHaveLength(1);
+ expect(events[0]!.renderer).toBe(CPU_RASTER_RENDERER_ID);
+ expect(events[0]!.degraded).toBe(false);
+ expect(events[0]!.neededPbr).toBe(false);
+ });
+
+ test('port injected + scene with a bound texture: port IS called, its PNG is what comes back', async () => {
+ const viewsPng = stubViewPngs();
+ const events: InLoopViewRender[] = [];
+ const requests: PbrRenderRequest[] = [];
+ const port: PbrRenderPort = async (req) => {
+ requests.push(req);
+ return { ok: true, rendererId: 'dawn-vulkan:test-gpu:1.0', viewsPng };
+ };
+ const def = createKilnRenderViewsDef({
+ viewRenderPort: port,
+ onViewsRendered: (e) => events.push(e),
+ });
+ const out = (await def.run({ code: TEXTURED_CODE })) as KilnRenderViewsResult;
+
+ expect(out.ok).toBe(true);
+ expect(requests).toHaveLength(1);
+ expect(requests[0]!.viewDirs).toHaveLength(6);
+ expect(requests[0]!.size).toBe(384);
+
+ const expected = compositeViewPngGrid(viewsPng, 3, SIX_VIEWS).png;
+ expect(Buffer.compare(Buffer.from(out.pngBase64!, 'base64'), expected)).toBe(0);
+
+ expect(events).toHaveLength(1);
+ expect(events[0]!.renderer).toBe('dawn-vulkan:test-gpu:1.0');
+ expect(events[0]!.degraded).toBe(false);
+ expect(events[0]!.neededPbr).toBe(true);
+ });
+
+ test('port injected + untextured metalness>0 scene: port IS called (the metal case)', async () => {
+ const requests: PbrRenderRequest[] = [];
+ const port: PbrRenderPort = async (req) => {
+ requests.push(req);
+ return { ok: true, rendererId: 'gpu:test', viewsPng: stubViewPngs() };
+ };
+ const def = createKilnRenderViewsDef({ viewRenderPort: port });
+ const out = (await def.run({ code: METAL_CODE })) as KilnRenderViewsResult;
+
+ expect(out.ok).toBe(true);
+ expect(requests).toHaveLength(1);
+ });
+
+ test('port returns ok:false: CPU fallback draws, degraded:true with the reason, result stays ok:true', async () => {
+ const events: InLoopViewRender[] = [];
+ const port: PbrRenderPort = async () => ({
+ ok: false,
+ rendererId: 'gpu:test',
+ error: 'device lost',
+ });
+ const def = createKilnRenderViewsDef({
+ viewRenderPort: port,
+ onViewsRendered: (e) => events.push(e),
+ });
+ const out = (await def.run({ code: TEXTURED_CODE })) as KilnRenderViewsResult;
+
+ expect(out.ok).toBe(true);
+ expect(out.pngBase64).toBeDefined();
+ expect(events).toHaveLength(1);
+ expect(events[0]!.renderer).toBe(CPU_RASTER_RENDERER_ID);
+ expect(events[0]!.degraded).toBe(true);
+ expect(events[0]!.degradedReason).toContain('device lost');
+ expect(events[0]!.neededPbr).toBe(true);
+ });
+
+ test('port throws: falls back to CPU, no throw escapes the tool', async () => {
+ const events: InLoopViewRender[] = [];
+ const port: PbrRenderPort = async () => {
+ throw new Error('GPU service unreachable');
+ };
+ const def = createKilnRenderViewsDef({
+ viewRenderPort: port,
+ onViewsRendered: (e) => events.push(e),
+ });
+ const out = (await def.run({ code: TEXTURED_CODE })) as KilnRenderViewsResult;
+
+ expect(out.ok).toBe(true);
+ expect(out.pngBase64).toBeDefined();
+ expect(events[0]!.degraded).toBe(true);
+ expect(events[0]!.degradedReason).toContain('GPU service unreachable');
+ });
+
+ test('port never resolves: the in-loop deadline trips and falls back to CPU', async () => {
+ const events: InLoopViewRender[] = [];
+ const port: PbrRenderPort = () => new Promise(() => {});
+ const def = createKilnRenderViewsDef({
+ viewRenderPort: port,
+ viewRenderTimeoutMs: 25,
+ onViewsRendered: (e) => events.push(e),
+ });
+ const out = (await def.run({ code: TEXTURED_CODE })) as KilnRenderViewsResult;
+
+ expect(out.ok).toBe(true);
+ expect(out.pngBase64).toBeDefined();
+ expect(events[0]!.degraded).toBe(true);
+ expect(events[0]!.degradedReason).toContain('timed out after 25ms');
+ });
+
+ test('an onViewsRendered callback that throws does not fail the render', async () => {
+ const context: KilnToolContext = {
+ onViewsRendered: () => {
+ throw new Error('host bookkeeping bug');
+ },
+ };
+ const def = createKilnRenderViewsDef(context);
+ const out = (await def.run({ code: UNTEXTURED_CODE })) as KilnRenderViewsResult;
+
+ expect(out.ok).toBe(true);
+ expect(out.pngBase64).toBeDefined();
+ });
+
+ test('GPU path view names and grid dimensions match the CPU path for the same capture config', async () => {
+ const viewsPng = stubViewPngs();
+ const port: PbrRenderPort = async () => ({ ok: true, rendererId: 'gpu:test', viewsPng });
+ const def = createKilnRenderViewsDef({ viewRenderPort: port });
+ const gpuOut = (await def.run({ code: TEXTURED_CODE })) as KilnRenderViewsResult;
+
+ const { root } = await executeKilnCode(TEXTURED_CODE);
+ const cpuGrid = await renderViewGrid(root);
+
+ expect(gpuOut.views).toEqual(cpuGrid.views);
+ expect(gpuOut.gridWidth).toBe(cpuGrid.width);
+ expect(gpuOut.gridHeight).toBe(cpuGrid.height);
+ expect(gpuOut.capture).toEqual(cpuGrid.capture);
+ });
+});
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index efb83275..9a213c9b 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -25,6 +25,9 @@ import { executeKilnCode, inspectSceneStructure, renderSceneToGLB } from '../ren
import { listPrimitives, type PrimitiveSpec } from '../list-primitives';
import type { AssetCategory, AssetIntentV1 } from '../contracts';
import type { AssetQaReportV1 } from '../qa';
+import type { PbrRenderPort } from '../composer/render-port';
+import type { ViewGridResult } from '../views';
+import { sceneNeedsPbrShading } from '../material-resources';
// =============================================================================
// Tool definition contract
@@ -65,8 +68,56 @@ export interface KilnToolDef {
export interface KilnToolContext {
intent?: AssetIntentV1;
category?: AssetCategory;
+ /**
+ * Host-injected GPU renderer for the in-loop view grid. Absent by default, and
+ * absent means every render stays on the CPU rasterizer — byte-identical to the
+ * behavior before this existed.
+ *
+ * The engine never opens a socket itself (AGENTS.md): the host owns the HTTP
+ * adapter, auth, and configuration, and {@link captureViewsViaPort} stays the
+ * single owner of the deadline, PNG validation, grid composition, and the
+ * never-throw CPU fallback. This field is the injection point, nothing more.
+ */
+ viewRenderPort?: PbrRenderPort;
+ /**
+ * Deadline for ONE in-loop port call. Deliberately separate from the deadline
+ * the host uses for the post-loop artifact sheet, and expected to be far
+ * shorter: nothing waits on the artifact sheet, whereas an in-loop render
+ * blocks the agent mid-thought. A slow GPU must fall back to the CPU raster
+ * quickly rather than stall the loop. Defaults to
+ * {@link DEFAULT_INLOOP_VIEW_RENDER_TIMEOUT_MS}.
+ */
+ viewRenderTimeoutMs?: number;
+ /**
+ * Host tally hook, called once per in-loop grid with whoever actually drew it.
+ *
+ * Reporting rides this callback rather than the tool's OUTPUT so the decision
+ * stays invisible to the model's own reasoning, and rides neither the input
+ * schema nor the description so the cached tool definition is untouched (the
+ * program's schema/prompt-invalidation window is reserved — see the P6 rule).
+ * Never throws into the render path: a host callback that throws is swallowed.
+ */
+ onViewsRendered?(event: InLoopViewRender): void;
+}
+
+/** One in-loop grid, and who drew it. Counted by the host, never shown to the model. */
+export interface InLoopViewRender {
+ /** The port's own renderer id when the GPU drew it; `cpu-raster` when it did not. */
+ renderer: string;
+ /** True when a port was injected and did not produce the grid. */
+ degraded: boolean;
+ /** Why the port was bypassed. Only set when `degraded`. */
+ degradedReason?: string;
+ /** Whether the scene held anything a flat raster cannot show (the routing predicate). */
+ neededPbr: boolean;
}
+/**
+ * In-loop port deadline. Well under the engine's post-loop default because the
+ * cost of waiting is completely different here: this one blocks the agent.
+ */
+export const DEFAULT_INLOOP_VIEW_RENDER_TIMEOUT_MS = 6000;
+
function trustedCategory(context: KilnToolContext): AssetCategory | undefined {
return context.intent?.category ?? context.category;
}
@@ -457,7 +508,13 @@ async function runRenderViews(
context: KilnToolContext,
): Promise<KilnRenderViewsResult> {
try {
- const { renderViewGrid } = await import('../views');
+ // `CPU_RASTER_RENDERER_ID` and `resolveGridCapture` come from this SAME lazy
+ // import rather than static ones on purpose. `../views/renderer-id` reads
+ // package.json with `readFileSync` at MODULE LOAD, so a static import would
+ // put a `node:fs` edge — evaluated on import, not on call — into this
+ // module's graph, which is exactly what the lazy `../views` import at the top
+ // of this file exists to prevent.
+ const { renderViewGrid, CPU_RASTER_RENDERER_ID, resolveGridCapture } = await import('../views');
const { root, clips } = await executeKilnCode(input.code);
const category = trustedCategory(context);
@@ -470,7 +527,67 @@ async function runRenderViews(
...(category ? { category } : {}),
...(context.intent ? { intent: context.intent } : {}),
});
- const grid = await renderViewGrid(root, input.capture ? { capture: input.capture } : {});
+
+ // Route to the GPU only when a flat-shaded raster would misrepresent the
+ // scene. A prop made of untextured `gameMaterial` looks the same either way,
+ // so sending it costs a round trip and a warm GPU to draw a picture the CPU
+ // already draws correctly. `renderSceneToGLB` above ALREADY produced the
+ // bytes the port needs — this reuses them rather than paying a second bake.
+ const neededPbr = context.viewRenderPort ? sceneNeedsPbrShading(root) : false;
+ let grid: ViewGridResult | undefined;
+ let drawnBy: InLoopViewRender | undefined;
+
+ if (context.viewRenderPort && neededPbr) {
+ // Lazy import: `../agent/generate` sits upstream of this module in the
+ // agent tool-surface graph (tools/registry <- agent/tools <- agent/surface
+ // <- agent/run <- agent/generate), so a static import of
+ // `captureViewsViaPort` here would be a real runtime import cycle. Loaded
+ // lazily exactly like the `../views` import above.
+ const { captureViewsViaPort } = await import('../agent/generate');
+ const ported = await captureViewsViaPort(
+ context.viewRenderPort,
+ rendered.bytes,
+ context.viewRenderTimeoutMs ?? DEFAULT_INLOOP_VIEW_RENDER_TIMEOUT_MS,
+ input.capture,
+ );
+ if (ported.ok) {
+ // The port reports pixels only, not view names. Derive the same names
+ // the CPU path would report for this capture config through the SAME
+ // resolver both producers share, so the two paths agree on cell order.
+ const resolvedViews = resolveGridCapture(input.capture, process.env['KILN_GRID_VARIANT']);
+ grid = {
+ png: ported.png,
+ views: resolvedViews.views.map((v) => v.name),
+ width: ported.width,
+ height: ported.height,
+ capture: ported.capture,
+ };
+ drawnBy = { renderer: ported.rendererId, degraded: false, neededPbr };
+ } else {
+ drawnBy = {
+ renderer: CPU_RASTER_RENDERER_ID,
+ degraded: true,
+ degradedReason: ported.reason,
+ neededPbr,
+ };
+ }
+ }
+
+ // The CPU path is unchanged and is still what runs for every scene that does
+ // not need PBR, every host with no port, and every port call that did not
+ // come back. It is never skipped as an optimisation — it is the fallback.
+ if (!grid) {
+ grid = await renderViewGrid(root, input.capture ? { capture: input.capture } : {});
+ }
+ drawnBy ??= { renderer: CPU_RASTER_RENDERER_ID, degraded: false, neededPbr };
+
+ // A host bookkeeping hook must never be able to fail a render the model is
+ // waiting on.
+ try {
+ context.onViewsRendered?.(drawnBy);
+ } catch {
+ /* ignore */
+ }
const warnings = [...structuralWarnings, ...rendered.warnings];