Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add clearcoat, transmission, sheen and specular material layers

Nguyen Xuan Anecbafcd3ea9b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 84e136cb..90fe25a2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Add material layers: `clearcoat` and `clearcoatRoughness`, `transmission` with `thickness`, `ior`, `attenuationColor` and `attenuationDistance`, `sheenColor` and `sheenRoughness`, and `specular` and `specularColor`. Recipes, the MCP schema, glTF import and export (`KHR_materials_clearcoat`, `transmission`, `volume`, `ior`, `specular`, `sheen`) all take them, each checked at the boundary. Transmission refracts the opaque scene like the `liquid` material. Anisotropy and iridescence are not rendered yet. Import of those two still warns
+- Change the glTF import of the six layer extensions above from accepted-and-ignored to rendered, so `asset.warnings` no longer lists them
- Add `subdivide` as a mesh edit and stack node: Catmull-Clark subdivision to 4 levels with semi-sharp creases picked by an edge rule, sharp boundaries, kept corners, n-gon support, and tags, UVs and edge attributes carried through each level. The size is checked before it allocates. Counts, area and positions match Blender at levels 1 to 3; the `pebble` task joins the agent modeling suite
- Remove `67js/addons/film` from the npm package. It held the 187-second trailer demo with its baked physics recording, 75 KB gzip of the archive. Nothing else in the package used it. To keep using it, copy `src/film.js`, `src/film-rig.js`, `src/film-character.js`, `src/film-physics-definition.js` and `src/film-physics-clip.json` from the repository, or read the trailer on the site at `/film.html`. The archive goes from 901,314 to 829,085 bytes
- Remove three.js from modeling and the agent scene: `lathe`, `extrude` and `tube` no longer import it, and `scene:agent-scene` drops from 185,681 to 117,290 bytes gzip. `lathe` and `tube` output is identical to before, vertex for vertex. `extrude` walls, bevels, UVs, normals and bounds are identical, and volume matches within 1e-4. Extrusion caps use a new ear-clipping triangulation, so a cap can split along other diagonals, and a cap with collinear points can add or drop a seam vertex. A clockwise hole under a clockwise contour is now flipped to face outward, where it used to keep inward walls
diff --git a/bench/reference/README.md b/bench/reference/README.md
index e121a53a..254e3a1f 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -46,6 +46,7 @@ EEVEE against Cycles is a yardstick: it shows what a good rasterizer scores. In
- 67.js reaches an HDRI only from code. A recipe can not set one yet, so these scores are better than what an agent gets today (issue #53).
- The Blender leaf material has no translucency, and the 67.js foliage shader adds it by a trick. `foliage` is therefore partly a difference in materials.
- `render-blender.py` does not read normal maps. No scene uses one yet, so a new scene with a normal map must add that first.
-- `glass` compares the 67.js `liquid` material with a Blender glass material. 67.js has no glass material (issue #51).
+- `glass` and `car-paint` use the real 67.js `transmission` and `clearcoat` layers, and the Blender side sets the same values on the Principled BSDF. 67.js refracts through the front surface only, so the sphere does not show the inverted sky that Cycles traces through the back face.
+- `car-paint` scored 0.1521 against Cycles and `glass` 0.1326 (it was 0.1450 with the `liquid` material). The other scenes scored the same as in the table above, to four digits. The table above is the 2026-10-30 baseline and has not been rewritten.
- `fog` has no noise on either side. EEVEE and 67.js approximate scattering, and Cycles follows 8 volume bounces.
- Sample counts are fixed: 256 for Cycles with denoising, 64 for EEVEE and 4 MSAA samples for 67.js.
diff --git a/bench/reference/baseline.json b/bench/reference/baseline.json
index 1321a7d9..1b961a1b 100644
--- a/bench/reference/baseline.json
+++ b/bench/reference/baseline.json
@@ -2,37 +2,9 @@
"metric": "FLIP (LDR), mean error, lower is better",
"blenderVersion": "5.2.2 LTS",
"seconds": {
- "character": {
- "cycles": 4.5,
- "eevee": 1.1
- },
- "fog": {
- "cycles": 16.6,
- "eevee": 1.1
- },
- "foliage": {
- "cycles": 5.8,
- "eevee": 1.0
- },
- "glass": {
- "cycles": 5.8,
- "eevee": 0.4
- },
"lit-interior": {
- "cycles": 10.0,
- "eevee": 0.6
- },
- "material-spheres": {
- "cycles": 6.7,
- "eevee": 0.4
- },
- "metal": {
- "cycles": 5.0,
- "eevee": 0.3
- },
- "outdoor-hdri": {
- "cycles": 4.1,
- "eevee": 0.4
+ "cycles": 14.5,
+ "eevee": 2.4
}
},
"graphics": {
@@ -40,6 +12,14 @@
"cpu": "ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)"
},
"scores": {
+ "car-paint": {
+ "gpu-vs-cycles": 0.1521,
+ "gpu-vs-eevee": 0.1323,
+ "cpu-vs-cycles": 0.152,
+ "cpu-vs-eevee": 0.1323,
+ "eevee-vs-cycles": 0.0819,
+ "gpu-vs-cpu": 0.0055
+ },
"character": {
"gpu-vs-cycles": 0.0995,
"gpu-vs-eevee": 0.0833,
@@ -65,12 +45,12 @@
"gpu-vs-cpu": 0.0096
},
"glass": {
- "gpu-vs-cycles": 0.145,
- "gpu-vs-eevee": 0.1469,
- "cpu-vs-cycles": 0.1447,
- "cpu-vs-eevee": 0.1471,
+ "gpu-vs-cycles": 0.1326,
+ "gpu-vs-eevee": 0.1472,
+ "cpu-vs-cycles": 0.1323,
+ "cpu-vs-eevee": 0.1474,
"eevee-vs-cycles": 0.115,
- "gpu-vs-cpu": 0.0074
+ "gpu-vs-cpu": 0.0075
},
"lit-interior": {
"gpu-vs-cycles": 0.4997,
diff --git a/bench/reference/images/car-paint.jpg b/bench/reference/images/car-paint.jpg
new file mode 100644
index 00000000..d68b1f63
Binary files /dev/null and b/bench/reference/images/car-paint.jpg differ
diff --git a/bench/reference/images/character.jpg b/bench/reference/images/character.jpg
index 3e1c03db..f690e048 100644
Binary files a/bench/reference/images/character.jpg and b/bench/reference/images/character.jpg differ
diff --git a/bench/reference/images/fog.jpg b/bench/reference/images/fog.jpg
index fc059c2f..71b45d6e 100644
Binary files a/bench/reference/images/fog.jpg and b/bench/reference/images/fog.jpg differ
diff --git a/bench/reference/images/foliage.jpg b/bench/reference/images/foliage.jpg
index f7211c79..ef2fd8bb 100644
Binary files a/bench/reference/images/foliage.jpg and b/bench/reference/images/foliage.jpg differ
diff --git a/bench/reference/images/glass.jpg b/bench/reference/images/glass.jpg
index b280c58b..22669d84 100644
Binary files a/bench/reference/images/glass.jpg and b/bench/reference/images/glass.jpg differ
diff --git a/bench/reference/images/lit-interior.jpg b/bench/reference/images/lit-interior.jpg
index 8c9b91ed..03ed2cd5 100644
Binary files a/bench/reference/images/lit-interior.jpg and b/bench/reference/images/lit-interior.jpg differ
diff --git a/bench/reference/images/material-spheres.jpg b/bench/reference/images/material-spheres.jpg
index 8e64566a..90af23af 100644
Binary files a/bench/reference/images/material-spheres.jpg and b/bench/reference/images/material-spheres.jpg differ
diff --git a/bench/reference/images/metal.jpg b/bench/reference/images/metal.jpg
index 48b06772..5c218308 100644
Binary files a/bench/reference/images/metal.jpg and b/bench/reference/images/metal.jpg differ
diff --git a/bench/reference/images/outdoor-hdri.jpg b/bench/reference/images/outdoor-hdri.jpg
index f0bc3297..69a50327 100644
Binary files a/bench/reference/images/outdoor-hdri.jpg and b/bench/reference/images/outdoor-hdri.jpg differ
diff --git a/bench/reference/render-blender.py b/bench/reference/render-blender.py
index 3bd64839..ae912bc9 100644
--- a/bench/reference/render-blender.py
+++ b/bench/reference/render-blender.py
@@ -128,6 +128,31 @@ def add_vertex_colors(material, principled, description):
links.new(multiply.outputs["Color"], principled.inputs["Base Color"])
+def add_material_layers(material, principled, description):
+ """Maps the 67.js material layers onto the Principled BSDF inputs of the same meaning."""
+ principled.inputs["Coat Weight"].default_value = description.get("clearcoat", 0)
+ principled.inputs["Coat Roughness"].default_value = description.get("clearcoatRoughness", 0)
+ principled.inputs["Transmission Weight"].default_value = description.get("transmission", principled.inputs["Transmission Weight"].default_value)
+ principled.inputs["IOR"].default_value = description.get("ior", principled.inputs["IOR"].default_value)
+ sheen_color = description.get("sheenColor", [0, 0, 0])
+ if any(sheen_color):
+ principled.inputs["Sheen Weight"].default_value = 1
+ set_linear_color(principled.inputs["Sheen Tint"], sheen_color)
+ principled.inputs["Sheen Roughness"].default_value = description.get("sheenRoughness", 0)
+ # Blender's specular level 0.5 is the 4 percent reflectance that 67.js 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]))
+ attenuation_distance = description.get("attenuationDistance")
+ if attenuation_distance:
+ absorption = material.node_tree.nodes.new("ShaderNodeVolumeAbsorption")
+ attenuation_color = description.get("attenuationColor", [1, 1, 1])
+ set_linear_color(absorption.inputs["Color"], attenuation_color)
+ # Beer-Lambert: the colour is what attenuationDistance metres let through.
+ mean_log = sum(math.log(max(channel, 0.001)) for channel in attenuation_color) / 3
+ absorption.inputs["Density"].default_value = -mean_log / attenuation_distance
+ material.node_tree.links.new(absorption.outputs["Volume"], material.node_tree.nodes["Material Output"].inputs["Volume"])
+
+
def build_material(name, description, has_vertex_colors):
material = bpy.data.materials.new(name)
material.use_nodes = True
@@ -138,6 +163,7 @@ def build_material(name, description, has_vertex_colors):
if description.get("tag") == "liquid":
principled.inputs["Transmission Weight"].default_value = 1
principled.inputs["IOR"].default_value = description["liquid"]["ior"]
+ add_material_layers(material, principled, description)
if "map" in description:
add_texture(material, principled, description, has_vertex_colors)
elif has_vertex_colors:
diff --git a/bench/reference/scenes.js b/bench/reference/scenes.js
index 905617e0..28f9fa4e 100644
--- a/bench/reference/scenes.js
+++ b/bench/reference/scenes.js
@@ -126,7 +126,7 @@ export const REFERENCE_SCENES = {
parts.push(part(`stripe-${index}`, cube, [(index - 1.5) * 1, 1, -1.5], [0.5, 2, 0.2], { color, roughness: 0.6 }));
});
parts.push(part('glass-sphere', sphere(96, 64), [0, 0.9, 0.5], [0.9, 0.9, 0.9], {
- tag: 'liquid', color: [1, 1, 1], roughness: 0.02, liquid: { ior: 1.5, thickness: 1.8, refraction: 1, scattering: 0 },
+ color: [1, 1, 1], roughness: 0.02, transmission: 1, ior: 1.5, thickness: 1.8,
}));
return {
parts, blenderWorld: lighting.blenderWorld,
@@ -136,6 +136,22 @@ export const REFERENCE_SCENES = {
};
},
+ async 'car-paint'() {
+ const lighting = await skyLighting();
+ const parts = [
+ floor([0.2, 0.2, 0.22]),
+ part('lacquer-red', sphere(96, 64), [-1.6, 0.8, 0], [0.8, 0.8, 0.8], { color: [0.55, 0.02, 0.02], roughness: 0.5, clearcoat: 1, clearcoatRoughness: 0.03 }),
+ part('flake-blue', sphere(96, 64), [0, 0.8, 0], [0.8, 0.8, 0.8], { color: [0.03, 0.12, 0.6], metallic: 0.8, roughness: 0.4, clearcoat: 1, clearcoatRoughness: 0.03 }),
+ part('uncoated-red', sphere(96, 64), [1.6, 0.8, 0], [0.8, 0.8, 0.8], { color: [0.55, 0.02, 0.02], roughness: 0.5 }),
+ ];
+ 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/budgets.json b/bench/size/budgets.json
index f307371c..9e792d52 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -5,12 +5,12 @@
"agent-scene": 100000
},
"budgets": {
- "entry:core": 67100,
+ "entry:core": 67800,
"entry:model": 14400,
"entry:nature": 13200,
"entry:motion": 13600,
"entry:canvas2d": 9400,
- "entry:gltf": 44100,
+ "entry:gltf": 44900,
"entry:modeling": 6600,
"entry:sculpt": 2500,
"entry:surface": 74500,
@@ -28,11 +28,11 @@
"entry:grass": 4400,
"entry:clutter": 5300,
"entry:texture-set": 900,
- "entry:agent-scene": 95300,
- "entry:agent-asset": 102600,
+ "entry:agent-scene": 96700,
+ "entry:agent-asset": 104100,
"entry:hdri": 3300,
- "scene:lit-box": 49800,
- "scene:gltf-box": 68900,
- "scene:agent-scene": 119700
+ "scene:lit-box": 50500,
+ "scene:gltf-box": 69400,
+ "scene:agent-scene": 121200
}
}
diff --git a/docs/gltf.md b/docs/gltf.md
index e7abd692..783412d9 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` | 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` | 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_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 3fedb43f..db2c74e1 100644
--- a/docs/material-maps.md
+++ b/docs/material-maps.md
@@ -111,6 +111,33 @@ Moss is shaded as its own material, not as a tint. Where it grows, roughness bec
A standard-tag material can carry `layers` (up to four `{ color, normal, roughness, height, scale, tint, triplanar }` entries built from `loadTextureSet`) and a `splat` rule object instead of these single maps. The layers are blended by slope, height and a weight mask, sampled in world space and packed into texture arrays on units 11 to 14. They replace `map`, `normalMap`, `metallicRoughnessMap` and `occlusionMap`, which must be absent, and parts batch only when `layers` and `splat` are the same objects. See [Terrain](/terrain.md).
+## Material layers
+
+A material on a standard tag (`surface` in recipes, `gltf` and `armor` in code) can carry these layers. The names are the glTF `KHR_materials_*` names, and each is checked at the boundary with an error that names the fix.
+
+| Field | Range | Meaning |
+| --- | --- | --- |
+| `clearcoat`, `clearcoatRoughness` | 0 to 1 | A clear lacquer lobe over the base (car paint, varnish). Light it reflects never reaches the base. |
+| `transmission` | 0 to 1 | The share of light that passes through. The material draws after the opaque scene and refracts it. |
+| `thickness` | 0 to 1000 metres | How far light travels inside. 0 is a thin sheet that does not bend the view. |
+| `ior` | 1 to 2.5 | Index of refraction. It bends transmitted light and sets the reflectance at normal incidence, 4 percent at 1.5. |
+| `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. |
+
+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`.
+
+Limits, stated plainly:
+
+- Transmission uses one refraction through the front surface with the thickness estimate the `liquid` material uses. It does not trace the back face, and roughness blurs the reflection only, not the view behind. The scene colour comes from opaque geometry, so blended surfaces do not show through glass.
+- 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.
+- 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.
+
## Limits
Texture transforms, UV channels beyond zero, and vertex alpha below one remain unsupported.
@@ -121,5 +148,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.
-Extensions such as clearcoat, transmission, anisotropy, and sheen, material layers, node graphs, and authored tangent support remain missing.
+Anisotropy, iridescence, 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 7325eb96..91e07a45 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -191,7 +191,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, and 8 point lights without shadows. There are no spot or area lights. | [lighting](../tests/lighting.test.js) | #52 |
| Rendering > Lights > Light Linking | missing | No light linking. | | #52 |
| Rendering > Lights > World Environment | partial | Recipes have sky colors, daylight and fog. Code can load an HDRI, and recipes can not reach it. | [environment](../tests/environment.test.js) | #53 |
-| Rendering > Materials > Components | partial | Surfaces with PBR factors and five maps. There are no volume materials 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. There is no anisotropy, iridescence, subsurface scattering, volume material or displacement. | [texture-set](../tests/texture-set.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 |
@@ -199,7 +199,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 | missing | No node graph. | | #50 |
| Rendering > Shader Nodes > Output | missing | No node graph. | | #50 |
-| Rendering > Shader Nodes > Shader | partial | A fixed metallic-roughness surface, with unlit, liquid and foam tags. There is no clearcoat, transmission, sheen or subsurface. | [renderer](../tests/renderer.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. There is no anisotropy, iridescence or subsurface. | [material-layers](../tests/material-layers.test.js) | #51 |
| Rendering > Shader Nodes > Displacement | partial | Normal maps. There is no bump from height or displacement. | | #50 |
| Rendering > Shader Nodes > Texture | partial | Image maps and 11 pattern presets. There is no graph, so an agent can not combine them. | [material-patterns](../tests/material-patterns.test.js) | #50 |
| Rendering > Shader Nodes > Color | missing | No node graph. | | #50 |
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 8d9126f4..4c766cc0 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -6,6 +6,7 @@ import { resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import packageMetadata from '../package.json' with { type: 'json' };
import { MATERIAL_PATTERN_TYPES } from '../src/agent-scene-capabilities.js';
+import { MATERIAL_LAYER_SCALAR_RANGES, MATERIAL_LAYER_COLOR_RANGES } from '../src/material-layers.js';
const finite = z.number().min(-3.4028234663852886e38).max(3.4028234663852886e38);
const positive = finite.positive();
@@ -37,7 +38,36 @@ const materialPattern = z.strictObject({
axis: z.enum(['x', 'y', 'z']).optional().describe('Object axis the grain runs along. Defaults to y.'),
resolution: z.union([z.literal(256), z.literal(512), z.literal(1024)]).optional().describe('Texture size. Defaults to 512; each pattern takes about 4 MiB at 512.'),
}).describe('Procedural texture baked for this material. Needs no UVs: it is projected along the object axes. color then tints it (defaults to white), and roughness and metallic scale it.');
+function layerNumber(field, description) {
+ const [minimum, maximum] = MATERIAL_LAYER_SCALAR_RANGES[field];
+ return z.number()
+ .min(minimum, `${field} must be at least ${minimum}. Raise it to ${minimum} or more.`)
+ .max(maximum, `${field} must be at most ${maximum}. Lower it to ${maximum} or less.`)
+ .describe(description).optional();
+}
+
+function layerColor(field, description) {
+ const [minimum, maximum] = MATERIAL_LAYER_COLOR_RANGES[field];
+ const component = z.number().min(minimum, `${field} components must be at least ${minimum}.`).max(maximum, `${field} components must be at most ${maximum}. Use linear values.`);
+ return z.tuple([component, component, component]).describe(description).optional();
+}
+
+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.'),
+};
+
const materialFields = {
+ ...materialLayerFields,
pattern: materialPattern.optional(),
color: color.optional().describe('Linear RGB base color, each component between zero and one.'),
metallic: unit.optional(),
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 1c7fe3b9..19780ad7 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -38,6 +38,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- Agent scene recipes use optional `src/agent-scene.js` and `docs/agent-scene.md`. Verify source versus published availability before importing.
- 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.
- 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`.
+- 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`.
- 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`. See "Inverse kinematics" 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-scene.js b/src/agent-scene.js
index d767db71..c43c7f9b 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -8,6 +8,7 @@ import { normalizeAgentMotion, compileAgentMotion } from './agent-motion.js';
import { meshReport, generateMeshGeometry, MESH_SMOOTH_ANGLE_DEFAULT } from './agent-mesh.js';
import { normalizeMeshEdits, normalizeMeshStack } from './mesh-recipe.js';
import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, MAX_MATERIAL_PATTERNS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';
+import { MATERIAL_LAYER_FIELDS, validateMaterialLayers } from './material-layers.js';
import { materialPatternTextures, normalizeMaterialPattern } from './material-patterns.js';
export { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS };
export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';
@@ -18,7 +19,7 @@ const DEFAULT_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;
const MAX_MESH_REPORTS = 16;
const CAMERA_DEFAULTS = Object.freeze({ eye: [4, 3, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 1000 });
const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material'];
-const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern'];
+const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', ...MATERIAL_LAYER_FIELDS];
const PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'boxMapScale', 'boxMapAxis'];
const CAMERA_FIELDS = Object.keys(CAMERA_DEFAULTS);
const LOOK_OPERATION_FIELDS = Object.freeze({
@@ -181,6 +182,14 @@ function resources(values, maximum, label, validate) {
});
}
+function copyMaterialLayers(value, result) {
+ for (const field of MATERIAL_LAYER_FIELDS) {
+ if (value[field] === undefined) continue;
+ result[field] = Array.isArray(value[field]) ? vector(value[field], 3, field) : value[field];
+ }
+ validateMaterialLayers(result);
+}
+
function materialFrom(value) {
knownKeys(value, ['id', 'tag', ...MATERIAL_FIELDS], 'material');
// A pattern brings its own colours, so the color field tints it and leaves it unchanged by default.
@@ -225,6 +234,7 @@ function materialFrom(value) {
throw new RangeError('emissiveColor must be nonnegative.');
}
}
+ copyMaterialLayers(value, result);
const emissiveColor = result.emissiveColor ?? result.color;
for (const component of emissiveColor) {
const radiance = Math.fround(component) * Math.fround(result.emission);
@@ -525,7 +535,8 @@ function geometryStats(records) {
function batchSignature(material) {
// Textures are fixed per renderer, so a changed pattern rebuilds it like a changed tag does.
- return `${material.tag}|${material.alphaMode}|${material.opacity}|${material.doubleSided}|${JSON.stringify(material.pattern ?? null)}`;
+ // Transmission moves a material to the pass that sees the opaque scene, which is fixed per renderer.
+ return `${material.tag}|${material.alphaMode}|${material.opacity}|${material.transmission > 0}|${material.doubleSided}|${JSON.stringify(material.pattern ?? null)}`;
}
function materialHandle(snapshot) {
diff --git a/src/environment.js b/src/environment.js
index edbc600e..28883587 100644
--- a/src/environment.js
+++ b/src/environment.js
@@ -289,7 +289,7 @@ vec3 environmentDiffuse(vec3 normal) {
// 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) {
float normalView = clamp(dot(normal, viewDirection), 0.001, 1.0);
- vec3 baseReflectance = mix(vec3(0.04), color, metallic);
+ 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;
diff --git a/src/export.js b/src/export.js
index 4198eb2f..324e0465 100644
--- a/src/export.js
+++ b/src/export.js
@@ -1,4 +1,5 @@
import { validateMorphGeometry, validateMorphPose } from './morph.js';
+import { gltfExtensionsFromLayers } from './gltf-layers.js';
const EMISSIVE_STRENGTH = 'KHR_materials_emissive_strength';
const COMPONENT_COUNTS = { SCALAR: 1, VEC2: 2, VEC3: 3 };
@@ -31,6 +32,11 @@ function writeAlphaFields(gltfMaterial, material) {
if (material.doubleSided === true) gltfMaterial.doubleSided = true;
}
+function declareExtensions(document, names, required) {
+ document.extensionsUsed = [...new Set([...(document.extensionsUsed ?? []), ...names])];
+ if (required) document.extensionsRequired = [...new Set([...(document.extensionsRequired ?? []), ...names])];
+}
+
function validateFactor(value, label, maximum = 1) {
if (!Number.isFinite(value) || !Number.isFinite(Math.fround(value)) || value < 0 || value > maximum) {
throw new RangeError(`${label} requires a finite nonnegative Float32 value${maximum === 1 ? ' within [0,1]' : ''}.`);
@@ -188,11 +194,15 @@ export function exportGlb(parts) {
emissiveFactor: (part.material.emission ?? 0) === 0 ? [0, 0, 0] : Array.from(part.material.emissiveColor ?? part.material.color),
};
writeAlphaFields(material, part.material);
+ const layerExtensions = gltfExtensionsFromLayers(part.material);
+ if (Object.keys(layerExtensions).length > 0) {
+ material.extensions = layerExtensions;
+ declareExtensions(document, Object.keys(layerExtensions), false);
+ }
const strength = part.material.emission ?? 0;
if (strength !== 0 && strength !== 1) {
- material.extensions = { [EMISSIVE_STRENGTH]: { emissiveStrength: strength } };
- document.extensionsUsed = [EMISSIVE_STRENGTH];
- document.extensionsRequired = [EMISSIVE_STRENGTH];
+ material.extensions = { ...material.extensions, [EMISSIVE_STRENGTH]: { emissiveStrength: strength } };
+ declareExtensions(document, [EMISSIVE_STRENGTH], true);
}
document.materials.push(material);
}
diff --git a/src/gltf-layers.js b/src/gltf-layers.js
new file mode 100644
index 00000000..62c3837f
--- /dev/null
+++ b/src/gltf-layers.js
@@ -0,0 +1,60 @@
+// Reads and writes the glTF material extensions that map onto the material layers of material-layers.js.
+// Texture slots inside these extensions (clearcoatTexture, transmissionTexture and so on) are not read: a factor is used.
+import { MATERIAL_LAYER_DEFAULTS, validateMaterialLayers } from './material-layers.js';
+
+export const GLTF_LAYER_EXTENSIONS = Object.freeze([
+ 'KHR_materials_clearcoat',
+ 'KHR_materials_transmission',
+ 'KHR_materials_volume',
+ 'KHR_materials_ior',
+ 'KHR_materials_specular',
+ 'KHR_materials_sheen',
+]);
+
+// Each row: extension, then the glTF property that feeds each material field.
+const IMPORT_RULES = Object.freeze([
+ ['KHR_materials_clearcoat', { clearcoat: 'clearcoatFactor', clearcoatRoughness: 'clearcoatRoughnessFactor' }],
+ ['KHR_materials_transmission', { transmission: 'transmissionFactor' }],
+ ['KHR_materials_volume', { thickness: 'thicknessFactor', attenuationDistance: 'attenuationDistance', attenuationColor: 'attenuationColor' }],
+ ['KHR_materials_ior', { ior: 'ior' }],
+ ['KHR_materials_specular', { specular: 'specularFactor', specularColor: 'specularColorFactor' }],
+ ['KHR_materials_sheen', { sheenColor: 'sheenColorFactor', sheenRoughness: 'sheenRoughnessFactor' }],
+]);
+
+/** Layer fields of one glTF material definition, validated, as a plain object to spread onto a material. */
+export function materialLayersFromGltf(definition) {
+ const layers = {};
+ for (const [extensionName, properties] of IMPORT_RULES) {
+ const extension = definition?.extensions?.[extensionName];
+ if (!extension) continue;
+ for (const [field, property] of Object.entries(properties)) {
+ if (extension[property] !== undefined) layers[field] = extension[property];
+ }
+ }
+ validateMaterialLayers(layers);
+ return layers;
+}
+
+function differsFromDefault(field, value) {
+ return JSON.stringify(value) !== JSON.stringify(MATERIAL_LAYER_DEFAULTS[field]);
+}
+
+function extensionProperties(material, properties) {
+ const written = {};
+ for (const [field, property] of Object.entries(properties)) {
+ if (material[field] === undefined || !differsFromDefault(field, material[field])) continue;
+ written[property] = Array.isArray(material[field]) ? [...material[field]] : material[field];
+ }
+ return written;
+}
+
+/** The KHR_materials_* objects a material needs, keyed by extension name; empty when it uses no layer. */
+export function gltfExtensionsFromLayers(material) {
+ validateMaterialLayers(material);
+ const extensions = {};
+ for (const [extensionName, properties] of IMPORT_RULES) {
+ const written = extensionProperties(material, properties);
+ if (Object.keys(written).length > 0) extensions[extensionName] = written;
+ }
+ return extensions;
+}
diff --git a/src/gltf.js b/src/gltf.js
index 4b8b9eda..4c728631 100644
--- a/src/gltf.js
+++ b/src/gltf.js
@@ -1,4 +1,5 @@
import { applyClip } from './gltf-animation.js';
+import { GLTF_LAYER_EXTENSIONS, materialLayersFromGltf } from './gltf-layers.js';
import { attributeFloats } from './gltf-accessors.js';
import { decodeGltf, textureSourceIndex } from './gltf-decode.js';
import { Matrix4 } from './gltf-nodes.js';
@@ -8,16 +9,16 @@ 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_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_clearcoat', 'KHR_materials_transmission', 'KHR_materials_ior', 'KHR_materials_specular', 'KHR_materials_sheen', 'KHR_materials_volume'],
- 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', 'rendering of ignored material extensions'],
+ 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'],
});
const DEFAULT_MAX_BYTES = 32 * 1024 * 1024;
const DEFAULT_MAX_VERTICES = 2_000_000;
const GLTF_ALPHA_MODES = { OPAQUE: 'opaque', MASK: 'mask', BLEND: 'blend' };
const DEFAULT_MAX_INSTANCES = 4096;
-const ALLOWED_EXTENSIONS = new Set(['KHR_mesh_quantization', 'KHR_materials_emissive_strength', 'KHR_texture_transform', 'EXT_mesh_gpu_instancing']);
+const ALLOWED_EXTENSIONS = new Set(['KHR_mesh_quantization', 'KHR_materials_emissive_strength', 'KHR_texture_transform', 'EXT_mesh_gpu_instancing', ...GLTF_LAYER_EXTENSIONS]);
const DECODER_BY_EXTENSION = { KHR_draco_mesh_compression: 'draco', EXT_meshopt_compression: 'meshopt', KHR_texture_basisu: 'ktx2' };
// Accepted when optional, because 67.js does not render them. Rejected when listed in extensionsRequired.
const IGNORED_EXTENSIONS = new Set(GLTF_CAPABILITIES.ignoredExtensions);
@@ -202,8 +203,7 @@ function bakeUvTransform(uvs, transform) {
function validateMaterialExtensions(material) {
materialUvTransform(material);
- const transmission = material.extensions?.KHR_materials_transmission?.transmissionFactor ?? 0;
- if (!Number.isFinite(transmission) || transmission < 0 || transmission > 1) throw new Error('KHR_materials_transmission transmissionFactor must be within zero and one.');
+ materialLayersFromGltf(material);
}
/** Validates EXT_mesh_gpu_instancing on a node and returns how many instances it expands to. */
@@ -723,9 +723,7 @@ function convertMaterial(source, limits, maps, definition = {}) {
material.alphaCutoff = definition.alphaCutoff ?? 0.5;
material.opacity = definition.pbrMetallicRoughness?.baseColorFactor?.[3] ?? 1;
material.doubleSided = definition.doubleSided ?? false;
- // Hint only: transmission is not rendered yet.
- const transmission = definition.extensions?.KHR_materials_transmission?.transmissionFactor ?? 0;
- if (transmission > 0) material.transmission = transmission;
+ Object.assign(material, materialLayersFromGltf(definition));
if (!material.emissiveColor.some(value => value > 0)) material.emission = 0;
if (!Number.isFinite(Math.fround(material.emission)) || material.emission < 0) throw new Error('Emissive intensity must be a finite nonnegative float.');
for (const [field, , colorSpace] of MATERIAL_TEXTURES) {
diff --git a/src/material-layers.js b/src/material-layers.js
new file mode 100644
index 00000000..3b9fd6cc
--- /dev/null
+++ b/src/material-layers.js
@@ -0,0 +1,116 @@
+// Extra PBR layers on top of the base metallic-roughness material, named as in the glTF KHR_materials_* extensions.
+// This module holds plain data only, so the MCP server, recipes, the glTF code and the renderer share one set of ranges.
+
+const UNIT = Object.freeze([0, 1]);
+
+export const MATERIAL_LAYER_DEFAULTS = Object.freeze({
+ clearcoat: 0,
+ clearcoatRoughness: 0,
+ transmission: 0,
+ thickness: 0,
+ ior: 1.5,
+ attenuationColor: Object.freeze([1, 1, 1]),
+ attenuationDistance: Infinity,
+ sheenColor: Object.freeze([0, 0, 0]),
+ sheenRoughness: 0,
+ specular: 1,
+ specularColor: Object.freeze([1, 1, 1]),
+});
+
+export const MATERIAL_LAYER_FIELDS = Object.freeze(Object.keys(MATERIAL_LAYER_DEFAULTS));
+
+export const MATERIAL_LAYER_SCALAR_RANGES = Object.freeze({
+ clearcoat: UNIT,
+ clearcoatRoughness: UNIT,
+ transmission: UNIT,
+ thickness: Object.freeze([0, 1000]),
+ ior: Object.freeze([1, 2.5]),
+ sheenRoughness: UNIT,
+ specular: Object.freeze([0, 4]),
+});
+
+export const MATERIAL_LAYER_COLOR_RANGES = Object.freeze({
+ attenuationColor: UNIT,
+ sheenColor: UNIT,
+ specularColor: Object.freeze([0, 4]),
+});
+
+function describeRange([minimum, maximum]) {
+ return `between ${minimum} and ${maximum}`;
+}
+
+function checkScalar(field, value) {
+ const [minimum, maximum] = MATERIAL_LAYER_SCALAR_RANGES[field];
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum) {
+ throw new RangeError(`${field} must be ${describeRange(MATERIAL_LAYER_SCALAR_RANGES[field])}, got ${value}. Use a number inside that range.`);
+ }
+}
+
+function checkColor(field, value) {
+ const [minimum, maximum] = MATERIAL_LAYER_COLOR_RANGES[field];
+ const isLinearColor = Array.isArray(value) && value.length === 3 &&
+ value.every(component => typeof component === 'number' && Number.isFinite(component) && component >= minimum && component <= maximum);
+ if (!isLinearColor) {
+ throw new RangeError(`${field} must be three linear RGB numbers ${describeRange(MATERIAL_LAYER_COLOR_RANGES[field])}. Pass [red, green, blue].`);
+ }
+}
+
+function checkAttenuationDistance(value) {
+ const isPositive = typeof value === 'number' && value > 0 && Number.isFinite(value);
+ if (!isPositive) {
+ throw new RangeError(`attenuationDistance must be a finite number above 0 (metres), got ${value}. Leave it out for no absorption.`);
+ }
+}
+
+/** Throws a RangeError that names the field and the fix for the first layer value that is out of range. */
+export function validateMaterialLayers(material) {
+ for (const field of Object.keys(MATERIAL_LAYER_SCALAR_RANGES)) {
+ if (material[field] !== undefined) checkScalar(field, material[field]);
+ }
+ for (const field of Object.keys(MATERIAL_LAYER_COLOR_RANGES)) {
+ if (material[field] !== undefined) checkColor(field, material[field]);
+ }
+ if (material.attenuationDistance !== undefined && material.attenuationDistance !== Infinity) {
+ checkAttenuationDistance(material.attenuationDistance);
+ }
+ if (material.transmission > 0 && material.tag !== undefined && material.tag !== 'surface' && material.tag !== 'gltf' && material.tag !== 'liquid') {
+ throw new RangeError(`transmission needs a standard PBR material tag, got ${material.tag}. Use the surface tag.`);
+ }
+}
+
+export function materialLayerValue(material, field) {
+ return material[field] ?? MATERIAL_LAYER_DEFAULTS[field];
+}
+
+/** True when the material asks for any layer beyond the base material. */
+export function hasMaterialLayers(material) {
+ return MATERIAL_LAYER_FIELDS.some(field => material[field] !== undefined && material[field] !== MATERIAL_LAYER_DEFAULTS[field]
+ && JSON.stringify(material[field]) !== JSON.stringify(MATERIAL_LAYER_DEFAULTS[field]));
+}
+
+/** Reflectance of a dielectric at normal incidence, as the glTF specular and IOR extensions combine it. */
+export function dielectricReflectance(material) {
+ const ior = materialLayerValue(material, 'ior');
+ const fromIor = ((ior - 1) / (ior + 1)) ** 2;
+ const weight = materialLayerValue(material, 'specular');
+ 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). */
+export function materialLayerState(material) {
+ validateMaterialLayers(material);
+ return [
+ ...dielectricReflectance(material),
+ materialLayerValue(material, 'clearcoat'),
+ materialLayerValue(material, 'clearcoatRoughness'),
+ ...materialLayerValue(material, 'sheenColor'),
+ materialLayerValue(material, 'sheenRoughness'),
+ materialLayerValue(material, 'transmission'),
+ materialLayerValue(material, 'ior'),
+ materialLayerValue(material, 'thickness'),
+ materialLayerValue(material, 'attenuationDistance'),
+ ...materialLayerValue(material, 'attenuationColor'),
+ ];
+}
+
+export const MATERIAL_LAYER_STATE_LENGTH = 16;
diff --git a/src/renderer.js b/src/renderer.js
index e1978f55..19849fb6 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -9,6 +9,7 @@ import { resolveVolumeFog } from './volumetric.js';
import { assertEnvironmentMap, createEnvironmentResources, environmentBackgroundFragment, estimateEnvironmentBytes } from './environment.js';
import { validateSkinGeometry, validateSkinPose, skinTextureLayout, packSkinInfluences } from './skinning.js';
import { validateSplatMaterial, splatBatchState, splatTextureBytes, resolveSplatSize, packSplatParameters, buildSplatPixels } from './splat.js';
+import { materialLayerState } from './material-layers.js';
import { validateMorphGeometry, validateMorphPose, validateMorphTransform, packMorphTargets } from './morph.js';
const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10, liquid: 11, foam: 12 };
@@ -16,6 +17,8 @@ const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, gr
const TRANSLUCENT_TAGS = new Set(['liquid', 'foam']);
const DEFAULT_LIQUID = Object.freeze({ thickness: 0.5, ior: 1.33, refraction: 1, scattering: 1, foamOpacity: 0.55, foamSoftness: 1 });
const INSTANCE_STRIDE = 41;
+// Shaders get this in place of an infinite attenuation distance, which is not a safe uniform value.
+const MAX_FINITE_DISTANCE = 3e38;
const ALPHA_MODES = { opaque: 0, mask: 1, blend: 2 };
const ZERO_VECTOR = Object.freeze([0, 0, 0]);
const MATERIAL_MAPS = ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];
@@ -28,6 +31,7 @@ const PROCEDURAL_MATERIAL_TAGS = new Set(['water', 'foliage', 'grass', 'terrain'
const SWAYING_TAGS = new Set(['foliage', 'grass']);
function renderPass(material) {
+ if (material.transmission > 0) return 'liquid';
return TRANSLUCENT_TAGS.has(material.tag) ? material.tag : 'opaque';
}
@@ -223,7 +227,7 @@ export function groupParts(parts, batching = true) {
const key = batching ? part.geometry : part;
if (!groups.has(key)) groups.set(key, new Map());
let maps = groups.get(key);
- for (const value of [...materialMapState(part.material), part.skin ?? null, part.morph ?? null, castsShadow(part), renderPass(part.material), ...materialAlphaState(part.material)]) {
+ for (const value of [...materialMapState(part.material), ...materialLayerState(part.material), part.skin ?? null, part.morph ?? null, castsShadow(part), renderPass(part.material), ...materialAlphaState(part.material)]) {
if (!maps.has(value)) maps.set(value, new Map());
maps = maps.get(value);
}
@@ -404,7 +408,7 @@ export class Renderer67 {
this.inverseViewProjection = mat4.create();
this.program = compileProgram(this.context, benchmark ? benchmarkVertexShader : vertexShader, benchmark ? benchmarkFragmentShader : fragmentShader);
this.depthProgram = compileProgram(this.context, depthVertexShader, depthFragmentShader);
- this.uniforms = Object.fromEntries(['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', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
+ 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', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
for (const name of ['pointLightCount', 'pointLightPositions[0]', 'pointLightColors[0]', 'pointLightRadii[0]', 'keyColor', 'fillIntensity', 'ambientIntensity']) {
this.uniforms[name] = this.context.getUniformLocation(this.program, name);
}
@@ -419,7 +423,7 @@ export class Renderer67 {
this.bloomUniforms = Object.fromEntries(['sourceTexture', 'texelDirection', 'threshold', 'extract'].map(name => [name, this.context.getUniformLocation(this.bloomProgram, name)]));
this.skyUniforms = Object.fromEntries(['skyTop', 'skyBottom', 'sunDirection', 'inverseViewProjection', 'eye', 'time', 'daylight', 'hdrEnabled'].map((name) => [name, this.context.getUniformLocation(this.skyProgram, name)]));
this.liquidProgram = compileProgram(this.context, vertexShader, liquidFragmentShader);
- this.liquidUniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'sceneColor', 'resolution', 'exposure', 'hdrEnabled', 'worldMode', 'daylight', 'lightDirection', 'keyColor', 'ambientIntensity', 'fogColor', 'fogDensity', 'liquidOptics', 'foamShape', ...ENVIRONMENT_LOOKUP_UNIFORMS, 'time', 'wind', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...SKIN_UNIFORMS, ...MORPH_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.liquidProgram, name)]));
+ this.liquidUniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'sceneColor', 'resolution', 'exposure', 'hdrEnabled', 'worldMode', 'daylight', 'lightDirection', 'keyColor', 'ambientIntensity', 'fogColor', 'fogDensity', 'glassState', 'glassTint', 'liquidOptics', 'foamShape', ...ENVIRONMENT_LOOKUP_UNIFORMS, 'time', 'wind', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...SKIN_UNIFORMS, ...MORPH_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.liquidProgram, name)]));
}
this.depthAlphaUniforms = Object.fromEntries(DEPTH_ALPHA_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));
this.depthUniform = this.context.getUniformLocation(this.depthProgram, 'lightProjection');
@@ -668,8 +672,9 @@ export class Renderer67 {
const morphTexture = morph ? this.createMorphTexture(geometry, morph) : null;
const morphWeights = morph ? new Float32Array(morph.weights) : null;
const [alphaMode, alphaCutoff, opacity, doubleSided] = materialAlphaState(parts[0].material);
- const batch = { alphaMode, alphaCutoff, opacity, doubleSided, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), pass: renderPass(parts[0].material) };
- parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));
+ const layerState = materialLayerState(parts[0].material);
+ const batch = { alphaMode, alphaCutoff, opacity, doubleSided, layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), pass: renderPass(parts[0].material) };
+ parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, layerState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));
return batch;
}
@@ -696,7 +701,8 @@ export class Renderer67 {
const sameState = location?.geometry === first.geometry && batch?.castShadow === castsShadow(first) &&
batch.floor === (first.material.tag === 'floor') && batchPass(batch) === renderPass(first.material) &&
[batch.alphaMode, batch.alphaCutoff, batch.opacity, batch.doubleSided].every((value, index) => value === alphaState[index]) &&
- batch.mapState.every((value, index) => value === mapState[index]);
+ batch.mapState.every((value, index) => value === mapState[index]) &&
+ batch.layerState.every((value, index) => value === materialLayerState(first.material)[index]);
if (sameParts && sameState) {
retained.add(batch);
return { group, batch };
@@ -861,7 +867,7 @@ export class Renderer67 {
for (let index = 0; index < MATERIAL_MAPS.length; index++) {
if ((part.material[MATERIAL_MAPS[index]] ?? null) !== mapState[index]) throw new Error(`Material map or scale changes require a new renderer: ${part.name}`);
}
- if (normalScale[0] !== mapState[5] || normalScale[1] !== mapState[6] || (part.material.occlusionStrength ?? 1) !== mapState[7] || mossState(part.material).some((value, index) => value !== mapState[8 + index])) throw new Error(`Material map or scale changes require a new renderer: ${part.name}`);
+ if (normalScale[0] !== mapState[5] || normalScale[1] !== mapState[6] || (part.material.occlusionStrength ?? 1) !== mapState[7] || mossState(part.material).some((value, index) => value !== mapState[8 + index]) || materialLayerState(part.material).some((value, index) => value !== location.layerState[index])) throw new Error(`Material map or scale changes require a new renderer: ${part.name}`);
validateTransform(part, location.normalMatrix);
}
// A palette upload also changes consumers absent from the submitted part list.
@@ -1250,6 +1256,9 @@ export class Renderer67 {
context.bindTexture(context.TEXTURE_2D, this.frameTexture);
context.uniform1i(uniforms.sceneColor, 0);
for (const batch of liquids) {
+ const layers = batch.layerState;
+ context.uniform4f(uniforms.glassState, layers[9], layers[10], layers[11], Math.min(layers[12], MAX_FINITE_DISTANCE));
+ context.uniform3f(uniforms.glassTint, layers[13], layers[14], layers[15]);
context.bindVertexArray(batch.vertexArray);
context.drawElementsInstanced(context.TRIANGLES, batch.indexCount, context.UNSIGNED_INT, 0, batch.instanceCount);
}
@@ -1414,6 +1423,10 @@ export class Renderer67 {
this.context.uniform2f(this.uniforms.normalScale, batch.mapState[5], batch.mapState[6]);
this.context.uniform1f(this.uniforms.occlusionStrength, batch.mapState[7]);
this.context.uniform4f(this.uniforms.materialMoss, batch.mapState[8], batch.mapState[9], batch.mapState[10], batch.mapState[11]);
+ const layers = batch.layerState;
+ 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.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 652826fd..bc4480b7 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -243,6 +243,9 @@ uniform vec3 fogColor;
uniform float fogDensity;
// x: thickness in metres, y: index of refraction, z: refraction strength, w: scattering
uniform vec4 liquidOptics;
+// A transmissive PBR material: x: transmission, y: index of refraction, z: thickness in metres, w: attenuation distance
+uniform vec4 glassState;
+uniform vec3 glassTint;
// x: foam opacity, y: foam edge softness
uniform vec2 foamShape;
out vec4 outputColor;
@@ -315,21 +318,29 @@ void main() {
float roughness = clamp(surface.y, 0.02, 1.0);
vec2 screen = gl_FragCoord.xy / resolution;
// A convex body is thickest where it faces the camera and thins to nothing at its silhouette.
- float thickness = liquidOptics.x * mix(0.15, 1.0, facing);
- vec3 bent = refract(-viewDirection, normal, 1.0 / liquidOptics.y);
+ bool glass = glassState.x > 0.0;
+ float indexOfRefraction = glass ? glassState.y : liquidOptics.y;
+ float thickness = (glass ? glassState.z : liquidOptics.x) * mix(0.15, 1.0, facing);
+ vec3 bent = refract(-viewDirection, normal, 1.0 / indexOfRefraction);
vec4 projected = viewProjection * vec4(worldPosition + bent * thickness, 1.0);
vec2 refracted = projected.w > 0.0 ? projected.xy / projected.w * 0.5 + 0.5 : screen;
- refracted = clamp(mix(screen, refracted, liquidOptics.z), vec2(0.001), vec2(0.999));
+ refracted = clamp(mix(screen, refracted, glass ? 1.0 : liquidOptics.z), vec2(0.001), vec2(0.999));
vec3 behind = texture(sceneColor, refracted).rgb;
// The material colour is what one metre of this liquid lets through.
- vec3 transmittance = pow(clamp(color, vec3(0.001), vec3(1.0)), vec3(thickness));
- float reflectance = 0.02 + 0.98 * pow(1.0 - facing, 5.0);
- vec3 inScatter = color * (ambientLight(normal) + keyColor * max(dot(normal, light), 0.0) * 0.2) * liquidOptics.w * (1.0 - transmittance);
+ // For a PBR material the colour tints what passes through and the attenuation colour is what attenuationDistance metres let through.
+ vec3 absorption = pow(clamp(glass ? glassTint : color, vec3(0.001), vec3(1.0)), vec3(glass ? thickness / glassState.w : thickness));
+ vec3 transmittance = glass ? color * absorption : absorption;
+ float surfaceReflectance = pow((indexOfRefraction - 1.0) / (indexOfRefraction + 1.0), 2.0);
+ float reflectance = surfaceReflectance + (1.0 - surfaceReflectance) * pow(1.0 - facing, 5.0);
+ vec3 inScatter = color * (ambientLight(normal) + keyColor * max(dot(normal, light), 0.0) * 0.2) * (glass ? 0.0 : liquidOptics.w) * (1.0 - transmittance);
+ // The share of a PBR material that does not transmit is lit like a diffuse surface.
+ vec3 diffuseShare = glass ? color * (1.0 - glassState.x) * (ambientLight(normal) + keyColor * max(dot(normal, light), 0.0) / PI) : vec3(0.0);
vec3 reflection = environmentColor(reflect(-viewDirection, normal), roughness) * ambientIntensity;
vec3 highlight = keyColor * specularLobe(normal, viewDirection, light, roughness);
- vec3 surfaceLight = inScatter * (1.0 - reflectance) + reflection * reflectance + highlight;
+ vec3 surfaceLight = (inScatter + diffuseShare) * (1.0 - reflectance) + reflection * reflectance + highlight;
surfaceLight = mix(surfaceLight, fogColor, fog);
- outputColor = vec4(behind * transmittance * (1.0 - reflectance) * (1.0 - fog) + displayed(surfaceLight), 1.0);
+ float transmitted = glass ? glassState.x : 1.0;
+ outputColor = vec4(behind * transmittance * transmitted * (1.0 - reflectance) * (1.0 - fog) + displayed(surfaceLight), 1.0);
}`;
export const fragmentShader = `#version 300 es
@@ -381,6 +392,10 @@ in vec3 boxNormal;
flat in mat3 boxNormalMatrix;
uniform float boxMapScale;
uniform int boxMapAxis;
+// Dielectric reflectance at normal incidence, clear coat (strength, roughness) and sheen (colour, roughness)
+uniform vec3 materialDielectric;
+uniform vec2 materialCoat;
+uniform vec4 materialSheen;
uniform vec4 materialMoss;
uniform float hdrEnabled;
uniform float alphaMode;
@@ -469,7 +484,7 @@ 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(vec3(0.04), color, metallic));
+ vec3 reflectance = fresnel(max(dot(halfway, viewDirection), 0.0), mix(materialDielectric, color, metallic));
vec3 specular = distribution * geometry * reflectance / max(4.0 * normalView * normalLight, 0.001);
vec3 diffuse = (1.0 - reflectance) * (1.0 - metallic) * color / PI;
return (diffuse + specular) * radiance * normalLight;
@@ -570,6 +585,40 @@ float surfaceAlpha(float textureAlpha) {
return 1.0;
}
+vec3 surroundingsColor(vec3 direction, float roughness) {
+ if (environmentEnabled > 0.5) return environmentRadiance(direction, roughness * environmentLevelMax);
+ if (worldMode > 0.5) return mix(fogColor * 0.8, vec3(0.20, 0.38, 0.52) * 1.6, smoothstep(-0.15, 0.7, direction.y)) * 0.5 * daylight;
+ return studio(direction, roughness);
+}
+
+// Clear coat: a second dielectric specular lobe over the base. Light that reflects off it never reaches the base.
+// 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);
+ float coatFresnel = fresnel(max(dot(normal, viewDirection), 0.001), vec3(0.04)).x * materialCoat.x;
+ vec3 mirror = surroundingsColor(reflect(-viewDirection, normal), roughness) * coatFresnel * ambientIntensity;
+ vec3 highlight = illuminate(normal, viewDirection, normalize(lightDirection), keyColor * visibility, vec3(0.04), 1.0, roughness);
+ return baseRadiance * (1.0 - coatFresnel) + mirror + highlight * materialCoat.x;
+}
+
+// Sheen: the Charlie distribution with the Neubelt visibility term (KHR_materials_sheen), plus a rim of ambient light.
+vec3 sheenLayer(vec3 baseRadiance, vec3 normal, vec3 viewDirection, float visibility) {
+ float roughness = clamp(materialSheen.w, 0.07, 1.0);
+ float inverseAlpha = 1.0 / (roughness * roughness);
+ vec3 lightVector = normalize(lightDirection);
+ vec3 halfway = normalize(viewDirection + lightVector);
+ float normalLight = max(dot(normal, lightVector), 0.0);
+ float normalView = max(dot(normal, viewDirection), 0.001);
+ float sine = sqrt(max(1.0 - pow(max(dot(normal, halfway), 0.0), 2.0), 0.0));
+ float distribution = (2.0 + inverseAlpha) * pow(sine, inverseAlpha) / (2.0 * PI);
+ float visibilityTerm = 1.0 / (4.0 * (normalLight + normalView - normalLight * normalView));
+ vec3 keyTerm = materialSheen.rgb * distribution * visibilityTerm * normalLight * keyColor * visibility;
+ vec3 ambientTerm = environmentEnabled > 0.5 ? environmentDiffuse(normal) : mix(vec3(0.16, 0.20, 0.22), vec3(0.19, 0.25, 0.30) * max(daylight, 0.08), worldMode);
+ vec3 rimTerm = materialSheen.rgb * ambientTerm * pow(1.0 - normalView, 3.0) * ambientIntensity;
+ float shadowedBase = 1.0 - 0.2 * max(materialSheen.r, max(materialSheen.g, materialSheen.b));
+ return baseRadiance * shadowedBase + keyTerm + rimTerm;
+}
+
void main() {
vec3 normal = normalize(worldNormal);
// Foliage and grass cards are single-sided geometry whose shading normal already leans toward the
@@ -677,7 +726,7 @@ void main() {
vec3 lightRadiance = pointLightColors[index].rgb * pointLightColors[index].w * attenuation;
radiance += illuminate(normal, viewDirection, offset * inversesqrt(distanceSquared), lightRadiance, color, metallic, roughness);
}
- vec3 reflectance = fresnel(max(dot(normal, viewDirection), 0.0), mix(vec3(0.04), color, metallic));
+ vec3 reflectance = fresnel(max(dot(normal, viewDirection), 0.0), mix(materialDielectric, color, metallic));
float occlusion = 1.0;
if (hasOcclusionMap > 0.5) occlusion = mix(1.0, texture(occlusionMap, textureUV).r, occlusionStrength);
occlusion *= splatCavity;
@@ -707,6 +756,8 @@ void main() {
float thinness = textureUV.x > -0.5 ? 1.0 - textureUV.y * 0.8 : 0.6;
radiance += color * vec3(1.1, 1.25, 0.55) * towardSun * thinness * 1.4 * keyResponse * visibility;
}
+ if (materialSheen.rgb != vec3(0.0)) radiance = sheenLayer(radiance, normal, viewDirection, visibility);
+ if (materialCoat.x > 0.0) radiance = clearCoatLayer(radiance, normal, viewDirection, visibility);
radiance += emission;
if (surface.w == 3.0) {
float reflectivity = 0.20 + 0.65 * pow(1.0 - max(dot(normal, viewDirection), 0.0), 3.0);
diff --git a/tests/gltf-extensions.test.js b/tests/gltf-extensions.test.js
index 177f31aa..6485f246 100644
--- a/tests/gltf-extensions.test.js
+++ b/tests/gltf-extensions.test.js
@@ -155,35 +155,61 @@ test('EXT_mesh_gpu_instancing handles several primitives and a bounded instance
await assert.rejects(parseGltf(instancingDocument([1, 0, 0], document => { document.nodes[0].extensions.EXT_mesh_gpu_instancing.attributes = {}; })), /needs TRANSLATION/);
});
-const OPTIONAL_MATERIAL_EXTENSIONS = {
- KHR_materials_clearcoat: { clearcoatFactor: 1 },
+const LAYER_MATERIAL_EXTENSIONS = {
+ KHR_materials_clearcoat: { clearcoatFactor: 1, clearcoatRoughnessFactor: 0.1 },
KHR_materials_transmission: { transmissionFactor: 0.6 },
KHR_materials_ior: { ior: 1.4 },
- KHR_materials_specular: { specularFactor: 0.5 },
- KHR_materials_sheen: { sheenRoughnessFactor: 0.3 },
- KHR_materials_volume: { thicknessFactor: 0.1 },
+ KHR_materials_specular: { specularFactor: 0.5, specularColorFactor: [1, 0.9, 0.8] },
+ 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 },
};
-test('optional KHR_materials extensions load with warnings and a transmission hint', async () => {
+test('KHR_materials layer extensions import as material layers', async () => {
const asset = await parseGltf(triangleDocument({
edit: document => {
- document.extensionsUsed = Object.keys(OPTIONAL_MATERIAL_EXTENSIONS);
- document.materials[0].extensions = structuredClone(OPTIONAL_MATERIAL_EXTENSIONS);
+ document.extensionsUsed = Object.keys(LAYER_MATERIAL_EXTENSIONS);
+ document.materials[0].extensions = structuredClone(LAYER_MATERIAL_EXTENSIONS);
},
}));
- assert.equal(asset.parts.length, 1);
- assert.equal(asset.parts[0].material.transmission, 0.6);
- assert.deepEqual(asset.warnings, Object.keys(OPTIONAL_MATERIAL_EXTENSIONS).sort().map(name => `${name} is accepted but not rendered.`));
+ const material = asset.parts[0].material;
+ assert.equal(material.clearcoat, 1);
+ assert.equal(material.clearcoatRoughness, 0.1);
+ assert.equal(material.transmission, 0.6);
+ assert.equal(material.ior, 1.4);
+ assert.equal(material.specular, 0.5);
+ assert.deepEqual(material.specularColor, [1, 0.9, 0.8]);
+ assert.deepEqual(material.sheenColor, [0.5, 0.4, 0.3]);
+ assert.equal(material.sheenRoughness, 0.3);
+ assert.equal(material.thickness, 0.1);
+ assert.equal(material.attenuationDistance, 2);
+ assert.deepEqual(material.attenuationColor, [0.8, 0.9, 1]);
+ assert.deepEqual(asset.warnings, []);
const plain = await parseGltf(triangleDocument());
assert.deepEqual(plain.warnings, []);
assert.equal('transmission' in plain.parts[0].material, false);
});
-test('required material extensions, bad transmission and missing decoders are rejected', async () => {
- const required = triangleDocument({ edit: document => { document.extensionsRequired = ['KHR_materials_clearcoat']; } });
- await assert.rejects(parseGltf(required), /Unsupported glTF extension: KHR_materials_clearcoat/);
+test('anisotropy and iridescence load with a warning because they are not rendered', async () => {
+ const asset = await parseGltf(triangleDocument({
+ edit: document => {
+ document.extensionsUsed = Object.keys(UNRENDERED_MATERIAL_EXTENSIONS);
+ document.materials[0].extensions = structuredClone(UNRENDERED_MATERIAL_EXTENSIONS);
+ },
+ }));
+ assert.deepEqual(asset.warnings, Object.keys(UNRENDERED_MATERIAL_EXTENSIONS).sort().map(name => `${name} is accepted but not rendered.`));
+});
+
+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 badTransmission = triangleDocument({ edit: document => { document.materials[0].extensions = { KHR_materials_transmission: { transmissionFactor: 2 } }; } });
- await assert.rejects(parseGltf(badTransmission), /transmissionFactor/);
+ 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 } }; } });
+ await assert.rejects(parseGltf(badIor), /ior must be between 1 and 2.5/);
for (const [extension, decoder] of [['KHR_draco_mesh_compression', 'draco'], ['EXT_meshopt_compression', 'meshopt'], ['KHR_texture_basisu', 'ktx2']]) {
const data = triangleDocument({ edit: document => { document.extensionsRequired = [extension]; } });
await assert.rejects(parseGltf(data), new RegExp(`options\\.decoders\\.${decoder}`));
diff --git a/tests/material-layers.test.js b/tests/material-layers.test.js
new file mode 100644
index 00000000..4d4310b5
--- /dev/null
+++ b/tests/material-layers.test.js
@@ -0,0 +1,91 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mat4 } from 'gl-matrix';
+import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
+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';
+
+function recipeWithMaterial(material) {
+ return {
+ format: '67js.scene',
+ schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box', bevel: 0 }],
+ materials: [{ id: 'finish', ...material }],
+ nodes: [{ id: 'block', geometry: 'box', material: 'finish' }],
+ };
+}
+
+test('a plain material keeps the 4 percent dielectric reflectance and no layers', () => {
+ const state = materialLayerState({});
+ assert.deepEqual(dielectricReflectance({}).map(value => Number(value.toFixed(6))), [0.04, 0.04, 0.04]);
+ assert.equal(state[3], 0, 'clearcoat');
+ assert.equal(state[9], 0, 'transmission');
+ assert.deepEqual(state.slice(5, 8), [0, 0, 0], 'sheen colour');
+});
+
+test('ior, specular and specular colour set the dielectric reflectance', () => {
+ const water = dielectricReflectance({ ior: 1.33 });
+ assert.ok(Math.abs(water[0] - 0.02) < 0.0005);
+ const weak = dielectricReflectance({ specular: 0.5, specularColor: [1, 0.5, 0] });
+ assert.ok(Math.abs(weak[0] - 0.02) < 1e-9);
+ assert.ok(Math.abs(weak[1] - 0.01) < 1e-9);
+ assert.equal(weak[2], 0);
+});
+
+test('every layer value is checked at the boundary and the error names the fix', () => {
+ const cases = [
+ [{ clearcoat: 1.5 }, /clearcoat must be between 0 and 1, got 1.5\. Use a number inside that range/],
+ [{ clearcoatRoughness: -0.1 }, /clearcoatRoughness must be between 0 and 1/],
+ [{ transmission: 'half' }, /transmission must be between 0 and 1/],
+ [{ thickness: -1 }, /thickness must be between 0 and 1000/],
+ [{ ior: 0.9 }, /ior must be between 1 and 2.5/],
+ [{ sheenRoughness: 2 }, /sheenRoughness must be between 0 and 1/],
+ [{ specular: NaN }, /specular must be between 0 and 4/],
+ [{ 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/],
+ [{ 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);
+ assert.doesNotThrow(() => validateMaterialLayers({ clearcoat: 1, ior: 2.5, transmission: 0, attenuationDistance: Infinity }));
+});
+
+test('recipes accept layer fields and reject out of range values', () => {
+ const scene = createAgentScene(recipeWithMaterial({ clearcoat: 1, clearcoatRoughness: 0.05, sheenColor: [0.4, 0.2, 0.2], transmission: 0.9, thickness: 0.4, ior: 1.45, attenuationColor: [0.7, 0.9, 0.8], attenuationDistance: 3 }));
+ const material = scene.exportRecipe().materials[0];
+ assert.equal(material.clearcoat, 1);
+ assert.equal(material.transmission, 0.9);
+ assert.deepEqual(material.attenuationColor, [0.7, 0.9, 0.8]);
+ assert.throws(() => createAgentScene(recipeWithMaterial({ ior: 3 })), /ior must be between 1 and 2.5/);
+ assert.throws(() => createAgentScene(recipeWithMaterial({ clearcoat: 2 })), /clearcoat must be between 0 and 1/);
+});
+
+test('a transmissive recipe material draws in the pass that sees the opaque scene', () => {
+ const scene = createAgentScene(recipeWithMaterial({ transmission: 1, thickness: 0.2 }));
+ assert.equal(scene.parts[0].material.transmission, 1);
+});
+
+test('layers survive a GLB export and import with their extensions declared', async () => {
+ const material = { color: [0.2, 0.5, 0.7], roughness: 0.4, metallic: 0, emission: 0, clearcoat: 0.8, clearcoatRoughness: 0.2, transmission: 0.7, thickness: 0.5, ior: 1.4, attenuationColor: [0.5, 0.8, 0.9], attenuationDistance: 2, sheenColor: [0.3, 0.2, 0.1], sheenRoughness: 0.6, specular: 0.8, specularColor: [1, 0.9, 0.8] };
+ const bytes = exportGlb([{ name: 'cube', geometry: box(0), matrix: mat4.create(), material }]);
+ const asset = await parseGltf(bytes);
+ const imported = asset.parts[0].material;
+ for (const field of ['clearcoat', 'clearcoatRoughness', 'transmission', 'thickness', 'ior', 'attenuationDistance', 'sheenRoughness', 'specular']) {
+ assert.ok(Math.abs(imported[field] - material[field]) < 1e-6, field);
+ }
+ for (const field of ['attenuationColor', 'sheenColor', 'specularColor']) {
+ imported[field].forEach((value, index) => assert.ok(Math.abs(value - material[field][index]) < 1e-6, field));
+ }
+ assert.deepEqual(asset.warnings, []);
+ const gltf = await new GLTFLoader().parseAsync(bytes, '');
+ assert.equal(gltf.scene.children.length > 0, true);
+});
+
+test('a plain export declares no layer extension and an invalid layer is rejected', () => {
+ const plain = exportGlb([{ name: 'cube', geometry: box(0), matrix: mat4.create(), material: { color: [0.2, 0.5, 0.7], roughness: 0.4, metallic: 0 } }]);
+ 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/);
+});
diff --git a/tests/morph-renderer.test.js b/tests/morph-renderer.test.js
index a19bde9e..8a801d4a 100644
--- a/tests/morph-renderer.test.js
+++ b/tests/morph-renderer.test.js
@@ -4,6 +4,7 @@ import { mat4, mat3 } from 'gl-matrix';
import { box } from '../src/geometry.js';
import { Renderer67, groupParts } from '../src/renderer.js';
import { createMorphPose, validateMorphGeometry } from '../src/morph.js';
+import { materialLayerState } from '../src/material-layers.js';
function makePart(name, geometry, morph) {
return { name, geometry, morph, matrix: mat4.create(), material: { color: [0.4, 0.5, 0.6], metallic: 0, roughness: 0.7, emission: 0 } };
@@ -40,7 +41,7 @@ function retainedRenderer(parts) {
group.forEach((part, index) => renderer.partLocations.set(part, {
batch, index, geometry: part.geometry, morph: part.morph,
morphWeights: part.morph.weights, morphTargets: part.geometry.morphTargets,
- skin: null, map: null, mapState: [null, null, null, null, null, 1, 1, 1, 0, 0.05, 0.085, 0.02],
+ skin: null, map: null, layerState: materialLayerState({}), mapState: [null, null, null, null, null, 1, 1, 1, 0, 0.05, 0.085, 0.02],
normalMatrix: mat3.create(),
}));
return batch;
diff --git a/tests/reference-baseline.test.js b/tests/reference-baseline.test.js
index bc076d05..b4aa3d5b 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 = ['character', 'fog', 'foliage', 'glass', 'lit-interior', 'material-spheres', 'metal', 'outdoor-hdri'];
+const EXPECTED_SCENES = ['car-paint', 'character', 'fog', 'foliage', 'glass', 'lit-interior', 'material-spheres', 'metal', 'outdoor-hdri'];
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/renderer.test.js b/tests/renderer.test.js
index c770c332..ea8610bf 100644
--- a/tests/renderer.test.js
+++ b/tests/renderer.test.js
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import { mat4, mat3 } from 'gl-matrix';
import { Renderer67, groupParts, resolveLiquidOptics, textureDescriptorInfo } from '../src/renderer.js';
import { createSkinPose } from '../src/skinning.js';
+import { materialLayerState } from '../src/material-layers.js';
function part(name, geometry = {}, map) {
return { name, geometry, matrix: mat4.create(), material: { color: [0.1, 0.2, 0.3], metallic: 0.5, roughness: 0.3, emission: 0, map } };
@@ -14,7 +15,7 @@ function retainedRenderer(parts) {
const batch = { instanceBuffer: {}, instanceData: new Float32Array(parts.length * 41).fill(7), castShadow: true, alphaMode: 'opaque', alphaCutoff: 0, opacity: 1, doubleSided: false };
renderer.context = { ARRAY_BUFFER: 34962, bindBuffer() {}, bufferSubData(target, offset, data) { writes.push({ target, offset, data: Array.from(data) }); } };
renderer.partLocations = new Map(parts.map((item, index) => [item, {
- batch, index, geometry: item.geometry, map: item.material.map ?? null, normalMatrix: mat3.create(), skin: item.skin ?? null,
+ batch, index, geometry: item.geometry, map: item.material.map ?? null, normalMatrix: mat3.create(), layerState: materialLayerState(item.material), skin: item.skin ?? null,
jointMatrices: item.skin?.jointMatrices, skinIndices: item.geometry.skinIndices, skinWeights: item.geometry.skinWeights,
mapState: ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'].map(field => item.material[field] ?? null).concat(item.material.normalScale ?? [1, 1], item.material.occlusionStrength ?? 1, item.material.moss ?? 0, item.material.mossColor ?? [0.05, 0.085, 0.02]),
}]));
@@ -326,22 +327,27 @@ test('draw batches bind all channels with their flags and scalar uniforms', () =
const renderer = Object.create(Renderer67.prototype);
const bindings = [];
const uniforms = [];
- renderer.uniforms = Object.fromEntries(['baseMap', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap', 'hasBaseMap', 'hasNormalMap', 'hasMetallicRoughnessMap', 'hasOcclusionMap', 'hasEmissiveMap', 'normalScale', 'occlusionStrength', 'materialMoss'].map(name => [name, name]));
+ renderer.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'baseMap', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap', 'hasBaseMap', 'hasNormalMap', 'hasMetallicRoughnessMap', 'hasOcclusionMap', 'hasEmissiveMap', 'normalScale', 'occlusionStrength', 'materialMoss'].map(name => [name, name]));
renderer.context = {
TEXTURE0: 33984,
activeTexture(unit) { bindings.push(unit); }, bindTexture() {}, bindVertexArray() {}, drawElementsInstanced() {},
uniform1i(name, value) { uniforms.push([name, value]); },
uniform1f(name, value) { uniforms.push([name, value]); },
uniform2f(name, first, second) { uniforms.push([name, first, second]); },
+ uniform3f(name, ...values) { uniforms.push([name, ...values]); },
uniform4f(name, ...values) { uniforms.push([name, ...values]); },
};
- renderer.drawBatch({ textures: [{}, {}, {}, {}, {}], mapState: [{}, {}, {}, null, {}, 0.5, -1, 0.4, 0.6, 0.1, 0.2, 0.05] }, true);
+ const layerState = materialLayerState({ clearcoat: 0.7, clearcoatRoughness: 0.2, sheenColor: [0.1, 0.2, 0.3], sheenRoughness: 0.4 });
+ renderer.drawBatch({ textures: [{}, {}, {}, {}, {}], layerState, mapState: [{}, {}, {}, null, {}, 0.5, -1, 0.4, 0.6, 0.1, 0.2, 0.05] }, true);
assert.deepEqual(bindings, [33985, 33986, 33987, 33988, 33989]);
assert.ok(uniforms.some(values => values[0] === 'hasOcclusionMap' && values[1] === 0));
assert.ok(uniforms.some(values => values[0] === 'metallicRoughnessMap' && values[1] === 3));
assert.ok(uniforms.some(values => values[0] === 'normalScale' && values[1] === 0.5 && values[2] === -1));
assert.ok(uniforms.some(values => values[0] === 'occlusionStrength' && values[1] === 0.4));
assert.ok(uniforms.some(values => values[0] === 'materialMoss' && values[1] === 0.6 && values[4] === 0.05));
+ assert.ok(uniforms.some(values => values[0] === 'materialCoat' && values[1] === 0.7 && values[2] === 0.2));
+ assert.ok(uniforms.some(values => values[0] === 'materialSheen' && values[1] === 0.1 && values[4] === 0.4));
+ assert.ok(uniforms.some(values => values[0] === 'materialDielectric' && Math.abs(values[1] - 0.04) < 1e-9));
});
function skinGeometry(vertexCount = 3) {