Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Per-node visible (keyable), castShadow, receiveShadow, holdout and shadowCatcher (issue #606)

Nguyen Xuan An4c54f73098d7
diff --git a/changes/606.md b/changes/606.md
new file mode 100644
index 00000000..38bc2e67
--- /dev/null
+++ b/changes/606.md
@@ -0,0 +1 @@
+- Nodes take visible (keyable in a motion track), castShadow, receiveShadow, holdout and shadowCatcher, so films hide parts without parking them and renders composite over footage (#606)
diff --git a/changes/606.size.md b/changes/606.size.md
new file mode 100644
index 00000000..8c8520f8
--- /dev/null
+++ b/changes/606.size.md
@@ -0,0 +1,15 @@
+- entry:core: per-part receiveShadow, holdout and shadowCatcher need batch state, two uniforms and three shader lines, the first renderer support for hiding a part and compositing over footage (#606).
+- entry:core+lazy: same renderer and shader lines as entry:core.
+- scene:lit-box: same renderer and shader lines as entry:core.
+- scene:lit-box+lazy: same renderer and shader lines as entry:core.
+- scene:gltf-box: same renderer and shader lines as entry:core.
+- scene:gltf-box+lazy: same renderer and shader lines as entry:core.
+- scene:agent-scene: five node fields, a visible motion track, hidden-subtree resolution and part flags (about 650 bytes beyond the renderer): films stop parking hidden parts in the batch list (#423).
+- scene:agent-scene+lazy: same agent-scene lines.
+- goal:lit-box: the renderer lines are the only way to give a part its own shadow and composite behaviour, and hiding or holding out a mesh for a composite is a visible capability.
+- goal:gltf-box: same renderer lines as goal:lit-box.
+- goal:agent-scene: five node fields and the keyed visible track replace a workaround that films used (#423).
+- tool-total: the five node fields appear in every scene tool that takes nodes; the descriptions are one line and the detail sits in scene_capabilities renderFlags.
+- tool:scene_create: the five node fields in the node schema.
+- tool:scene_apply: the five node fields in the node schema, repeated for add-node and set-node.
+- result:scene_capabilities: the renderFlags entry that carries the detail the tool schemas leave out.
diff --git a/docs/agent-scene.md b/docs/agent-scene.md
index 85f67e90..d5f6fb2e 100644
--- a/docs/agent-scene.md
+++ b/docs/agent-scene.md
@@ -307,6 +307,16 @@ An asset placement with a `crowd` field fills its group node with `count` (1 to
Three node fields fix what looks wrong where meshes meet; `add-node` and `set-node` take all of them. `blend: { "radius": 0.15 }` (metres, 0.005 to 2) softens the seam where a rock or trunk cuts into the ground and needs a preview with depth; see [mesh-blend.md](mesh-blend.md). `decal: true` and `depthLayer` (0 to 4) stop z-fighting on flush faces; see `depthBias` in `scene_capabilities`.
+### Visibility and render flags
+
+Five node fields change how a node renders; `add-node` and `set-node` take them, and `scene_capabilities` lists them as `renderFlags`.
+
+- `visible: false` hides the node and every child: nothing is drawn and nothing casts a shadow, but the parts stay in their batches, so a film can cut between shots without parking parts out of view. Key it in a motion track with `{ "kind": "node", "id": "robot", "property": "visible", "keyframes": [{ "time": 0, "value": 1 }, { "time": 2, "value": 0 }] }`; values are 1 or 0 and the track steps by default.
+- `castShadow: false` and `receiveShadow: false` (mesh nodes) stop a mesh casting or receiving shadows. Both default to true; glass casts none unless `castShadow` is set.
+- `holdout: true` writes zero colour and zero alpha where the mesh covers, and still hides what is behind it and still casts its shadow. `shadowCatcher: true` draws only the shadow it receives, black with the shadow as premultiplied alpha, and casts none. Both are for compositing over footage and need a transparent canvas: `new Renderer67(canvas, parts, { transparent: true })`. A node is never both. The shadow catcher shows the sun shadow only.
+
+Parts with different `castShadow`, `receiveShadow`, `holdout` or `shadowCatcher` values batch apart; `visible` never splits a batch. `receiveShadow`, `holdout` and `shadowCatcher` changes need `replaceParts`, not `updateParts`.
+
### Relations between parts
A mesh node can list `relations` that place it against other mesh nodes, so a resized body keeps its handle where it
diff --git a/docs/volumetric.md b/docs/volumetric.md
index d8faf39c..12639f2e 100644
--- a/docs/volumetric.md
+++ b/docs/volumetric.md
@@ -88,7 +88,7 @@ The same option carries a second term, the light that surfaces give the fog. The
The fullscreen march clips against resolved opaque depth, supports perspective and orthographic cameras, and stops at the volume boundary or maximum distance. It integrates Beer-Lambert extinction and directional single scattering with a Henyey-Greenstein phase function. It uses the existing directional shadow map and key-light color. Keep authored shadow bounds aligned with the light direction and covering the medium.
-`part.castShadow: false` excludes a mesh from shadow rendering while keeping it visible and opaque in the color/depth pass. The flag defaults to true and must be boolean. Shadow-casting groups use separate batches. Changing a part's casting regime requires a new renderer. `updateParts()` rejects that change. A luminous window can omit its shadow, but remains an opaque emissive surface rather than transparent glass.
+Parts also take `receiveShadow`, `holdout`, `shadowCatcher` and `visible`; see [agent-scene.md](agent-scene.md#visibility-and-render-flags). `part.castShadow: false` excludes a mesh from shadow rendering while keeping it visible and opaque in the color/depth pass. The flag defaults to true and must be boolean. Shadow-casting groups use separate batches. Changing a part's casting regime requires a new renderer. `updateParts()` rejects that change. A luminous window can omit its shadow, but remains an opaque emissive surface rather than transparent glass.
## Cost and limits
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index fca6ec92..968f3b6f 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -39,6 +39,11 @@ const nodeFields = {
skin: skinSpec.optional(),
decal: z.boolean().optional(),
depthLayer: z.number().int().min(0).max(4).optional(),
+ visible: z.boolean().optional().describe('false hides the node and children; keyable in motion. Flags: scene_capabilities renderFlags.'),
+ castShadow: z.boolean().optional(),
+ receiveShadow: z.boolean().optional(),
+ holdout: z.boolean().optional(),
+ shadowCatcher: z.boolean().optional(),
blend: z.strictObject({ radius: z.number().min(0.005).max(2) }).optional().describe('Soft seam into another mesh, radius in m; docs/mesh-blend.md.'),
label: z.string().max(256).optional().describe('Human-readable label. Identity remains the node ID.'),
parent: identifier.nullable().optional().describe('Parent node ID, or null for a root. Local transforms stay unchanged.'),
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 1d9cd854..14ae3343 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -46,6 +46,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- Layered skeletal animation in code (a clip on some joints only, additive clips, foot planting, reaching, looking at a point) uses `createAssetPose` from `src/skeleton-pose.js` and the checkout's `docs/skeleton-pose.md`. Clip layers are not available through MCP.
- Jointed motion (an arm reaching, a lamp or head tracking a point) on a recipe or an imported character uses `motion.ik`, which needs no quaternions: on a recipe parent the joint nodes and put sizes on child mesh nodes, on an asset find `node-N` IDs with `scene_inspect` kind hierarchy and aim with `worldForward`. Read `motionIk` from `scene_inspect`: besides `reached`, it lists `warnings` (`wrong-bend` when a knee or elbow bends the unnatural way, `hyperextended`) and `limited` (poses a joint limit changed). Give a leg or arm `bendToward` (a world direction, such as `[0, 0, 1]` for a knee on a character facing +z) and `limits` per joint in degrees, and fix any warning before you finish. `motion.constraints` (copy, limit, `track_to`, `child_of`, `floor`, Blender's meanings, Euler XYZ degrees) and `motion.drivers` (a node or material property from a bounded JSON expression) run after IK and give the same pose at any time. On an imported asset, `motion.layers` plays its clips together (a walk layer plus a wave layer masked to `{ "joints": ["node-N"] }` for the arm): list clip ids with `scene_inspect` (`animations`), find joints with kind hierarchy, set `morph: false` on a layer that should not touch the face, and use `bones` to send a clip's track to another node. See "Inverse kinematics", "Clip layers on an asset", "Constraints" and "Drivers" in the checkout's `docs/agent-motion.md`.
- Where meshes meet: a rock or trunk sunk into ground gets node `blend: { "radius": 0.15 }` (soft seam, needs depth, `docs/mesh-blend.md`); flush faces get `decal` or `depthLayer`. A sun-lit closed room bounces sun light on its own; `environment.sunBounce` scales it (0 off). Water over a bed needs `opacity` below one to show the bed, and the bed's shadow fades with depth (`docs/agent-scene.md`).
+- Hide or flag a node without removing it: `visible: false` (also keyable in a motion track, so films stop parking parts at y=-5000), `castShadow`, `receiveShadow`, `holdout` and `shadowCatcher` (transparent canvas, for footage composites); see "Visibility and render flags" in `docs/agent-scene.md`.
- A skeleton-only GLB (`meshes: 0` in `scene_asset_catalog`) cannot be placed, but its clips drive a character through `motion.layers[].from`.
- Agent tool calls use the installed `67js-mcp` stdio server from release `0.5.0` onward. Read `docs/mcp.md` for launch and PNG feedback.
- Agent render jobs use `docs/agent-render-jobs.md`. Check source versus published support, configure a private store and poll until terminal.
diff --git a/src/agent-motion.js b/src/agent-motion.js
index af9ad921..ce6e997c 100644
--- a/src/agent-motion.js
+++ b/src/agent-motion.js
@@ -8,7 +8,8 @@ import { normalizeFootLock } from './foot-lock.js';
import { bounded, denseArray, finite, knownKeys, valueFrom } from './motion-validation.js';
const PROPERTIES = {
- node: { translation: 3, rotation: 4, scale: 3 },
+ // visible is 1 or 0 and defaults to STEP interpolation; a hidden node and its children draw and cast nothing.
+ node: { translation: 3, rotation: 4, scale: 3, visible: 1 },
material: { color: 3, emissiveColor: 3, emission: 1, metallic: 1, roughness: 1 },
camera: { eye: 3, target: 3, fov: 1, roll: 1 },
// An imported asset's morph target weight, addressed by the target's name.
@@ -24,6 +25,9 @@ function validateValue(kind, property, value) {
for (const component of components) {
finite(component, `${kind} ${property}`);
}
+ if (property === 'visible' && components.some(component => component !== 0 && component !== 1)) {
+ throw new RangeError('Motion visible must be 1 (shown) or 0 (hidden).');
+ }
if (property === 'scale' && components.some(component => Math.fround(component) <= 0)) {
throw new RangeError('Motion scale must remain positive at Float32 precision.');
}
@@ -334,7 +338,7 @@ export function normalizeAgentMotion(input, recipe) {
throw new RangeError('Duplicate motion target property.');
}
identities.add(identity);
- const interpolation = track.interpolation ?? 'LINEAR';
+ const interpolation = track.interpolation ?? (track.property === 'visible' ? 'STEP' : 'LINEAR');
if (!INTERPOLATIONS.includes(interpolation)) {
throw new RangeError('Unsupported motion interpolation.');
}
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 982a9f3d..ab3b6ce4 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -228,6 +228,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
choose: 'agx for lit scenes and Blender comparisons, neutral for product and brand colour, aces for contrast; needs loadAgentSceneModules',
}),
// Flush surfaces flicker (z-fighting). scene_inspect and renderer.diagnostics warn with coplanar-overlap; these fix it at draw time.
+ renderFlags: Object.freeze({ nodeFields: Object.freeze(['visible', 'castShadow', 'receiveShadow', 'holdout', 'shadowCatcher']), motion: 'node track property visible: 1 or 0, STEP', note: 'visible:false hides a node and children; holdout and shadowCatcher need a transparent canvas (Renderer67 transparent:true); flags split batches.' }),
depthBias: Object.freeze({ nodeFields: Object.freeze(['decal', 'depthLayer']), maxDepthLayer: 4, environment: 'environment.resolveCoplanar', modes: Object.freeze(['offset']), warning: 'coplanar-overlap', note: 'decal wins over the surface below; depthLayer stacks decals; resolveCoplanar offset biases the smaller part of a flagged pair.' }),
proceduralMotion: true,
motionIk: Object.freeze(['two-bone', 'aim']),
diff --git a/src/agent-scene.js b/src/agent-scene.js
index cdf54644..008f8e42 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -23,7 +23,10 @@ const MAX_MESH_REPORTS = 16;
// Terrain meshes carry one more float for each vertex (sky visibility) than the 56 bytes the budget estimates.
const TERRAIN_SKY_VISIBILITY_BYTES = 4;
const CAMERA_DEFAULTS = Object.freeze({ eye: [4, 3, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 1000 });
-const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material', 'skin', 'relations', 'asset', 'vegetation', 'decal', 'depthLayer', 'blend'];
+// Per-node render flags: `visible` hides a node and its children; the rest become renderer part flags of a mesh node.
+const RENDER_FLAG_FIELDS = ['visible', 'castShadow', 'receiveShadow', 'holdout', 'shadowCatcher'];
+const PART_FLAG_FIELDS = RENDER_FLAG_FIELDS.slice(1);
+const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material', 'skin', 'relations', 'asset', 'vegetation', 'decal', 'depthLayer', 'blend', ...RENDER_FLAG_FIELDS];
const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', 'map', 'subsurface', 'snippet', 'waterPreset', 'absorption', 'turbidity', ...MATERIAL_LAYER_FIELDS];
const PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'emissiveMap', 'boxMapScale', 'boxMapAxis'];
const CAMERA_FIELDS = Object.keys(CAMERA_DEFAULTS);
@@ -309,6 +312,11 @@ function nodeFrom(value) {
if (value.depthLayer !== undefined) {
integer(value.depthLayer, 0, MAXIMUM_DEPTH_LAYER, 'depthLayer');
}
+ for (const flag of RENDER_FLAG_FIELDS) {
+ if (value[flag] !== undefined && typeof value[flag] !== 'boolean') throw new TypeError(`${flag} must be boolean.`);
+ if (flag !== 'visible' && value[flag] !== undefined && value.geometry === undefined) throw new TypeError(`Node ${value.id}: ${flag} belongs on a mesh node.`);
+ }
+ if (value.holdout === true && value.shadowCatcher === true) throw new TypeError(`Node ${value.id}: a node is a holdout or a shadow catcher, not both.`);
if (value.skin !== undefined) {
if (value.geometry === undefined) {
throw new TypeError('Only mesh nodes can have a skin.');
@@ -836,6 +844,7 @@ function cameraPoseFrom(pose) {
// Candidate buffers are private. A failed seek cannot publish half a pose to render handles.
function stagePose(stagedState, time) {
const sampled = time === null ? null : stagedState.motionSampler?.sample(time);
+ const hiddenNodes = hiddenNodeIds(stagedState.recipe, sampled);
// Physics holds its last pose after its duration, so a seek past the end is the resting state.
const simulated = time === null ? null : stagedState.physicsSampler?.sample(Math.min(time, stagedState.physicsSampler.duration));
const graph = stagedState.poseGraph ?? stagedState.graph;
@@ -879,7 +888,7 @@ function stagePose(stagedState, time) {
const clothGeometries = sampledGeometries(stagedState, time);
// Staged last: a pose pending on a decoded asset must be committed or discarded, so nothing above may throw after it.
const assetClips = stagedState.assetRuntime.animators.length ? agentSceneModule('assets').stageAssetClips(stagedState.assetRuntime, graph, time) : null;
- return { graph, materialUpdates, camera, time, clothGeometries, assetClips };
+ return { graph, materialUpdates, camera, time, clothGeometries, assetClips, hiddenNodes };
}
// Cloth and particles replace the geometry of their own nodes at a sampled time; no node belongs to both.
@@ -894,6 +903,38 @@ function sampledGeometries(stagedState, time) {
return geometries.size ? geometries : null;
}
+function partFlagsOf(node) {
+ return Object.fromEntries(PART_FLAG_FIELDS.filter(flag => node[flag] !== undefined).map(flag => [flag, node[flag]]));
+}
+
+function sameRenderFlags(part, node, usesVisibility, assetExtras) {
+ return PART_FLAG_FIELDS.every(flag => part[flag] === (node[flag] ?? assetExtras?.[flag])) && Boolean(part.visibility) === usesVisibility;
+}
+
+function recipeUsesVisibility(recipe) {
+ return recipe.nodes.some(node => node.visible !== undefined) || Boolean(recipe.motion?.tracks?.some(track => track.kind === 'node' && track.property === 'visible'));
+}
+
+/** Node IDs hidden at a pose: a node set invisible by its field or a sampled track, and everything under it. */
+function hiddenNodeIds(recipe, sampled) {
+ const hidden = new Set();
+ if (!recipeUsesVisibility(recipe)) return hidden;
+ const byId = new Map(recipe.nodes.map(node => [node.id, node]));
+ const hiddenOwn = node => {
+ const keyed = sampled?.nodes.get(node.id)?.visible;
+ return keyed === undefined ? node.visible === false : keyed < 0.5;
+ };
+ for (const node of recipe.nodes) {
+ for (let cursor = node, depth = 0; cursor && depth < 256; cursor = byId.get(cursor.parent), depth++) {
+ if (hiddenOwn(cursor)) {
+ hidden.add(node.id);
+ break;
+ }
+ }
+ }
+ return hidden;
+}
+
// Cloth keeps one geometry per sheet that every sample rewrites, so the parts of a later seek are the previous ones and the
// renderer sees no topology change. Particles still bring a new geometry per time, so those parts are replaced.
function partsWithCloth(restParts, clothGeometries, previousParts) {
@@ -910,6 +951,7 @@ function partsWithCloth(restParts, clothGeometries, previousParts) {
/** Returns true when the parts handed to a renderer changed, which the caller counts as a topology change. */
function publishPose(stagedState, pose) {
for (const part of stagedState.restParts) {
+ if (part.visibility) part.visibility.visible = !pose.hiddenNodes.has(part.name);
Float32Array.prototype.set.call(part.matrix, pose.graph.getNode(part.name).worldMatrix);
}
for (const update of pose.materialUpdates) {
@@ -1119,6 +1161,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
}
const activeParts = new Map(state?.sourceRestParts.map(part => [part.name, part]) ?? []);
const preferredParts = new Map(preferred?.sourceRestParts.map(part => [part.name, part]) ?? []);
+ const usesVisibility = recipeUsesVisibility(recipe);
const nextParts = recipe.nodes.filter(node => node.geometry !== undefined).map(node => {
const binding = skinBindings.get(node.id);
const geometry = binding?.geometry ?? geometries.get(node.geometry);
@@ -1126,10 +1169,13 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
const assetExtras = assetRuntime.partExtras.get(node.id);
const activePart = removedNodes.has(node.id) ? null : activeParts.get(node.id);
const existing = [activePart, preferredParts.get(node.id)]
- .find(part => part?.geometry === geometry && part.material === material && part.skin === (assetExtras?.skin ?? binding?.skin) && part.morph === assetExtras?.morph && depthLayerOf(part) === depthLayerOf(node));
+ .find(part => part?.geometry === geometry && part.material === material && part.skin === (assetExtras?.skin ?? binding?.skin) && part.morph === assetExtras?.morph && depthLayerOf(part) === depthLayerOf(node) && sameRenderFlags(part, node, usesVisibility, assetExtras));
return existing ?? Object.freeze({
name: node.id, geometry, material,
...(depthLayerOf(node) ? { depthLayer: depthLayerOf(node) } : {}),
+ ...partFlagsOf(node),
+ // The renderer reads this holder every update, and publishPose rewrites it for each pose.
+ ...(usesVisibility ? { visibility: { visible: true } } : {}),
matrix: new Float32Array(graph.getNode(node.id).worldMatrix),
...(binding ? { skin: binding.skin } : {}),
...assetExtras,
diff --git a/src/renderer.js b/src/renderer.js
index 65bd9a19..4ecbed73 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -217,10 +217,28 @@ function materialAlphaState(material) {
// Larger layers win over smaller ones; geometry never moves.
// Translucent glass and additive light are not shadow casters unless the part asks for it.
+// A shadow catcher only shows the shadow it receives, so it never casts one unless the part asks for it.
function castsShadow(part) {
- return part.castShadow ?? !isTranslucentMode(part.material.alphaMode ?? 'opaque');
+ return part.castShadow ?? !(part.shadowCatcher === true || isTranslucentMode(part.material.alphaMode ?? 'opaque'));
}
+const receivesShadow = part => part.receiveShadow !== false;
+
+// Uniform value of a batch: 0 draws normally, 1 is a holdout (zero colour, zero alpha), 2 is a shadow catcher (black, alpha = shadow).
+const compositeModeOf = part => (part.holdout === true ? 1 : part.shadowCatcher === true ? 2 : 0);
+
+const BOOLEAN_PART_FLAGS = ['castShadow', 'receiveShadow', 'holdout', 'shadowCatcher', 'visible'];
+
+function validatePartFlags(part) {
+ for (const flag of BOOLEAN_PART_FLAGS) {
+ if (part[flag] !== undefined && typeof part[flag] !== 'boolean') throw new TypeError(`${flag} must be a boolean`);
+ }
+ if (part.holdout === true && part.shadowCatcher === true) throw new Error(`A part is a holdout or a shadow catcher, not both: ${part.name}`);
+}
+
+/** A hidden part keeps its slot in the batch but draws and casts nothing: its instance matrices are packed as zeros. */
+const isHidden = part => part.visible === false || part.visibility?.visible === false;
+
function hasMaterialMap(material) {
return MATERIAL_MAPS.some(field => material[field]);
}
@@ -268,8 +286,12 @@ function copyVector3(target, offset, source) {
function packInstance(data, index, part, normalMatrix) {
const offset = index * INSTANCE_STRIDE;
const material = part.material;
- data.set(part.matrix, offset);
- data.set(normalMatrix, offset + 16);
+ if (isHidden(part)) {
+ data.fill(0, offset, offset + 25);
+ } else {
+ data.set(part.matrix, offset);
+ data.set(normalMatrix, offset + 16);
+ }
copyVector3(data, offset + 25, material.color);
data[offset + 28] = material.metallic;
data[offset + 29] = material.roughness;
@@ -366,7 +388,7 @@ export function groupParts(parts, batching = true) {
const morphInfos = new Map();
for (const part of parts) {
validateTransform(part);
- if (part.castShadow !== undefined && typeof part.castShadow !== 'boolean') throw new TypeError('castShadow must be a boolean');
+ validatePartFlags(part);
if (hasSkinData(part)) {
const { validateSkinGeometry, validateSkinPose } = skinSupport();
validateSkinGeometry(part.geometry, part.skin);
@@ -383,7 +405,7 @@ export function groupParts(parts, batching = true) {
const key = batching ? part.geometry : part;
if (!groups.has(key)) groups.set(key, new Map());
let maps = groups.get(key);
- for (const value of [...materialMapState(part.material), ...materialLayerState(part.material), part.skin ?? null, part.material.snippet, part.crowd ?? null, part.morph ?? null, castsShadow(part), depthLayerOf(part), renderPass(part.material), part.lods ?? null, part.shadowLods ?? null, ...materialAlphaState(part.material)]) {
+ for (const value of [...materialMapState(part.material), ...materialLayerState(part.material), part.skin ?? null, part.material.snippet, part.crowd ?? null, part.morph ?? null, castsShadow(part), receivesShadow(part), compositeModeOf(part), depthLayerOf(part), renderPass(part.material), part.lods ?? null, part.shadowLods ?? null, ...materialAlphaState(part.material)]) {
if (!maps.has(value)) maps.set(value, new Map());
maps = maps.get(value);
}
@@ -757,7 +779,7 @@ export class Renderer67 {
finishMainProgram(pendingProgram) {
this.program = finishProgram(this.context, pendingProgram);
- this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'materialAnisotropy', 'materialIridescence', 'lightLinkMask', 'boxMapScale', 'boxMapAxis', 'lightMap', 'lightMapScale', 'hasLightMap', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'shadowBiasPerSlope', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', 'baseColor', 'surface', 'instanceEmission', 'instanceOpacity', 'boxNormalMatrix', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
+ this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'materialAnisotropy', 'materialIridescence', 'lightLinkMask', 'boxMapScale', 'boxMapAxis', 'lightMap', 'lightMapScale', 'hasLightMap', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'shadowBiasPerSlope', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', 'baseColor', 'surface', 'instanceEmission', 'instanceOpacity', 'boxNormalMatrix', 'shadowBlind', 'compositeMode', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
for (const name of LIGHT_UNIFORMS) {
this.uniforms[name] = this.context.getUniformLocation(this.program, name);
}
@@ -1061,7 +1083,7 @@ export class Renderer67 {
const [alphaMode, alphaCutoff, opacity, doubleSided] = materialAlphaState(parts[0].material);
const layerState = materialLayerState(parts[0].material);
const culling = this.createCullingState(parts);
- const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, lightMapTexture, texture: textures[0], map, skin, skinTexture, influenceTexture, crowd, crowdTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), depthLayer: depthLayerOf(parts[0]), pass: renderPass(parts[0].material) };
+ const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, lightMapTexture, texture: textures[0], map, skin, skinTexture, influenceTexture, crowd, crowdTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), receivesShadow: receivesShadow(parts[0]), compositeMode: compositeModeOf(parts[0]), depthLayer: depthLayerOf(parts[0]), pass: renderPass(parts[0].material) };
if (parts[0].lods) culling.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level));
culling.shadowLevels?.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level, batch.shadowLevels));
parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, layerState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));
@@ -1088,7 +1110,7 @@ export class Renderer67 {
const mapState = materialMapState(first.material);
const sameParts = batch?.parts.length === group.length && batch.parts.every((part, index) => part === group[index]);
const alphaState = materialAlphaState(first.material);
- const sameState = location?.geometry === first.geometry && batch?.castShadow === castsShadow(first) && (batch.depthLayer ?? 0) === depthLayerOf(first) &&
+ const sameState = location?.geometry === first.geometry && batch?.castShadow === castsShadow(first) && batch.receivesShadow === receivesShadow(first) && batch.compositeMode === compositeModeOf(first) && (batch.depthLayer ?? 0) === depthLayerOf(first) &&
batch.floor === (first.material.tag === 'floor') && batchPass(batch) === renderPass(first.material) &&
[batch.alphaMode, batch.alphaCutoff, batch.opacity, batch.doubleSided].every((value, index) => value === alphaState[index]) &&
batch.mapState.every((value, index) => value === mapState[index]) &&
@@ -1248,8 +1270,9 @@ export class Renderer67 {
if (!location) throw new Error(`Unknown part identity: ${part.name}`);
locations[partIndex] = location;
if (part.skin || part.morph) this.updatePartIdentities.add(part);
- if (part.castShadow !== undefined && typeof part.castShadow !== 'boolean') throw new TypeError('castShadow must be a boolean');
+ validatePartFlags(part);
if (castsShadow(part) !== location.batch.castShadow) throw new Error(`Shadow casting changes require a new renderer: ${part.name}`);
+ if (receivesShadow(part) !== location.batch.receivesShadow || compositeModeOf(part) !== location.batch.compositeMode) throw new Error(`receiveShadow, holdout and shadowCatcher changes require replaceParts: ${part.name}`);
if (depthLayerOf(part) !== (location.batch.depthLayer ?? 0)) throw new Error(`depthLayer changes require replaceParts: ${part.name}`);
// A material whose fields still equal the ones that passed the full checks below needs none of them again.
const materialUnchanged = location.materialSnapshot?.matches(part.material) === true;
@@ -2090,6 +2113,8 @@ export class Renderer67 {
}
}
if (textured && !this.benchmark) {
+ this.context.uniform1f(this.uniforms.shadowBlind, batch.receivesShadow === false ? 1 : 0);
+ this.context.uniform1f(this.uniforms.compositeMode, batch.compositeMode ?? 0);
for (let index = 0; index < MATERIAL_MAPS.length; index++) {
this.context.activeTexture(this.context.TEXTURE0 + index + 1);
this.context.bindTexture(this.context.TEXTURE_2D, batch.textures[index]);
diff --git a/src/shaders.js b/src/shaders.js
index f32973dc..6acf8fb8 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -304,6 +304,8 @@ uniform float alphaCutoff;
uniform float materialOpacity;
uniform float alphaToCoverage;
uniform float doubleSided;
+uniform float shadowBlind;
+uniform float compositeMode;
out vec4 outputColor;
const float PI = 3.14159265359;
@@ -618,7 +620,7 @@ ${featureCode("mainSetup")} if (ENVIRONMENT_ENABLED && !LIGHT_SHADING) {
vec2 brdfLookup = texture(environmentBrdf, vec2(clamp(dot(normal, viewDirection), 0.001, 1.0), roughness)).rg;
directSpecularGain = multipleScatterGain(brdfLookup, baseReflectance);
}
- float visibility = shadowVisibility(normal);
+ float visibility = shadowBlind > 0.5 ? 1.0 : shadowVisibility(normal);
${featureCode("worldVisibility")} vec3 radiance = illuminate(normal, viewDirection, normalize(lightDirection), keyColor * visibility${featureCode("linkSun")}, color, metallic, roughness);
if (FILL_ON) {
radiance += illuminate(normal, viewDirection, normalize(vec3(4.0, 2.0, -3.0)), mix(vec3(0.8, 2.0, 1.8), vec3(0.12, 0.17, 0.20) * daylight, worldMode) * fillIntensity * mix(1.0, vertexSkyVisibility, worldMode), color, metallic, roughness);
@@ -634,7 +636,7 @@ ${featureCode("worldVisibility")} vec3 radiance = illuminate(normal, viewDirect
${featureCode("linkPoint")} vec3 lightRadiance = pointLightColors[index].rgb * pointLightColors[index].w * attenuation;
if (USES_LOCAL_SHADOWS && pointLightShadowTiles[index] >= 0.0) {
float tile = pointLightShadowTiles[index] + pointShadowFace(-offset);
- lightRadiance *= localShadowVisibility(tile, worldPosition, normal, sqrt(distanceSquared));
+ lightRadiance *= shadowBlind > 0.5 ? 1.0 : localShadowVisibility(tile, worldPosition, normal, sqrt(distanceSquared));
}
radiance += illuminate(normal, viewDirection, offset * inversesqrt(distanceSquared), lightRadiance, color, metallic, roughness);
}
@@ -652,7 +654,7 @@ ${featureCode("linkPoint")} vec3 lightRadiance = pointLightColors[index].rgb
if (attenuation == 0.0) continue;
${featureCode("linkSpot")} vec3 lightRadiance = spotLightColors[index].rgb * spotLightColors[index].w * attenuation;
if (USES_LOCAL_SHADOWS && spotLightParameters[index].z >= 0.0) {
- lightRadiance *= localShadowVisibility(spotLightParameters[index].z, worldPosition, normal, sqrt(distanceSquared));
+ lightRadiance *= shadowBlind > 0.5 ? 1.0 : localShadowVisibility(spotLightParameters[index].z, worldPosition, normal, sqrt(distanceSquared));
}
radiance += illuminate(normal, viewDirection, toLight, lightRadiance, color, metallic, roughness);
}
@@ -727,6 +729,8 @@ ${featureCode("worldFinal")} float fog = 1.0 - exp(-length(worldPosition - eye)
vec3 result = floorColor * (0.72 + 0.28 * visibility) * contact;
outputColor = vec4(hdrEnabled > 0.5 ? pow(result, vec3(2.2)) : result, 1.0);
}
+ // Holdout: nothing, not even alpha. Shadow catcher: black with the shadow it receives as premultiplied alpha.
+ if (compositeMode > 0.5) outputColor = compositeMode < 1.5 ? vec4(0.0) : vec4(0.0, 0.0, 0.0, 1.0 - visibility);
}`;
}
diff --git a/tests/morph-renderer.test.js b/tests/morph-renderer.test.js
index b2130b2f..1113e486 100644
--- a/tests/morph-renderer.test.js
+++ b/tests/morph-renderer.test.js
@@ -32,7 +32,7 @@ function retainedRenderer(parts) {
morphWeights: new Float32Array(first.morph.weights),
instanceBuffer: {},
instanceData: new Float32Array(group.length * 42),
- castShadow: true,
+ castShadow: true, receivesShadow: true, compositeMode: 0,
alphaMode: 'opaque',
alphaCutoff: 0,
opacity: 1,
diff --git a/tests/render-flags-scene.test.js b/tests/render-flags-scene.test.js
new file mode 100644
index 00000000..dbed9ffe
--- /dev/null
+++ b/tests/render-flags-scene.test.js
@@ -0,0 +1,92 @@
+// Per-node render flags (issue 606): visible keyed in a motion track, and the flags reaching the renderer parts.
+import './support/load-agent-scene-modules.mjs';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createAgentScene } from '../src/agent-scene.js';
+import { groupParts } from '../src/renderer.js';
+
+function recipe(overrides = {}) {
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box', bevel: 0 }],
+ materials: [{ id: 'finish', color: [0.2, 0.4, 0.6], emission: 0 }],
+ nodes: [
+ { id: 'group' },
+ { id: 'first', parent: 'group', geometry: 'box', material: 'finish' },
+ { id: 'second', geometry: 'box', material: 'finish', translation: [2, 0, 0] },
+ ],
+ camera: { eye: [4, 3, 5], target: [0, 0, 0] },
+ ...overrides,
+ };
+}
+
+const visibleTrack = { kind: 'node', id: 'group', property: 'visible', keyframes: [
+ { time: 0, value: 1 }, { time: 1, value: 0 }, { time: 2, value: 1 },
+] };
+
+function hiddenNames(scene) {
+ return scene.parts.filter(part => part.visibility?.visible === false).map(part => part.name);
+}
+
+test('a visible track hides a node and its children from the keyed time, with the same parts', () => {
+ const scene = createAgentScene(recipe({ motion: { duration: 2, tracks: [visibleTrack] } }));
+ const parts = scene.parts;
+ assert.deepEqual(hiddenNames(scene), []);
+ scene.sampleMotion(1.5);
+ assert.deepEqual(hiddenNames(scene), ['first']);
+ scene.sampleMotion(0.5);
+ assert.deepEqual(hiddenNames(scene), []);
+ scene.sampleMotion(2);
+ assert.deepEqual(hiddenNames(scene), []);
+ scene.sampleMotion(1);
+ assert.deepEqual(hiddenNames(scene), ['first']);
+ assert.equal(scene.parts, parts, 'a keyed visibility is not a topology change');
+});
+
+test('a static visible:false node is hidden and a track can show it again', () => {
+ const hidden = createAgentScene(recipe({ nodes: [{ id: 'only', geometry: 'box', material: 'finish', visible: false }] }));
+ assert.deepEqual(hiddenNames(hidden), ['only']);
+ const keyed = createAgentScene(recipe({
+ nodes: [{ id: 'only', geometry: 'box', material: 'finish', visible: false }],
+ motion: { duration: 1, tracks: [{ kind: 'node', id: 'only', property: 'visible', keyframes: [{ time: 0, value: 0 }, { time: 0.5, value: 1 }] }] },
+ }));
+ assert.deepEqual(hiddenNames(keyed), ['only']);
+ keyed.sampleMotion(0.75);
+ assert.deepEqual(hiddenNames(keyed), []);
+});
+
+test('scenes that never use visibility add no part fields', () => {
+ const scene = createAgentScene(recipe());
+ for (const part of scene.parts) {
+ assert.deepEqual(Object.keys(part).sort(), ['geometry', 'material', 'matrix', 'name']);
+ }
+});
+
+test('shadow and composite flags reach the part and split batches', () => {
+ const scene = createAgentScene(recipe({ nodes: [
+ { id: 'plain', geometry: 'box', material: 'finish' },
+ { id: 'blind', geometry: 'box', material: 'finish', receiveShadow: false },
+ { id: 'quiet', geometry: 'box', material: 'finish', castShadow: false },
+ { id: 'cut', geometry: 'box', material: 'finish', holdout: true },
+ { id: 'catcher', geometry: 'box', material: 'finish', shadowCatcher: true },
+ { id: 'other', geometry: 'box', material: 'finish' },
+ ] }));
+ const byName = new Map(scene.parts.map(part => [part.name, part]));
+ assert.equal(byName.get('blind').receiveShadow, false);
+ assert.equal(byName.get('quiet').castShadow, false);
+ assert.equal(byName.get('cut').holdout, true);
+ assert.equal(byName.get('catcher').shadowCatcher, true);
+ assert.equal(byName.get('plain').holdout, undefined);
+ const batches = groupParts(scene.parts).map(batch => batch.map(part => part.name).sort());
+ assert.equal(batches.length, 5, 'plain and other share a batch, each flag gets its own');
+ assert.ok(batches.some(names => names.join() === 'other,plain'));
+});
+
+test('flags must be booleans on mesh nodes and a node is not both holdout and catcher', () => {
+ const node = fields => recipe({ nodes: [{ id: 'one', geometry: 'box', material: 'finish', ...fields }] });
+ assert.throws(() => createAgentScene(node({ castShadow: 'no' })), /castShadow must be boolean/);
+ assert.throws(() => createAgentScene(node({ visible: 0 })), /visible must be boolean/);
+ assert.throws(() => createAgentScene(node({ holdout: true, shadowCatcher: true })), /not both/);
+ assert.throws(() => createAgentScene(recipe({ nodes: [{ id: 'g', holdout: true }] })), /belongs on a mesh node/);
+ assert.throws(() => createAgentScene(recipe({ motion: { duration: 1, tracks: [{ kind: 'node', id: 'first', property: 'visible', keyframes: [{ time: 0, value: 0.5 }] }] } })), /1 \(shown\) or 0/);
+});
diff --git a/tests/render-flags.test.js b/tests/render-flags.test.js
new file mode 100644
index 00000000..ba4450e2
--- /dev/null
+++ b/tests/render-flags.test.js
@@ -0,0 +1,129 @@
+// Per-part render flags (issue 606) drawn for real: visible, castShadow, receiveShadow, holdout and shadowCatcher.
+// It draws in headless Chrome (SwiftShader, no GPU) from the Vite dev server, and skips when Chrome cannot start.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { freePort } from './helpers/free-port.js';
+
+async function startServer(port) {
+ const server = spawn(process.execPath, ['node_modules/vite/bin/vite.js', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
+ await new Promise((resolve, reject) => {
+ const timeout = setTimeout(() => reject(new Error('The dev server did not start.')), 30000);
+ server.stdout.on('data', (data) => {
+ if (/ready in/.test(data.toString())) {
+ clearTimeout(timeout);
+ resolve();
+ }
+ });
+ server.on('exit', (code) => {
+ clearTimeout(timeout);
+ reject(new Error(`The dev server exited ${code}.`));
+ });
+ });
+ return server;
+}
+
+// A floor and a caster above it, drawn on a transparent canvas. Each scenario changes flags on one or both parts.
+async function drawScenarios(page, scenarios) {
+ const task = async (list) => {
+ const { box } = await import('/src/geometry.js');
+ const { Renderer67 } = await import('/src/renderer.js');
+ const canvas = document.createElement('canvas');
+ canvas.width = 96;
+ canvas.height = 96;
+ document.body.append(canvas);
+ const copy = document.createElement('canvas');
+ copy.width = 96;
+ copy.height = 96;
+ const copyContext = copy.getContext('2d', { willReadFrequently: true });
+ const geometry = box(0, 1);
+ const material = color => ({ tag: 'surface', color, metallic: 0, roughness: 0.7, emission: 0 });
+ const scaled = (sx, sy, sz, x, y, z) => new Float32Array([sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, sz, 0, x, y, z, 1]);
+ const results = [];
+ for (const scenario of list) {
+ const parts = [
+ { name: 'floor', geometry, matrix: scaled(8, 0.2, 8, 0, -0.1, 0), material: material([0.8, 0.8, 0.8]), ...scenario.floor },
+ { name: 'caster', geometry, matrix: scaled(1.4, 1.4, 1.4, 0, 2, 0), material: material([0.9, 0.2, 0.2]), ...scenario.caster },
+ ];
+ const renderer = new Renderer67(canvas, parts, { ground: false, samples: 1, pixelRatio: 1, transparent: true });
+ renderer.render({ eye: [0, 6, 6], target: [0, 0, 0] });
+ copyContext.clearRect(0, 0, 96, 96);
+ copyContext.drawImage(canvas, 0, 0, 96, 96);
+ results.push(Array.from(copyContext.getImageData(0, 0, 96, 96).data));
+ renderer.dispose?.();
+ }
+ return results;
+ };
+ return page.evaluate(task, scenarios);
+}
+
+function opaquePixels(image) {
+ let count = 0;
+ for (let index = 3; index < image.length; index += 4) if (image[index] > 0) count++;
+ return count;
+}
+
+function differingPixels(first, second) {
+ let count = 0;
+ for (let index = 0; index < first.length; index += 4) {
+ if (Math.abs(first[index] - second[index]) + Math.abs(first[index + 1] - second[index + 1]) + Math.abs(first[index + 2] - second[index + 2]) + Math.abs(first[index + 3] - second[index + 3]) > 6) count++;
+ }
+ return count;
+}
+
+test('visible, castShadow, receiveShadow, holdout and shadowCatcher draw as documented', async (context) => {
+ let chromium;
+ try {
+ ({ chromium } = await import('playwright'));
+ } catch {
+ context.skip('playwright is not installed');
+ return;
+ }
+ const port = await freePort();
+ const server = await startServer(port);
+ let browser;
+ try {
+ try {
+ browser = await chromium.launch({ headless: true, args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'] });
+ } catch (error) {
+ context.skip(`Chrome did not start: ${error.message.split('\n')[0]}`);
+ return;
+ }
+ const page = await browser.newPage({ viewport: { width: 96, height: 96 } });
+ await page.goto(`http://127.0.0.1:${port}/`);
+ const names = ['plain', 'noCaster', 'hiddenCaster', 'holdoutCaster', 'holdoutNoCast', 'holdoutBlindFloor', 'catcherLit', 'catcherNoCaster', 'hiddenAll'];
+ const images = await drawScenarios(page, [
+ { floor: {}, caster: {} },
+ { floor: {}, caster: { holdout: true } },
+ { floor: {}, caster: { visible: false } },
+ { floor: {}, caster: { holdout: true } },
+ { floor: {}, caster: { holdout: true, castShadow: false } },
+ { floor: { receiveShadow: false }, caster: { holdout: true } },
+ { floor: { shadowCatcher: true }, caster: { holdout: true } },
+ { floor: { shadowCatcher: true }, caster: { visible: false } },
+ { floor: { visible: false }, caster: { visible: false } },
+ ]);
+ const image = Object.fromEntries(names.map((name, index) => [name, images[index]]));
+ assert.ok(opaquePixels(image.plain) > 3000, 'the plain scene draws the floor and the caster');
+ assert.equal(opaquePixels(image.hiddenAll), 0, 'visible:false parts draw nothing');
+ assert.ok(opaquePixels(image.holdoutCaster) < opaquePixels(image.hiddenCaster) + 1, 'a holdout writes zero alpha');
+ assert.ok(differingPixels(image.plain, image.hiddenCaster) > 150, 'the caster is visible in the plain scene');
+ // A holdout still occludes: the floor behind its footprint is gone, but its shadow stays unless castShadow is false.
+ assert.ok(differingPixels(image.holdoutCaster, image.hiddenCaster) > 150, 'a holdout erases the floor behind it and keeps casting');
+ assert.ok(differingPixels(image.holdoutCaster, image.holdoutNoCast) > 30, 'castShadow:false removes the shadow');
+ assert.ok(differingPixels(image.holdoutNoCast, image.holdoutBlindFloor) < 5, 'no caster shadow and a blind floor draw the same');
+ assert.ok(differingPixels(image.holdoutCaster, image.holdoutBlindFloor) > 30, 'receiveShadow:false removes the shadow on the floor');
+ // A hidden caster casts no shadow either: its scene equals the one whose caster is a holdout that does not cast.
+ const hiddenNoShadow = differingPixels(image.hiddenCaster, image.holdoutNoCast);
+ assert.ok(hiddenNoShadow > 150, 'holdout still occludes while a hidden caster leaves the floor whole');
+ // Shadow catcher: black pixels whose alpha is the shadow, and nothing without a caster.
+ assert.equal(opaquePixels(image.catcherNoCaster), 0, 'a lit shadow catcher is fully transparent');
+ assert.ok(opaquePixels(image.catcherLit) > 30, 'the received shadow is written as alpha');
+ for (let index = 0; index < image.catcherLit.length; index += 4) {
+ assert.ok(image.catcherLit[index] + image.catcherLit[index + 1] + image.catcherLit[index + 2] <= 3, 'the catcher draws only black');
+ }
+ } finally {
+ await browser?.close();
+ server.kill();
+ }
+});
diff --git a/tests/renderer.test.js b/tests/renderer.test.js
index 13ac6531..6d6bdd9e 100644
--- a/tests/renderer.test.js
+++ b/tests/renderer.test.js
@@ -13,7 +13,7 @@ function part(name, geometry = {}, map) {
function retainedRenderer(parts) {
const writes = [];
const renderer = Object.create(Renderer67.prototype);
- const batch = { instanceBuffer: {}, instanceData: new Float32Array(parts.length * 42).fill(7), castShadow: true, alphaMode: 'opaque', alphaCutoff: 0, opacity: 1, doubleSided: false };
+ const batch = { instanceBuffer: {}, instanceData: new Float32Array(parts.length * 42).fill(7), castShadow: true, receivesShadow: true, compositeMode: 0, alphaMode: 'opaque', alphaCutoff: 0, opacity: 1, doubleSided: false };
renderer.context = { ARRAY_BUFFER: 34962, bindBuffer() {}, bufferSubData(target, offset, data) { writes.push({ target, offset, data: Array.from(data) }); } };
renderer.partLocations = new Map(parts.map((item, index) => [item, {
batch, index, geometry: item.geometry, map: item.material.map ?? null, normalMatrix: mat3.create(), layerState: materialLayerState(item.material), skin: item.skin ?? null,
diff --git a/tests/update-parts-fast-path.test.js b/tests/update-parts-fast-path.test.js
index ceabdf62..aa420871 100644
--- a/tests/update-parts-fast-path.test.js
+++ b/tests/update-parts-fast-path.test.js
@@ -13,7 +13,7 @@ function createPart(name, material = {}) {
function createRenderer(parts) {
const renderer = Object.create(Renderer67.prototype);
- const batch = { instanceBuffer: {}, instanceData: new Float32Array(parts.length * 42), castShadow: true, alphaMode: 'opaque', alphaCutoff: 0, opacity: 1, doubleSided: false, pass: 'opaque' };
+ const batch = { instanceBuffer: {}, instanceData: new Float32Array(parts.length * 42), castShadow: true, receivesShadow: true, compositeMode: 0, alphaMode: 'opaque', alphaCutoff: 0, opacity: 1, doubleSided: false, pass: 'opaque' };
renderer.context = { ARRAY_BUFFER: 34962, bindBuffer() {}, bufferSubData() {} };
renderer.partLocations = new Map(parts.map((part, index) => [part, {
batch, index, geometry: GEOMETRY, map: null, normalMatrix: mat3.create(), layerState: materialLayerState({}), skin: null,