3D engine that AI agents drive
Move anisotropy and iridescence shader code out of the core bundle
Nguyen Xuan An0bd131365f4a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 467422fb..ad4c5d71 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@## Unreleased+- Move the anisotropy and iridescence shader code out of the core bundle (part of issue #51). It lives in the new `addons/material-layer-shaders` entry, which registers it on import; the renderer asks for it only when a part uses a layer, so a lit box no longer pays for it. A scene that uses a layer in code must import the entry first, or the renderer throws a message that names the import. Recipes load it through `loadAgentSceneModules`, the MCP server does so itself, and the glTF loader loads it for a file that uses either extension. The unused short overloads of `environmentLighting` are gone. Pictures are unchanged.- Add anisotropy and iridescence material layers, and a depth of field for each timeline shot (part of issue #51). Recipe materials take `anisotropy` and `anisotropyRotation` (highlights stretch along a grain, as `KHR_materials_anisotropy`) and `iridescence`, `iridescenceIor` and `iridescenceThickness` (a thin film that shifts reflection colour with the view angle, as `KHR_materials_iridescence`, after Belcour and Barla). Both are compiled out of the shader unless a part uses them, the MCP schema takes them with one short line each, and glTF import and export read and write the two extensions, so they no longer warn as accepted but not rendered. Transmissive materials draw in their own pass and ignore both; `scene_inspect` diagnostics say so. Recipe materials already accepted `clearcoat`, `transmission`, `thickness` and `ior` with the `surface` tag (a demo film that could not ask for them was running an older build, and its murky marble came from the `liquid` tag, which absorbs by thickness): `scene_capabilities` now lists every layer with its range under `scene.materialLayers`, and `npm run smoke:material-layers` renders a glass ball through the real MCP server and checks that the stripes behind it are bent. A timeline shot also takes `focusDistance` (0.01 to 100000 m) and `blur` (0 to 1), which replace the recipe depth of field for that shot only; sampling stays stateless, so a seek gives the same bytes as the frame in a sequence. `bench/reference` gets a `brushed-film` scene scored against Cycles and EEVEE, and the 11 older scenes did not move by more than 0.002 against Cycles.- Add `67js/addons/path-tracer` (part of issue #57; the Cycles comparison is partial). `renderPathTracedImage({ parts, environment, camera }, options)` draws a still by CPU path tracing against the triangle BVH of the light bake, with next-event estimation for the sun, point, spot and area lights, an importance-sampled environment map, GGX metal, clear coat, glass, maps and cutouts, and a wavelet denoiser, on up to eight module workers. An `image` render job selects it with `settings.renderer: { type: "pathTracer", samples, bounces, denoise, seed, maxSeconds }`; the same recipe and seed give the same PNG, a job past `maxSeconds` fails with no image, and samples, size and ray work are bounded. It loads on demand: the core bundle and the agent scene do not carry it (the limits live in `src/path-tracer-capabilities.js`, listed under `jobs.pathTracer` in `scene_capabilities`; the tool schemas gain one `renderer` field inside the total budget). `npm run reference -- --path-tracer` scores it against Cycles: better than the rasterizer on 7 of the 11 reference scenes (`lit-interior` 0.5055 to 0.1993, `spot-area` 0.1242 to 0.0639), worse on `outdoor-hdri`, `character` and `fog`, mean 0.171 against 0.189. Not drawn: volume fog, normal maps, translucent leaves, caustics, lights seen in mirrors. `src/ray-query.js` now holds the ray query and light falloff that `light-bake` used to carry. `npm run smoke:path-tracer` checks it through MCP.- Test the docs and the MCP server on clients other than Claude Code (part of issue #69). New `npm run check:tool-schemas` and `tests/other-clients.test.js` check all 22 tool definitions against rules other clients apply: name characters and length, a description under 1024 characters, an object root, a type on every constrained schema, resolvable `$ref`, declared `required` fields, a strict JSON Schema 2020-12 compile (Ajv 8, now a dev dependency) and an empty-argument call. Reports for OpenAI `strict: true` and for Gemini's documented keyword subset list each gap with its schema path; the test fails when a new kind of gap appears. Measured: the MCP SDK client and the MCP Inspector CLI list the 22 tools and call `scene_create`; a draft-07 Ajv compile rejects every tool (`$schema`, then `prefixItems`), strict OpenAI tools would reject the optional-heavy schemas, and nothing was run on Codex, Cursor, Gemini or any non-Anthropic model. A cold Haiku read of only the README and `llms.txt` installed the package and rendered a box but found no route to a PNG without MCP, so `docs/guide.md` gains a tested "Render a PNG from a script without MCP" recipe that the README and `llms.txt` point to; `docs/mcp.md` gains an "Other clients and models" table and no longer pins the standalone launch to 0.9.1. A test checks that every page `llms.txt` and the README link to exists. Schema bytes are unchanged.diff --git a/bench/reference/harness.js b/bench/reference/harness.jsindex 5c1f8672..71932c75 100644--- a/bench/reference/harness.js+++ b/bench/reference/harness.js@@ -2,6 +2,7 @@import { Renderer67 } from '/src/renderer.js';import { REFERENCE_SCENES } from './scenes.js';import { skinnedGeometry } from '/src/path-tracer-scene.js';+import '/src/material-layer-shaders.js';function encodeBytes(typedArray) {const bytes = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);diff --git a/bench/size/baseline.json b/bench/size/baseline.jsonindex 36e2bac9..481348bd 100644--- a/bench/size/baseline.json+++ b/bench/size/baseline.json@@ -14,9 +14,9 @@},"bundles": {"entry:core": {- "min": 283499,- "gzip": 80972,- "brotli": 69112+ "min": 285004,+ "gzip": 81468,+ "brotli": 69421},"entry:model": {"min": 40093,@@ -39,9 +39,14 @@"brotli": 7331},"entry:gltf": {- "min": 154791,- "gzip": 47466,- "brotli": 40652+ "min": 155888,+ "gzip": 47824,+ "brotli": 41448+ },+ "entry:gltf+lazy": {+ "min": 162321,+ "gzip": 49816,+ "brotli": 43258},"entry:modeling": {"min": 21149,@@ -139,29 +144,29 @@"brotli": 762},"entry:agent-scene": {- "min": 204745,- "gzip": 62551,- "brotli": 54219+ "min": 207007,+ "gzip": 63240,+ "brotli": 55154},"entry:agent-scene+lazy": {- "min": 597754,- "gzip": 202334,- "brotli": 176571+ "min": 606840,+ "gzip": 205144,+ "brotli": 179345},"entry:agent-asset": {- "min": 299072,- "gzip": 93045,- "brotli": 81048+ "min": 301225,+ "gzip": 94044,+ "brotli": 82276},"entry:agent-asset+lazy": {- "min": 633820,- "gzip": 212853,- "brotli": 185359+ "min": 642797,+ "gzip": 215974,+ "brotli": 188447},"entry:hdri": {"min": 8075,"gzip": 3138,- "brotli": 2801+ "brotli": 2802},"entry:camera-effects": {"min": 23985,@@ -173,25 +178,35 @@"gzip": 1608,"brotli": 1425},+ "entry:material-layer-shaders": {+ "min": 71379,+ "gzip": 18505,+ "brotli": 16205+ },"scene:lit-box": {- "min": 214877,- "gzip": 58928,- "brotli": 50227+ "min": 215844,+ "gzip": 59286,+ "brotli": 50588},"scene:gltf-box": {- "min": 273787,- "gzip": 78107,- "brotli": 67034+ "min": 275471,+ "gzip": 79332,+ "brotli": 68903+ },+ "scene:gltf-box+lazy": {+ "min": 281904,+ "gzip": 81319,+ "brotli": 70712},"scene:agent-scene": {- "min": 314066,- "gzip": 91720,- "brotli": 78757+ "min": 316815,+ "gzip": 93587,+ "brotli": 81398},"scene:agent-scene+lazy": {- "min": 707075,- "gzip": 231506,- "brotli": 201092+ "min": 716648,+ "gzip": 235492,+ "brotli": 205636}}}diff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex f11fd99b..07af6f90 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -6,12 +6,13 @@"agent-scene": 100000},"budgets": {- "entry:core": 82600,+ "entry:core": 83100,"entry:model": 14400,"entry:nature": 13200,"entry:motion": 13600,"entry:canvas2d": 9400,- "entry:gltf": 48500,+ "entry:gltf": 48800,+ "entry:gltf+lazy": 50900,"entry:modeling": 8700,"entry:sculpt": 2500,"entry:surface": 10100,@@ -31,16 +32,18 @@"entry:light-bake": 25400,"entry:path-tracer": 12900,"entry:texture-set": 900,- "entry:agent-scene": 63900,- "entry:agent-scene+lazy": 206400,- "entry:agent-asset": 95000,- "entry:agent-asset+lazy": 217200,+ "entry:agent-scene": 64600,+ "entry:agent-scene+lazy": 209300,+ "entry:agent-asset": 96000,+ "entry:agent-asset+lazy": 220300,"entry:hdri": 3300,"entry:camera-effects": 8600,"entry:render-passes": 1700,- "scene:lit-box": 60200,- "scene:gltf-box": 79700,- "scene:agent-scene": 93600,- "scene:agent-scene+lazy": 236200+ "entry:material-layer-shaders": 18900,+ "scene:lit-box": 60500,+ "scene:gltf-box": 81000,+ "scene:gltf-box+lazy": 83000,+ "scene:agent-scene": 95500,+ "scene:agent-scene+lazy": 240300}}diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.jsonindex 6fc77d65..7b728ab1 100644--- a/bench/tool-cost-budgets.json+++ b/bench/tool-cost-budgets.json@@ -1,5 +1,5 @@{- "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818)",+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 11520 (measured 11457)","schemaTotalBytes": 190830,"schemaToolBytes": {"scene_create": 62480,@@ -10,7 +10,7 @@},"schemaOtherToolBytes": 4000,"resultBytes": {- "scene_capabilities": 9910,+ "scene_capabilities": 11520,"scene_create": 1400,"scene_inspect": 1400,"mesh_inspect": 1200,diff --git a/docs/material-maps.md b/docs/material-maps.mdindex 3b853aed..ecce3b4c 100644--- a/docs/material-maps.md+++ b/docs/material-maps.md@@ -127,7 +127,7 @@ A material on a standard tag (`surface` in recipes, `gltf` and `armor` in code)| `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. |-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 code is compiled out of the shader unless a part uses them (the `anisotropy` and `iridescence` shader features), so a scene without them draws with the same shader as before.+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`.Limits, stated plainly:diff --git a/package.json b/package.jsonindex e9c6dabd..b2cb18c6 100644--- a/package.json+++ b/package.json@@ -78,6 +78,7 @@"./addons/hdri": "./build/hdri.js","./addons/camera-effects": "./build/camera-effects.js","./addons/render-passes": "./build/render-passes.js",+ "./addons/material-layer-shaders": "./build/material-layer-shaders.js","./package.json": "./package.json"},"scripts": {diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.jsindex b0e732b3..d1b41d7e 100644--- a/src/agent-scene-modules.js+++ b/src/agent-scene-modules.js@@ -1,5 +1,5 @@// Code that most recipes never run loads on demand, so the agent scene entry stays small. A recipe that uses mesh-// editing, procedural modeling, motion or material patterns needs its module loaded before createAgentScene runs:+// editing, procedural modeling, motion, material patterns or the anisotropy and iridescence layers needs its module loaded before createAgentScene runs:// call `await loadAgentSceneModules(recipe)` (or `loadAllAgentSceneModules()` in a host that does not mind the// size). createAgentScene is still synchronous; when a needed module is missing it says which call to make.@@ -14,6 +14,7 @@ const MODULE_LOADERS = {patterns: () => import('./material-patterns.js'),relations: () => import('./agent-relations.js'),timeline: () => import('./film-timeline.js'),+ layerShaders: () => import('./material-layer-shaders.js'),};const loadedModules = {};@@ -33,6 +34,7 @@ const MODULE_MARKERS = {patterns: ['"pattern"'],relations: ['"relations":'],timeline: ['"timeline":{'],+ layerShaders: ['"anisotropy"', '"iridescence"'],};/** Whether a recipe, operation list or edit list contains a boolean edit, which needs loadMeshBooleans() first. */diff --git a/src/agent-scene.js b/src/agent-scene.jsindex 2b8375e5..d3ce4727 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -189,6 +189,7 @@ function copyMaterialLayers(value, result) {result[field] = Array.isArray(value[field]) ? vector(value[field], 3, field) : value[field];}validateMaterialLayers(result);+ if (result.anisotropy > 0 || result.iridescence > 0) agentSceneModule('layerShaders');}function materialFrom(value) {diff --git a/src/environment.js b/src/environment.jsindex e603b597..6f58baa7 100644--- a/src/environment.js+++ b/src/environment.js@@ -296,13 +296,6 @@ vec3 environmentLighting(vec3 normal, vec3 specularNormal, vec3 baseReflectance,return (specular + diffuse) * occlusion * ambient;}-vec3 environmentLighting(vec3 normal, vec3 viewDirection, vec3 color, float metallic, float roughness, float occlusion, float ambient, float specularWeight) {- return environmentLighting(normal, normal, mix(materialDielectric, color, metallic), viewDirection, color, metallic, roughness, occlusion, ambient, specularWeight);-}--vec3 environmentLighting(vec3 normal, vec3 viewDirection, vec3 color, float metallic, float roughness, float occlusion, float ambient) {- return environmentLighting(normal, viewDirection, color, metallic, roughness, occlusion, ambient, 1.0);-}`;export const environmentBackgroundFragment = `#version 300 esdiff --git a/src/gltf.js b/src/gltf.jsindex 941707f8..8e148d0a 100644--- a/src/gltf.js+++ b/src/gltf.js@@ -14,6 +14,14 @@ export const GLTF_CAPABILITIES = Object.freeze({unsupported: ['more than four skin influences', 'singular weighted skin transforms', 'reflected skin transforms', 'TANGENT morph targets', 'morph targets without authored base normals', 'vertex alpha below one', 'different texture transforms on one material', 'skinned or morphed GPU instancing', 'textures inside material layer extensions (factors only)'],});+const LAYER_SHADER_EXTENSIONS = Object.freeze(['KHR_materials_anisotropy', 'KHR_materials_iridescence']);++// The shader code for anisotropy and iridescence is not in the core bundle; a file that uses either brings it in.+async function loadLayerShadersFor(document) {+ const usesLayerShaders = (document.materials ?? []).some(material => LAYER_SHADER_EXTENSIONS.some(extension => material?.extensions?.[extension]));+ if (usesLayerShaders) await import('./material-layer-shaders.js');+}+const DEFAULT_MAX_BYTES = 32 * 1024 * 1024;const DEFAULT_MAX_VERTICES = 2_000_000;const GLTF_ALPHA_MODES = { OPAQUE: 'opaque', MASK: 'mask', BLEND: 'blend' };@@ -758,6 +766,7 @@ export async function parseGltf(data, options = {}) {const document = documentFrom(data, limits.maxBytes);const decoders = options.decoders ?? {};const { ignoredExtensions } = validateDocument(document, limits, allowedExtensionsFor(decoders));+ await loadLayerShadersFor(document);const warnings = ignoredExtensions.map(extension => `${extension} is accepted but not rendered.`);const dataBytes = typeof data === 'string' ? new TextEncoder().encode(data).byteLength : data.byteLength;const resourceBytes = await prepareResources(document, data, dataBytes, options, limits);diff --git a/src/material-layer-shaders.js b/src/material-layer-shaders.jsnew file mode 100644index 00000000..3f51edf1--- /dev/null+++ b/src/material-layer-shaders.js@@ -0,0 +1,157 @@+import { registerShaderFeatureCode } from './shaders.js';++// Shader code for the anisotropy and iridescence material layers. It lives outside shaders.js so that a scene that+// uses neither layer never downloads it: the renderer asks for it only when a part uses a layer, and importing this+// module (or loading it through loadAgentSceneModules or the glTF loader) registers it.+// The GLSL has no comments, because comments ship to every page:+// - anisotropyStrength, anisotropyTangent, anisotropyBitangent, iridescenceWeight and iridescentReflectance are the+// per-pixel state main sets once and every light reads; clearCoatLayer zeroes it because the coat is plain.+// - anisotropicSpecular is anisotropic GGX with height-correlated visibility as in KHR_materials_anisotropy (rougher+// along the tangent), including the 1 / (4 N.L N.V) term. setAnisotropyFrame takes the UV tangent, or rings the+// world up axis without UVs, and turns it about the normal. Image-based light is looked up along a normal bent+// toward the grain (Filament).+// - filmReflectance is thin-film interference after Belcour and Barla 2017, as three.js uses it for+// KHR_materials_iridescence; filmReflectanceAtNormal turns the film's Fresnel at this view angle back into the+// reflectance at normal incidence that a Schlick curve needs.++const ANISOTROPY_DECLARATIONS = `uniform vec2 materialAnisotropy;+float anisotropyStrength = 0.0;+vec3 anisotropyTangent = vec3(1.0, 0.0, 0.0);+vec3 anisotropyBitangent = vec3(0.0, 0.0, 1.0);+float anisotropicSpecular(vec3 normal, vec3 viewDirection, vec3 lightDirection, vec3 halfway, float alpha) {+ float alphaTangent = mix(alpha, 1.0, anisotropyStrength * anisotropyStrength);+ float alphaBitangent = alpha;+ float normalLight = max(dot(normal, lightDirection), 0.0001);+ float normalView = max(dot(normal, viewDirection), 0.001);+ float normalHalf = max(dot(normal, halfway), 0.0);+ float tangentHalf = dot(anisotropyTangent, halfway) / alphaTangent;+ float bitangentHalf = dot(anisotropyBitangent, halfway) / alphaBitangent;+ float shape = tangentHalf * tangentHalf + bitangentHalf * bitangentHalf + normalHalf * normalHalf;+ float distribution = 1.0 / (PI * alphaTangent * alphaBitangent * shape * shape);+ vec3 viewScaled = vec3(alphaTangent * dot(anisotropyTangent, viewDirection), alphaBitangent * dot(anisotropyBitangent, viewDirection), normalView);+ vec3 lightScaled = vec3(alphaTangent * dot(anisotropyTangent, lightDirection), alphaBitangent * dot(anisotropyBitangent, lightDirection), normalLight);+ float visibility = 0.5 / max(normalLight * length(viewScaled) + normalView * length(lightScaled), 0.00001);+ return distribution * visibility;+}++void setAnisotropyFrame(vec3 normal) {+ vec3 tangent = vec3(0.0);+ vec2 uvX = dFdx(textureUV);+ vec2 uvY = dFdy(textureUV);+ float uvScale = max(max(abs(uvX.x), abs(uvX.y)), max(abs(uvY.x), abs(uvY.y)));+ if (uvScale > 0.0) {+ uvX /= uvScale;+ uvY /= uvScale;+ float determinant = uvX.x * uvY.y - uvX.y * uvY.x;+ if (determinant != 0.0) tangent = (dFdx(worldPosition) * uvY.y - dFdy(worldPosition) * uvX.y) / determinant;+ }+ tangent -= normal * dot(normal, tangent);+ float tangentScale = max(max(abs(tangent.x), abs(tangent.y)), abs(tangent.z));+ if (tangentScale == 0.0) {+ vec3 ringAxis = abs(normal.y) > 0.99 ? vec3(1.0, 0.0, 0.0) : vec3(0.0, 1.0, 0.0);+ tangent = cross(ringAxis, normal);+ tangentScale = 1.0;+ }+ tangent = normalize(tangent / tangentScale);+ vec3 bitangent = cross(normal, tangent);+ anisotropyTangent = tangent * cos(materialAnisotropy.y) + bitangent * sin(materialAnisotropy.y);+ anisotropyBitangent = cross(normal, anisotropyTangent);+}++`;++const ANISOTROPY_ILLUMINATE_SPECULAR = ` if (anisotropyStrength > 0.0) specular = anisotropicSpecular(normal, viewDirection, lightDirection, halfway, max(alpha, 0.002)) * reflectance;+`;++const ANISOTROPY_COAT_RESET = ` anisotropyStrength = 0.0;+`;++const ANISOTROPY_MAIN_SETUP = ` if (materialAnisotropy.x > 0.0) {+ anisotropyStrength = materialAnisotropy.x;+ setAnisotropyFrame(normal);+ vec3 grainSide = cross(anisotropyBitangent, viewDirection);+ vec3 grainNormal = cross(grainSide, anisotropyBitangent);+ specularNormal = normalize(mix(normal, grainNormal, anisotropyStrength * clamp(5.0 * roughness, 0.0, 1.0)));+ }+`;++registerShaderFeatureCode('anisotropy', Object.freeze({+ declarations: ANISOTROPY_DECLARATIONS,+ illuminateSpecular: ANISOTROPY_ILLUMINATE_SPECULAR,+ coatReset: ANISOTROPY_COAT_RESET,+ mainSetup: ANISOTROPY_MAIN_SETUP,+}));++const IRIDESCENCE_DECLARATIONS = `uniform vec3 materialIridescence;+float iridescenceWeight = 0.0;+vec3 iridescentReflectance = vec3(0.04);++vec3 filmSensitivity(float pathDifference, vec3 phaseShift) {+ float phase = 2.0 * PI * pathDifference * 1.0e-9;+ vec3 amplitude = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13);+ vec3 position = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06);+ vec3 variance = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09);+ vec3 xyz = amplitude * sqrt(2.0 * PI * variance) * cos(position * phase + phaseShift) * exp(-phase * phase * variance);+ xyz.x += 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + phaseShift.x) * exp(-4.5282e+09 * phase * phase);+ xyz /= 1.0685e-7;+ mat3 xyzToLinearRgb = mat3(3.2404542, -0.9692660, 0.0556434, -1.5371385, 1.8760108, -0.2040259, -0.4985314, 0.0415560, 1.0572252);+ return xyzToLinearRgb * xyz;+}++vec3 filmReflectance(float filmIor, float cosineView, float thickness, vec3 baseReflectance) {+ float outsideIor = 1.0;+ float filmIndex = mix(outsideIor, filmIor, smoothstep(0.0, 0.03, thickness));+ float sineFilmSquared = pow(outsideIor / filmIndex, 2.0) * (1.0 - cosineView * cosineView);+ if (sineFilmSquared > 1.0) return vec3(1.0);+ float cosineFilm = sqrt(1.0 - sineFilmSquared);+ float topNormal = pow((filmIndex - outsideIor) / (filmIndex + outsideIor), 2.0);+ float topFresnel = topNormal + (1.0 - topNormal) * pow(1.0 - cosineView, 5.0);+ float topTransmission = 1.0 - topFresnel;+ float topPhase = filmIndex < outsideIor ? PI : 0.0;+ vec3 clampedBase = clamp(baseReflectance, 0.0, 0.9999);+ vec3 baseIor = (1.0 + sqrt(clampedBase)) / (1.0 - sqrt(clampedBase));+ vec3 bottomNormal = pow((baseIor - filmIndex) / (baseIor + filmIndex), vec3(2.0));+ vec3 bottomFresnel = bottomNormal + (1.0 - bottomNormal) * pow(1.0 - cosineFilm, 5.0);+ vec3 bottomPhase = vec3(baseIor.x < filmIndex ? PI : 0.0, baseIor.y < filmIndex ? PI : 0.0, baseIor.z < filmIndex ? PI : 0.0);+ float pathDifference = 2.0 * filmIndex * thickness * cosineFilm;+ vec3 phase = vec3(PI - topPhase) + bottomPhase;+ vec3 roundTrip = clamp(topFresnel * bottomFresnel, 1e-5, 0.9999);+ vec3 roundTripRoot = sqrt(roundTrip);+ vec3 multiple = topTransmission * topTransmission * bottomFresnel / (vec3(1.0) - roundTrip);+ vec3 total = topFresnel + multiple;+ vec3 term = multiple - topTransmission;+ for (int order = 1; order <= 2; order++) {+ term *= roundTripRoot;+ total += term * 2.0 * filmSensitivity(float(order) * pathDifference, float(order) * phase);+ }+ return max(total, vec3(0.0));+}++vec3 filmReflectanceAtNormal(vec3 filmFresnel, float cosineView) {+ float power = clamp(pow(1.0 - cosineView, 5.0), 0.0, 0.9999);+ return clamp((filmFresnel - power) / (1.0 - power), 0.0, 1.0);+}++`;++const IRIDESCENCE_ILLUMINATE_REFLECTANCE = ` baseReflectance = mix(baseReflectance, iridescentReflectance, iridescenceWeight);+`;++const IRIDESCENCE_COAT_RESET = ` iridescenceWeight = 0.0;+`;++const IRIDESCENCE_MAIN_SETUP = ` if (materialIridescence.x > 0.0) {+ float cosineView = clamp(dot(normal, viewDirection), 0.001, 1.0);+ vec3 filmFresnel = filmReflectance(materialIridescence.y, cosineView, materialIridescence.z, baseReflectance);+ iridescentReflectance = filmReflectanceAtNormal(filmFresnel, cosineView);+ iridescenceWeight = materialIridescence.x;+ baseReflectance = mix(baseReflectance, iridescentReflectance, iridescenceWeight);+ }+`;++registerShaderFeatureCode('iridescence', Object.freeze({+ declarations: IRIDESCENCE_DECLARATIONS,+ illuminateReflectance: IRIDESCENCE_ILLUMINATE_REFLECTANCE,+ coatReset: IRIDESCENCE_COAT_RESET,+ mainSetup: IRIDESCENCE_MAIN_SETUP,+}));diff --git a/src/shaders.js b/src/shaders.jsindex 08081a5d..c34d5a41 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -345,7 +345,7 @@ void main() {outputColor = vec4(behind * transmittance * transmitted * (1.0 - reflectance) * (1.0 - fog) + displayed(surfaceLight), 1.0);}`;-function buildFragmentShader(featureDefines) {+function buildFragmentShader(featureDefines, featureCode) {return `#version 300 es${featureDefines}precision highp float;@@ -418,8 +418,6 @@ uniform int boxMapAxis;uniform vec3 materialDielectric;uniform vec2 materialCoat;uniform vec4 materialSheen;-uniform vec2 materialAnisotropy;-uniform vec3 materialIridescence;uniform vec4 materialMoss;uniform float hdrEnabled;uniform float alphaMode;@@ -536,29 +534,7 @@ vec3 studio(vec3 direction, float roughness) {${environmentLookupGlsl}${environmentShadingGlsl}-float anisotropyStrength = 0.0;-vec3 anisotropyTangent = vec3(1.0, 0.0, 0.0);-vec3 anisotropyBitangent = vec3(0.0, 0.0, 1.0);-float iridescenceWeight = 0.0;-vec3 iridescentReflectance = vec3(0.04);--float anisotropicSpecular(vec3 normal, vec3 viewDirection, vec3 lightDirection, vec3 halfway, float alpha) {- float alphaTangent = mix(alpha, 1.0, anisotropyStrength * anisotropyStrength);- float alphaBitangent = alpha;- float normalLight = max(dot(normal, lightDirection), 0.0001);- float normalView = max(dot(normal, viewDirection), 0.001);- float normalHalf = max(dot(normal, halfway), 0.0);- float tangentHalf = dot(anisotropyTangent, halfway) / alphaTangent;- float bitangentHalf = dot(anisotropyBitangent, halfway) / alphaBitangent;- float shape = tangentHalf * tangentHalf + bitangentHalf * bitangentHalf + normalHalf * normalHalf;- float distribution = 1.0 / (PI * alphaTangent * alphaBitangent * shape * shape);- vec3 viewScaled = vec3(alphaTangent * dot(anisotropyTangent, viewDirection), alphaBitangent * dot(anisotropyBitangent, viewDirection), normalView);- vec3 lightScaled = vec3(alphaTangent * dot(anisotropyTangent, lightDirection), alphaBitangent * dot(anisotropyBitangent, lightDirection), normalLight);- float visibility = 0.5 / max(normalLight * length(viewScaled) + normalView * length(lightScaled), 0.00001);- return distribution * visibility;-}--vec3 illuminate(vec3 normal, vec3 viewDirection, vec3 lightDirection, vec3 radiance, vec3 color, float metallic, float roughness) {+${featureCode("declarations")}vec3 illuminate(vec3 normal, vec3 viewDirection, vec3 lightDirection, vec3 radiance, vec3 color, float metallic, float roughness) {float normalLight = max(dot(normal, lightDirection), 0.0);if (normalLight == 0.0) return vec3(0);vec3 halfway = normalize(viewDirection + lightDirection);@@ -571,11 +547,9 @@ vec3 illuminate(vec3 normal, vec3 viewDirection, vec3 lightDirection, vec3 radiafloat geometry = normalView / (normalView * (1.0 - masking) + masking);geometry *= normalLight / (normalLight * (1.0 - masking) + masking);vec3 baseReflectance = mix(materialDielectric, color, metallic);- if (USES_IRIDESCENCE) baseReflectance = mix(baseReflectance, iridescentReflectance, iridescenceWeight);- vec3 reflectance = fresnel(max(dot(halfway, viewDirection), 0.0), baseReflectance);+${featureCode("illuminateReflectance")} vec3 reflectance = fresnel(max(dot(halfway, viewDirection), 0.0), baseReflectance);vec3 specular = distribution * geometry * reflectance / max(4.0 * normalView * normalLight, 0.001);- if (USES_ANISOTROPY && anisotropyStrength > 0.0) specular = anisotropicSpecular(normal, viewDirection, lightDirection, halfway, max(alpha, 0.002)) * reflectance;- vec3 diffuse = (1.0 - reflectance) * (1.0 - metallic) * color / PI;+${featureCode("illuminateSpecular")} vec3 diffuse = (1.0 - reflectance) * (1.0 - metallic) * color / PI;return (diffuse + specular) * radiance * normalLight;}@@ -684,9 +658,7 @@ vec3 surroundingsColor(vec3 direction, float roughness) {// Passing 0.04 as the colour of a fully metallic surface gives the lobe's own reflectance and no diffuse part.vec3 clearCoatLayer(vec3 baseRadiance, vec3 normal, vec3 viewDirection, float visibility) {float roughness = clamp(materialCoat.y, 0.075, 1.0);- anisotropyStrength = 0.0;- iridescenceWeight = 0.0;- float coatFresnel = fresnel(max(dot(normal, viewDirection), 0.001), vec3(0.04)).x * materialCoat.x;+${featureCode("coatReset")} float coatFresnel = fresnel(max(dot(normal, viewDirection), 0.001), vec3(0.04)).x * materialCoat.x;vec3 mirror = surroundingsColor(reflect(-viewDirection, normal), roughness) * coatFresnel * ambientIntensity;vec3 highlight = illuminate(normal, viewDirection, normalize(lightDirection), keyColor * visibility, vec3(0.04), 1.0, roughness);return baseRadiance * (1.0 - coatFresnel) + mirror + highlight * materialCoat.x;@@ -710,76 +682,6 @@ vec3 sheenLayer(vec3 baseRadiance, vec3 normal, vec3 viewDirection, float visibireturn baseRadiance * shadowedBase + keyTerm + rimTerm;}-void setAnisotropyFrame(vec3 normal) {- vec3 tangent = vec3(0.0);- vec2 uvX = dFdx(textureUV);- vec2 uvY = dFdy(textureUV);- float uvScale = max(max(abs(uvX.x), abs(uvX.y)), max(abs(uvY.x), abs(uvY.y)));- if (uvScale > 0.0) {- uvX /= uvScale;- uvY /= uvScale;- float determinant = uvX.x * uvY.y - uvX.y * uvY.x;- if (determinant != 0.0) tangent = (dFdx(worldPosition) * uvY.y - dFdy(worldPosition) * uvX.y) / determinant;- }- tangent -= normal * dot(normal, tangent);- float tangentScale = max(max(abs(tangent.x), abs(tangent.y)), abs(tangent.z));- if (tangentScale == 0.0) {- vec3 ringAxis = abs(normal.y) > 0.99 ? vec3(1.0, 0.0, 0.0) : vec3(0.0, 1.0, 0.0);- tangent = cross(ringAxis, normal);- tangentScale = 1.0;- }- tangent = normalize(tangent / tangentScale);- vec3 bitangent = cross(normal, tangent);- anisotropyTangent = tangent * cos(materialAnisotropy.y) + bitangent * sin(materialAnisotropy.y);- anisotropyBitangent = cross(normal, anisotropyTangent);-}--vec3 filmSensitivity(float pathDifference, vec3 phaseShift) {- float phase = 2.0 * PI * pathDifference * 1.0e-9;- vec3 amplitude = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13);- vec3 position = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06);- vec3 variance = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09);- vec3 xyz = amplitude * sqrt(2.0 * PI * variance) * cos(position * phase + phaseShift) * exp(-phase * phase * variance);- xyz.x += 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + phaseShift.x) * exp(-4.5282e+09 * phase * phase);- xyz /= 1.0685e-7;- mat3 xyzToLinearRgb = mat3(3.2404542, -0.9692660, 0.0556434, -1.5371385, 1.8760108, -0.2040259, -0.4985314, 0.0415560, 1.0572252);- return xyzToLinearRgb * xyz;-}--vec3 filmReflectance(float filmIor, float cosineView, float thickness, vec3 baseReflectance) {- float outsideIor = 1.0;- float filmIndex = mix(outsideIor, filmIor, smoothstep(0.0, 0.03, thickness));- float sineFilmSquared = pow(outsideIor / filmIndex, 2.0) * (1.0 - cosineView * cosineView);- if (sineFilmSquared > 1.0) return vec3(1.0);- float cosineFilm = sqrt(1.0 - sineFilmSquared);- float topNormal = pow((filmIndex - outsideIor) / (filmIndex + outsideIor), 2.0);- float topFresnel = topNormal + (1.0 - topNormal) * pow(1.0 - cosineView, 5.0);- float topTransmission = 1.0 - topFresnel;- float topPhase = filmIndex < outsideIor ? PI : 0.0;- vec3 clampedBase = clamp(baseReflectance, 0.0, 0.9999);- vec3 baseIor = (1.0 + sqrt(clampedBase)) / (1.0 - sqrt(clampedBase));- vec3 bottomNormal = pow((baseIor - filmIndex) / (baseIor + filmIndex), vec3(2.0));- vec3 bottomFresnel = bottomNormal + (1.0 - bottomNormal) * pow(1.0 - cosineFilm, 5.0);- vec3 bottomPhase = vec3(baseIor.x < filmIndex ? PI : 0.0, baseIor.y < filmIndex ? PI : 0.0, baseIor.z < filmIndex ? PI : 0.0);- float pathDifference = 2.0 * filmIndex * thickness * cosineFilm;- vec3 phase = vec3(PI - topPhase) + bottomPhase;- vec3 roundTrip = clamp(topFresnel * bottomFresnel, 1e-5, 0.9999);- vec3 roundTripRoot = sqrt(roundTrip);- vec3 multiple = topTransmission * topTransmission * bottomFresnel / (vec3(1.0) - roundTrip);- vec3 total = topFresnel + multiple;- vec3 term = multiple - topTransmission;- for (int order = 1; order <= 2; order++) {- term *= roundTripRoot;- total += term * 2.0 * filmSensitivity(float(order) * pathDifference, float(order) * phase);- }- return max(total, vec3(0.0));-}--vec3 filmReflectanceAtNormal(vec3 filmFresnel, float cosineView) {- float power = clamp(pow(1.0 - cosineView, 5.0), 0.0, 0.9999);- return clamp((filmFresnel - power) / (1.0 - power), 0.0, 1.0);-}-// Raw data for a render pass: modes are 1 albedo, 2 normal, 3 emission, 4 depth, 5 object ID. Depth packs 16 bits// into red and green, object IDs pack 24 bits into red, green and blue. Nothing here is tone mapped or graded.vec3 renderPassValue(vec3 color, vec3 normal, vec3 emission) {@@ -888,21 +790,7 @@ void main() {}vec3 specularNormal = normal;vec3 baseReflectance = mix(materialDielectric, color, metallic);- if (USES_ANISOTROPY && materialAnisotropy.x > 0.0) {- anisotropyStrength = materialAnisotropy.x;- setAnisotropyFrame(normal);- vec3 grainSide = cross(anisotropyBitangent, viewDirection);- vec3 grainNormal = cross(grainSide, anisotropyBitangent);- specularNormal = normalize(mix(normal, grainNormal, anisotropyStrength * clamp(5.0 * roughness, 0.0, 1.0)));- }- if (USES_IRIDESCENCE && materialIridescence.x > 0.0) {- float cosineView = clamp(dot(normal, viewDirection), 0.001, 1.0);- vec3 filmFresnel = filmReflectance(materialIridescence.y, cosineView, materialIridescence.z, baseReflectance);- iridescentReflectance = filmReflectanceAtNormal(filmFresnel, cosineView);- iridescenceWeight = materialIridescence.x;- baseReflectance = mix(baseReflectance, iridescentReflectance, iridescenceWeight);- }- float visibility = shadowVisibility(normal);+${featureCode("mainSetup")} float visibility = shadowVisibility(normal);vec3 radiance = illuminate(normal, viewDirection, normalize(lightDirection), keyColor * visibility, color, metallic, roughness);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, color, metallic, roughness);radiance += illuminate(normal, viewDirection, normalize(vec3(1.0, 2.0, 5.0)), vec3(0.6, 0.7, 0.8) * mix(1.0, 0.25 * daylight, worldMode) * fillIntensity, color, metallic, roughness);@@ -1030,16 +918,6 @@ void main() {}`;}-// Anisotropy and iridescence (the GLSL has no comments, because comments ship to every page):-// - anisotropyStrength, anisotropyTangent, anisotropyBitangent, iridescenceWeight and iridescentReflectance are the-// per-pixel state main sets once and every light reads; clearCoatLayer zeroes it because the coat is plain.-// - anisotropicSpecular is anisotropic GGX with height-correlated visibility as in KHR_materials_anisotropy (rougher-// along the tangent), including the 1 / (4 N.L N.V) term. setAnisotropyFrame takes the UV tangent, or rings the-// world up axis without UVs, and turns it about the normal. Image-based light is looked up along a normal bent-// toward the grain (Filament).-// - filmReflectance is thin-film interference after Belcour and Barla 2017, as three.js uses it for-// KHR_materials_iridescence; filmReflectanceAtNormal turns the film's Fresnel at this view angle back into the-// reflectance at normal incidence that a Schlick curve needs.// Every feature the main fragment shader can leave out, with the GLSL condition that turns it on. A feature that a scene// never uses becomes the constant `false`, so the driver drops its code instead of compiling and branching over it.const SHADER_FEATURE_CONDITIONS = {@@ -1051,8 +929,6 @@ const SHADER_FEATURE_CONDITIONS = {splat: ['USES_SPLAT', 'splatEnabled > 0.5'],moss: ['USES_MOSS', 'materialMoss.x > 0.0'],alphaMode: ['USES_ALPHA_MODE', 'alphaMode > 0.5'],- anisotropy: ['USES_ANISOTROPY', 'materialAnisotropy.x > 0.0'],- iridescence: ['USES_IRIDESCENCE', 'materialIridescence.x > 0.0'],floor: ['TAG_FLOOR', 'surface.w == 2.0'],water: ['TAG_WATER', 'surface.w == 3.0'],foliage: ['TAG_FOLIAGE', 'surface.w == 4.0'],@@ -1067,13 +943,37 @@ const SHADER_FEATURE_CONDITIONS = {renderPass: ['USES_RENDER_PASS', 'renderPassMode > 0.5'],};+// A feature that is not in the list above has its GLSL in another module, so a scene that never uses it does not carry+// it. That module calls registerShaderFeatureCode on import, with blocks of GLSL that createFragmentShader splices in:+// declarations, illuminateReflectance, illuminateSpecular, coatReset and mainSetup, each ending in a newline.+const registeredFeatureCode = new Map();++/** Register the GLSL of an optional feature. Called by the module that holds it, on import. */+export function registerShaderFeatureCode(feature, slots) {+ registeredFeatureCode.set(feature, slots);+}++function requireFeatureCode(feature) {+ const slots = registeredFeatureCode.get(feature);+ if (!slots) {+ throw new Error(`The ${feature} layer needs its shader code: add import '@codepawlhq/67js/addons/material-layer-shaders' (a recipe: await loadAgentSceneModules(recipe)).`);+ }+ return slots;+}++function featureCodeSplicer(features) {+ const codes = features.filter(feature => !(feature in SHADER_FEATURE_CONDITIONS)).map(requireFeatureCode);+ return slot => codes.map(code => code[slot] ?? '').join('');+}+export const SHADER_FEATURES = Object.freeze(Object.keys(SHADER_FEATURE_CONDITIONS));+/** The fragment shader for a set of features. A feature with separate code throws until its module is imported. */export function createFragmentShader(features = SHADER_FEATURES) {const enabled = new Set(features);const lines = Object.entries(SHADER_FEATURE_CONDITIONS).map(([feature, [macro, condition]]) => `#define ${macro} ${enabled.has(feature) ? `(${condition})` : 'false'}`);lines.push('#define CANOPY_TAG (TAG_FOLIAGE || TAG_GRASS)');- return buildFragmentShader(lines.join('\n'));+ return buildFragmentShader(lines.join('\n'), featureCodeSplicer([...enabled]));}export const fragmentShader = createFragmentShader();diff --git a/tests/material-layer-shaders.test.js b/tests/material-layer-shaders.test.jsnew file mode 100644index 00000000..d2dbc308--- /dev/null+++ b/tests/material-layer-shaders.test.js@@ -0,0 +1,37 @@+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import test from 'node:test';++const SHADERS_PATH = new URL('../src/shaders.js', import.meta.url);+const RENDERER_PATH = new URL('../src/renderer.js', import.meta.url);++test('the core shader sources carry no anisotropy or iridescence code', () => {+ for (const path of [SHADERS_PATH, RENDERER_PATH]) {+ const source = readFileSync(path, 'utf8');+ assert.doesNotMatch(source, /anisotropicSpecular|filmReflectance|setAnisotropyFrame/, `${path.pathname} holds layer GLSL`);+ }+});++test('the static graph of the core shaders does not reach the layer shader module', () => {+ for (const path of [SHADERS_PATH, RENDERER_PATH]) {+ assert.doesNotMatch(readFileSync(path, 'utf8'), /(from|import\() *'\.\/material-layer-shaders/);+ }+});++test('a layer without registered code fails with the import to add', async () => {+ const { createFragmentShader, fragmentShader } = await import('../src/shaders.js?without-layer-code');+ assert.doesNotMatch(fragmentShader, /anisotropicSpecular|filmReflectance/);+ assert.throws(() => createFragmentShader(['anisotropy']), /anisotropy material layer needs its shader code.*addons\/material-layer-shaders/);+ assert.throws(() => createFragmentShader(['iridescence']), /iridescence material layer needs its shader code.*addons\/material-layer-shaders/);+ assert.doesNotThrow(() => createFragmentShader(['water']));+});++test('importing the layer shader module registers the code for the shader that asked for it', async () => {+ await import('../src/material-layer-shaders.js');+ const { createFragmentShader } = await import('../src/shaders.js');+ const shader = createFragmentShader(['anisotropy', 'iridescence']);+ assert.match(shader, /float anisotropicSpecular\(/);+ assert.match(shader, /vec3 filmReflectance\(/);+ assert.doesNotMatch(createFragmentShader(['anisotropy']), /filmReflectance/);+ assert.doesNotMatch(createFragmentShader(['iridescence']), /anisotropicSpecular/);+});diff --git a/tests/shader-features.test.js b/tests/shader-features.test.jsindex 00f5a6ca..71bdf881 100644--- a/tests/shader-features.test.js+++ b/tests/shader-features.test.js@@ -1,6 +1,7 @@import assert from 'node:assert/strict';import test from 'node:test';import { createFragmentShader, fragmentShader, SHADER_FEATURES } from '../src/shaders.js';+import '../src/material-layer-shaders.js';test('the default fragment shader keeps every feature', () => {assert.equal(fragmentShader, createFragmentShader(SHADER_FEATURES));@@ -10,7 +11,7 @@ test('the default fragment shader keeps every feature', () => {test('a feature that a scene does not use becomes a constant false', () => {const plain = createFragmentShader([]);- for (const macro of ['USES_NORMAL_MAP', 'USES_SPLAT', 'USES_MOSS', 'USES_ALPHA_MODE', 'USES_ANISOTROPY', 'USES_IRIDESCENCE', 'TAG_WATER', 'TAG_FIRE']) {+ for (const macro of ['USES_NORMAL_MAP', 'USES_SPLAT', 'USES_MOSS', 'USES_ALPHA_MODE', 'TAG_WATER', 'TAG_FIRE']) {assert.match(plain, new RegExp(`#define ${macro} false`));}const withWater = createFragmentShader(['water']);@@ -27,10 +28,12 @@ test('every feature condition is a macro that the shader body uses', () => {});test('anisotropy and iridescence compile in only when a material asks for them', () => {+ const plain = createFragmentShader([]);+ assert.doesNotMatch(plain, /anisotropicSpecular|filmReflectance|materialAnisotropy|materialIridescence/);const withAnisotropy = createFragmentShader(['anisotropy']);- assert.match(withAnisotropy, /#define USES_ANISOTROPY \(materialAnisotropy\.x > 0\.0\)/);- assert.match(withAnisotropy, /#define USES_IRIDESCENCE false/);+ assert.match(withAnisotropy, /uniform vec2 materialAnisotropy;/);+ assert.doesNotMatch(withAnisotropy, /materialIridescence/);const withIridescence = createFragmentShader(['iridescence']);- assert.match(withIridescence, /#define USES_IRIDESCENCE \(materialIridescence\.x > 0\.0\)/);- assert.match(withIridescence, /#define USES_ANISOTROPY false/);+ assert.match(withIridescence, /uniform vec3 materialIridescence;/);+ assert.doesNotMatch(withIridescence, /materialAnisotropy/);});diff --git a/vite.lib.config.js b/vite.lib.config.jsindex 4611299f..8ca43649 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -43,6 +43,7 @@ export default defineConfig({hdri: 'src/hdri.js','camera-effects': 'src/camera-effects.js','render-passes': 'src/render-passes.js',+ 'material-layer-shaders': 'src/material-layer-shaders.js',// Page of the MCP preview. It imports the engine chunks above instead of bundling its own copy.'mcp/preview': 'scripts/agent-preview-browser.js',},