Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add a material subsurface block with a lazily loaded rasterizer addon

Nguyen Xuan An794b244b71ad
diff --git a/bench/reference/harness.js b/bench/reference/harness.js
index bd11d639..e959488c 100644
--- a/bench/reference/harness.js
+++ b/bench/reference/harness.js
@@ -9,6 +9,7 @@ import '/src/material-layer-shaders.js';
import '/src/view-transform-shader.js';
import '/src/liquid-shader.js';
import '/src/splat-shader.js';
+import '/src/subsurface-shader.js';
import { skyOpenness } from '/src/closed-room.js';
import { fogSkyVisibility } from '/src/fog-sky-visibility.js';
import { createCascadedShadows } from '/src/cascaded-shadows.js';
diff --git a/bench/reference/raster-only.mjs b/bench/reference/raster-only.mjs
new file mode 100644
index 00000000..8ad8ef95
--- /dev/null
+++ b/bench/reference/raster-only.mjs
@@ -0,0 +1,32 @@
+// Draws reference scenes with the rasterizer only, no Blender and no scoring: node bench/reference/raster-only.mjs <out-directory> <gpu|cpu> <scene-id>,<scene-id>
+// For looking at a change before the Cycles queue has a turn. Each scene lands in <out-directory>/<scene-id>-<backend>.png.
+import { mkdir, writeFile } from 'node:fs/promises';
+import { chromium } from 'playwright';
+import { createServer } from 'vite';
+
+const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+const [outputDirectory, backend = 'cpu', sceneList = 'subsurface'] = process.argv.slice(2);
+const BACKEND_ARGUMENTS = {
+ gpu: ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'],
+ cpu: ['--enable-webgl', '--ignore-gpu-blocklist', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'],
+};
+
+await mkdir(outputDirectory, { recursive: true });
+const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
+await server.listen();
+const serverUrl = `http://127.0.0.1:${server.httpServer.address().port}`;
+const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: BACKEND_ARGUMENTS[backend] });
+try {
+ for (const sceneId of sceneList.split(',')) {
+ const page = await browser.newPage({ viewport: { width: 960, height: 540 } });
+ await page.goto(`${serverUrl}/bench/reference/harness.html`, { timeout: 180000 });
+ await page.waitForFunction(() => window.renderReferenceScene, null, { timeout: 180000 });
+ const result = await page.evaluate(id => window.renderReferenceScene(id, { describe: false }), sceneId);
+ await writeFile(`${outputDirectory}/${sceneId}-${backend}.png`, Buffer.from(result.image, 'base64'));
+ console.log(`${sceneId}: glError ${result.glError}`);
+ await page.close();
+ }
+} finally {
+ await browser.close();
+ await server.close();
+}
diff --git a/bench/reference/render-blender.py b/bench/reference/render-blender.py
index 4e66733a..2f2b70a2 100644
--- a/bench/reference/render-blender.py
+++ b/bench/reference/render-blender.py
@@ -190,6 +190,17 @@ def add_thin_film(principled, description):
principled.inputs["Thin Film IOR"].default_value = description.get("iridescenceIor", 1.3)
+def add_subsurface(principled, description):
+ """Maps the 67js subsurface block onto the Principled BSDF subsurface inputs (random walk). Blender 4 and later takes the base color as the scatter color."""
+ block = description.get("subsurface")
+ if not block or block.get("weight", 0) <= 0:
+ return
+ principled.subsurface_method = "RANDOM_WALK"
+ principled.inputs["Subsurface Weight"].default_value = block["weight"]
+ principled.inputs["Subsurface Radius"].default_value = block.get("radius", [1, 0.2, 0.1])
+ principled.inputs["Subsurface Scale"].default_value = block.get("scale", 0.05)
+
+
def add_material_layers(material, principled, description):
"""Maps the 67js material layers onto the Principled BSDF inputs of the same meaning."""
principled.inputs["Coat Weight"].default_value = description.get("clearcoat", 0)
@@ -206,6 +217,7 @@ def add_material_layers(material, principled, description):
set_linear_color(principled.inputs["Specular Tint"], description.get("specularColor", [1, 1, 1]))
add_anisotropy(principled, description)
add_thin_film(principled, description)
+ add_subsurface(principled, description)
attenuation_distance = description.get("attenuationDistance")
if attenuation_distance:
absorption = material.node_tree.nodes.new("ShaderNodeVolumeAbsorption")
diff --git a/bench/reference/scenes.js b/bench/reference/scenes.js
index 56d4bcc4..4bf25b50 100644
--- a/bench/reference/scenes.js
+++ b/bench/reference/scenes.js
@@ -652,7 +652,37 @@ async function emissiveSignScene() {
};
}
+// Subsurface scattering against Cycles (issue #283): a wax candle, a skin sphere and a leaf slab with the sun behind and to the side,
+// so the shadow edge and the light through the thin parts show. 'subsurface-off' is the same scene at weight 0, the control that
+// 'subsurface' must score better than.
+const SUBSURFACE_SUN_DIRECTION = [4, 3, -2];
+const SUBSURFACE_LAYERS = {
+ wax: { radius: [1, 0.6, 0.3], scale: 0.04 },
+ skin: { radius: [1, 0.2, 0.1], scale: 0.05 },
+ leaf: { radius: [0.5, 1, 0.3], scale: 0.02 },
+};
+
+async function subsurfaceScene(weight) {
+ const lighting = await skyLighting();
+ const layer = name => ({ subsurface: { weight, ...SUBSURFACE_LAYERS[name] } });
+ const parts = [
+ floor([0.2, 0.2, 0.22]),
+ part('wax-candle', cylinder(64, 0, 1), [-1.1, 0.4, 0], [0.3, 0.8, 0.3], { color: [0.85, 0.72, 0.5], roughness: 0.45, ...layer('wax') }),
+ part('skin-sphere', sphere(96, 64), [0.2, 0.45, 0], [0.9, 0.9, 0.9], { color: [0.8, 0.45, 0.35], roughness: 0.5, ...layer('skin') }),
+ part('leaf-slab', box(0, 1), [1.5, 0.55, 0], [0.7, 0.9, 0.012], { color: [0.12, 0.3, 0.04], roughness: 0.5, ...layer('leaf') }),
+ ];
+ return {
+ parts, blenderWorld: lighting.blenderWorld,
+ environment: environment(lighting, { keyColor: SUN_COLOR, lightDirection: SUBSURFACE_SUN_DIRECTION }),
+ camera: { eye: [0, 1.6, 6], target: [0, 0.5, 0], up: [0, 1, 0], fov: 35, near: 0.1, far: 200 },
+ shadow: shadowAlongSun(SUBSURFACE_SUN_DIRECTION, { target: [0, 0.5, 0], distance: 13, extent: 4, near: 0.1, far: 40 }),
+ };
+}
+
export const REFERENCE_SCENES = {
+ subsurface: () => subsurfaceScene(1),
+ 'subsurface-off': () => subsurfaceScene(0),
+
'emissive-sign': emissiveSignScene,
'mountain-valley': mountainValleyScene,
'temple-hall': templeHallScene,
diff --git a/changes/283.md b/changes/283.md
new file mode 100644
index 00000000..4647c045
--- /dev/null
+++ b/changes/283.md
@@ -0,0 +1 @@
+- Add a material `subsurface` block for skin, wax and leaves (part of #283): `weight` (0 to 1), `radius` (red, green, blue mean free path in units of `scale`, default `[1, 0.2, 0.1]`), `scale` (metres, default 0.05) and an optional `color`, named as Blender's Principled BSDF Subsurface Weight, Radius and Scale. Recipes and the MCP `scene_create` schema accept it with bounded numbers. The rasterizer widens the sun's diffuse past the shadow edge per channel and lets light through thin parts by the thickness the sun shadow map gives; the code is a lazily loaded addon (`@codepawlhq/67js/addons/subsurface-shader`, loaded by a recipe on its own) that compiles in only when a part has a weight above 0, so a scene without it draws the same picture and pays nothing. The path tracer does not read the block yet. `bench/reference/render-blender.py` exports it as Random Walk subsurface, and the reference scenes `subsurface` and `subsurface-off` score it against Cycles.
diff --git a/changes/283.size.md b/changes/283.size.md
new file mode 100644
index 00000000..3e765714
--- /dev/null
+++ b/changes/283.size.md
@@ -0,0 +1,5 @@
+- entry:agent-scene: the recipe reads a material subsurface block (a field name and a lazy loader line) and scene_capabilities names it.
+- entry:agent-scene+lazy: the subsurface addon loads lazily for a recipe that has a subsurface block.
+- scene:agent-scene: the same recipe field, lazy loader and capabilities line as entry:agent-scene.
+- scene:agent-scene+lazy: the subsurface addon loads lazily, as in entry:agent-scene.
+- archive: the subsurface addon (shader, limits) and docs ship in the package.
diff --git a/docs/material-maps.md b/docs/material-maps.md
index d2d908ce..757028fc 100644
--- a/docs/material-maps.md
+++ b/docs/material-maps.md
@@ -126,6 +126,7 @@ A material on a standard tag (`surface` in recipes, `gltf` and `armor` in code)
| `specular`, `specularColor` | 0 to 4, colour 0 to 4 | Strength and tint of the non-metal reflection. |
| `anisotropy`, `anisotropyRotation` | 0 to 1, -2π to 2π | Stretches highlights along a grain (brushed metal, hair): the surface is rougher along the tangent than across it, as in `KHR_materials_anisotropy`. The grain follows the UV direction, or rings the world up axis on a mesh without UVs. The rotation turns it around the normal, in radians. |
| `iridescence`, `iridescenceIor`, `iridescenceThickness` | 0 to 1, 1 to 3, 0 to 1200 nm | A thin film over the surface (soap, oil, beetle shell, anodised metal) that shifts the reflection colour with the view angle, as in `KHR_materials_iridescence`. The film is as thick as `iridescenceThickness` everywhere; the glTF thickness minimum and texture are not kept. |
+| `subsurface` (`weight`, `radius`, `scale`, `color`) | 0 to 1, each channel 0 to 100 (units of `scale`), 0 to 10 m, 0 to 1 | Light scattered under the surface (skin, wax, leaves), named as Blender's Principled BSDF Subsurface Weight, Radius and Scale. `radius` is the mean free path of red, green and blue in units of `scale` (metres); defaults `[1, 0.2, 0.1]` and `0.05`; `weight` 0 is off. The rasterizer widens the sun's diffuse past the shadow edge per channel and lets light through thin parts by the thickness the sun shadow map gives; the code loads only for a recipe that has a `subsurface` block (`@codepawlhq/67js/addons/subsurface-shader` otherwise). Sun only, surface tag, no anisotropy; `color` is read by 67js but Blender takes the base colour. The path tracer ignores it. |
A material that uses none of them costs nothing extra: the shader branches on uniforms that are zero, and transmission only exists in the pass that was already there for `liquid`. Anisotropy and iridescence go further: their shader code is not in the core bundle at all. It lives in `@codepawlhq/67js/addons/material-layer-shaders`, and the renderer asks for it only when a part uses a layer, so a scene without them downloads and draws with the same shader as before. In code, add `import "@codepawlhq/67js/addons/material-layer-shaders"` before rendering such a part; without it the renderer throws a message that names the import. A recipe loads it through `await loadAgentSceneModules(recipe)`, the MCP server does so itself, and the glTF loader brings it in for a file that uses `KHR_materials_anisotropy` or `KHR_materials_iridescence`.
diff --git a/docs/parity.md b/docs/parity.md
index 7f3ac6a3..1755c093 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -193,7 +193,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Rendering > Lights > Light Objects | partial | One directional light with a shadow, 16 point lights, 8 spot lights and 7 rectangular area lights. Point and spot lights can cast shadows from one 24-tile atlas (a point light takes 6 tiles, a spot light 1). Area lights use a representative point and cast no shadow. The directional shadow is a single map, or up to four cascades through `addons/cascaded-shadows` (`shadowCascades` on the renderer and `environment.shadowCascades` in recipes, three by themselves when `shadow.extent` is above 40): scene `long-street` scores 0.1555 against Cycles with one map and 0.1398 with three cascades, for about 0.2 ms more a frame on an RTX 3060 when the camera moves. | [lighting](../tests/lighting.test.js), [cascades](../tests/cascaded-shadows.test.js), `npm run reference` scenes `spot-area` and `long-street` | #52 |
| Rendering > Lights > Light Linking | partial | `addons/light-linking`: a light's `affects` list (and `environment.keyAffects` for the sun) limits it to the named parts through `applyLightLinks`, as a Blender receiver collection does; the shader skips a light whose bit in the part's mask is clear. Linking changes what a light adds, not what it shadows. The path tracer (issue #215) and the light bake honour it, and recipes reach it through `affects` and `environment.keyAffects` (`lightLinking` in `scene_capabilities`). There is no blocker list. Scene `light-linking` scores 0.0998 against Cycles. | [light-linking](../tests/light-linking.test.js), `npm run reference` scene `light-linking` | #52 |
| Rendering > Lights > World Environment | partial | Recipes pick a named setup (`daylight`, `overcast`, `sunset`, `studio`) that carries a procedural environment map, with opt-in screen-space ambient occlusion. Code can load any HDRI; recipes reach only the named maps, with no URLs or files. No reflections between objects yet. The MCP preview adds an automatic floor with a contact shadow (`environment.ground: false` removes it). Cold-run reference-free score for sitting on a surface, summed over six tasks and 0 to 3 each: 0 before, 6 with the floor and 7 after a lone flat object (a gear) stopped being read as a floor; the front and side cameras see it edge-on, so only the three-quarter view shows it. A blind pairwise Sonnet judge (`default-judge.mjs`, six cold recipes, two cameras, 18 calls) prefers the floor to none 18 of 18 (p 0.0000076) and the darker floor now used (0.22) to the first one (0.6) 18 of 18; its control, one image against itself, picks the first 17 of 18. | [environment](../tests/environment.test.js), [default look](../tests/default-look.test.js) | #53 |
-| Rendering > Materials > Components | partial | Surfaces with PBR factors and five maps, a clear coat, transmission with thickness, attenuation and IOR, sheen, and specular weight and tint. Anisotropic highlights and a thin-film iridescence layer, as in the glTF extensions, are compiled in only when a part uses them. There is no subsurface scattering, volume material or displacement. | [texture-set](../tests/texture-set.test.js), [material-layers](../tests/material-layers.test.js) | #50, #51 |
+| Rendering > Materials > Components | partial | Surfaces with PBR factors and five maps, a clear coat, transmission with thickness, attenuation and IOR, sheen, and specular weight and tint. Anisotropic highlights and a thin-film iridescence layer, as in the glTF extensions, are compiled in only when a part uses them. Subsurface scattering (the `subsurface` block: weight, radius, scale, color; sun light only, rasterizer only, compiled in only when a part uses it) approximates skin, wax and leaves; the path tracer ignores it. There is no volume material or displacement. | [texture-set](../tests/texture-set.test.js), [material-layers](../tests/material-layers.test.js) | #50, #51 |
| Rendering > Materials > Assignment | done | A node names one material. | [agent-scene](../tests/agent-scene.test.js) | |
| Rendering > Materials > Preview | out of scope | Interface for a person. Agents use `scene_look`. | | |
| Rendering > Materials > Settings | partial | Opaque and blend in recipes, and mask on imported assets, with double-sided support. | [gltf-extensions](../tests/gltf-extensions.test.js) | #51 |
@@ -201,7 +201,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Rendering > Materials > Legacy Textures | out of scope | Blender keeps these for old files. | | |
| Rendering > Shader Nodes > Input | partial | `uv` coordinates only. There is no object, geometry, camera or light-path input. | [material-graph](../tests/material-graph.test.js) | #50 |
| Rendering > Shader Nodes > Output | partial | A graph makes base colour, roughness, metallic, emission and height. It is baked to textures on the CPU, so it can not react to light, view or position. The `brick-graph` reference scene scores 0.2269 against Cycles; its `brick-flat` control (the graph's average colour, no maps) is the baseline it is compared with, and a bump of 0 would score 0.2065, so the bump is stronger than Blender's, not weaker. | [material-graph](../tests/material-graph.test.js), [brick-graph scene](../bench/reference/scenes.js) | #50 |
-| Rendering > Shader Nodes > Shader | partial | A metallic-roughness surface with clear coat, transmission, sheen and specular layers, and unlit, liquid and foam tags. Anisotropy (key, fill and local lights, and a bent environment lookup) and thin-film iridescence follow the glTF extensions rather than Blender's tangent and thin-film inputs, scored in the `brushed-film` reference scene. Khronos sample assets (`npm run reference -- --khronos`, files downloaded by hand) score 0.23 to 0.48 against Cycles on the pixels the asset covers (0.13 to 0.38 for EEVEE): the glTF clear coat (strength, roughness, normal), anisotropy and sheen textures are read (`layerMaps`, shader code in `material-layer-shaders`), which took the barn lamp from 0.4758 to 0.3584 and the anisotropy disc from 0.3481 to 0.2808; the transmission, iridescence and specular textures are not read, and `SheenChair` imports since a normal map may carry its own scale and offset. There is no subsurface. | [material-layers](../tests/material-layers.test.js) | #51 |
+| Rendering > Shader Nodes > Shader | partial | A metallic-roughness surface with clear coat, transmission, sheen and specular layers, and unlit, liquid and foam tags. Anisotropy (key, fill and local lights, and a bent environment lookup) and thin-film iridescence follow the glTF extensions rather than Blender's tangent and thin-film inputs, scored in the `brushed-film` reference scene. Khronos sample assets (`npm run reference -- --khronos`, files downloaded by hand) score 0.23 to 0.48 against Cycles on the pixels the asset covers (0.13 to 0.38 for EEVEE): the glTF clear coat (strength, roughness, normal), anisotropy and sheen textures are read (`layerMaps`, shader code in `material-layer-shaders`), which took the barn lamp from 0.4758 to 0.3584 and the anisotropy disc from 0.3481 to 0.2808; the transmission, iridescence and specular textures are not read, and `SheenChair` imports since a normal map may carry its own scale and offset. Subsurface maps Principled BSDF Subsurface Weight, Radius and Scale (Random Walk in Cycles) to a wrapped sun diffuse plus shadow-map thickness; it is scored in the `subsurface` reference scene. | [material-layers](../tests/material-layers.test.js) | #51 |
| Rendering > Shader Nodes > Displacement | partial | Bump: a graph's height becomes a normal map. There is no displacement of the surface. | [material-graph](../tests/material-graph.test.js) | #50 |
| Rendering > Shader Nodes > Texture | partial | Image maps, 11 pattern presets, and graph nodes for noise, voronoi, wave, checker and gradient. Noise is not Blender's noise function, and there is no brick, musgrave, magic or environment node. Patterns follow UVs or box projection. | [material-patterns](../tests/material-patterns.test.js), [material-graph](../tests/material-graph.test.js), [brick-graph scene](../bench/reference/scenes.js) | #50 |
| Rendering > Shader Nodes > Color | partial | Color ramp, mix and invert. There is no hue, curves, gamma or blend modes. | [material-graph](../tests/material-graph.test.js) | #50 |
diff --git a/package.json b/package.json
index aefc8f21..cd8ef3e7 100644
--- a/package.json
+++ b/package.json
@@ -93,6 +93,7 @@
"./addons/liquid-shader": "./build/liquid-shader.js",
"./addons/world-material-shader": "./build/world-material-shader.js",
"./addons/splat-shader": "./build/splat-shader.js",
+ "./addons/subsurface-shader": "./build/subsurface-shader.js",
"./addons/light-linking": "./build/light-linking.js",
"./addons/cascaded-shadows": "./build/cascaded-shadows.js",
"./addons/gaussian-splats": "./build/gaussian-splats.js",
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 3724319a..47b2e726 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -9,6 +9,7 @@ import packageMetadata from '../package.json' with { type: 'json' };
import { MODIFIER_OPERATIONS } from '../src/mesh-operations.js';
import { MATERIAL_PATTERN_TYPES, MATERIAL_MAPPINGS, LIGHTING_SETUP_NAMES, RENDER_PASS_NAMES, VIDEO_ENCODERS, MAXIMUM_JOB_SIDE, MAXIMUM_MEMORY_MIB } from '../src/agent-scene-capabilities.js';
import { MATERIAL_LAYER_SCALAR_RANGES, MATERIAL_LAYER_COLOR_RANGES } from '../src/material-layers.js';
+import { SUBSURFACE_RANGES } from '../src/subsurface-limits.js';
const finite = z.number().min(-3.4028234663852886e38).max(3.4028234663852886e38);
const positive = finite.positive();
@@ -101,8 +102,17 @@ const materialLayerFields = {
};
+const subsurfaceColor = (field, [minimum, maximum]) => z.tuple([0, 1, 2].map(() => z.number().min(minimum, `subsurface.${field} components must be at least ${minimum}.`).max(maximum, `subsurface.${field} components must be at most ${maximum}.`)));
+const subsurface = z.strictObject({
+ weight: z.number().min(SUBSURFACE_RANGES.weight[0]).max(SUBSURFACE_RANGES.weight[1]).optional().describe('Share of light that scatters under the surface; 0 is off.'),
+ radius: subsurfaceColor('radius', SUBSURFACE_RANGES.radius).optional().describe('Red, green, blue mean free path in units of scale. Default [1, 0.2, 0.1] (skin).'),
+ scale: z.number().min(SUBSURFACE_RANGES.scale[0]).max(SUBSURFACE_RANGES.scale[1]).optional().describe('Metres per radius unit. Default 0.05.'),
+ color: subsurfaceColor('color', SUBSURFACE_RANGES.color).optional().describe('Linear RGB scatter colour; the base color when left out.'),
+}).describe('Light scattered under the surface (skin, wax, leaves), as Blender Principled BSDF Subsurface. Rasterizer only; the path tracer ignores it.');
+
const materialFields = {
...materialLayerFields,
+ subsurface: subsurface.optional(),
pattern: materialPattern.optional(),
color: color.optional().describe('Linear RGB base color, each component between zero and one.'),
metallic: unit.optional(),
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 15eb2cb0..5e0bddfd 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -176,6 +176,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
range: MATERIAL_LAYER_SCALAR_RANGES[field] ?? MATERIAL_LAYER_COLOR_RANGES[field] ?? 'above 0',
note: MATERIAL_LAYER_NOTES[field],
})]))),
+ materialSubsurface: 'material.subsurface { weight, radius, scale, color } as Blender Principled BSDF Subsurface; surface tag, rasterizer only. Ranges in scene_create.',
alphaModes: RECIPE_ALPHA_MODES,
materialPatterns: MATERIAL_PATTERN_TYPES, maxMaterialPatterns: MAX_MATERIAL_PATTERNS,
materialMappings: MATERIAL_MAPPINGS,
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index 7c8b355d..b4b04cea 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -18,6 +18,7 @@ const MODULE_LOADERS = {
timeline: () => import('./film-timeline.js'),
layerShaders: () => import('./material-layer-shaders.js'),
liquidShader: () => import('./liquid-shader.js'),
+ subsurfaceShader: () => import('./subsurface-shader.js'),
worldMaterials: () => import('./world-material-shader.js'),
terrain: () => import('./agent-terrain.js'),
navigation: () => import('./agent-navigation.js'),
@@ -51,6 +52,7 @@ const MODULE_MARKERS = {
timeline: ['"timeline":{'],
layerShaders: ['"anisotropy"', '"iridescence"'],
liquidShader: ['"transmission"', '"liquid"', '"foam"'],
+ subsurfaceShader: ['"subsurface"'],
worldMaterials: ['"tag":"water"', '"tag":"foliage"', '"tag":"grass"', '"tag":"terrain"', '"tag":"fire"', '"tag":"smoke"', '"moss"'],
terrain: ['"type":"terrain"'],
// No recipe text asks for it, only the path option of scene_inspect does, so a host loads it with loadAllAgentSceneModules.
diff --git a/src/agent-scene.js b/src/agent-scene.js
index e255d4d9..e42bdcab 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -24,7 +24,7 @@ const MAX_MESH_REPORTS = 16;
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', 'decal', 'depthLayer'];
-const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', ...MATERIAL_LAYER_FIELDS];
+const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', 'subsurface', ...MATERIAL_LAYER_FIELDS];
const PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'emissiveMap', 'boxMapScale', 'boxMapAxis'];
const CAMERA_FIELDS = Object.keys(CAMERA_DEFAULTS);
const LOOK_OPERATION_FIELDS = Object.freeze({
@@ -193,6 +193,7 @@ function copyMaterialLayers(value, result) {
result[field] = Array.isArray(value[field]) ? vector(value[field], 3, field) : value[field];
}
validateMaterialLayers(result);
+ if (value.subsurface !== undefined) result.subsurface = agentSceneModule('subsurfaceShader').copySubsurface(value.subsurface, result.tag);
if (result.anisotropy > 0 || result.iridescence > 0) agentSceneModule('layerShaders');
if (result.toon > 0) agentSceneModule('lineArt');
}
diff --git a/src/material-layer-shaders.js b/src/material-layer-shaders.js
index dabb2dee..95f3540e 100644
--- a/src/material-layer-shaders.js
+++ b/src/material-layer-shaders.js
@@ -321,8 +321,8 @@ const MAP_STATE_LAYER_MAPS = 18;
// Other optional features (reflection probes) also bind per batch, so this keeps whatever was registered first.
const previousBind = layerTextureSupport.bind;
-layerTextureSupport.bind = (renderer, mapState) => {
- previousBind?.(renderer, mapState);
+layerTextureSupport.bind = (renderer, mapState, layerState) => {
+ previousBind?.(renderer, mapState, layerState);
if (!renderer.shaderFeatures) return;
const context = renderer.context;
const layerMaps = mapState[MAP_STATE_LAYER_MAPS];
diff --git a/src/material-layers.js b/src/material-layers.js
index a9d9488f..a2627162 100644
--- a/src/material-layers.js
+++ b/src/material-layers.js
@@ -112,7 +112,7 @@ export function dielectricReflectance(material) {
/**
* Plain values the renderer batches by: dielectric F0 (3), coat (2), sheen (4), transmission (4), attenuation colour (3),
- * anisotropy strength and rotation (2), iridescence factor, film IOR and film thickness in nanometres (3), light mask (1), toon bands (1).
+ * anisotropy strength and rotation (2), iridescence factor, film IOR and film thickness in nanometres (3), light mask (1), toon bands (1), and the subsurface block as JSON, or '' (1; subsurface-limits.js and the addon read it).
*/
export function materialLayerState(material) {
validateMaterialLayers(material);
@@ -134,7 +134,8 @@ export function materialLayerState(material) {
materialLayerValue(material, 'iridescenceThickness'),
material.lightMask ?? ALL_LIGHTS_MASK,
materialLayerValue(material, 'toon'),
+ material.subsurface ? JSON.stringify(material.subsurface) : '',
];
}
-export const MATERIAL_LAYER_STATE_LENGTH = 23;
+export const MATERIAL_LAYER_STATE_LENGTH = 24;
diff --git a/src/material-snapshot.js b/src/material-snapshot.js
index 3aa30684..7df220da 100644
--- a/src/material-snapshot.js
+++ b/src/material-snapshot.js
@@ -6,7 +6,7 @@
export const SNAPSHOT_VALUE_FIELDS = Object.freeze(['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap', 'tag', 'alphaMode', 'alphaCutoff', 'opacity', 'doubleSided', 'occlusionStrength', 'moss', 'boxMapScale', 'boxMapAxis', 'lightMapScale', 'layerMaps', 'lightMask', 'clearcoat', 'clearcoatRoughness', 'transmission', 'thickness', 'ior', 'sheenRoughness', 'specular', 'anisotropy', 'anisotropyRotation', 'iridescence', 'iridescenceIor', 'iridescenceThickness', 'attenuationDistance', 'toon']);
/** Fields holding an array or descriptor, which can change in place. A material that sets one is never snapshotted. */
-export const SNAPSHOT_REFERENCE_FIELDS = Object.freeze(['normalScale', 'mossColor', 'lightMap', 'attenuationColor', 'sheenColor', 'specularColor']);
+export const SNAPSHOT_REFERENCE_FIELDS = Object.freeze(['normalScale', 'mossColor', 'lightMap', 'attenuationColor', 'sheenColor', 'specularColor', 'subsurface']);
function hasNoReferenceFields(material) {
return material.normalScale === undefined &&
@@ -14,7 +14,8 @@ function hasNoReferenceFields(material) {
material.lightMap === undefined &&
material.attenuationColor === undefined &&
material.sheenColor === undefined &&
- material.specularColor === undefined;
+ material.specularColor === undefined &&
+ material.subsurface === undefined;
}
export class MaterialSnapshot {
diff --git a/src/reflection-probes.js b/src/reflection-probes.js
index ccbcdf4a..47dac48f 100644
--- a/src/reflection-probes.js
+++ b/src/reflection-probes.js
@@ -167,7 +167,7 @@ function bindProbe(renderer, mapState) {
}
const previousBind = layerTextureSupport.bind;
-layerTextureSupport.bind = (renderer, mapState) => {
- previousBind?.(renderer, mapState);
+layerTextureSupport.bind = (renderer, mapState, layerState) => {
+ previousBind?.(renderer, mapState, layerState);
bindProbe(renderer, mapState);
};
diff --git a/src/renderer.js b/src/renderer.js
index a12bcbc1..c4015e2c 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -87,6 +87,7 @@ function shaderFeaturesOfParts(parts) {
if (material.iridescence > 0) features.add('iridescence');
if (material.toon > 0) features.add('toon');
if ((material.alphaMode ?? 'opaque') !== 'opaque') features.add('alphaMode');
+ if (material.subsurface?.weight > 0) features.add('subsurface');
if (materialLayerValue(material, 'clearcoat') > 0) features.add('clearcoat');
if (materialLayerValue(material, 'sheenColor').some(channel => channel !== 0)) features.add('sheen');
if (TAG_SHADER_FEATURES.has(material.tag)) features.add(material.tag);
@@ -2012,7 +2013,7 @@ export class Renderer67 {
this.context.uniform1f(this.uniforms.boxMapScale, batch.mapState[12]);
this.context.uniform1i(this.uniforms.boxMapAxis, batch.mapState[13]);
if (this.shaderFeatures?.has('splat')) requireSplatSupport().bind(this, batch.splat);
- layerTextureSupport.bind?.(this, batch.mapState);
+ layerTextureSupport.bind?.(this, batch.mapState, layers);
this.context.uniform1f(this.uniforms.hasLightMap, batch.lightMapTexture ? 1 : 0);
if (batch.lightMapTexture) {
this.context.activeTexture(this.context.TEXTURE0 + LIGHT_MAP_UNIT);
diff --git a/src/shader-registry.js b/src/shader-registry.js
index 1c660c38..f69d2d42 100644
--- a/src/shader-registry.js
+++ b/src/shader-registry.js
@@ -39,7 +39,7 @@ export function registerShaderFeatureCode(feature, slots) {
}
// The addon that registers each feature's code; a feature not listed here is registered by material-layer-shaders.
-const FEATURE_ADDONS = { splat: 'splat-shader', liquid: 'liquid-shader', worldMaterials: 'world-material-shader' };
+const FEATURE_ADDONS = { splat: 'splat-shader', liquid: 'liquid-shader', worldMaterials: 'world-material-shader', subsurface: 'subsurface-shader' };
export function requireFeatureCode(feature) {
const slots = registeredFeatureCode.get(feature);
diff --git a/src/subsurface-limits.js b/src/subsurface-limits.js
new file mode 100644
index 00000000..a25d9241
--- /dev/null
+++ b/src/subsurface-limits.js
@@ -0,0 +1,49 @@
+// The ranges, defaults and checks of the material `subsurface` block. Plain data, kept out of material-layers.js so a
+// renderer without subsurface parts does not carry them: the MCP server, the recipe code and the subsurface addon share them.
+//
+// The block mirrors Blender's Principled BSDF (Subsurface Weight, Radius, Scale). radius is the mean free path of red,
+// green and blue in units of scale, and scale is metres. A missing color means the base color, as in Blender 4 and later.
+
+const UNIT = Object.freeze([0, 1]);
+
+export const SUBSURFACE_DEFAULTS = Object.freeze({ weight: 0, radius: Object.freeze([1, 0.2, 0.1]), scale: 0.05 });
+export const SUBSURFACE_RANGES = Object.freeze({ weight: UNIT, radius: Object.freeze([0, 100]), scale: Object.freeze([0, 10]), color: UNIT });
+
+function describeRange([minimum, maximum]) {
+ return `between ${minimum} and ${maximum}`;
+}
+
+function checkTriple(label, value) {
+ const [minimum, maximum] = SUBSURFACE_RANGES[label];
+ const isTriple = Array.isArray(value) && value.length === 3 && value.every(component => typeof component === 'number' && Number.isFinite(component) && component >= minimum && component <= maximum);
+ if (!isTriple) throw new RangeError(`subsurface.${label} must be three numbers ${describeRange(SUBSURFACE_RANGES[label])}. Pass [red, green, blue].`);
+}
+
+/** Throws for a subsurface block that is not an object with the known fields inside their ranges, or sits on a non-surface material. */
+export function validateSubsurface(block, tag = 'surface') {
+ if (block === null || typeof block !== 'object' || Array.isArray(block)) throw new TypeError('subsurface must be an object: { weight, radius, scale, color }.');
+ for (const key of Object.keys(block)) {
+ if (!(key in SUBSURFACE_RANGES)) throw new RangeError(`Unknown subsurface field ${key}. Use weight, radius, scale or color.`);
+ }
+ for (const field of ['weight', 'scale']) {
+ const value = block[field];
+ if (value === undefined) continue;
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < SUBSURFACE_RANGES[field][0] || value > SUBSURFACE_RANGES[field][1]) {
+ throw new RangeError(`subsurface.${field} must be ${describeRange(SUBSURFACE_RANGES[field])}, got ${value}.`);
+ }
+ }
+ if (block.radius !== undefined) checkTriple('radius', block.radius);
+ if (block.color !== undefined) checkTriple('color', block.color);
+ if ((block.weight ?? 0) > 0 && tag !== 'surface' && tag !== 'gltf') {
+ throw new RangeError(`subsurface needs a standard PBR material tag, got ${tag}. Use the surface tag.`);
+ }
+}
+
+/**
+ * The seven numbers a shader needs: weight, the mean free path in metres (radius times scale) for red, green and blue,
+ * and the color, whose red is -1 for the base color.
+ */
+export function subsurfaceUniformValues(block) {
+ const { weight = SUBSURFACE_DEFAULTS.weight, radius = SUBSURFACE_DEFAULTS.radius, scale = SUBSURFACE_DEFAULTS.scale, color = [-1, -1, -1] } = block;
+ return [weight, ...radius.map(channel => channel * scale), ...color];
+}
diff --git a/src/subsurface-shader.js b/src/subsurface-shader.js
new file mode 100644
index 00000000..7c146a12
--- /dev/null
+++ b/src/subsurface-shader.js
@@ -0,0 +1,97 @@
+import { layerTextureSupport, registerShaderFeatureCode } from './shader-registry.js';
+import { validateSubsurface, subsurfaceUniformValues } from './subsurface-limits.js';
+
+// Shader code for the material `subsurface` block (skin, wax, leaves). It lives outside shaders.js so a scene without a
+// subsurface part never downloads or compiles it: the renderer asks for the `subsurface` feature only when a part has a
+// subsurface weight above 0, and importing this module (or loading it through loadAgentSceneModules) registers it.
+// The GLSL has no comments, because comments ship to every page. What it does:
+// - The base lighting is untouched. Subsurface adds a correction on top, scaled by the weight, so weight 0 is today's picture.
+// - Per colour channel the sun's diffuse light is wrapped past the terminator by a width that grows with the mean free path
+// (radius times scale, metres): (n.l + w) / (1 + w)^2, which keeps the total diffuse energy of a Lambert surface. Red
+// travels furthest, so the shadow edge turns red on skin.
+// - Light that reaches a surface from behind passes through the part. Its thickness along the sun comes from four to five
+// comparison fetches of the sun shadow map at growing depths (the map only answers lit or shadowed), and each channel keeps
+// exp(-thickness / mean free path). A thin leaf has thickness near 0 and glows when the sun is behind it; a head blocks it.
+// max(n.l) of the back face (BACK_TRANSLUCENCY) is the light that leaves a thin part on the side the camera sees.
+// - Only the sun is treated; point, spot and area lights keep their plain diffuse.
+
+const REFERENCE_LENGTH = '0.1';
+const BACK_TRANSLUCENCY = '0.5';
+
+const SUBSURFACE_DECLARATIONS = `uniform vec4 materialSubsurface;
+uniform vec3 materialSubsurfaceColor;
+uniform mat4 lightProjection;
+`;
+
+const SUBSURFACE_LIBRARIES = `float sunThickness(float reference) {
+ vec3 projected = shadowPosition.xyz / shadowPosition.w * 0.5 + 0.5;
+ if (projected.z > 1.0 || projected.z < 0.0 || any(lessThan(projected.xy, vec2(0.0))) || any(greaterThan(projected.xy, vec2(1.0)))) return 0.0;
+ float unit = reference * abs(lightProjection[2][2]) * 0.5;
+ float depth = projected.z - shadowBiasPerSlope;
+ float thickness = 0.0;
+ thickness += (1.0 - texture(shadowMap, vec3(projected.xy, depth - 0.25 * unit))) * 0.25;
+ thickness += (1.0 - texture(shadowMap, vec3(projected.xy, depth - 0.5 * unit))) * 0.25;
+ thickness += (1.0 - texture(shadowMap, vec3(projected.xy, depth - unit))) * 0.5;
+ thickness += (1.0 - texture(shadowMap, vec3(projected.xy, depth - 2.0 * unit)));
+ thickness += (1.0 - texture(shadowMap, vec3(projected.xy, depth - 4.0 * unit))) * 2.0;
+ return thickness * reference;
+}
+
+vec3 subsurfaceLight(vec3 normal, vec3 baseColor, float visibility) {
+ vec3 mean = materialSubsurface.yzw;
+ vec3 tint = materialSubsurfaceColor.x < 0.0 ? baseColor : materialSubsurfaceColor;
+ float facing = dot(normal, normalize(lightDirection));
+ vec3 wrap = mean / (mean + ${REFERENCE_LENGTH});
+ vec3 spread = max((facing + wrap) / ((1.0 + wrap) * (1.0 + wrap)), 0.0) + max(-facing, 0.0) * ${BACK_TRANSLUCENCY};
+ float thickness = visibility < 1.0 ? sunThickness(max(mean.x, max(mean.y, mean.z))) : 0.0;
+ vec3 reach = max(vec3(visibility), exp(-thickness / max(mean, vec3(0.0001))));
+ vec3 gained = tint * reach * spread - baseColor * visibility * max(facing, 0.0);
+ return materialSubsurface.x * gained * keyColor / PI;
+}
+`;
+
+const SUBSURFACE_LIGHT = ` if (materialSubsurface.x > 0.0) radiance = max(radiance + (1.0 - metallic) * subsurfaceLight(normal, color, visibility), vec3(0.0));
+`;
+
+registerShaderFeatureCode('subsurface', Object.freeze({
+ declarations: SUBSURFACE_DECLARATIONS,
+ libraries: SUBSURFACE_LIBRARIES,
+ worldLight: SUBSURFACE_LIGHT,
+}));
+
+const LAYER_STATE_SUBSURFACE = 23;
+const NO_SUBSURFACE = [0, 0, 0, 0, -1, -1, -1];
+const valuesOfState = new Map();
+
+// The renderer batches by the block's JSON (material-layers.js); the numbers come from parsing it once per distinct block.
+function uniformValuesOf(state) {
+ if (!valuesOfState.has(state)) {
+ const block = JSON.parse(state);
+ validateSubsurface(block);
+ valuesOfState.set(state, subsurfaceUniformValues(block));
+ }
+ return valuesOfState.get(state);
+}
+
+/** Checks a recipe material's subsurface block and returns a copy. Called by createAgentScene once this module is loaded. */
+export function copySubsurface(block, tag) {
+ validateSubsurface(block, tag);
+ return structuredClone(block);
+}
+
+function uniformOf(renderer, name) {
+ renderer.uniforms[name] ??= renderer.context.getUniformLocation(renderer.program, name);
+ return renderer.uniforms[name];
+}
+
+// Other optional features also bind per batch, so this keeps whatever was registered first.
+const previousBind = layerTextureSupport.bind;
+layerTextureSupport.bind = (renderer, mapState, layerState) => {
+ previousBind?.(renderer, mapState, layerState);
+ if (!renderer.shaderFeatures?.has('subsurface')) return;
+ const context = renderer.context;
+ const state = layerState[LAYER_STATE_SUBSURFACE];
+ const [weight, red, green, blue, colorRed, colorGreen, colorBlue] = state ? uniformValuesOf(state) : NO_SUBSURFACE;
+ context.uniform4f(uniformOf(renderer, 'materialSubsurface'), weight, red, green, blue);
+ context.uniform3f(uniformOf(renderer, 'materialSubsurfaceColor'), colorRed, colorGreen, colorBlue);
+};
diff --git a/src/water-reflection.js b/src/water-reflection.js
index 11751132..474ae7f7 100644
--- a/src/water-reflection.js
+++ b/src/water-reflection.js
@@ -292,8 +292,8 @@ function bindWater(renderer, mapState) {
}
const previousBind = layerTextureSupport.bind;
-layerTextureSupport.bind = (renderer, mapState) => {
- previousBind?.(renderer, mapState);
+layerTextureSupport.bind = (renderer, mapState, layerState) => {
+ previousBind?.(renderer, mapState, layerState);
bindWater(renderer, mapState);
};
diff --git a/tests/line-art.test.js b/tests/line-art.test.js
index fa9035af..302a5f81 100644
--- a/tests/line-art.test.js
+++ b/tests/line-art.test.js
@@ -73,8 +73,8 @@ test('a material toon value is a layer field with its own range and shows in the
assert.throws(() => createAgentScene({ ...recipe, materials: [{ id: 'gray', toon: 9 }] }), /toon must be between 0 and 8/);
const state = materialLayerState({ tag: 'surface', toon: 4 });
assert.equal(state.length, MATERIAL_LAYER_STATE_LENGTH);
- assert.equal(state.at(-1), 4);
- assert.equal(materialLayerState({ tag: 'surface' }).at(-1), 0);
+ assert.equal(state[22], 4);
+ assert.equal(materialLayerState({ tag: 'surface' })[22], 0);
});
test('the toon feature splices its light steps into illuminate, and no other shader mentions it', () => {
diff --git a/tests/subsurface.test.js b/tests/subsurface.test.js
new file mode 100644
index 00000000..6cf11bd8
--- /dev/null
+++ b/tests/subsurface.test.js
@@ -0,0 +1,75 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import './support/load-agent-scene-modules.mjs';
+import { createAgentScene } from '../src/agent-scene.js';
+import { agentSceneModulesNeeded } from '../src/agent-scene-modules.js';
+import { materialLayerState, MATERIAL_LAYER_STATE_LENGTH } from '../src/material-layers.js';
+import { SUBSURFACE_DEFAULTS, SUBSURFACE_RANGES, subsurfaceUniformValues, validateSubsurface } from '../src/subsurface-limits.js';
+import { createFragmentShader, SHADER_FEATURES } from '../src/shaders.js';
+import { AGENT_SCENE_CAPABILITIES } from '../src/agent-scene-capabilities.js';
+
+function recipeWithMaterial(material) {
+ return {
+ format: '67js.scene',
+ schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box', bevel: 0 }],
+ materials: [{ id: 'finish', ...material }],
+ nodes: [{ id: 'block', geometry: 'box', material: 'finish' }],
+ };
+}
+
+test('the subsurface block is checked against bounded ranges and names the field that is wrong', () => {
+ validateSubsurface({ weight: 1, radius: [1, 0.2, 0.1], scale: 0.05, color: [0.8, 0.4, 0.3] });
+ validateSubsurface({});
+ assert.throws(() => validateSubsurface({ weight: 1.5 }), /subsurface.weight must be between 0 and 1/);
+ assert.throws(() => validateSubsurface({ weight: Number.NaN }), /subsurface.weight/);
+ assert.throws(() => validateSubsurface({ scale: -1 }), /subsurface.scale must be between 0 and 10/);
+ assert.throws(() => validateSubsurface({ radius: [1, 2] }), /subsurface.radius must be three numbers/);
+ assert.throws(() => validateSubsurface({ radius: [1, 2, 101] }), /subsurface.radius must be three numbers between 0 and 100/);
+ assert.throws(() => validateSubsurface({ color: [0, 0, 2] }), /subsurface.color must be three numbers between 0 and 1/);
+ assert.throws(() => validateSubsurface({ anisotropy: 0.5 }), /Unknown subsurface field anisotropy/);
+ assert.throws(() => validateSubsurface([1]), /subsurface must be an object/);
+ assert.throws(() => validateSubsurface({ weight: 1 }, 'foam'), /subsurface needs a standard PBR material tag/);
+});
+
+test('a recipe material takes the subsurface block and rejects values out of range', () => {
+ const scene = createAgentScene(recipeWithMaterial({ subsurface: { weight: 1, radius: [1, 0.2, 0.1], scale: 0.05 } }));
+ assert.deepEqual(scene.parts[0].material.subsurface, { weight: 1, radius: [1, 0.2, 0.1], scale: 0.05 });
+ assert.throws(() => createAgentScene(recipeWithMaterial({ subsurface: { weight: 2 } })), /subsurface.weight/);
+ assert.throws(() => createAgentScene(recipeWithMaterial({ subsurface: { radius: [1, 1] } })), /subsurface.radius/);
+ assert.match(AGENT_SCENE_CAPABILITIES.materialSubsurface, /Principled BSDF Subsurface/);
+ assert.deepEqual(SUBSURFACE_DEFAULTS.radius, [1, 0.2, 0.1]);
+ assert.deepEqual(SUBSURFACE_RANGES.weight, [0, 1]);
+});
+
+test('a material without subsurface keeps its batching state and its shader exactly', () => {
+ const plain = materialLayerState({ tag: 'surface' });
+ assert.equal(plain.length, MATERIAL_LAYER_STATE_LENGTH);
+ assert.equal(plain[23], '', 'no block, no extra state');
+ const skin = materialLayerState({ tag: 'surface', subsurface: { weight: 0.5, radius: [1, 0.2, 0.1], scale: 0.05 } });
+ assert.deepEqual(skin.slice(0, 23), plain.slice(0, 23), 'the layers before subsurface do not move');
+ assert.deepEqual(JSON.parse(skin[23]), { weight: 0.5, radius: [1, 0.2, 0.1], scale: 0.05 });
+ const values = subsurfaceUniformValues(JSON.parse(skin[23]));
+ assert.deepEqual(values.slice(0, 1).concat(values.slice(1, 4).map(value => Number(value.toFixed(6)))), [0.5, 0.05, 0.01, 0.005]);
+ assert.deepEqual(values.slice(4), [-1, -1, -1], 'a missing color means the base color');
+
+ const features = SHADER_FEATURES.filter(feature => feature !== 'subsurface');
+ assert.doesNotMatch(createFragmentShader(features), /ubsurface/, 'a shader built without the feature has no subsurface code');
+});
+
+test('the subsurface code loads on demand: the recipe marker finds it, and a renderer without it says which import to add', () => {
+ assert.deepEqual(agentSceneModulesNeeded(recipeWithMaterial({ subsurface: { weight: 1 } })), ['subsurfaceShader']);
+ assert.deepEqual(agentSceneModulesNeeded(recipeWithMaterial({ roughness: 0.4 })), []);
+ const script = `
+ const { createFragmentShader } = await import('./src/shaders.js');
+ try { createFragmentShader(['subsurface']); console.log('no error'); } catch (error) { console.log(error.message); }
+ await import('./src/subsurface-shader.js');
+ console.log(createFragmentShader(['subsurface']).includes('subsurfaceLight(normal, color, visibility)'));
+ console.log(createFragmentShader([]).includes('subsurfaceLight'));
+ `;
+ const output = execFileSync(process.execPath, ['--input-type=module', '-e', script], { cwd: new URL('..', import.meta.url), encoding: 'utf8' }).trim().split('\n');
+ assert.match(output[0], /subsurface feature needs its shader code: add import '@codepawlhq\/67js\/addons\/subsurface-shader'/);
+ assert.equal(output[1], 'true');
+ assert.equal(output[2], 'false');
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index b9ac3e4f..ccd04664 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -61,6 +61,7 @@ export default defineConfig({
'liquid-shader': 'src/liquid-shader.js',
'world-material-shader': 'src/world-material-shader.js',
'splat-shader': 'src/splat-shader.js',
+ 'subsurface-shader': 'src/subsurface-shader.js',
'light-linking': 'src/light-linking.js',
'cascaded-shadows': 'src/cascaded-shadows.js',
'gaussian-splats': 'src/gaussian-splats.js',