Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add anisotropy, iridescence and per-shot depth of field

Nguyen Xuan Anbc8c07ddeccf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 84d2c8bb..dd34bb63 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- 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.
+
- Fix the next agent tool errors (part of issue #66). `scene_review` and `scene_look` with `labels` on an imported asset failed with "needs the mesh code" because asset creation loaded the on-demand scene modules only for mesh edits; it now always does, and a test walks every preview path in a fresh process. `geometries` and `materials` are optional in a recipe. A failed `scene_create` says no scene was created and to call it again. `scene_inspect` on an asset accepts a source-node ID that holds one part and names the parts of one that holds several.
- Fix the most common agent tool errors (part of issue #66). `scene_look` and `scene_review` with `labels` on an imported asset threw `Cannot read properties of undefined (reading 'map')` (an asset recipe has no materials list, and asset mesh reports are keyed by part ID); an engine fault now reaches the agent as one advice message and goes to stderr. A node that names a geometry and no material gets an explicit `default` material instead of an error. `sessionId` is optional on every tool and defaults to the active scene (189,159 to 188,872 schema bytes); an ID that names another scene is still rejected. `scene_apply` names the fix when `set-node` fields are wrapped in `node`. The bench look harness loads the on-demand scene modules, so motion recipes get a look score.
diff --git a/bench/reference/README.md b/bench/reference/README.md
index a66c2e87..39bea2bb 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -1,6 +1,6 @@
# Reference renders
-This suite scores how close a 67js render is to Blender on 11 fixed scenes. Later work uses these scores as its starting point.
+This suite scores how close a 67js render is to Blender on 12 fixed scenes. Later work uses these scores as its starting point.
## Run it
@@ -26,6 +26,7 @@ Measured on 2026-10-30 with an RTX 3060, SwiftShader and Blender 5.2.2. The metr
| `lit-interior` | 0.4997 | 0.5159 | 0.1204 | No indirect light, and point lights cast no shadows |
| `spot-area` | 0.1242 | 0.1935 | 0.1707 | The sphere is lit more weakly at its shaded edge, and the wall has no bounce light |
| `brick-graph` | 0.2269 | 0.1440 | 0.1480 | Bump is weaker than Blender's Bump node, so the joints cast less shadow, and Blender's noise is not 67js noise, so brick tone differs |
+| `brushed-film` | 0.1613 | 0.0939 | 0.1601 | The film colours on the dark sphere are close to Cycles, but its reflections are softer; the brushed highlight is pinched less at the pole, and there is no ground bounce under the spheres |
Rows are the baseline taken before shadows for point lights. The `lit-interior` scene now sets `castShadow` on its three point lights. With shadows, 67js scores 0.5055 against Cycles (0.4997 before, so 0.0058 worse) and 0.0923 against EEVEE (0.1204 before, better): the shadow shape now matches, but Cycles fills its shadows with indirect light and 67js leaves them dark. The committed `lit-interior` row stays at the earlier numbers. `spot-area` is new with shadows, a spot light and an area light.
@@ -33,6 +34,8 @@ Light bake (issue #55): `npm run reference -- --bake lit-interior` bakes bounced
`brick-graph` (issue #50) is a wall of bricks written as one material graph (triangle waves for the joints, half a brick of shift on every second course, noise through a colour ramp, height as bump) on a quad with UVs, so it uses `mapping: "uv"`. `render-blender.py` translates the same graph JSON into Blender nodes (Math, Map Range, Noise Texture, Color Ramp, Mix and Bump), so each side evaluates its own nodes. It measured 0.2269 against Cycles and 0.1440 for EEVEE on 2026-10-31. A first run scored 0.4027 and showed a black wall in 67js: the `min` and `max` nodes returned NaN. The scene found that bug. The other rows were re-measured in the same run; `glass` against Cycles moved from 0.1450 to 0.1326 and `lit-interior` to the with-shadows numbers described above, and no other score moved by more than 0.002.
+`brushed-film` (issue #51) holds a brushed gold sphere (`anisotropy` 0.8), a dark sphere with a thin film (`iridescence`, IOR 1.3, 400 nm) and a silver sphere with the same film. `render-blender.py` maps the glTF anisotropy model onto Blender's aspect ratio (alpha along the tangent is `mix(alpha, 1, strength^2)`, so Blender gets Anisotropic = (1 - alpha / alpha_tangent) / 0.9 and the geometric-mean roughness) and feeds a UV-map Tangent node, because Blender's default tangent is a different field: with the default tangent the first run scored 0.1673 against Cycles and the highlight ran in rings where 67js had bands; with the UV tangent it scores 0.1613 and the highlight direction matches. Thin film goes to Principled Thin Film Thickness and IOR. EEVEE draws no thin film, so its sphere stays black. The two models are not the same: Blender's film is its own Fresnel integration, 67js uses Belcour and Barla at the view angle, so match the colours by eye in the image, not by the score alone. Measured 2026-11-01 on the RTX 3060 and SwiftShader. Before and after adding anisotropy and iridescence, every older scene scored the same against Cycles and EEVEE to four digits (largest change 0.0000, limit 0.002), because their shaders compile the two layers out.
+
The mean against Cycles is 0.198 for 67js and 0.160 for EEVEE. The mean difference between the RTX 3060 and SwiftShader is 0.007.
EEVEE against Cycles is a yardstick: it shows what a good rasterizer scores. In `lit-interior` and `fog`, EEVEE scores no better than 67js. Those two scenes depend on indirect light, and this suite does not use EEVEE light probes. A low score does not mean a good picture on its own, so read each score with its image in `images/`.
diff --git a/bench/reference/baseline.json b/bench/reference/baseline.json
index dfa58394..d12c095b 100644
--- a/bench/reference/baseline.json
+++ b/bench/reference/baseline.json
@@ -6,6 +6,10 @@
"cycles": 8.9,
"eevee": 15.2
},
+ "brushed-film": {
+ "cycles": 7.6,
+ "eevee": 7.4
+ },
"car-paint": {
"cycles": 35.4,
"eevee": 82.5
@@ -60,6 +64,14 @@
"eevee-vs-cycles": 0.144,
"gpu-vs-cpu": 0.0074
},
+ "brushed-film": {
+ "gpu-vs-cycles": 0.1613,
+ "gpu-vs-eevee": 0.1601,
+ "cpu-vs-cycles": 0.1613,
+ "cpu-vs-eevee": 0.1601,
+ "eevee-vs-cycles": 0.0939,
+ "gpu-vs-cpu": 0.0058
+ },
"car-paint": {
"gpu-vs-cycles": 0.1521,
"gpu-vs-eevee": 0.1323,
diff --git a/bench/reference/images/brushed-film.jpg b/bench/reference/images/brushed-film.jpg
new file mode 100644
index 00000000..ce7b47d4
Binary files /dev/null and b/bench/reference/images/brushed-film.jpg differ
diff --git a/bench/reference/render-blender.py b/bench/reference/render-blender.py
index 3e395b00..97a4ee3a 100644
--- a/bench/reference/render-blender.py
+++ b/bench/reference/render-blender.py
@@ -134,6 +134,32 @@ def add_vertex_colors(material, principled, description):
links.new(multiply.outputs["Color"], principled.inputs["Base Color"])
+def add_anisotropy(principled, description):
+ """Maps the glTF anisotropy model (rougher along the tangent) onto Blender's aspect-ratio model."""
+ strength = description.get("anisotropy", 0)
+ if strength <= 0:
+ return
+ alpha = description.get("roughness", 0.5) ** 2
+ alpha_tangent = alpha + (1 - alpha) * strength ** 2
+ # Blender stretches alpha by 1 / aspect along the tangent and by aspect across it, aspect = sqrt(1 - 0.9 * Anisotropic).
+ principled.inputs["Anisotropic"].default_value = min((1 - alpha / alpha_tangent) / 0.9, 1)
+ principled.inputs["Roughness"].default_value = (alpha * alpha_tangent) ** 0.25
+ principled.inputs["Anisotropic Rotation"].default_value = description.get("anisotropyRotation", 0) / (2 * math.pi)
+ # 67js takes the grain along the U direction of the UV map; Blender's default tangent is a different field.
+ tree = principled.id_data
+ tangent = tree.nodes.new("ShaderNodeTangent")
+ tangent.direction_type = "UV_MAP"
+ tangent.uv_map = "UVMap"
+ tree.links.new(tangent.outputs["Tangent"], principled.inputs["Tangent"])
+
+
+def add_thin_film(principled, description):
+ if description.get("iridescence", 0) <= 0:
+ return
+ principled.inputs["Thin Film Thickness"].default_value = description.get("iridescenceThickness", 400)
+ principled.inputs["Thin Film IOR"].default_value = description.get("iridescenceIor", 1.3)
+
+
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)
@@ -148,6 +174,8 @@ def add_material_layers(material, principled, description):
# Blender's specular level 0.5 is the 4 percent reflectance that 67js calls specular 1.
principled.inputs["Specular IOR Level"].default_value = 0.5 * description.get("specular", 1)
set_linear_color(principled.inputs["Specular Tint"], description.get("specularColor", [1, 1, 1]))
+ add_anisotropy(principled, description)
+ add_thin_film(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 26cca8c1..2a3cf816 100644
--- a/bench/reference/scenes.js
+++ b/bench/reference/scenes.js
@@ -219,6 +219,23 @@ export const REFERENCE_SCENES = {
};
},
+ // Anisotropy and iridescence against Cycles: a brushed gold sphere, a dark dielectric with a thin film and a silver one.
+ async 'brushed-film'() {
+ const lighting = await skyLighting();
+ const parts = [
+ floor([0.2, 0.2, 0.22]),
+ part('brushed-gold', sphere(96, 64), [-1.6, 0.8, 0], [0.8, 0.8, 0.8], { color: [1, 0.77, 0.34], metallic: 1, roughness: 0.35, anisotropy: 0.8 }),
+ part('oil-film', sphere(96, 64), [0, 0.8, 0], [0.8, 0.8, 0.8], { color: [0.02, 0.02, 0.025], roughness: 0.15, iridescence: 1, iridescenceIor: 1.3, iridescenceThickness: 400 }),
+ part('film-on-silver', sphere(96, 64), [1.6, 0.8, 0], [0.8, 0.8, 0.8], { color: [0.9, 0.9, 0.92], metallic: 1, roughness: 0.2, iridescence: 1, iridescenceIor: 1.3, iridescenceThickness: 400 }),
+ ];
+ return {
+ parts, blenderWorld: lighting.blenderWorld,
+ environment: environment(lighting, { keyColor: SUN_COLOR }),
+ camera: { eye: [0, 2.2, 7], target: [0, 0.7, 0], up: [0, 1, 0], fov: 35, near: 0.1, far: 200 },
+ shadow: { eye: [-6, 12, 8], target: [0, 0, 0], up: [0, 1, 0], extent: 6, near: 0.1, far: 40 },
+ };
+ },
+
async metal() {
const lighting = await skyLighting();
const parts = [
diff --git a/bench/size/baseline.json b/bench/size/baseline.json
index dfc42b9e..29ceaed8 100644
--- a/bench/size/baseline.json
+++ b/bench/size/baseline.json
@@ -14,9 +14,9 @@
},
"bundles": {
"entry:core": {
- "min": 283396,
- "gzip": 80960,
- "brotli": 69030
+ "min": 291224,
+ "gzip": 82878,
+ "brotli": 70674
},
"entry:model": {
"min": 40093,
@@ -39,9 +39,9 @@
"brotli": 7331
},
"entry:gltf": {
- "min": 154791,
- "gzip": 47466,
- "brotli": 40652
+ "min": 162083,
+ "gzip": 49171,
+ "brotli": 42078
},
"entry:modeling": {
"min": 21149,
@@ -134,28 +134,28 @@
"brotli": 762
},
"entry:agent-scene": {
- "min": 204341,
- "gzip": 62404,
- "brotli": 54057
+ "min": 213311,
+ "gzip": 64903,
+ "brotli": 56243
},
"entry:agent-scene+lazy": {
- "min": 597350,
- "gzip": 202187,
- "brotli": 176409
+ "min": 606683,
+ "gzip": 204805,
+ "brotli": 178684
},
"entry:agent-asset": {
- "min": 298200,
- "gzip": 92709,
- "brotli": 80775
+ "min": 307638,
+ "gzip": 95450,
+ "brotli": 83096
},
"entry:agent-asset+lazy": {
- "min": 632948,
- "gzip": 212517,
- "brotli": 185086
+ "min": 642749,
+ "gzip": 215373,
+ "brotli": 187445
},
"entry:hdri": {
"min": 8075,
- "gzip": 3138,
+ "gzip": 3139,
"brotli": 2801
},
"entry:camera-effects": {
@@ -169,24 +169,24 @@
"brotli": 1425
},
"scene:lit-box": {
- "min": 214877,
- "gzip": 58928,
- "brotli": 50227
+ "min": 222335,
+ "gzip": 60778,
+ "brotli": 51782
},
"scene:gltf-box": {
- "min": 273787,
- "gzip": 78107,
- "brotli": 67034
+ "min": 281459,
+ "gzip": 80004,
+ "brotli": 68504
},
"scene:agent-scene": {
- "min": 313662,
- "gzip": 91569,
- "brotli": 78717
+ "min": 323006,
+ "gzip": 94308,
+ "brotli": 81013
},
"scene:agent-scene+lazy": {
- "min": 706671,
- "gzip": 231355,
- "brotli": 201052
+ "min": 716378,
+ "gzip": 234207,
+ "brotli": 203426
}
}
}
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index c1facaf7..c6b3d84e 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -6,12 +6,12 @@
"agent-scene": 100000
},
"budgets": {
- "entry:core": 82600,
+ "entry:core": 82900,
"entry:model": 14400,
"entry:nature": 13200,
"entry:motion": 13600,
"entry:canvas2d": 9400,
- "entry:gltf": 48500,
+ "entry:gltf": 49200,
"entry:modeling": 8700,
"entry:sculpt": 2500,
"entry:surface": 10100,
@@ -30,16 +30,16 @@
"entry:clutter": 5300,
"entry:light-bake": 25400,
"entry:texture-set": 900,
- "entry:agent-scene": 63700,
+ "entry:agent-scene": 65000,
"entry:agent-scene+lazy": 206300,
- "entry:agent-asset": 94600,
+ "entry:agent-asset": 95500,
"entry:agent-asset+lazy": 216800,
"entry:hdri": 3300,
"entry:camera-effects": 8600,
"entry:render-passes": 1700,
- "scene:lit-box": 60200,
- "scene:gltf-box": 79700,
- "scene:agent-scene": 93500,
+ "scene:lit-box": 60800,
+ "scene:gltf-box": 80100,
+ "scene:agent-scene": 94400,
"scene:agent-scene+lazy": 236000
}
}
diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.json
index 3ac2b7fd..4c7523b0 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",
+ "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 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 schema total fell to 190086 (budget unchanged at 190730) and the scene_capabilities result rose to 11520 (measured 11457)",
"schemaTotalBytes": 190730,
"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/agent-render-jobs.md b/docs/agent-render-jobs.md
index dca5721a..016ea45c 100644
--- a/docs/agent-render-jobs.md
+++ b/docs/agent-render-jobs.md
@@ -68,6 +68,7 @@ editor is a non-goal of the engine (issue #23), so there are no layers, overlaps
| `duration` | 0.1 to 30 s. The timeline holds up to 64 shots and 60 s. |
| `motionStart` | Second of the motion clock the shot starts at. Omitted, the shot reads the motion at its place on the timeline, so a non-looping motion must cover it. Only for recipes with motion, physics or cloth. |
| `camera` | A partial camera (`eye`, `target`, `up`, `fov`, `near`, `far`) on top of the sampled camera. Omitted, the shot keeps the camera of the motion tracks. |
+| `focusDistance`, `blur` | Depth of field for this shot: focus distance 0.01 to 100000 m and blur 0 to 1. Each is optional and replaces the recipe `effects.depthOfField` value for the shot only, so a close-up can pull focus without a global setting. A seek into a shot gives the same bytes as the frame in a sequence. |
| `dip` | 0.05 to 4 s. The previous shot fades to black over the first half and this one fades up over the second half. |
`set-timeline` edits the section and `null` removes it. A job renders it with `settings.timeline: { start }` (default 0) for kind `image`, `stills` or `video`.
diff --git a/docs/gltf.md b/docs/gltf.md
index 50818840..ca43b839 100644
--- a/docs/gltf.md
+++ b/docs/gltf.md
@@ -140,7 +140,7 @@ Line and point primitives are unsupported.
| `KHR_draco_mesh_compression` | Needs `options.decoders.draco`. |
| `EXT_meshopt_compression` | Needs `options.decoders.meshopt`. |
| `KHR_texture_basisu` | Needs `options.decoders.ktx2`. |
-| `KHR_materials_clearcoat`, `_transmission`, `_ior`, `_specular`, `_sheen`, `_volume` | Read as factors and rendered as material layers, see `docs/material-maps.md`. Their textures are ignored. `KHR_materials_anisotropy` and `KHR_materials_iridescence` are accepted but not rendered. Each one used adds a line to `asset.warnings`. Listing one in `extensionsRequired` fails the import. |
+| `KHR_materials_clearcoat`, `_transmission`, `_ior`, `_specular`, `_sheen`, `_volume`, `_anisotropy`, `_iridescence` | Read as factors and rendered as material layers, see `docs/material-maps.md`. Their textures are ignored, and an iridescent film takes the thickness maximum. Export writes them back. |
`KHR_materials_transmission` with a factor above zero sets `material.transmission` to that factor.
It is a hint only: the renderer does not draw transmission yet.
diff --git a/docs/material-maps.md b/docs/material-maps.md
index 5b1444b5..3b853aed 100644
--- a/docs/material-maps.md
+++ b/docs/material-maps.md
@@ -124,8 +124,10 @@ A material on a standard tag (`surface` in recipes, `gltf` and `armor` in code)
| `attenuationColor`, `attenuationDistance` | colour 0 to 1, distance above 0 | The colour light keeps after that many metres inside. Leave the distance out for no absorption. |
| `sheenColor`, `sheenRoughness` | colour 0 to 1, 0 to 1 | A soft glow at grazing angles for cloth. Black is off. |
| `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. |
-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`.
+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.
Limits, stated plainly:
@@ -133,10 +135,12 @@ Limits, stated plainly:
- A transmissive material does not take a clear coat, sheen or maps. Its base map and normal map are ignored.
- The clear coat uses the surface normal and the key light. Point lights add no coat highlight.
- Sheen is the Charlie distribution on the key light plus an ambient rim. It does not use a lookup table for energy loss.
-- Anisotropy and iridescence are not rendered. `KHR_materials_anisotropy` and `KHR_materials_iridescence` load with a warning.
+- A transmissive material draws in its own pass and ignores anisotropy and iridescence; `scene_inspect` diagnostics say so.
+- Anisotropy shapes the key light, the fill, point, spot and area lights and the reflected environment (the lookup is bent along the grain). The clear coat above it stays isotropic.
+- Iridescence uses the thin-film model of Belcour and Barla at the view angle, so the film colour follows the viewer but not each light separately. The clear coat stays plain.
- Textures inside the layer extensions are ignored. Only the factors are read.
-glTF import and export carry these layers through `KHR_materials_clearcoat`, `transmission`, `volume`, `ior`, `specular` and `sheen`. `bench/reference` scores `glass` and `car-paint` against Blender's Principled BSDF with the same values.
+glTF import and export carry these layers through `KHR_materials_clearcoat`, `transmission`, `volume`, `ior`, `specular`, `sheen`, `anisotropy` and `iridescence`. `bench/reference` scores `glass`, `car-paint` and `brushed-film` against Blender's Principled BSDF with the same values.
## Baked graphs and UV patterns
@@ -156,5 +160,5 @@ Unlit materials accept base and emissive maps only.
Texture alpha is ignored for opaque materials, as required by glTF's opaque mode.
This feature does not complete the full material system.
-Anisotropy, iridescence, texture slots inside the layer extensions, node graphs, and authored tangent support remain missing.
+Texture slots inside the layer extensions, node graphs, and authored tangent support remain missing.
GLB export of these material maps is outside this feature.
diff --git a/docs/parity.md b/docs/parity.md
index 7cbaec99..501180ea 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, 8 point lights, 8 spot lights and 4 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, not cascaded. | [lighting](../tests/lighting.test.js), `npm run reference` scene `spot-area` | #52 |
| Rendering > Lights > Light Linking | missing | No 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. | [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. There is no anisotropy, iridescence, subsurface scattering, volume material or displacement. | [texture-set](../tests/texture-set.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. 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 > 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. | [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. There is no anisotropy, iridescence or 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. There is no subsurface. | [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 30f2b4d9..7a872fcf 100644
--- a/package.json
+++ b/package.json
@@ -104,6 +104,7 @@
"smoke:agent-render-jobs": "node scripts/smoke-agent-render-jobs.mjs",
"smoke:render-passes": "node scripts/smoke-render-passes.mjs",
"smoke:film-timeline": "node scripts/smoke-film-timeline.mjs",
+ "smoke:material-layers": "node scripts/smoke-material-layers.mjs",
"smoke:agent-motion": "node scripts/smoke-agent-motion.mjs",
"smoke:agent-physics": "node scripts/smoke-agent-physics.mjs",
"smoke:agent-cloth": "node scripts/smoke-agent-cloth.mjs",
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index bfc34dab..55f26866 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -439,8 +439,8 @@ window.__agentPreview = {
}
},
// `pass` draws one render pass instead of the lit image. Object ID frames also list the part behind each ID.
- // `camera` overrides camera fields (a timeline shot) and `brightness` scales exposure for a dip through black.
- frame({ sessionId, animation, motionTime, rendererTime = 0, pass, passDepthRange, camera: cameraOverrides, brightness = 1 }) {
+ // `camera` overrides camera fields and `depthOfField` the blur and focus distance (a timeline shot); `brightness` scales exposure for a dip through black.
+ frame({ sessionId, animation, motionTime, rendererTime = 0, pass, passDepthRange, camera: cameraOverrides, depthOfField: depthOfFieldOverrides, brightness = 1 }) {
const record = requireSession(sessionId);
if (!Number.isFinite(brightness) || brightness < 0 || brightness > 1) throw new RangeError('Invalid frame brightness.');
if (!Number.isFinite(rendererTime) || rendererTime < 0 || rendererTime > 3600) throw new RangeError('Invalid render time.');
@@ -454,7 +454,11 @@ window.__agentPreview = {
const sampledPreviousCamera = pass ? undefined : previousCameraFor(record, motionTime);
const previousCamera = sampledPreviousCamera && cameraOverrides ? withCameraOverrides(sampledPreviousCamera, cameraOverrides) : sampledPreviousCamera;
const exposure = record.scene.effects.exposure * brightness;
- draw(record, rendererTime, shotCamera, { pass, passDepthRange, previousCamera, ...(brightness === 1 ? {} : { exposure }) });
+ const shotEffects = depthOfFieldOverrides
+ ? { ...record.scene.effects, depthOfField: { ...record.scene.effects.depthOfField, ...depthOfFieldOverrides } }
+ : undefined;
+ draw(record, rendererTime, shotCamera, { pass, passDepthRange, previousCamera,
+ ...(brightness === 1 ? {} : { exposure }), ...(shotEffects ? { effects: shotEffects } : {}) });
const info = renderInfo(record.renderer);
return pass === 'objectId' ? { ...info, objectNames: record.renderer.passSupport.objectNames() } : info;
},
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index 485dbe0c..dc80199f 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -339,6 +339,7 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
...(settings.motion ? { motionTime: settings.motion.start + elapsed } : {}),
...(shotSample?.motionTime == null ? {} : { motionTime: shotSample.motionTime }),
...(shotSample?.camera ? { camera: shotSample.camera } : {}),
+ ...(shotSample?.depthOfField ? { depthOfField: shotSample.depthOfField } : {}),
...(shotSample && shotSample.brightness < 1 ? { brightness: shotSample.brightness } : {}),
...(settings.animation ? { animation: { clip: settings.animation.clip, time: settings.animation.start + elapsed } } : {}) };
const renderStarted = performance.now();
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index cfce04fd..f67eac93 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -77,20 +77,27 @@ function layerColor(field, description) {
return z.tuple([component, component, component]).describe(description).optional();
}
+// One short line each; ranges and details are in scene_capabilities materialLayers.
const materialLayerFields = {
- clearcoat: layerNumber('clearcoat', 'Clear lacquer layer strength, 0 to 1 (car paint, varnish). Needs the surface tag.'),
- clearcoatRoughness: layerNumber('clearcoatRoughness', 'Roughness of the clear coat, 0 mirror to 1 rough.'),
- transmission: layerNumber('transmission', 'Share of light that passes through, 0 to 1 (glass, water, gems). It refracts the opaque scene behind it; blended surfaces do not show through it.'),
- thickness: layerNumber('thickness', 'Metres of material the light crosses. 0 is a thin sheet that does not bend the view; set it with transmission.'),
- ior: layerNumber('ior', 'Index of refraction, 1 to 2.5 (air 1, water 1.33, glass 1.5, diamond 2.42). Also sets how reflective the surface is.'),
- attenuationColor: layerColor('attenuationColor', 'Linear RGB colour that light keeps after attenuationDistance metres inside the material.'),
- attenuationDistance: z.number().positive('attenuationDistance must be above 0. Leave it out for no absorption.').max(3.4e38).describe('Metres inside the material after which light is reduced to attenuationColor.').optional(),
- sheenColor: layerColor('sheenColor', 'Linear RGB soft grazing-angle glow of cloth and velvet; [0, 0, 0] is off.'),
- sheenRoughness: layerNumber('sheenRoughness', 'Width of the sheen glow, 0 tight to 1 broad.'),
- specular: layerNumber('specular', 'Strength of the non-metal reflection, 0 to 4 (1 is normal).'),
- specularColor: layerColor('specularColor', 'Linear RGB tint of the non-metal reflection.'),
+ clearcoat: layerNumber('clearcoat', 'Clear coat strength.'),
+ clearcoatRoughness: layerNumber('clearcoatRoughness', 'Coat roughness.'),
+ transmission: layerNumber('transmission', 'Light passing through (glass).'),
+ thickness: layerNumber('thickness', 'Metres light crosses.'),
+ ior: layerNumber('ior', 'Index of refraction.'),
+ attenuationColor: layerColor('attenuationColor', 'Linear RGB kept after attenuationDistance.'),
+ attenuationDistance: z.number().positive('attenuationDistance must be above 0. Leave it out for no absorption.').max(3.4e38).describe('Metres to reach attenuationColor.').optional(),
+ sheenColor: layerColor('sheenColor', 'Linear RGB cloth glow.'),
+ sheenRoughness: layerNumber('sheenRoughness', 'Sheen width.'),
+ specular: layerNumber('specular', 'Reflection strength.'),
+ specularColor: layerColor('specularColor', 'Reflection tint.'),
+ anisotropy: layerNumber('anisotropy', 'Highlight stretch along a grain.'),
+ anisotropyRotation: layerNumber('anisotropyRotation', 'Grain turn, radians.'),
+ iridescence: layerNumber('iridescence', 'Thin-film colour shift.'),
+ iridescenceIor: layerNumber('iridescenceIor', 'Film index of refraction.'),
+ iridescenceThickness: layerNumber('iridescenceThickness', 'Film thickness, nanometres.'),
};
+
const materialFields = {
...materialLayerFields,
pattern: materialPattern.optional(),
diff --git a/scripts/smoke-material-layers.mjs b/scripts/smoke-material-layers.mjs
new file mode 100644
index 00000000..9f57b2cf
--- /dev/null
+++ b/scripts/smoke-material-layers.mjs
@@ -0,0 +1,176 @@
+// Proves the material layers and the per-shot depth of field through the real MCP server, with stills a person can read.
+// - glass: a surface ball with transmission bends the stripes behind it, and the same ball with transmission 0 does not;
+// - anisotropy: a stretched highlight differs from the round one, and rotating the grain turns it;
+// - iridescence: a thin film changes the colour of the reflection;
+// - shot depth of field: each shot of a timeline blurs and focuses by itself, and a seek repeats the same bytes.
+// Usage: node scripts/smoke-material-layers.mjs [cli] [cpu|gpu]. Stills land in the folder named by LAYER_STILLS if set.
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { copyFile, mkdir, mkdtemp, readFile } from 'node:fs/promises';
+import { tmpdir, constants, setPriority } from 'node:os';
+import { join, resolve } from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const directory = await mkdtemp(join(tmpdir(), '67js-mcp-layers-'));
+const jobs = join(directory, 'jobs');
+const cli = resolve(process.argv[2] ?? 'bin/67js-mcp.mjs');
+const backend = process.argv[3] ?? 'cpu';
+const stillsFolder = process.env.LAYER_STILLS;
+const transport = new StdioClientTransport({ command: process.execPath,
+ args: [cli, '--backend', backend, '--memory', '128', '--jobs', jobs], cwd: directory, stderr: 'pipe' });
+let diagnostics = '';
+transport.stderr.on('data', bytes => { diagnostics = (diagnostics + bytes).slice(-8192); });
+const client = new Client({ name: '67js-material-layers-proof', version: '1' });
+const WIDTH = 320;
+const HEIGHT = 240;
+
+async function call(name, argumentsValue = {}, timeout = 120000) {
+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout });
+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);
+ return result;
+}
+
+async function waitForJob(jobId) {
+ const deadline = Date.now() + 300000;
+ while (Date.now() < deadline) {
+ const record = (await call('scene_render_status', { jobId })).structuredContent;
+ if (['completed', 'cancelled', 'failed'].includes(record.state)) return record;
+ await delay(200);
+ }
+ throw new Error('Job did not finish in time.');
+}
+
+async function renderStill(recipe, settings = {}, name) {
+ const created = (await call('scene_create', { recipe }, 180000)).structuredContent;
+ const sessionId = created.sessionId;
+ try {
+ const submitted = (await call('scene_render_submit', { sessionId, expectedRevision: 0, settings: { kind: 'image', width: WIDTH, height: HEIGHT, ...settings } })).structuredContent;
+ const record = await waitForJob(submitted.jobId);
+ assert.equal(record.state, 'completed', record.reason);
+ const result = (await call('scene_render_result', { jobId: submitted.jobId })).structuredContent;
+ const path = result.artifacts[0].path;
+ if (stillsFolder && name) {
+ await mkdir(stillsFolder, { recursive: true });
+ await copyFile(path, join(stillsFolder, `${name}.png`));
+ }
+ return await readFile(path);
+ } finally {
+ await call('scene_dispose', { sessionId }).catch(() => {});
+ }
+}
+
+function decodeRgb(png) {
+ const result = spawnSync('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-i', 'pipe:0', '-f', 'rawvideo', '-pix_fmt', 'rgb24', 'pipe:1'], { input: png, maxBuffer: 64 * 1024 ** 2 });
+ assert.equal(result.status, 0, String(result.stderr));
+ return result.stdout;
+}
+
+function meanAbsoluteDifference(first, second, region) {
+ const firstPixels = decodeRgb(first);
+ const secondPixels = decodeRgb(second);
+ let total = 0;
+ let count = 0;
+ for (let row = region.top; row < region.bottom; row++) {
+ for (let column = region.left; column < region.right; column++) {
+ for (let channel = 0; channel < 3; channel++) {
+ const index = (row * WIDTH + column) * 3 + channel;
+ total += Math.abs(firstPixels[index] - secondPixels[index]);
+ count++;
+ }
+ }
+ }
+ return total / count;
+}
+
+// Spread of the red channel along the middle row of a region: stripes seen through glass raise it, a flat ball does not.
+function rowSpread(png, region) {
+ const pixels = decodeRgb(png);
+ const row = Math.floor((region.top + region.bottom) / 2);
+ const values = [];
+ for (let column = region.left; column < region.right; column++) values.push(pixels[(row * WIDTH + column) * 3]);
+ const mean = values.reduce((sum, value) => sum + value, 0) / values.length;
+ return Math.sqrt(values.reduce((sum, value) => sum + (value - mean) ** 2, 0) / values.length);
+}
+
+const STRIPE_COLORS = [[0.9, 0.05, 0.05], [0.95, 0.95, 0.95], [0.05, 0.1, 0.9]];
+
+// A wall of vertical colour stripes with one ball in front of it, lit by the default studio.
+function stripesBehindBall(material, { ballTag, extraLook } = {}) {
+ const stripeNodes = [];
+ const stripeMaterials = STRIPE_COLORS.map((color, index) => ({ id: `stripe${index}`, color, roughness: 0.8 }));
+ for (let index = 0; index < 9; index++) {
+ stripeNodes.push({ id: `stripe-${index}`, geometry: 'box', material: `stripe${index % 3}`, translation: [(index - 4) * 0.5, 1, -1.6], scale: [0.5, 3, 0.1] });
+ }
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box' }, { id: 'sphere', type: 'sphere', segments: 48, rings: 32 }],
+ materials: [{ id: 'floor', color: [0.12, 0.12, 0.13], roughness: 0.9 }, ...stripeMaterials, { id: 'ball', ...(ballTag ? { tag: ballTag } : {}), ...material }],
+ nodes: [
+ { id: 'floor', geometry: 'box', material: 'floor', translation: [0, -0.1, 0], scale: [12, 0.2, 12] },
+ ...stripeNodes,
+ { id: 'ball', geometry: 'sphere', material: 'ball', translation: [0, 1, 0], scale: [1.6, 1.6, 1.6] },
+ ],
+ camera: { eye: [0, 1.1, 5], target: [0, 1, 0], fov: 35 },
+ ...extraLook,
+ };
+}
+
+const BALL_REGION = { left: 125, right: 195, top: 85, bottom: 155 };
+
+try {
+ await client.connect(transport);
+ const capabilities = (await call('scene_capabilities')).structuredContent;
+ const layerNames = Object.keys(capabilities.scene?.materialLayers ?? {});
+ for (const field of ['clearcoat', 'transmission', 'thickness', 'ior', 'anisotropy', 'iridescence']) {
+ assert.ok(layerNames.includes(field), `scene_capabilities materialLayers lists ${field}`);
+ }
+
+ // Glass: a recipe material asks for transmission with the surface tag.
+ const glassMaterial = { color: [1, 1, 1], roughness: 0.02, metallic: 0, transmission: 1, thickness: 0.8, ior: 1.5 };
+ const glass = await renderStill(stripesBehindBall(glassMaterial), {}, 'glass');
+ const solid = await renderStill(stripesBehindBall({ ...glassMaterial, transmission: 0 }), {}, 'solid');
+ const glassSpread = rowSpread(glass, BALL_REGION);
+ const solidSpread = rowSpread(solid, BALL_REGION);
+ assert.ok(glassSpread > solidSpread * 2, `Stripes should show through the glass ball (spread ${glassSpread.toFixed(1)} against ${solidSpread.toFixed(1)} for the same ball with no transmission).`);
+ assert.ok(meanAbsoluteDifference(glass, solid, BALL_REGION) > 12, 'Glass and the opaque ball should differ inside the ball.');
+ console.log(`glass: stripe spread ${glassSpread.toFixed(1)} against ${solidSpread.toFixed(1)} without transmission (${backend})`);
+
+ // Anisotropy and iridescence on a brushed metal ball.
+ const metal = { color: [0.9, 0.7, 0.4], metallic: 1, roughness: 0.35 };
+ const round = await renderStill(stripesBehindBall(metal), {}, 'metal-round');
+ const brushed = await renderStill(stripesBehindBall({ ...metal, anisotropy: 0.9 }), {}, 'metal-anisotropic');
+ const turned = await renderStill(stripesBehindBall({ ...metal, anisotropy: 0.9, anisotropyRotation: Math.PI / 2 }), {}, 'metal-anisotropic-turned');
+ assert.ok(meanAbsoluteDifference(round, brushed, BALL_REGION) > 2, 'Anisotropy should change the highlight.');
+ assert.ok(meanAbsoluteDifference(brushed, turned, BALL_REGION) > 2, 'Rotating the grain should turn the highlight.');
+ const plain = { color: [0.05, 0.05, 0.06], metallic: 0, roughness: 0.15 };
+ const filmless = await renderStill(stripesBehindBall(plain), {}, 'film-off');
+ const film = await renderStill(stripesBehindBall({ ...plain, iridescence: 1, iridescenceIor: 1.8, iridescenceThickness: 450 }), {}, 'film-on');
+ assert.ok(meanAbsoluteDifference(filmless, film, BALL_REGION) > 2, 'A thin film should change the reflection colour.');
+ console.log('anisotropy and iridescence stills differ from their plain twins');
+
+ // A shot sets its own depth of field; a seek repeats the same bytes.
+ const shotRecipe = stripesBehindBall({ color: [0.8, 0.8, 0.8], roughness: 0.5 }, {
+ extraLook: { timeline: { shots: [
+ { name: 'sharp', duration: 1 },
+ { name: 'near', duration: 1, focusDistance: 5, blur: 1 },
+ { name: 'far', duration: 1, focusDistance: 40, blur: 1 },
+ ] } },
+ });
+ const sharp = await renderStill(shotRecipe, { timeline: { start: 0.5 } }, 'shot-sharp');
+ const near = await renderStill(shotRecipe, { timeline: { start: 1.5 } }, 'shot-near');
+ const far = await renderStill(shotRecipe, { timeline: { start: 2.5 } }, 'shot-far');
+ const nearAgain = await renderStill(shotRecipe, { timeline: { start: 1.5 } });
+ assert.deepEqual(near, nearAgain, 'A seek into the same shot should repeat the same bytes.');
+ const wholeFrame = { left: 0, right: WIDTH, top: 0, bottom: HEIGHT };
+ assert.ok(meanAbsoluteDifference(sharp, near, wholeFrame) > 0.5, 'The near shot should blur what lies away from its focus.');
+ assert.ok(meanAbsoluteDifference(near, far, wholeFrame) > 0.5, 'Each shot should focus on its own distance.');
+ console.log('shot depth of field: three shots differ and a seek repeats the same bytes');
+} catch (error) {
+ console.error(diagnostics);
+ throw error;
+} finally {
+ await client.close().catch(() => {});
+}
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 8974539d..a6754ab7 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -41,7 +41,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- Polygon modeling by an agent (extrude, inset, loop cut, bevel, booleans, mirror, array, solidify) uses the recipe `mesh` geometry and the MCP tools `mesh_inspect`, `mesh_edit` and `mesh_stack`. Read [mesh-modeling.md](references/mesh-modeling.md) before the first edit; check that the checkout's `docs/mesh.md` exists, since it is unreleased after npm 0.10.0.
- Parts that sit against each other (a handle on a body, a lid on a tank, legs under a top) use the node `relations` field: `attach`, `gap`, `flush`, `align` or `centered` against another mesh node, optionally a tagged `region` of it. They are solved again after every edit, so resize the body with one `set-node` instead of recomputing each part's translation. One relation per axis, no loops. Fields are in `scene_capabilities` `relations`; see "Relations between parts" in the checkout's `docs/agent-scene.md`.
- A surface look in a recipe (wood, planks, bricks, tiles, marble, stone, concrete, metal, rust, fabric) uses the material `pattern` field, which needs no UVs. See "Material patterns" in the checkout's `docs/agent-scene.md`. Your own look (bricks from noise and a ramp, stripes, a pattern that follows `uv_unwrap`) is `pattern: { type: "graph", graph, mapping: "uv" }`: a bounded JSON node graph baked to textures, never shader text; see "Material graphs" there.
-- Glass, water, gems, car paint and cloth in a recipe use the material layer fields `transmission` (with `thickness` and `ior`), `clearcoat`, `sheenColor` and `specular`. A transmissive material needs a nonzero `thickness` to bend the view behind it, and does not show blended surfaces. Ranges and limits are in "Material layers" in the checkout's `docs/material-maps.md`.
+- Glass, water, gems, car paint and cloth in a recipe use the material layer fields `transmission` (with `thickness` and `ior`), `clearcoat`, `sheenColor`, `specular`, `anisotropy` (brushed metal) and `iridescence` (soap, oil). Give glass the default `surface` tag, not `liquid`, which absorbs by thickness and reads murky; anisotropy and iridescence are ignored on a transmissive material. A transmissive material needs a nonzero `thickness` to bend the view behind it, and does not show blended surfaces. Ranges and limits are in "Material layers" in the checkout's `docs/material-maps.md`.
- Layered skeletal animation in code (a clip on some joints only, additive clips, foot planting, reaching, looking at a point) uses `createAssetPose` from `src/skeleton-pose.js` and the checkout's `docs/skeleton-pose.md`. Clip layers are not available through MCP.
- Jointed motion (an arm reaching, a lamp or head tracking a point) on a recipe or an imported character uses `motion.ik`, which needs no quaternions: on a recipe parent the joint nodes and put sizes on child mesh nodes, on an asset find `node-N` IDs with `scene_inspect` kind hierarchy and aim with `worldForward`. Read `motionIk` from `scene_inspect`: besides `reached`, it lists `warnings` (`wrong-bend` when a knee or elbow bends the unnatural way, `hyperextended`) and `limited` (poses a joint limit changed). Give a leg or arm `bendToward` (a world direction, such as `[0, 0, 1]` for a knee on a character facing +z) and `limits` per joint in degrees, and fix any warning before you finish. `motion.constraints` (copy, limit, `track_to`, `child_of`, `floor`, Blender's meanings, Euler XYZ degrees) and `motion.drivers` (a node or material property from a bounded JSON expression) run after IK and give the same pose at any time. On an imported asset, `motion.layers` plays its clips together (a walk layer plus a wave layer masked to `{ "joints": ["node-N"] }` for the arm): list clip ids with `scene_inspect` (`animations`), find joints with kind hierarchy, set `morph: false` on a layer that should not touch the face, and use `bones` to send a clip's track to another node. See "Inverse kinematics", "Clip layers on an asset", "Constraints" and "Drivers" in the checkout's `docs/agent-motion.md`.
- Agent tool calls use the installed `67js-mcp` stdio server from release `0.5.0` onward. Read `docs/mcp.md` for launch and PNG feedback.
diff --git a/src/agent-diagnostics.js b/src/agent-diagnostics.js
index 90664c15..4883055a 100644
--- a/src/agent-diagnostics.js
+++ b/src/agent-diagnostics.js
@@ -5,7 +5,9 @@
* Reads of an inspected scene include them only when there is something to say, to keep default results small.
*/
const PLAIN_SURFACE_TAGS = new Set(['surface', 'gltf']);
-const LAYER_FIELDS = ['clearcoat', 'sheenColor', 'specular', 'specularColor'];
+const LAYER_FIELDS = ['clearcoat', 'sheenColor', 'specular', 'specularColor', 'anisotropy', 'iridescence'];
+// The pass that draws transmission is a separate shader without these layers.
+const FIELDS_IGNORED_BY_TRANSMISSION = ['anisotropy', 'iridescence'];
const TRANSMISSION_DETAIL_FIELDS = ['thickness', 'attenuationColor', 'attenuationDistance'];
function diagnostic(kind, severity, target, message, fix) {
@@ -29,7 +31,13 @@ function materialProblems(material) {
`Remove ${field}, or set the material tag to surface with scene_apply set-material.`));
}
}
- if (!transmitting) {
+ if (transmitting) {
+ for (const field of FIELDS_IGNORED_BY_TRANSMISSION.filter(layer => hasValue(material, layer))) {
+ problems.push(diagnostic('ignored-material-field', 'warning', material.id,
+ `${field} is ignored on a transmitting material.`,
+ `Set transmission to 0 to see ${field}, or remove ${field}.`));
+ }
+ } else {
for (const field of TRANSMISSION_DETAIL_FIELDS.filter(detail => hasValue(material, detail))) {
problems.push(diagnostic('ignored-material-field', 'warning', material.id,
`${field} only matters with transmission, and transmission is 0.`,
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index fc1db414..1e5d0d0e 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -3,6 +3,7 @@ import {
FIELD_OPERATOR_NAMES, FIELD_ATTRIBUTES, MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, INSTANCE_SOURCES, MAX_INSTANCE_CANDIDATES,
IMPORTED_MESH_EDIT_LIMITS,
} from './mesh-operations.js';
+import { MATERIAL_LAYER_FIELDS, MATERIAL_LAYER_SCALAR_RANGES, MATERIAL_LAYER_COLOR_RANGES } from './material-layers.js';
// What agent scenes support and their default limits, as plain data. The MCP server reads these without bundling
// the scene engine (geometry, three.js decoders, the mesh core), which runs in the preview page instead.
@@ -13,7 +14,27 @@ export const AGENT_SCENE_DEFAULT_LIMITS = Object.freeze({
maxOperations: 256, maxCheckpoints: 8, maxRecipeBytes: 1024 * 1024,
});
-export const MATERIAL_PATTERN_TYPES = Object.freeze(['noise', 'wood', 'planks', 'bricks', 'tiles', 'marble', 'stone', 'concrete', 'metal', 'rust', 'fabric']);
+// What each recipe material layer does, beside its range; the MCP schema keeps one short line per field.
+const MATERIAL_LAYER_NOTES = Object.freeze({
+ clearcoat: 'Lacquer lobe over the base, surface tag.',
+ clearcoatRoughness: 'Coat roughness.',
+ transmission: 'Refracts the opaque scene behind it, surface or liquid tag; blended parts do not show through; no anisotropy, iridescence, sheen or coat.',
+ thickness: 'Metres crossed; 0 does not bend the view.',
+ ior: 'Glass 1.5, water 1.33, diamond 2.42; sets the base reflectance.',
+ attenuationColor: 'Linear RGB kept after attenuationDistance.',
+ attenuationDistance: 'Metres to reach attenuationColor; omit for none.',
+ sheenColor: 'Linear RGB glow at grazing angles; black is off.',
+ sheenRoughness: 'Glow width.',
+ specular: 'Non-metal reflection, 1 is normal.',
+ specularColor: 'Linear RGB tint.',
+ anisotropy: 'Stretches highlights along the grain; the grain follows the UV direction, or rings the up axis without UVs.',
+ anisotropyRotation: 'Turns the grain around the normal, radians.',
+ iridescence: 'Thin-film colour shift on reflections.',
+ iridescenceIor: 'Film index of refraction.',
+ iridescenceThickness: 'Film nanometres; colours cycle as it grows.',
+});
+
+export const MATERIAL_PATTERN_TYPES =Object.freeze(['noise', 'wood', 'planks', 'bricks', 'tiles', 'marble', 'stone', 'concrete', 'metal', 'rust', 'fabric']);
export const MAX_MATERIAL_PATTERNS = 16;
// A material graph bakes to textures on the CPU and never becomes shader text. Its node and depth limits are the field
// expression limits; maxWork is work units per pixel times pixels, so a costly graph needs a smaller texture.
@@ -98,6 +119,10 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
'set-environment', 'set-effects', 'set-shadow', 'set-motion', 'set-armatures', 'set-physics', 'set-cloth', 'set-timeline', 'set-particles', 'edit-mesh', 'set-mesh-stack',
]),
materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam']),
+ materialLayers: Object.freeze(Object.fromEntries(MATERIAL_LAYER_FIELDS.map(field => [field, Object.freeze({
+ range: MATERIAL_LAYER_SCALAR_RANGES[field] ?? MATERIAL_LAYER_COLOR_RANGES[field] ?? 'above 0',
+ note: MATERIAL_LAYER_NOTES[field],
+ })]))),
alphaModes: RECIPE_ALPHA_MODES,
materialPatterns: MATERIAL_PATTERN_TYPES, maxMaterialPatterns: MAX_MATERIAL_PATTERNS,
materialMappings: MATERIAL_MAPPINGS,
@@ -105,7 +130,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
// Recipe timeline (src/film-timeline.js), rendered with settings.timeline; the rest is in docs/agent-render-jobs.md.
filmTimeline: Object.freeze({
maxShots: 64, maxTotalSeconds: 60, maxShotSeconds: 30,
- shot: 'name (unique), duration, motionStart (default: the shot start, so non-looping motion must cover it), camera (partial: eye target up fov near far), dip (s; fades through black at the cut into this shot).',
+ shot: 'name (unique), duration, motionStart (default: the shot start, so non-looping motion must cover it), camera (partial: eye target up fov near far), focusDistance (m) and blur (0 to 1) for the depth of field of the shot, dip (s; fades through black at the cut into this shot).',
notSupported: 'layers, overlaps, crossfades, markers, events, imported assets',
}),
curveText: Object.freeze({
diff --git a/src/environment.js b/src/environment.js
index d0714948..e603b597 100644
--- a/src/environment.js
+++ b/src/environment.js
@@ -287,16 +287,19 @@ vec3 environmentDiffuse(vec3 normal) {
return max(result, vec3(0.0)) * environmentIntensity;
}
// specularWeight scales only the reflected sky; leaf cards use less, since their bent normals face the view at grazing angles.
-vec3 environmentLighting(vec3 normal, vec3 viewDirection, vec3 color, float metallic, float roughness, float occlusion, float ambient, float specularWeight) {
+vec3 environmentLighting(vec3 normal, vec3 specularNormal, vec3 baseReflectance, vec3 viewDirection, vec3 color, float metallic, float roughness, float occlusion, float ambient, float specularWeight) {
float normalView = clamp(dot(normal, viewDirection), 0.001, 1.0);
- vec3 baseReflectance = mix(materialDielectric, color, metallic);
vec2 lookup = texture(environmentBrdf, vec2(normalView, roughness)).rg;
vec3 specularColor = (baseReflectance * lookup.x + lookup.y) * specularWeight;
- vec3 specular = environmentRadiance(reflect(-viewDirection, normal), roughness * environmentLevelMax) * specularColor;
+ vec3 specular = environmentRadiance(reflect(-viewDirection, specularNormal), roughness * environmentLevelMax) * specularColor;
vec3 diffuse = environmentDiffuse(normal) * color * (1.0 - metallic) * (1.0 - specularColor);
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);
}
diff --git a/src/film-timeline.js b/src/film-timeline.js
index 293a9a95..82e906ea 100644
--- a/src/film-timeline.js
+++ b/src/film-timeline.js
@@ -7,7 +7,8 @@ export const FILM_TIMELINE_LIMITS = Object.freeze({
});
const SHOT_NAME_PATTERN = /^[A-Za-z0-9_-]{1,24}$/;
-const SHOT_FIELDS = ['name', 'duration', 'motionStart', 'camera', 'dip'];
+const SHOT_FIELDS = ['name', 'duration', 'motionStart', 'camera', 'dip', 'focusDistance', 'blur'];
+const MAX_FOCUS_DISTANCE = 100000;
function plainObject(value, label) {
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype) {
@@ -77,6 +78,12 @@ export function normalizeFilmTimeline(timeline, recipe, { checkCamera } = {}) {
plainObject(shot.camera, `Shot ${shot.name} camera`);
result.camera = checkCamera ? checkCamera(shot.camera) : { ...shot.camera };
}
+ if (shot.focusDistance !== undefined) {
+ result.focusDistance = numberBetween(shot.focusDistance, 0.01, MAX_FOCUS_DISTANCE, `Shot ${shot.name} focusDistance`);
+ }
+ if (shot.blur !== undefined) {
+ result.blur = numberBetween(shot.blur, 0, 1, `Shot ${shot.name} blur`);
+ }
startSeconds += duration;
return result;
});
@@ -114,9 +121,16 @@ function brightnessAt(timeline, starts, index, shotTime) {
return Math.max(0, Math.min(1, brightness));
}
+function depthOfFieldOverrides(shot) {
+ const overrides = {};
+ if (shot.focusDistance !== undefined) overrides.focusDistance = shot.focusDistance;
+ if (shot.blur !== undefined) overrides.blur = shot.blur;
+ return Object.keys(overrides).length > 0 ? overrides : null;
+}
+
/**
* Everything one frame needs at timeline time `time`: the shot, the motion clock (null for a static recipe), the
- * camera overrides and the brightness of a dip through black. It keeps no state, so any seek gives the same answer.
+ * camera overrides, the depth of field overrides (null keeps the recipe's) and the brightness of a dip through black. It keeps no state, so any seek gives the same answer.
*/
export function sampleFilmTimeline(timeline, recipe, time) {
const starts = filmTimelineShotStarts(timeline);
@@ -136,6 +150,6 @@ export function sampleFilmTimeline(timeline, recipe, time) {
const motionTime = hasAnimatedScene(recipe) ? (shot.motionStart ?? starts[index].start) + shotTime : null;
return {
shotIndex: index, shotName: shot.name, shotTime, motionTime,
- camera: shot.camera ?? null, brightness: brightnessAt(timeline, starts, index, shotTime),
+ camera: shot.camera ?? null, depthOfField: depthOfFieldOverrides(shot), brightness: brightnessAt(timeline, starts, index, shotTime),
};
}
diff --git a/src/gltf-layers.js b/src/gltf-layers.js
index 62c3837f..d8b5f480 100644
--- a/src/gltf-layers.js
+++ b/src/gltf-layers.js
@@ -9,6 +9,8 @@ export const GLTF_LAYER_EXTENSIONS = Object.freeze([
'KHR_materials_ior',
'KHR_materials_specular',
'KHR_materials_sheen',
+ 'KHR_materials_anisotropy',
+ 'KHR_materials_iridescence',
]);
// Each row: extension, then the glTF property that feeds each material field.
@@ -19,6 +21,9 @@ const IMPORT_RULES = Object.freeze([
['KHR_materials_ior', { ior: 'ior' }],
['KHR_materials_specular', { specular: 'specularFactor', specularColor: 'specularColorFactor' }],
['KHR_materials_sheen', { sheenColor: 'sheenColorFactor', sheenRoughness: 'sheenRoughnessFactor' }],
+ ['KHR_materials_anisotropy', { anisotropy: 'anisotropyStrength', anisotropyRotation: 'anisotropyRotation' }],
+ // Without a thickness texture the film is as thick as the maximum, so the minimum is not kept.
+ ['KHR_materials_iridescence', { iridescence: 'iridescenceFactor', iridescenceIor: 'iridescenceIor', iridescenceThickness: 'iridescenceThicknessMaximum' }],
]);
/** Layer fields of one glTF material definition, validated, as a plain object to spread onto a material. */
diff --git a/src/gltf.js b/src/gltf.js
index 7676df69..941707f8 100644
--- a/src/gltf.js
+++ b/src/gltf.js
@@ -9,9 +9,9 @@ import { MAX_MORPH_TARGETS, createMorphPose, validateMorphGeometry, validateMorp
export const GLTF_CAPABILITIES = Object.freeze({
formats: ['glb', 'gltf'],
- supported: ['triangle meshes', 'world transforms', 'rigid node animations', 'four-influence skeletal skinning', 'joint node animations', 'relative POSITION/NORMAL morph targets', 'morph weight animations', 'PNG/JPEG base color textures', 'normal/occlusion/emissive/metallic-roughness textures', 'TEXCOORD_0', 'linear RGB vertex colors', 'metallic roughness factors', 'emissive factors', 'alpha mask and blend modes', 'double-sided materials', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength', 'KHR_materials_clearcoat, transmission, volume, ior, specular and sheen factors', 'KHR_texture_transform baked into UVs', 'EXT_mesh_gpu_instancing expanded into parts', 'KHR_draco_mesh_compression with options.decoders.draco', 'EXT_meshopt_compression with options.decoders.meshopt', 'KHR_texture_basisu with options.decoders.ktx2'],
- ignoredExtensions: ['KHR_materials_anisotropy', 'KHR_materials_iridescence'],
- 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)', 'rendering of KHR_materials_anisotropy and KHR_materials_iridescence'],
+ supported: ['triangle meshes', 'world transforms', 'rigid node animations', 'four-influence skeletal skinning', 'joint node animations', 'relative POSITION/NORMAL morph targets', 'morph weight animations', 'PNG/JPEG base color textures', 'normal/occlusion/emissive/metallic-roughness textures', 'TEXCOORD_0', 'linear RGB vertex colors', 'metallic roughness factors', 'emissive factors', 'alpha mask and blend modes', 'double-sided materials', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength', 'KHR_materials_clearcoat, transmission, volume, ior, specular, sheen, anisotropy and iridescence factors', 'KHR_texture_transform baked into UVs', 'EXT_mesh_gpu_instancing expanded into parts', 'KHR_draco_mesh_compression with options.decoders.draco', 'EXT_meshopt_compression with options.decoders.meshopt', 'KHR_texture_basisu with options.decoders.ktx2'],
+ ignoredExtensions: [],
+ 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 DEFAULT_MAX_BYTES = 32 * 1024 * 1024;
diff --git a/src/material-layers.js b/src/material-layers.js
index 3b9fd6cc..f14a5001 100644
--- a/src/material-layers.js
+++ b/src/material-layers.js
@@ -15,6 +15,11 @@ export const MATERIAL_LAYER_DEFAULTS = Object.freeze({
sheenRoughness: 0,
specular: 1,
specularColor: Object.freeze([1, 1, 1]),
+ anisotropy: 0,
+ anisotropyRotation: 0,
+ iridescence: 0,
+ iridescenceIor: 1.3,
+ iridescenceThickness: 400,
});
export const MATERIAL_LAYER_FIELDS = Object.freeze(Object.keys(MATERIAL_LAYER_DEFAULTS));
@@ -27,6 +32,11 @@ export const MATERIAL_LAYER_SCALAR_RANGES = Object.freeze({
ior: Object.freeze([1, 2.5]),
sheenRoughness: UNIT,
specular: Object.freeze([0, 4]),
+ anisotropy: UNIT,
+ anisotropyRotation: Object.freeze([-2 * Math.PI, 2 * Math.PI]),
+ iridescence: UNIT,
+ iridescenceIor: Object.freeze([1, 3]),
+ iridescenceThickness: Object.freeze([0, 1200]),
});
export const MATERIAL_LAYER_COLOR_RANGES = Object.freeze({
@@ -96,7 +106,10 @@ export function dielectricReflectance(material) {
return materialLayerValue(material, 'specularColor').map(component => Math.min(fromIor * component, 1) * weight);
}
-/** Plain values the renderer batches by: dielectric F0 (3), coat (2), sheen (4), transmission (4), attenuation colour (3). */
+/**
+ * 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).
+ */
export function materialLayerState(material) {
validateMaterialLayers(material);
return [
@@ -110,7 +123,12 @@ export function materialLayerState(material) {
materialLayerValue(material, 'thickness'),
materialLayerValue(material, 'attenuationDistance'),
...materialLayerValue(material, 'attenuationColor'),
+ materialLayerValue(material, 'anisotropy'),
+ materialLayerValue(material, 'anisotropyRotation'),
+ materialLayerValue(material, 'iridescence'),
+ materialLayerValue(material, 'iridescenceIor'),
+ materialLayerValue(material, 'iridescenceThickness'),
];
}
-export const MATERIAL_LAYER_STATE_LENGTH = 16;
+export const MATERIAL_LAYER_STATE_LENGTH = 21;
diff --git a/src/renderer.js b/src/renderer.js
index 7ae59a68..fdb8e502 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -56,6 +56,8 @@ function shaderFeaturesOfParts(parts) {
});
if (material.layers) features.add('splat');
if (material.moss > 0) features.add('moss');
+ if (material.anisotropy > 0) features.add('anisotropy');
+ if (material.iridescence > 0) features.add('iridescence');
if ((material.alphaMode ?? 'opaque') !== 'opaque') features.add('alphaMode');
if (TAG_SHADER_FEATURES.has(material.tag)) features.add(material.tag);
}
@@ -520,7 +522,7 @@ export class Renderer67 {
finishMainProgram(pendingProgram) {
this.program = finishProgram(this.context, pendingProgram);
- this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'boxMapScale', 'boxMapAxis', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
+ this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'materialAnisotropy', 'materialIridescence', 'boxMapScale', 'boxMapAxis', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
for (const name of LIGHT_UNIFORMS) {
this.uniforms[name] = this.context.getUniformLocation(this.program, name);
}
@@ -1757,6 +1759,8 @@ export class Renderer67 {
this.context.uniform3f(this.uniforms.materialDielectric, layers[0], layers[1], layers[2]);
this.context.uniform2f(this.uniforms.materialCoat, layers[3], layers[4]);
this.context.uniform4f(this.uniforms.materialSheen, layers[5], layers[6], layers[7], layers[8]);
+ this.context.uniform2f(this.uniforms.materialAnisotropy, layers[16], layers[17]);
+ this.context.uniform3f(this.uniforms.materialIridescence, layers[18], layers[19], layers[20]);
this.context.uniform1f(this.uniforms.boxMapScale, batch.mapState[12]);
this.context.uniform1i(this.uniforms.boxMapAxis, batch.mapState[13]);
this.bindSplat(batch.splat);
diff --git a/src/shaders.js b/src/shaders.js
index 55c99cce..08081a5d 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -418,6 +418,8 @@ 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;
@@ -534,6 +536,28 @@ 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) {
float normalLight = max(dot(normal, lightDirection), 0.0);
if (normalLight == 0.0) return vec3(0);
@@ -546,8 +570,11 @@ vec3 illuminate(vec3 normal, vec3 viewDirection, vec3 lightDirection, vec3 radia
float masking = pow(roughness + 1.0, 2.0) / 8.0;
float geometry = normalView / (normalView * (1.0 - masking) + masking);
geometry *= normalLight / (normalLight * (1.0 - masking) + masking);
- vec3 reflectance = fresnel(max(dot(halfway, viewDirection), 0.0), mix(materialDielectric, color, metallic));
+ vec3 baseReflectance = mix(materialDielectric, color, metallic);
+ if (USES_IRIDESCENCE) baseReflectance = mix(baseReflectance, iridescentReflectance, iridescenceWeight);
+ 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;
return (diffuse + specular) * radiance * normalLight;
}
@@ -657,6 +684,8 @@ 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;
vec3 mirror = surroundingsColor(reflect(-viewDirection, normal), roughness) * coatFresnel * ambientIntensity;
vec3 highlight = illuminate(normal, viewDirection, normalize(lightDirection), keyColor * visibility, vec3(0.04), 1.0, roughness);
@@ -681,6 +710,76 @@ vec3 sheenLayer(vec3 baseRadiance, vec3 normal, vec3 viewDirection, float visibi
return 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) {
@@ -787,6 +886,22 @@ void main() {
roughness = mix(roughness, 1.0, mossCover);
metallic = mix(metallic, 0.0, mossCover);
}
+ 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);
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);
@@ -847,17 +962,17 @@ void main() {
radiance += illuminate(normal, viewDirection, toLight, lightRadiance, color, metallic, roughness);
}
}
- vec3 reflectance = fresnel(max(dot(normal, viewDirection), 0.0), mix(materialDielectric, color, metallic));
+ vec3 reflectance = fresnel(max(dot(normal, viewDirection), 0.0), baseReflectance);
float occlusion = 1.0;
if (USES_OCCLUSION_MAP) occlusion = mix(1.0, texture(occlusionMap, textureUV).r, occlusionStrength);
occlusion *= splatCavity;
// Leaf and grass cards keep a faint sheen; full sky reflection washed grazing cards grey-blue.
float skyReflection = canopyShaded ? 0.3 : 1.0;
if (environmentEnabled > 0.5) {
- radiance += environmentLighting(normal, viewDirection, color, metallic, roughness, occlusion, ambientIntensity, skyReflection);
+ radiance += environmentLighting(normal, specularNormal, baseReflectance, viewDirection, color, metallic, roughness, occlusion, ambientIntensity, skyReflection);
} else {
// Outdoors the surroundings are sky and haze; reflecting the studio softboxes there lit grazing leaves white and cyan.
- vec3 reflected = reflect(-viewDirection, normal);
+ vec3 reflected = reflect(-viewDirection, specularNormal);
vec3 surroundings = worldMode > 0.5 ? mix(fogColor * 0.8, vec3(0.20, 0.38, 0.52) * 1.6, smoothstep(-0.15, 0.7, reflected.y)) : studio(reflected, roughness);
radiance += surroundings * reflectance * skyReflection * (1.0 - roughness * 0.55) * mix(1.0, 0.5 * daylight, worldMode) * occlusion * ambientIntensity;
radiance += color * (1.0 - metallic) * mix(vec3(0.16, 0.20, 0.22), vec3(0.19, 0.25, 0.30) * max(daylight, 0.08), worldMode) * (0.45 + 0.55 * max(normal.y, 0.0)) * occlusion * ambientIntensity;
@@ -915,6 +1030,16 @@ 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 = {
@@ -926,6 +1051,8 @@ 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'],
diff --git a/tests/film-timeline.test.js b/tests/film-timeline.test.js
index 398dc6c1..13a82c32 100644
--- a/tests/film-timeline.test.js
+++ b/tests/film-timeline.test.js
@@ -184,3 +184,35 @@ test('the audio library resolves plain files only and refuses links, empty files
}
assert.throws(() => createAudioLibrary('relative/folder'), /absolute/);
});
+
+test('a shot sets its own focus distance and blur, and a seek gives the same answer', () => {
+ const recipe = recipeWith();
+ const timeline = normalizeFilmTimeline({ shots: [
+ { name: 'wide', duration: 2 },
+ { name: 'portrait', duration: 2, focusDistance: 1.8, blur: 0.7 },
+ { name: 'distance', duration: 2, focusDistance: 40 },
+ ] }, recipe);
+ assert.equal(sampleFilmTimeline(timeline, recipe, 1).depthOfField, null, 'a shot with neither field keeps the recipe depth of field');
+ assert.deepEqual(sampleFilmTimeline(timeline, recipe, 3).depthOfField, { focusDistance: 1.8, blur: 0.7 });
+ assert.deepEqual(sampleFilmTimeline(timeline, recipe, 5).depthOfField, { focusDistance: 40 });
+ const order = [5, 3, 1, 3, 5.5, 3];
+ const samples = order.map(time => JSON.stringify(sampleFilmTimeline(timeline, recipe, time)));
+ assert.equal(samples[1], samples[3]);
+ assert.equal(samples[1], samples[5]);
+ const kept = createAgentScene(recipeWith({ timeline: { shots: [{ name: 'a', duration: 1, focusDistance: 2, blur: 0.5 }] } })).exportRecipe();
+ assert.equal(kept.timeline.shots[0].focusDistance, 2);
+ assert.equal(kept.timeline.shots[0].blur, 0.5);
+});
+
+test('shot focus distance and blur are checked at the boundary', () => {
+ const rejected = [
+ [{ focusDistance: 0 }, /focusDistance must be a number from 0.01 to 100000/],
+ [{ focusDistance: 100001 }, /focusDistance must be/],
+ [{ focusDistance: '2' }, /focusDistance must be/],
+ [{ blur: 1.5 }, /blur must be a number from 0 to 1/],
+ [{ blur: -0.1 }, /blur must be/],
+ ];
+ for (const [fields, message] of rejected) {
+ assert.throws(() => createAgentScene(recipeWith({ timeline: { shots: [{ name: 'a', duration: 1, ...fields }] } })), message);
+ }
+});
diff --git a/tests/gltf-extensions.test.js b/tests/gltf-extensions.test.js
index 6485f246..6bc4f9e3 100644
--- a/tests/gltf-extensions.test.js
+++ b/tests/gltf-extensions.test.js
@@ -163,9 +163,9 @@ const LAYER_MATERIAL_EXTENSIONS = {
KHR_materials_sheen: { sheenColorFactor: [0.5, 0.4, 0.3], sheenRoughnessFactor: 0.3 },
KHR_materials_volume: { thicknessFactor: 0.1, attenuationDistance: 2, attenuationColor: [0.8, 0.9, 1] },
};
-const UNRENDERED_MATERIAL_EXTENSIONS = {
- KHR_materials_anisotropy: { anisotropyStrength: 0.5 },
- KHR_materials_iridescence: { iridescenceFactor: 1 },
+const SURFACE_EFFECT_MATERIAL_EXTENSIONS = {
+ KHR_materials_anisotropy: { anisotropyStrength: 0.6, anisotropyRotation: 1.2 },
+ KHR_materials_iridescence: { iridescenceFactor: 0.8, iridescenceIor: 1.6, iridescenceThicknessMinimum: 150, iridescenceThicknessMaximum: 500 },
};
test('KHR_materials layer extensions import as material layers', async () => {
@@ -193,19 +193,27 @@ test('KHR_materials layer extensions import as material layers', async () => {
assert.equal('transmission' in plain.parts[0].material, false);
});
-test('anisotropy and iridescence load with a warning because they are not rendered', async () => {
+test('anisotropy and iridescence import as material layers without a warning', async () => {
const asset = await parseGltf(triangleDocument({
edit: document => {
- document.extensionsUsed = Object.keys(UNRENDERED_MATERIAL_EXTENSIONS);
- document.materials[0].extensions = structuredClone(UNRENDERED_MATERIAL_EXTENSIONS);
+ document.extensionsUsed = Object.keys(SURFACE_EFFECT_MATERIAL_EXTENSIONS);
+ document.materials[0].extensions = structuredClone(SURFACE_EFFECT_MATERIAL_EXTENSIONS);
},
}));
- assert.deepEqual(asset.warnings, Object.keys(UNRENDERED_MATERIAL_EXTENSIONS).sort().map(name => `${name} is accepted but not rendered.`));
+ const material = asset.parts[0].material;
+ assert.equal(material.anisotropy, 0.6);
+ assert.equal(material.anisotropyRotation, 1.2);
+ assert.equal(material.iridescence, 0.8);
+ assert.equal(material.iridescenceIor, 1.6);
+ assert.equal(material.iridescenceThickness, 500, 'without a thickness texture the film is as thick as the maximum');
+ assert.deepEqual(asset.warnings, []);
});
test('required material extensions, bad layer values and missing decoders are rejected', async () => {
- const required = triangleDocument({ edit: document => { document.extensionsRequired = ['KHR_materials_iridescence']; } });
- await assert.rejects(parseGltf(required), /Unsupported glTF extension: KHR_materials_iridescence/);
+ const required = triangleDocument({ edit: document => { document.extensionsRequired = ['KHR_materials_unlit']; } });
+ await assert.rejects(parseGltf(required), /Unsupported glTF extension: KHR_materials_unlit/);
+ const badIridescence = triangleDocument({ edit: document => { document.materials[0].extensions = { KHR_materials_iridescence: { iridescenceFactor: 2 } }; } });
+ await assert.rejects(parseGltf(badIridescence), /iridescence must be between 0 and 1/);
const badTransmission = triangleDocument({ edit: document => { document.materials[0].extensions = { KHR_materials_transmission: { transmissionFactor: 2 } }; } });
await assert.rejects(parseGltf(badTransmission), /transmission must be between 0 and 1.*Use a number inside that range/);
const badIor = triangleDocument({ edit: document => { document.materials[0].extensions = { KHR_materials_ior: { ior: 0.5 } }; } });
diff --git a/tests/material-layers.test.js b/tests/material-layers.test.js
index 4d4310b5..36f99bc6 100644
--- a/tests/material-layers.test.js
+++ b/tests/material-layers.test.js
@@ -6,7 +6,7 @@ import { box } from '../src/geometry.js';
import { exportGlb } from '../src/export.js';
import { parseGltf } from '../src/gltf.js';
import { createAgentScene } from '../src/agent-scene.js';
-import { dielectricReflectance, materialLayerState, validateMaterialLayers } from '../src/material-layers.js';
+import { dielectricReflectance, materialLayerState, validateMaterialLayers, MATERIAL_LAYER_STATE_LENGTH } from '../src/material-layers.js';
function recipeWithMaterial(material) {
return {
@@ -47,6 +47,11 @@ test('every layer value is checked at the boundary and the error names the fix',
[{ attenuationColor: [1, 1] }, /attenuationColor must be three linear RGB numbers between 0 and 1\. Pass \[red, green, blue\]/],
[{ sheenColor: [0, 2, 0] }, /sheenColor must be three linear RGB numbers/],
[{ attenuationDistance: 0 }, /attenuationDistance must be a finite number above 0.*Leave it out for no absorption/],
+ [{ anisotropy: 1.2 }, /anisotropy must be between 0 and 1/],
+ [{ anisotropyRotation: 20 }, /anisotropyRotation must be between/],
+ [{ iridescence: -1 }, /iridescence must be between 0 and 1/],
+ [{ iridescenceIor: 0.5 }, /iridescenceIor must be between 1 and 3/],
+ [{ iridescenceThickness: 5000 }, /iridescenceThickness must be between 0 and 1200/],
[{ tag: 'unlit', transmission: 0.5 }, /transmission needs a standard PBR material tag.*Use the surface tag/],
];
for (const [material, message] of cases) assert.throws(() => validateMaterialLayers(material), message);
@@ -89,3 +94,39 @@ test('a plain export declares no layer extension and an invalid layer is rejecte
assert.equal(Buffer.from(plain).includes('KHR_materials_clearcoat'), false);
assert.throws(() => exportGlb([{ name: 'cube', geometry: box(0), matrix: mat4.create(), material: { color: [0.2, 0.5, 0.7], roughness: 0.4, metallic: 0, clearcoat: 3 } }]), /clearcoat must be between 0 and 1/);
});
+
+test('anisotropy and iridescence reach the renderer state and default to off', () => {
+ const plain = materialLayerState({});
+ assert.equal(plain.length, MATERIAL_LAYER_STATE_LENGTH);
+ assert.deepEqual(plain.slice(16), [0, 0, 0, 1.3, 400], 'anisotropy, rotation, iridescence, film IOR and thickness');
+ const brushed = materialLayerState({ anisotropy: 0.7, anisotropyRotation: 1, iridescence: 0.9, iridescenceIor: 1.8, iridescenceThickness: 250 });
+ assert.deepEqual(brushed.slice(16), [0.7, 1, 0.9, 1.8, 250]);
+});
+
+test('recipes accept anisotropy and iridescence and export them', () => {
+ const scene = createAgentScene(recipeWithMaterial({ metallic: 1, anisotropy: 0.8, anisotropyRotation: 0.5, iridescence: 1, iridescenceIor: 1.7, iridescenceThickness: 380 }));
+ const material = scene.exportRecipe().materials[0];
+ assert.equal(material.anisotropy, 0.8);
+ assert.equal(material.iridescenceThickness, 380);
+ assert.throws(() => createAgentScene(recipeWithMaterial({ anisotropy: 2 })), /anisotropy must be between 0 and 1/);
+});
+
+test('anisotropy and iridescence survive a GLB export and import through their glTF extensions', async () => {
+ const material = { color: [0.8, 0.6, 0.3], roughness: 0.3, metallic: 1, emission: 0, anisotropy: 0.6, anisotropyRotation: 1.1, iridescence: 0.75, iridescenceIor: 1.7, iridescenceThickness: 320 };
+ const bytes = exportGlb([{ name: 'cube', geometry: box(0), matrix: mat4.create(), material }]);
+ const text = Buffer.from(bytes).toString('latin1');
+ assert.ok(text.includes('KHR_materials_anisotropy'), 'the anisotropy extension is declared');
+ assert.ok(text.includes('KHR_materials_iridescence'), 'the iridescence extension is declared');
+ const asset = await parseGltf(bytes);
+ const imported = asset.parts[0].material;
+ for (const field of ['anisotropy', 'anisotropyRotation', 'iridescence', 'iridescenceIor', 'iridescenceThickness']) {
+ assert.ok(Math.abs(imported[field] - material[field]) < 1e-6, field);
+ }
+ assert.deepEqual(asset.warnings, []);
+ const gltf = await new GLTFLoader().parseAsync(bytes, '');
+ const mesh = gltf.scene.getObjectByProperty('isMesh', true);
+ assert.ok(Math.abs(mesh.material.anisotropy - 0.6) < 1e-6, 'three.js reads the anisotropy strength');
+ assert.ok(Math.abs(mesh.material.iridescence - 0.75) < 1e-6, 'three.js reads the iridescence factor');
+ assert.ok(Math.abs(mesh.material.iridescenceIOR - 1.7) < 1e-6);
+ assert.ok(Math.abs(mesh.material.iridescenceThicknessRange[1] - 320) < 1e-6);
+});
diff --git a/tests/reference-baseline.test.js b/tests/reference-baseline.test.js
index 9ae33c9d..e6690737 100644
--- a/tests/reference-baseline.test.js
+++ b/tests/reference-baseline.test.js
@@ -4,7 +4,7 @@ import test from 'node:test';
const REFERENCE_DIRECTORY = new URL('../bench/reference/', import.meta.url);
const baseline = JSON.parse(readFileSync(new URL('baseline.json', REFERENCE_DIRECTORY), 'utf8'));
-const EXPECTED_SCENES = ['brick-graph', 'car-paint', 'character', 'fog', 'foliage', 'glass', 'lit-interior', 'material-spheres', 'metal', 'outdoor-hdri', 'spot-area'];
+const EXPECTED_SCENES = ['brick-graph', 'brushed-film', 'car-paint', 'character', 'fog', 'foliage', 'glass', 'lit-interior', 'material-spheres', 'metal', 'outdoor-hdri', 'spot-area'];
const EXPECTED_SCORES = ['cpu-vs-cycles', 'cpu-vs-eevee', 'eevee-vs-cycles', 'gpu-vs-cpu', 'gpu-vs-cycles', 'gpu-vs-eevee'];
test('the render baseline scores every scene with every renderer pair', () => {
diff --git a/tests/shader-features.test.js b/tests/shader-features.test.js
index d3dbdfb8..00f5a6ca 100644
--- a/tests/shader-features.test.js
+++ b/tests/shader-features.test.js
@@ -10,7 +10,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', 'TAG_WATER', 'TAG_FIRE']) {
+ for (const macro of ['USES_NORMAL_MAP', 'USES_SPLAT', 'USES_MOSS', 'USES_ALPHA_MODE', 'USES_ANISOTROPY', 'USES_IRIDESCENCE', 'TAG_WATER', 'TAG_FIRE']) {
assert.match(plain, new RegExp(`#define ${macro} false`));
}
const withWater = createFragmentShader(['water']);
@@ -25,3 +25,12 @@ test('every feature condition is a macro that the shader body uses', () => {
assert.ok(uses > 1, `${macro} is defined but never used`);
}
});
+
+test('anisotropy and iridescence compile in only when a material asks for them', () => {
+ const withAnisotropy = createFragmentShader(['anisotropy']);
+ assert.match(withAnisotropy, /#define USES_ANISOTROPY \(materialAnisotropy\.x > 0\.0\)/);
+ assert.match(withAnisotropy, /#define USES_IRIDESCENCE false/);
+ const withIridescence = createFragmentShader(['iridescence']);
+ assert.match(withIridescence, /#define USES_IRIDESCENCE \(materialIridescence\.x > 0\.0\)/);
+ assert.match(withIridescence, /#define USES_ANISOTROPY false/);
+});