3D engine that AI agents drive
Write the part ID from the lit pass instead of a second draw (#478)
Nguyen Xuan An06c4b215a9df
diff --git a/bench/reference/mesh-blend-harness.js b/bench/reference/mesh-blend-harness.jsindex 093bcd81..cac451bf 100644--- a/bench/reference/mesh-blend-harness.js+++ b/bench/reference/mesh-blend-harness.js@@ -67,14 +67,14 @@ window.setupScene = async ({ scene, mode }) => {...(built.shadowBounds ? { shadowBounds: built.shadowBounds } : {}),});if (mode !== 'plain') {- const { installRenderPasses } = await import('/src/render-passes.js');const { installMeshBlend } = await import(/* @vite-ignore */ ['/src/mesh', 'blend.js'].join('-'));- installMeshBlend(installRenderPasses(renderer));+ installMeshBlend(renderer);}+ watch(renderer.context);renderer.resize();- frame = { ...built.camera, environment: { lightDirection: [-3, 6, 4] }, time: 0, exposure: 1, effects: { ambientOcclusion: 0 } };+ frame ={ ...built.camera, environment: { lightDirection: [-3, 6, 4] }, time: 0, exposure: 1, effects: { ambientOcclusion: 0 } };renderer.render(frame);- return { width: canvas.width, height: canvas.height, glError: renderer.context.getError() };+ return { width: canvas.width, height: canvas.height, glError: window.debugFirstError ? 1 : 0, debug: window.debugFirstError };};window.snapshot = () => {@@ -103,4 +103,20 @@ window.teardown = () => {renderer.dispose();renderer = null;};+window.debugFirstError = null;+function watch(context) {+ const proto = Object.getPrototypeOf(context);+ for (const name of Object.getOwnPropertyNames(proto)) {+ if (name === 'getError' || name === 'constructor' || typeof context[name] !== 'function') continue;+ const original = context[name].bind(context);+ context[name] = (...args) => {+ const result = original(...args);+ if (!window.debugFirstError) {+ const error = context.getError();+ if (error) window.debugFirstError = `${name}(${args.map(value => (typeof value === 'number' ? value : typeof value)).join(',')}) -> ${error}`;+ }+ return result;+ };+ }+}window.harnessReady = true;diff --git a/bench/reference/mesh-blend.mjs b/bench/reference/mesh-blend.mjsindex 3ee2a5c1..7b7295b4 100644--- a/bench/reference/mesh-blend.mjs+++ b/bench/reference/mesh-blend.mjs@@ -62,6 +62,28 @@ async function maxDifference(firstPng, secondPng) {return { largest, differing };}+async function measureCost() {+ const times = { plain: [], off: [], on: [] };+ await withPage(resolve('.'), async page => {+ for (let round = 0; round < rounds; round++) {+ for (const [label2, mode] of round % 2 ? [['plain', 'plain'], ['off', 'installed'], ['on', 'blend']] : [['on', 'blend'], ['off', 'installed'], ['plain', 'plain']]) {+ await page.evaluate(options => window.setupScene(options), { scene: 'nature', mode });+ times[label2].push(...await page.evaluate(count => window.measureFrames(count), frames));+ await page.evaluate(() => window.teardown());+ }+ }+ });+ const middle = values => [...values].sort((first, second) => first - second)[Math.floor(values.length / 2)];+ const off = middle(times.off);+ const on = middle(times.on);+ console.log(`1080p frame, ${rounds} rounds x ${frames} frames pooled: no addon ${middle(times.plain).toFixed(3)} ms, off ${off.toFixed(3)} ms, on ${on.toFixed(3)} ms, cost ${(on - off).toFixed(3)} ms`);+}++if (argumentsGiven.includes('--only-cost')) {+ await measureCost();+ process.exit(0);+}+const stills = {};await withPage(resolve('.'), async page => {for (const [scene, mode] of [['nature', 'plain'], ['nature', 'installed'], ['nature', 'blend'], ['lit-box', 'plain'], ['lit-box', 'installed']]) {@@ -138,19 +160,4 @@ tiles.forEach((tile, index) => {await sharp({ create: { width: half * 2, height: (halfHeight + 44) * 2, channels: 3, background: '#14161a' } }).composite(composites).png().toFile(`${output}/478-sheet.png`);console.log(`sheet: ${resolve(output, '478-sheet.png')}`);-if (!argumentsGiven.includes('--skip-cost')) {- const times = { off: [], on: [] };- await withPage(resolve('.'), async page => {- for (let round = 0; round < rounds; round++) {- for (const [label2, mode] of round % 2 ? [['off', 'installed'], ['on', 'blend']] : [['on', 'blend'], ['off', 'installed']]) {- await page.evaluate(options => window.setupScene(options), { scene: 'nature', mode });- times[label2].push(...await page.evaluate(count => window.measureFrames(count), frames));- await page.evaluate(() => window.teardown());- }- }- });- const middle = values => [...values].sort((first, second) => first - second)[Math.floor(values.length / 2)];- const off = middle(times.off);- const on = middle(times.on);- console.log(`1080p frame, ${rounds} rounds x ${frames} frames pooled: off ${off.toFixed(3)} ms, on ${on.toFixed(3)} ms, cost ${(on - off).toFixed(3)} ms`);-}+if (!argumentsGiven.includes('--skip-cost')) await measureCost();diff --git a/changes/478.md b/changes/478.mdindex 4e9e84db..47d4bd20 100644--- a/changes/478.md+++ b/changes/478.md@@ -1 +1 @@-- Add mesh blend (`67js/addons/mesh-blend`, issue #478), a screen-space pass that softens the seam where one mesh cuts into another (a rock sunk into terrain, a trunk into the ground). A part opts in with `blend: { radius }` in metres, as a part option in code or a `blend` field on a recipe node (MCP `set-node` takes it too). The pass finds seams from the object ID render pass (part change), the frame depth (a depth match, so silhouettes against the sky are skipped) and a normal discontinuity rebuilt from the depth, then mixes the other part's colour over the radius. It adds nothing to the core entry and is off unless a part has `blend`: frames of scenes without it are pixel-identical to main (max difference 0 on a lit box and on a nature terrain). It costs one extra object ID draw plus a fullscreen pass; `docs/mesh-blend.md` has the numbers and limits, and `bench/reference/mesh-blend.mjs` renders the before and after still.+- Add mesh blend (`67js/addons/mesh-blend`, issue #478), a screen-space pass that softens the seam where one mesh cuts into another (a rock sunk into terrain, a trunk into the ground). A part opts in with `blend: { radius }` in metres, as a part option in code or a `blend` field on a recipe node (MCP `set-node` takes it too). The pass finds seams from the part ID (a change of part), the frame depth (a depth match, so silhouettes against the sky are skipped) and a normal discontinuity rebuilt from the depth, then mixes the other part's colour over the radius. It adds nothing to the core entry and is off unless a part has `blend`: frames of scenes without it are pixel-identical to main (max difference 0 on a lit box and on a nature terrain). The lit pass writes the part IDs into a second colour attachment (a shader feature that exists only while a part has `blend`), so there is no second draw; `docs/mesh-blend.md` has the numbers and limits, and `bench/reference/mesh-blend.mjs` renders the before and after still.diff --git a/changes/478.size.md b/changes/478.size.mdindex ce0b4c9c..69eaf26a 100644--- a/changes/478.size.md+++ b/changes/478.size.md@@ -1,2 +1,2 @@-- entry:mesh-blend: a new lazy addon, 3,494 bytes gzip (the pass shader, the radius table and the option check); entry:core, scene:lit-box and scene:gltf-box grow 0 B, scene:agent-scene grows 3 B (the `blend` node field name)+- entry:mesh-blend: a new lazy addon, 4,036 bytes gzip (the pass shader, the ID output of the lit pass, the radius table and the option check); entry:core, scene:lit-box and scene:gltf-box grow 0 B, scene:agent-scene grows 3 B (the `blend` node field name)- result:scene_capabilities: one 100-byte line that tells an agent the `blend` node field exists and where its doc isdiff --git a/docs/mesh-blend.md b/docs/mesh-blend.mdindex f565d171..9d844383 100644--- a/docs/mesh-blend.md+++ b/docs/mesh-blend.md@@ -10,25 +10,24 @@ Mark the rocks, trunks and roots, and the terrain too if you want its colour to## How it works-For each pixel of a blend part, the pass looks at 24 taps on a spiral within `radius` (converted to pixels at that distance, 1 to 40 pixels). A tap counts when it shows another part (an object ID differs), its surface point lies within three radii of this pixel (a depth match: a silhouette against the sky or a far wall never counts), and the two surfaces are not parallel (a normal discontinuity, rebuilt from the depth). The share of taps that count, weighted toward the pixel, sets how much of the other part's colour mixes in. It does not blend across a part's own edges.+For each pixel of a blend part, the pass looks at 24 taps on a spiral within `radius` (converted to pixels at that distance, 1 to 40 pixels). A tap counts when it shows another part (an object ID differs), its surface point lies within three radii of this pixel (a depth match: a silhouette against the sky or a far wall never counts), and the two surfaces are not parallel (a normal discontinuity, rebuilt from the depth). The part IDs come from the lit pass itself: while a part has `blend`, the main shader writes the ID into a second colour attachment of the multisample framebuffer (the `meshBlend` shader feature, so a scene without `blend` compiles no extra output), and the stage resolves it. WebGL2 cannot multisample an integer target, so the resolve averages the samples of an edge pixel; the ID is three bytes plus a checksum byte, and an edge pixel that fails the checksum is read as no part (it is already an antialiased mix of both sides). The share of taps that count, weighted toward the pixel, sets how much of the other part's colour mixes in. It does not blend across a part's own edges.## Cost and limits-- One extra draw of the opaque geometry in the object ID mode (the render passes addon draws it), and one fullscreen pass that returns at once for every pixel outside a blend part. Measured on an RTX 3060 at 1080p with 4x MSAA, on a terrain with five sunk rocks and a trunk (median of 6 rounds of 150 frames, other sessions sharing the machine): 2.46 ms without blend, 3.42 ms with it, so about 0.97 ms. Most of that is the extra draw, so it grows with the geometry of the scene and the fullscreen pass stays small.-- Needs a renderer with `depth: true` and `installRenderPasses` first, like line art. The MCP preview does both.-- Opaque and cutout parts only. A blended or transmissive surface has no part ID.+- No second draw of the geometry: the cost is the extra RGBA8 attachment (multisample, resolved) and one fullscreen pass that returns at once for every pixel outside a blend part. Measured with the earlier two-draw version on an RTX 3060 at 1080p (4x MSAA, a terrain with five sunk rocks and a trunk): 2.46 ms without blend, 3.42 ms with it. After the second draw was removed, a clean run was not possible because other jobs held the GPU at 100 percent (frames took 380 to 625 ms even with no addon); in that window the frame with the pass was 1.07 to 1.12 times the frame without it, against 1.39 times for the two-draw version. Run `node bench/reference/mesh-blend.mjs --only-cost` on a quiet GPU for the millisecond cost.+- Needs a renderer with `depth: true`; the render passes addon is not needed. The MCP preview has depth.+- Opaque and cutout parts only. A blended part writes no ID, and translucent water or glass drawn over a blend part leaves that pixel unblended or with a stale ID (the liquid programs do not write the attachment).- A blend part mixes toward the part on the other side of its seam; the other part changes only if it has `blend` too. Marking both gives the soft seam from both sides.- A seam under about one pixel wide (a tiny radius far from the camera) is left alone. The path tracer does not run the pass.-- The part ID is the draw order of opaque instances. A part count above 16 million is not supported (the ID has 24 bits).+- The part ID is the draw order of opaque instances. A batch (one geometry and material) that holds a blend part is drawn without frustum culling or level selection while the pass is on, so its IDs stay in order; a large instanced forest with one blend part pays that. More than 16 million parts is not supported (the ID has 24 bits).- In a recipe, a wrong `blend` value (`radius` outside 0.005 to 2, an unknown field) is reported when the preview draws the frame, with the message of the field.## Code```js-import { installRenderPasses } from '@codepawlhq/67js/addons/render-passes';import { installMeshBlend } from '@codepawlhq/67js/addons/mesh-blend';-const renderer = installMeshBlend(installRenderPasses(new Renderer67(canvas, parts, { depth: true, hdr: true })));+const renderer = installMeshBlend(new Renderer67(canvas, parts, { depth: true, hdr: true }));// parts: [{ name, geometry, material, matrix, blend: { radius: 0.15 } }, ...]```diff --git a/src/mesh-blend.js b/src/mesh-blend.jsindex 0a898204..fb128a6a 100644--- a/src/mesh-blend.js+++ b/src/mesh-blend.js@@ -6,9 +6,11 @@// A pixel of a blend part looks at taps on a spiral within `radius` (in screen pixels at its distance) and counts the taps// that show another part. A tap counts only when its surface point lies within a short reach of this pixel (a depth match:// a silhouette against the sky or a far wall is skipped) and the surfaces do not run parallel (a normal discontinuity,-// rebuilt from the depth). The part IDs come from the object ID render pass, drawn just before the frame; the depth is the-// depth texture of the frame, so the renderer needs `depth: true`, as line art does. Cost: one extra draw of the opaque-// geometry in the ID mode, plus a fullscreen pass that exits early for every pixel outside a blend part.+// rebuilt from the depth). The part IDs are written by the lit pass itself into a second colour attachment (the shader feature+// `meshBlend`, requested only when a part has `blend`), so there is no second draw; the depth is the depth texture of the frame,+// so the renderer needs `depth: true`. Cost: the extra attachment and a fullscreen pass that exits early outside blend parts.++import { registerShaderFeatureCode, shaderTransforms } from './shader-registry.js';export const MESH_BLEND_LIMITS = Object.freeze({ radius: Object.freeze([0.005, 2]) });export const MESH_BLEND_TAPS = Object.freeze({ count: 24, angleStep: 2.39996323 });@@ -66,8 +68,13 @@ uniform float pixelsPerMetre;uniform float orthographic;out vec4 outputColor;ivec2 lastPixel;+// The far depth marks the background. The multisample resolve averages the IDs of an edge pixel into a value that is no ID, so+// the alpha channel carries a checksum of the three ID bytes; a pixel that fails it is an edge pixel and reads as no part.int partAt(ivec2 pixel) {- ivec3 bytes = ivec3(texelFetch(partTexture, clamp(pixel, ivec2(0), lastPixel), 0).rgb * 255.0 + 0.5);+ ivec2 clamped = clamp(pixel, ivec2(0), lastPixel);+ if (texelFetch(sceneDepth, clamped, 0).r >= 1.0) return 0;+ ivec4 bytes = ivec4(texelFetch(partTexture, clamped, 0) * 255.0 + 0.5);+ if (bytes.w != (bytes.x * 3 + bytes.y * 5 + bytes.z * 11) % 251 + 1) return 0;return bytes.x + bytes.y * 256 + bytes.z * 65536;}vec3 positionAt(ivec2 pixel) {@@ -175,22 +182,53 @@ function sameTable(first, second) {return first?.length === second.length && first.every((value, index) => value === second[index]);}+// The main opaque pass writes the part ID into a second colour attachment while this feature is on. The ID is the object ID of the+// render passes (the draw order of opaque instances, plus one) in three bytes, with a checksum byte (WebGL2 has no multisampled+// integer target, so the resolve averages; see partAt). Blended parts write 0: they draw over the opaque pixel without writing depth.+registerShaderFeatureCode('meshBlend', Object.freeze({+ declarations: 'layout(location = 1) out highp vec4 partIdentifier;\n',+ surfaceHook: ` uint partNumber = alphaMode > 1.5 ? 0u : uint(renderPassObjectBase + instanceEmission.w + 1.0);+ uvec3 partBytes = uvec3(partNumber & 255u, (partNumber >> 8) & 255u, partNumber >> 16);+ partIdentifier = vec4(vec3(partBytes), float((partBytes.x * 3u + partBytes.y * 5u + partBytes.z * 11u) % 251u + 1u)) / 255.0;+`,+}));++// With two outputs the colour output needs its own location too, so a source that declares the ID output gets it spelled out.+shaderTransforms.push(source => (source.includes('partIdentifier') ? source.replace('\nout vec4 outputColor;', '\nlayout(location = 0) out vec4 outputColor;') : source));++function createPartTarget(context, width, height) {+ const texture = context.createTexture();+ context.bindTexture(context.TEXTURE_2D, texture);+ context.texImage2D(context.TEXTURE_2D, 0, context.RGBA8, width, height, 0, context.RGBA, context.UNSIGNED_BYTE, null);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.NEAREST);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.NEAREST);+ const framebuffer = context.createFramebuffer();+ context.bindFramebuffer(context.FRAMEBUFFER, framebuffer);+ context.framebufferTexture2D(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.TEXTURE_2D, texture, 0);+ if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) {+ throw new Error('Mesh blend framebuffer allocation failed. Choose a lower quality preset.');+ }+ return { texture, framebuffer };+}+/**- * Adds the seam blend to a renderer. The renderer needs `depth: true` and installRenderPasses first. A part opts in with- * `blend: { radius }`; a frame whose parts have none draws exactly as before.+ * Adds the seam blend to a renderer. The renderer needs `depth: true`. A part opts in with `blend: { radius }`; a frame whose+ * parts have none draws exactly as before (no shader output, no attachment, no pass). With a blend part, the lit pass writes the+ * part IDs into an extra attachment of the multisample framebuffer and the stage resolves it, so there is no second draw.*/export function installMeshBlend(renderer) {if (renderer.meshBlend) return renderer;- if (!renderer.passSupport) throw new Error('Mesh blend needs installRenderPasses(renderer) from 67js/addons/render-passes first.');const state = { active: false, table: null };let program = null;let uniforms = null;let partTarget = null;+ let partRenderbuffer = null;+ let attachedFramebuffer = null;let outputTarget = null;let radiusTexture = null;- function opaqueParts() {- return renderer.batches.filter(batch => renderer.drawsInOpaqueLoop(batch)).flatMap(batch => batch.parts);+ function opaqueBatches() {+ return renderer.batches.filter(batch => renderer.drawsInOpaqueLoop(batch));}function uploadTable(table) {@@ -207,18 +245,50 @@ export function installMeshBlend(renderer) {context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.NEAREST);}- function captureParts() {+ function releasePartAttachment(context) {+ if (partRenderbuffer) context.deleteRenderbuffer(partRenderbuffer);+ if (partTarget) {+ context.deleteTexture(partTarget.texture);+ context.deleteFramebuffer(partTarget.framebuffer);+ }+ partRenderbuffer = null;+ partTarget = null;+ attachedFramebuffer = null;+ }++ // The multisample framebuffer is made again on every resize, so the attachment follows it.+ function attachPartBuffer() {const { context, canvas } = renderer;- partTarget ??= createColorTarget(context, canvas.width, canvas.height, false, context.NEAREST);- context.bindFramebuffer(context.READ_FRAMEBUFFER, renderer.passSupport.framebuffer);+ if (attachedFramebuffer === renderer.multisampleFramebuffer) return;+ releasePartAttachment(context);+ partRenderbuffer = context.createRenderbuffer();+ context.bindRenderbuffer(context.RENDERBUFFER, partRenderbuffer);+ context.renderbufferStorageMultisample(context.RENDERBUFFER, renderer.multisampleSamples, context.RGBA8, canvas.width, canvas.height);+ context.bindFramebuffer(context.FRAMEBUFFER, renderer.multisampleFramebuffer);+ context.framebufferRenderbuffer(context.FRAMEBUFFER, context.COLOR_ATTACHMENT1, context.RENDERBUFFER, partRenderbuffer);+ context.drawBuffers([context.COLOR_ATTACHMENT0, context.NONE]);+ context.bindFramebuffer(context.FRAMEBUFFER, null);+ partTarget = createPartTarget(context, canvas.width, canvas.height);+ renderer.renderTargets.record('partId', { width: canvas.width, height: canvas.height, format: 'RGBA8', samples: renderer.multisampleSamples });+ renderer.renderTargets.record('partIdResolved', { width: canvas.width, height: canvas.height, format: 'RGBA8' });+ attachedFramebuffer = renderer.multisampleFramebuffer;+ }++ // The resolve averages the samples of an edge pixel; the checksum byte in the shader finds those pixels.+ function resolveParts() {+ const { context, canvas } = renderer;+ context.bindFramebuffer(context.READ_FRAMEBUFFER, renderer.multisampleFramebuffer);+ context.readBuffer(context.COLOR_ATTACHMENT1);context.bindFramebuffer(context.DRAW_FRAMEBUFFER, partTarget.framebuffer);context.blitFramebuffer(0, 0, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height, context.COLOR_BUFFER_BIT, context.NEAREST);+ context.readBuffer(context.COLOR_ATTACHMENT0);}function apply(rendererInUse, frame, effects, sourceTexture) {if (!state.active) return null;if (!renderer.depthTexture) throw new Error('Mesh blend requires depth:true on the renderer.');const { context, canvas } = renderer;+ resolveParts();if (!program) {program = compileProgram(context, fullscreenVertex, blendFragment);uniforms = Object.fromEntries(['sourceTexture', 'sceneDepth', 'partTexture', 'radiusTexture', 'inverseViewProjection', 'eye', 'pixelsPerMetre', 'orthographic']@@ -245,13 +315,13 @@ export function installMeshBlend(renderer) {}function releaseTargets(context) {- for (const target of [partTarget, outputTarget]) {- if (!target) continue;- context.deleteTexture(target.texture);- context.deleteFramebuffer(target.framebuffer);+ if (outputTarget) {+ context.deleteTexture(outputTarget.texture);+ context.deleteFramebuffer(outputTarget.framebuffer);}- partTarget = null;outputTarget = null;+ releasePartAttachment(context);+ renderer.renderTargets.release('partId', 'partIdResolved');}function dispose(context) {@@ -263,16 +333,45 @@ export function installMeshBlend(renderer) {state.table = null;}+ // A batch the frustum culls draws its visible instances packed, which renumbers them; a batch with a blend part draws all+ // of its instances in order for the frame, so the part IDs the shader writes stay the table's indices.+ function pinBlendBatches(table) {+ const pinned = [];+ let firstId = 1;+ for (const batch of opaqueBatches()) {+ const hasBlend = table.subarray(firstId, firstId + batch.parts.length).some(radius => radius > 0);+ if (hasBlend && batch.cullable) {+ batch.cullable = false;+ pinned.push(batch);+ }+ firstId += batch.parts.length;+ }+ return pinned;+ }++ // A draw into an enabled draw buffer its program has no output for is an error, and only the main program writes the ID, so+ // the ID attachment is enabled while that program draws into the multisample framebuffer and off for the sky, liquid and others.+ const { context } = renderer;+ const useProgram = context.useProgram.bind(context);+ context.useProgram = program => {+ useProgram(program);+ if (state.active && context.getParameter(context.DRAW_FRAMEBUFFER_BINDING) === renderer.multisampleFramebuffer) {+ context.drawBuffers([context.COLOR_ATTACHMENT0, program === renderer.program ? context.COLOR_ATTACHMENT1 : context.NONE]);+ }+ };+renderer.postStages.push({ name: 'Mesh blend', apply, releaseTargets, dispose });const drawFrame = renderer.render.bind(renderer);renderer.render = frame => {state.active = false;+ let pinned = [];if (frame.pass === undefined && !frame.reflectionTarget && !renderer.benchmark) {- const table = blendRadiusTable(opaqueParts(), renderer.meshBlend.radii);+ const table = blendRadiusTable(opaqueBatches().flatMap(batch => batch.parts), renderer.meshBlend.radii);if (table.some(radius => radius > 0)) {uploadTable(table);- drawFrame({ ...frame, pass: 'objectId' });- captureParts();+ renderer.requireFeatureNames(['meshBlend']);+ attachPartBuffer();+ pinned = pinBlendBatches(table);state.active = true;}}@@ -280,6 +379,7 @@ export function installMeshBlend(renderer) {drawFrame(frame);} finally {state.active = false;+ for (const batch of pinned) batch.cullable = true;}};renderer.meshBlend = { limits: MESH_BLEND_LIMITS, radii: new Map() };diff --git a/tests/mesh-blend.test.js b/tests/mesh-blend.test.jsindex 35c1c1b4..1dcc0ee1 100644--- a/tests/mesh-blend.test.js+++ b/tests/mesh-blend.test.js@@ -118,66 +118,85 @@ function fakeContext() {function fakeRenderer(parts) {const drawn = [];+ const required = [];+ const batch = { parts, cullable: true };const renderer = {context: fakeContext(),canvas: { width: 8, height: 8 },benchmark: false,hdr: true,depthTexture: {},+ multisampleFramebuffer: {},+ multisampleSamples: 4,projection: new Float32Array(16),inverseViewProjection: new Float32Array(16),postStages: [],- passSupport: { framebuffer: {} },- batches: [{ parts }],+ renderTargets: { record() {}, release() {} },+ batches: [batch],+ requireFeatureNames: names => required.push(...names),drawsInOpaqueLoop: () => true,- render: frame => drawn.push(frame),+ render: frame => drawn.push({ frame, cullableWhileDrawing: batch.cullable }),};- return { renderer, drawn };+ return { renderer, drawn, required, batch };}-test('installing needs the render passes addon', () => {- const { renderer } = fakeRenderer([]);- renderer.passSupport = null;- assert.throws(() => installMeshBlend(renderer), /installRenderPasses/);-});--test('with no blend part a frame is drawn once, as given, and the stage does nothing', () => {- const { renderer, drawn } = fakeRenderer([{ name: 'ground' }, { name: 'rock' }]);+test('with no blend part a frame is drawn once, as given, and nothing is added to the renderer', () => {+ const { renderer, drawn, required, batch } = fakeRenderer([{ name: 'ground' }, { name: 'rock' }]);installMeshBlend(renderer);const frame = { eye: [0, 0, 5] };renderer.render(frame);assert.equal(drawn.length, 1);- assert.equal(drawn[0], frame, 'the very same frame object reaches the renderer');+ assert.equal(drawn[0].frame, frame, 'the very same frame object reaches the renderer');+ assert.deepEqual(required, [], 'no shader feature is requested, so the main program keeps its single output');+ assert.equal(drawn[0].cullableWhileDrawing, true);+ assert.equal(batch.cullable, true);assert.equal(renderer.postStages[0].apply(renderer, frame, {}, {}), null);});-test('a blend part adds one object ID draw before the frame, and the stage runs only for that frame', () => {- const { renderer, drawn } = fakeRenderer([{ name: 'ground' }, { name: 'rock', blend: { radius: 0.2 } }]);+test('a blend part needs no extra draw: the frame asks for the ID output and the stage runs for that frame only', () => {+ const { renderer, drawn, required, batch } = fakeRenderer([{ name: 'ground' }, { name: 'rock', blend: { radius: 0.2 } }]);installMeshBlend(renderer);const frame = { eye: [0, 0, 5] };renderer.render(frame);- assert.equal(drawn.length, 2);- assert.equal(drawn[0].pass, 'objectId');- assert.equal(drawn[1], frame);+ assert.equal(drawn.length, 1, 'one draw of the scene, not two');+ assert.equal(drawn[0].frame, frame);+ assert.deepEqual(required, ['meshBlend']);+ assert.equal(drawn[0].cullableWhileDrawing, false, 'a batch with a blend part draws all instances so IDs stay in order');+ assert.equal(batch.cullable, true, 'culling is restored after the frame');assert.equal(renderer.postStages[0].apply(renderer, frame, {}, {}), null, 'the stage is off again after the frame');});test('a radius from the radii map opts a part in like its own blend field', () => {- const { renderer, drawn } = fakeRenderer([{ name: 'ground' }, { name: 'rock' }]);+ const { renderer, required } = fakeRenderer([{ name: 'ground' }, { name: 'rock' }]);installMeshBlend(renderer);renderer.meshBlend.radii = new Map([['rock', 0.2]]);renderer.render({ eye: [0, 0, 5] });- assert.equal(drawn.length, 2);+ assert.deepEqual(required, ['meshBlend']);});test('passes, mirrors and benchmark frames are never blended', () => {- const { renderer, drawn } = fakeRenderer([{ name: 'rock', blend: { radius: 0.2 } }]);+ const { renderer, drawn, required } = fakeRenderer([{ name: 'rock', blend: { radius: 0.2 } }]);installMeshBlend(renderer);renderer.render({ eye: [0, 0, 5], pass: 'normal' });renderer.render({ eye: [0, 0, 5], reflectionTarget: {} });renderer.benchmark = true;renderer.render({ eye: [0, 0, 5] });assert.equal(drawn.length, 3);+ assert.deepEqual(required, []);+});++test('the ID output is a registered shader feature with a checksum and an explicit colour location', async () => {+ const { registeredFeatureCode, shaderTransforms } = await import('../src/shader-registry.js');+ const slots = registeredFeatureCode.get('meshBlend');+ assert.match(slots.declarations, /layout\(location = 1\) out highp vec4 partIdentifier/);+ assert.match(slots.surfaceHook, /renderPassObjectBase \+ instanceEmission\.w \+ 1\.0/);+ assert.match(slots.surfaceHook, /alphaMode > 1\.5 \? 0u/, 'blended parts write no ID');+ const withOutput = '\nout vec4 outputColor;\nvoid main() { partIdentifier = vec4(0.0); }';+ const transformed = shaderTransforms.reduce((text, transform) => transform(text), withOutput);+ assert.match(transformed, /layout\(location = 0\) out vec4 outputColor;/);+ const plain = '\nout vec4 outputColor;\nvoid main() {}';+ assert.equal(shaderTransforms.reduce((text, transform) => transform(text), plain), plain, 'a shader without the ID output is untouched');+ assert.ok(blendFragment.includes('% 251 + 1'), 'the stage checks the same checksum the shader writes');});test('a recipe node takes blend and keeps it through export and set-node', () => {