Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add a bounded material node graph and UV mapping for patterns

Nguyen Xuan Anb8c4048a6e2b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6de0efe4..07c7487e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
## Unreleased
+- Add a bounded material node graph (issue #50): material `pattern` of `type: "graph"` bakes noise, voronoi, wave, checker, gradient, ramp, maths and `uv` nodes on the CPU into base colour, roughness, metallic, emission and height (a normal map, so bump). The graph is data, never shader text; nodes, depth, ramp stops, texture size and work are checked before any pixel is computed. Add `mapping: "uv"` to every pattern so it follows `uv_unwrap` UVs instead of box projection; the emissive map now box-maps like the other maps. The 11 presets bake the same bytes as before. Covered in the MCP schema, `scene_capabilities` (`materialGraph`, `materialMappings`), GLB export, `docs/agent-scene.md`, `docs/material-maps.md` and the `brick-graph` reference scene.
- Load agent scene code on demand: mesh editing, `lathe`/`extrude`/`tube`, material `pattern` and `motion` now sit behind `loadAgentSceneModules(recipe)` (or `loadAllAgentSceneModules()`), and `createAgentScene` throws an error naming that call when a needed module is missing. A recipe of primitives drops from 141,241 to 73,581 bytes gzip in `scene:agent-scene` (every lazy chunk still totals 145,049). `npm run size` now bundles with code splitting and reports the initial load, plus a `+lazy` row for the total. `npm test` preloads every module. The archive no longer carries 29 docs that the site serves (physics, lighting, terrain and the other addon docs); agent docs stay
- Add joint limits, node constraints and drivers to motion (issue #58). Two-bone IK takes `limits` per joint and axis in degrees and `bendToward`; `scene_inspect` `motionIk` now carries `limited` (each pose a limit changed) and `warnings` (`hyperextended`, and `wrong-bend` for a knee or elbow bent the unnatural way, which a wrong pole used to hide behind `reached`). `motion.constraints` adds `copy_location`, `copy_rotation`, `copy_scale`, `limit_location`, `limit_rotation`, `track_to`, `child_of` (with an inverse and an influence blend) and `floor`, and `motion.drivers` sets a node component or material property from a bounded JSON expression over time and other nodes (never run as code). The order is tracks, IK, drivers, constraints, with no state between samples, so a seek equals playing. `copy_rotation`, `limit_rotation`, `track_to`, `child_of` and `floor` match Blender 5.2 world matrices in 8 recorded cases (`tests/fixtures/blender/constraints.json`). Joint limits are also in `67js/addons/skeleton-pose`. The `leg-plant` task joins the agent modeling suite. The expression language is a new small one in `src/motion-expression.js`: the field expressions of the mesh addon were not on `main` yet
diff --git a/bench/agent-modeling/check.mjs b/bench/agent-modeling/check.mjs
index e1f41a45..e147579f 100644
--- a/bench/agent-modeling/check.mjs
+++ b/bench/agent-modeling/check.mjs
@@ -56,6 +56,12 @@ function checkOne(check, measures) {
const found = measures.patternTypes.filter(type => check.types.includes(type));
return { pass: found.length > 0, detail: measures.patternTypes.join(', ') || 'no material pattern' };
}
+ case 'uvPattern': {
+ // A graph material that follows the geometry UVs, and every part that wears it has them.
+ const followsUvs = measures.patternTypes.some((type, index) => type === 'graph' && measures.patternMappings[index] === 'uv');
+ const everyPart = measures.uv.parts === measures.uv.of;
+ return { pass: followsUvs && everyPart && measures.uv.stretch <= check.maxStretch, detail: followsUvs ? `graph on UVs, stretch ${round(measures.uv.stretch)}, ${measures.uv.parts}/${measures.uv.of} parts with UVs` : 'no graph material with mapping uv' };
+ }
case 'nodeAt': {
const position = measures.nodePosition(check.node, check.time);
if (!position) return { pass: false, detail: `no drawn node ${check.node}` };
diff --git a/bench/agent-modeling/measure.mjs b/bench/agent-modeling/measure.mjs
index 47e6cecc..034a2a2a 100644
--- a/bench/agent-modeling/measure.mjs
+++ b/bench/agent-modeling/measure.mjs
@@ -278,6 +278,7 @@ export async function measureRecipe(recipe) {
physics,
physicsSeekStable,
patternTypes: scene.exportRecipe().materials.filter(material => material.pattern).map(material => material.pattern.type),
+ patternMappings: scene.exportRecipe().materials.filter(material => material.pattern).map(material => material.pattern.mapping ?? 'box'),
parts,
closedParts,
holes: allClosed ? (2 * parts - eulerCharacteristic) / 2 : null,
diff --git a/bench/agent-modeling/references.mjs b/bench/agent-modeling/references.mjs
index e50f4777..f53ac44a 100644
--- a/bench/agent-modeling/references.mjs
+++ b/bench/agent-modeling/references.mjs
@@ -214,6 +214,23 @@ export const REFERENCES = {
),
materials: [{ id: 'paint', pattern: { type: 'planks', size: 0.6, count: 5 }, roughness: 1 }],
},
+ 'crate-graph': {
+ ...scene(
+ [{ id: 'crate', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: [...crateEdits, { op: 'uv_unwrap' }] }],
+ [{ id: 'crate', geometry: 'crate', translation: [0, 0.3, 0] }],
+ ),
+ materials: [{
+ id: 'paint',
+ pattern: {
+ type: 'graph', mapping: 'uv', bump: 0.6,
+ graph: {
+ color: { ramp: { value: { add: [{ mul: [{ wave: { frequency: 6, direction: 'u', shape: 'triangle' } }, 0.7] }, { mul: [{ noise: { scale: 16, seed: 4 } }, 0.3] }] }, stops: [[0, [0.05, 0.12, 0.2]], [1, [0.8, 0.7, 0.45]]] } },
+ roughness: { mix: [0.5, 0.9, { noise: { scale: 16, seed: 4 } }] },
+ height: { noise: { scale: 24, seed: 7 } },
+ },
+ },
+ }],
+ },
'crate-uv': scene(
[{ id: 'crate', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: [...crateEdits, { op: 'uv_unwrap' }] }],
[{ id: 'crate', geometry: 'crate', translation: [0, 0.3, 0] }],
diff --git a/bench/agent-modeling/tasks.mjs b/bench/agent-modeling/tasks.mjs
index 0d7e48db..299dc179 100644
--- a/bench/agent-modeling/tasks.mjs
+++ b/bench/agent-modeling/tasks.mjs
@@ -171,6 +171,15 @@ sides has a recessed panel: a frame about 0.04 m wide around a panel sunk about
raised lid, inset about 0.05 m from the top edges and 0.03 m tall.`,
checks: [...crateChecks, { kind: 'pattern', types: ['wood', 'planks'] }],
},
+ {
+ id: 'crate-graph',
+ prompt: `A crate with a painted look of your own design: dark and light stripes with a worn, noisy edge, not a ready-made wood or
+planks preset. The body is a 0.6 m cube. Each of its four sides has a recessed panel: a frame about 0.04 m wide around a
+panel sunk about 0.02 m into the side. On top sits a raised lid, inset about 0.05 m from the top edges and 0.03 m tall.
+The stripes must follow the crate's own UV coordinates, so they stay put on the panels and the lid. Give every part UV
+coordinates with even texel density and no stretching.`,
+ checks: [...crateChecks, { kind: 'uvPattern', maxStretch: 0.15 }],
+ },
{
id: 'dice',
prompt: `A six-sided die as one solid piece: a 0.1 m cube with every edge and corner rounded to a radius of about
diff --git a/bench/reference/README.md b/bench/reference/README.md
index 8f5b1e93..36897ef7 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -1,6 +1,6 @@
# Reference renders
-This suite scores how close a 67.js render is to Blender on 9 fixed scenes. Later work uses these scores as its starting point.
+This suite scores how close a 67.js render is to Blender on 11 fixed scenes. Later work uses these scores as its starting point.
## Run it
@@ -25,9 +25,12 @@ Measured on 2026-10-30 with an RTX 3060, SwiftShader and Blender 5.2.2. The metr
| `fog` | 0.2612 | 0.2662 | 0.0542 | No multiple scattering |
| `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 67.js noise, so brick tone differs |
Rows are the baseline taken before shadows for point lights. The `lit-interior` scene now sets `castShadow` on its three point lights. With shadows, 67.js 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 67.js 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.
+`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 67.js: 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.
+
The mean against Cycles is 0.198 for 67.js 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 67.js. 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 a31bdab8..605b8dab 100644
--- a/bench/reference/baseline.json
+++ b/bench/reference/baseline.json
@@ -1,128 +1,144 @@
{
- "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
- },
- "glass": {
- "cycles": 5.8,
- "eevee": 0.4
- },
- "lit-interior": {
- "cycles": 10,
- "eevee": 0.6
- },
- "material-spheres": {
- "cycles": 6.7,
- "eevee": 0.4
- },
- "metal": {
- "cycles": 5,
- "eevee": 0.3
- },
- "outdoor-hdri": {
- "cycles": 4.1,
- "eevee": 0.4
- },
- "spot-area": {
- "cycles": 20.3,
- "eevee": 13.2
- }
- },
- "graphics": {
- "gpu": "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 (0x00002487) Direct3D11 vs_5_0 ps_5_0, D3D11)",
- "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,
- "cpu-vs-cycles": 0.099,
- "cpu-vs-eevee": 0.0826,
- "eevee-vs-cycles": 0.074,
- "gpu-vs-cpu": 0.0068
- },
- "fog": {
- "gpu-vs-cycles": 0.2612,
- "gpu-vs-eevee": 0.0542,
- "cpu-vs-cycles": 0.2608,
- "cpu-vs-eevee": 0.0542,
- "eevee-vs-cycles": 0.2662,
- "gpu-vs-cpu": 0.0085
- },
- "foliage": {
- "gpu-vs-cycles": 0.1594,
- "gpu-vs-eevee": 0.1386,
- "cpu-vs-cycles": 0.159,
- "cpu-vs-eevee": 0.1384,
- "eevee-vs-cycles": 0.0783,
- "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,
- "eevee-vs-cycles": 0.115,
- "gpu-vs-cpu": 0.0074
- },
- "lit-interior": {
- "gpu-vs-cycles": 0.4997,
- "gpu-vs-eevee": 0.1204,
- "cpu-vs-cycles": 0.4993,
- "cpu-vs-eevee": 0.1209,
- "eevee-vs-cycles": 0.5159,
- "gpu-vs-cpu": 0.006
- },
- "material-spheres": {
- "gpu-vs-cycles": 0.1598,
- "gpu-vs-eevee": 0.1196,
- "cpu-vs-cycles": 0.1595,
- "cpu-vs-eevee": 0.1194,
- "eevee-vs-cycles": 0.1006,
- "gpu-vs-cpu": 0.0069
- },
- "metal": {
- "gpu-vs-cycles": 0.1868,
- "gpu-vs-eevee": 0.1565,
- "cpu-vs-cycles": 0.1867,
- "cpu-vs-eevee": 0.1565,
- "eevee-vs-cycles": 0.0934,
- "gpu-vs-cpu": 0.0063
- },
- "outdoor-hdri": {
- "gpu-vs-cycles": 0.0676,
- "gpu-vs-eevee": 0.052,
- "cpu-vs-cycles": 0.0672,
- "cpu-vs-eevee": 0.0515,
- "eevee-vs-cycles": 0.0383,
- "gpu-vs-cpu": 0.0058
- },
- "spot-area": {
- "gpu-vs-cycles": 0.1242,
- "gpu-vs-eevee": 0.1707,
- "cpu-vs-cycles": 0.1242,
- "cpu-vs-eevee": 0.1709,
- "eevee-vs-cycles": 0.1935,
- "gpu-vs-cpu": 0.0032
- }
+ "metric": "FLIP (LDR), mean error, lower is better",
+ "blenderVersion": "5.2.2 LTS",
+ "seconds": {
+ "brick-graph": {
+ "cycles": 8.9,
+ "eevee": 15.2
+ },
+ "car-paint": {
+ "cycles": 13.8,
+ "eevee": 11.5
+ },
+ "character": {
+ "cycles": 21.6,
+ "eevee": 6.2
+ },
+ "fog": {
+ "cycles": 40.5,
+ "eevee": 7.2
+ },
+ "foliage": {
+ "cycles": 13.0,
+ "eevee": 4.6
+ },
+ "glass": {
+ "cycles": 11.5,
+ "eevee": 2.6
+ },
+ "lit-interior": {
+ "cycles": 19.4,
+ "eevee": 2.6
+ },
+ "material-spheres": {
+ "cycles": 12.7,
+ "eevee": 9.4
+ },
+ "metal": {
+ "cycles": 38.4,
+ "eevee": 13.3
+ },
+ "outdoor-hdri": {
+ "cycles": 17.1,
+ "eevee": 7.1
+ },
+ "spot-area": {
+ "cycles": 31.3,
+ "eevee": 5.6
+ }
+ },
+ "graphics": {
+ "gpu": "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 (0x00002487) Direct3D11 vs_5_0 ps_5_0, D3D11)",
+ "cpu": "ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)"
+ },
+ "scores": {
+ "brick-graph": {
+ "gpu-vs-cycles": 0.2269,
+ "gpu-vs-eevee": 0.148,
+ "cpu-vs-cycles": 0.2268,
+ "cpu-vs-eevee": 0.1479,
+ "eevee-vs-cycles": 0.144,
+ "gpu-vs-cpu": 0.0074
+ },
+ "car-paint": {
+ "gpu-vs-cycles": 0.1521,
+ "gpu-vs-eevee": 0.1324,
+ "cpu-vs-cycles": 0.152,
+ "cpu-vs-eevee": 0.1324,
+ "eevee-vs-cycles": 0.082,
+ "gpu-vs-cpu": 0.0055
+ },
+ "character": {
+ "gpu-vs-cycles": 0.0995,
+ "gpu-vs-eevee": 0.0833,
+ "cpu-vs-cycles": 0.099,
+ "cpu-vs-eevee": 0.0826,
+ "eevee-vs-cycles": 0.074,
+ "gpu-vs-cpu": 0.0068
+ },
+ "fog": {
+ "gpu-vs-cycles": 0.2612,
+ "gpu-vs-eevee": 0.0542,
+ "cpu-vs-cycles": 0.2608,
+ "cpu-vs-eevee": 0.0543,
+ "eevee-vs-cycles": 0.2662,
+ "gpu-vs-cpu": 0.0085
+ },
+ "foliage": {
+ "gpu-vs-cycles": 0.1594,
+ "gpu-vs-eevee": 0.1386,
+ "cpu-vs-cycles": 0.159,
+ "cpu-vs-eevee": 0.1384,
+ "eevee-vs-cycles": 0.0783,
+ "gpu-vs-cpu": 0.0096
+ },
+ "glass": {
+ "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.0075
+ },
+ "lit-interior": {
+ "gpu-vs-cycles": 0.5055,
+ "gpu-vs-eevee": 0.0923,
+ "cpu-vs-cycles": 0.5051,
+ "cpu-vs-eevee": 0.0928,
+ "eevee-vs-cycles": 0.5159,
+ "gpu-vs-cpu": 0.0062
+ },
+ "material-spheres": {
+ "gpu-vs-cycles": 0.1598,
+ "gpu-vs-eevee": 0.1196,
+ "cpu-vs-cycles": 0.1595,
+ "cpu-vs-eevee": 0.1194,
+ "eevee-vs-cycles": 0.1006,
+ "gpu-vs-cpu": 0.0069
+ },
+ "metal": {
+ "gpu-vs-cycles": 0.1868,
+ "gpu-vs-eevee": 0.1565,
+ "cpu-vs-cycles": 0.1867,
+ "cpu-vs-eevee": 0.1565,
+ "eevee-vs-cycles": 0.0934,
+ "gpu-vs-cpu": 0.0063
+ },
+ "outdoor-hdri": {
+ "gpu-vs-cycles": 0.0676,
+ "gpu-vs-eevee": 0.052,
+ "cpu-vs-cycles": 0.0672,
+ "cpu-vs-eevee": 0.0515,
+ "eevee-vs-cycles": 0.0383,
+ "gpu-vs-cpu": 0.0058
+ },
+ "spot-area": {
+ "gpu-vs-cycles": 0.1242,
+ "gpu-vs-eevee": 0.1707,
+ "cpu-vs-cycles": 0.1242,
+ "cpu-vs-eevee": 0.1709,
+ "eevee-vs-cycles": 0.1935,
+ "gpu-vs-cpu": 0.0032
}
+ }
}
diff --git a/bench/reference/images/brick-graph.jpg b/bench/reference/images/brick-graph.jpg
new file mode 100644
index 00000000..fa469a04
Binary files /dev/null and b/bench/reference/images/brick-graph.jpg differ
diff --git a/bench/reference/images/car-paint.jpg b/bench/reference/images/car-paint.jpg
index d68b1f63..23d3a6a2 100644
Binary files a/bench/reference/images/car-paint.jpg and b/bench/reference/images/car-paint.jpg differ
diff --git a/bench/reference/images/character.jpg b/bench/reference/images/character.jpg
index f690e048..17b7593f 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 71b45d6e..d5583e23 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 ef2fd8bb..bd2059d9 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 22669d84..1465e35a 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 03ed2cd5..e7775cb3 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 90af23af..a7f09e4d 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 5c218308..ffd44828 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 69a50327..8f7f4e15 100644
Binary files a/bench/reference/images/outdoor-hdri.jpg and b/bench/reference/images/outdoor-hdri.jpg differ
diff --git a/bench/reference/images/spot-area.jpg b/bench/reference/images/spot-area.jpg
index ca687a0f..5e096635 100644
Binary files a/bench/reference/images/spot-area.jpg and b/bench/reference/images/spot-area.jpg differ
diff --git a/bench/reference/render-blender.py b/bench/reference/render-blender.py
index ddb86a0e..6c669535 100644
--- a/bench/reference/render-blender.py
+++ b/bench/reference/render-blender.py
@@ -53,6 +53,7 @@ def build_mesh(name, geometry):
triangles = decode(geometry["indices"]).reshape(-1, 3)
mesh = bpy.data.meshes.new(name)
mesh.from_pydata(positions.tolist(), [], triangles.tolist())
+ mesh.validate()
mesh.normals_split_custom_set_from_vertices(normals.tolist())
uvs = decode(geometry.get("uvs"))
if uvs is not None:
@@ -154,6 +155,173 @@ def add_material_layers(material, principled, description):
material.node_tree.links.new(absorption.outputs["Volume"], material.node_tree.nodes["Material Output"].inputs["Volume"])
+GRAPH_MATH_OPERATIONS = {
+ "add": "ADD", "sub": "SUBTRACT", "mul": "MULTIPLY", "div": "DIVIDE", "min": "MINIMUM", "max": "MAXIMUM",
+ "pow": "POWER", "abs": "ABSOLUTE", "floor": "FLOOR", "fract": "FRACT", "sqrt": "SQRT",
+}
+# 67.js noise has no seed in Blender, and Blender's noise function differs from the one in src/material-texture-kit.js,
+# so a graph with noise only matches in how it looks, not pixel for pixel.
+GRAPH_BUMP_DISTANCE = 0.15
+
+
+class GraphTranslator:
+ """Builds the Blender nodes for a 67.js material graph (src/material-graph.js). Values are a number, a socket,
+ {"color": socket or three numbers} or {"vector": three numbers or sockets}. Only the nodes the reference scenes use exist."""
+
+ def __init__(self, material):
+ self.nodes = material.node_tree.nodes
+ self.links = material.node_tree.links
+ self.coordinates = None
+
+ def connect(self, socket, value):
+ if isinstance(value, (int, float)):
+ socket.default_value = value
+ else:
+ self.links.new(value, socket)
+
+ def math(self, operation, *inputs):
+ node = self.nodes.new("ShaderNodeMath")
+ node.operation = operation
+ for index, value in enumerate(inputs):
+ self.connect(node.inputs[index], value)
+ return node.outputs[0]
+
+ def uv_parts(self):
+ if self.coordinates is None:
+ attribute = self.nodes.new("ShaderNodeUVMap")
+ separate = self.nodes.new("ShaderNodeSeparateXYZ")
+ self.links.new(attribute.outputs["UV"], separate.inputs[0])
+ # The mesh stores 1 - v, because Blender's image rows run the other way (see build_mesh).
+ self.coordinates = (separate.outputs["X"], self.math("SUBTRACT", 1.0, separate.outputs["Y"]))
+ return self.coordinates
+
+ def position(self, settings):
+ if "at" in settings:
+ at = self.compile(settings["at"])
+ return at["vector"][0], at["vector"][1]
+ return self.uv_parts()
+
+ def scalar(self, node):
+ value = self.compile(node)
+ if isinstance(value, dict):
+ raise NotImplementedError("This graph node needs a number.")
+ return value
+
+ def compile(self, node):
+ if isinstance(node, (int, float)):
+ return float(node)
+ if isinstance(node, list):
+ return {"color": node}
+ name, settings = next(iter(node.items()))
+ if name == "uv":
+ u, v = self.uv_parts()
+ return {"u": u, "v": v}.get(settings) or {"vector": [u, v, 0.0]}
+ if name == "vec":
+ return {"vector": [self.scalar(part) for part in settings]}
+ if name == "noise":
+ return self.noise(settings)
+ if name == "wave":
+ return self.wave(settings)
+ if name == "smoothstep":
+ low, high, value = (self.scalar(part) for part in settings)
+ return self.smooth_step(value, low, high)
+ if name == "ramp":
+ return self.ramp(settings)
+ if name == "mix":
+ return self.mix(settings)
+ if name in GRAPH_MATH_OPERATIONS:
+ operands = settings if isinstance(settings, list) else [settings]
+ return self.math(GRAPH_MATH_OPERATIONS[name], *(self.scalar(operand) for operand in operands))
+ raise NotImplementedError(f"The Blender translation has no node for {name}.")
+
+ def smooth_step(self, value, low, high):
+ node = self.nodes.new("ShaderNodeMapRange")
+ node.data_type = "FLOAT"
+ node.interpolation_type = "SMOOTHSTEP"
+ node.clamp = True
+ self.connect(node.inputs["Value"], value)
+ self.connect(node.inputs["From Min"], low)
+ self.connect(node.inputs["From Max"], high)
+ return node.outputs["Result"]
+
+ def noise(self, settings):
+ node = self.nodes.new("ShaderNodeTexNoise")
+ node.noise_dimensions = "2D"
+ node.inputs["Scale"].default_value = settings.get("scale", 4)
+ node.inputs["Detail"].default_value = settings.get("octaves", 4) - 1
+ node.inputs["Roughness"].default_value = 0.5
+ combine = self.nodes.new("ShaderNodeCombineXYZ")
+ for index, part in enumerate(self.position(settings)):
+ self.connect(combine.inputs[index], part)
+ self.links.new(combine.outputs[0], node.inputs["Vector"])
+ return node.outputs["Fac"]
+
+ def wave(self, settings):
+ u, v = self.position(settings)
+ direction = settings.get("direction", "u")
+ along = u if direction == "u" else v
+ if direction == "diagonal":
+ along = self.math("ADD", u, v)
+ phase = self.math("MULTIPLY", along, float(settings.get("frequency", 4)))
+ shape = settings.get("shape", "sine")
+ if shape == "sine":
+ return self.math("MULTIPLY_ADD", self.math("SINE", self.math("MULTIPLY", phase, 2 * math.pi)), 0.5, 0.5)
+ fraction = self.math("FRACT", phase)
+ if shape == "saw":
+ return fraction
+ return self.math("SUBTRACT", 1.0, self.math("ABSOLUTE", self.math("SUBTRACT", self.math("MULTIPLY", fraction, 2.0), 1.0)))
+
+ def ramp(self, settings):
+ node = self.nodes.new("ShaderNodeValToRGB")
+ node.color_ramp.interpolation = "LINEAR"
+ stops = settings["stops"]
+ elements = node.color_ramp.elements
+ while len(elements) < len(stops):
+ elements.new(0.5)
+ for element, (position, color) in zip(elements, stops):
+ element.position = position
+ element.color = (color[0], color[1], color[2], 1)
+ self.connect(node.inputs["Fac"], self.scalar(settings["value"]))
+ return {"color": node.outputs["Color"]}
+
+ def color_socket(self, value, node, index):
+ if isinstance(value, dict) and isinstance(value["color"], list):
+ node.inputs[index].default_value = (value["color"][0], value["color"][1], value["color"][2], 1)
+ else:
+ self.links.new(value["color"], node.inputs[index])
+
+ def mix(self, settings):
+ first, second, factor = (self.compile(part) for part in settings)
+ if not isinstance(first, dict):
+ return self.math("ADD", first, self.math("MULTIPLY", self.math("SUBTRACT", second, first), factor))
+ node = self.nodes.new("ShaderNodeMixRGB")
+ node.blend_type = "MIX"
+ self.connect(node.inputs[0], factor)
+ self.color_socket(first, node, 1)
+ self.color_socket(second, node, 2)
+ return {"color": node.outputs["Color"]}
+
+
+def add_graph(material, principled, description):
+ """Builds the material from its graph, so Blender evaluates the same nodes 67.js baked into textures."""
+ translator = GraphTranslator(material)
+ graph = description["graph"]
+ links = material.node_tree.links
+ if "color" in graph:
+ links.new(translator.compile(graph["color"])["color"], principled.inputs["Base Color"])
+ for output, socket_name in (("roughness", "Roughness"), ("metallic", "Metallic")):
+ if output in graph:
+ translator.connect(principled.inputs[socket_name], translator.scalar(graph[output]))
+ if "height" in graph:
+ bump = material.node_tree.nodes.new("ShaderNodeBump")
+ bump.inputs["Distance"].default_value = GRAPH_BUMP_DISTANCE * description.get("graphBump", 1)
+ translator.connect(bump.inputs["Height"], translator.scalar(graph["height"]))
+ links.new(bump.outputs["Normal"], principled.inputs["Normal"])
+ if "emission" in graph:
+ links.new(translator.compile(graph["emission"])["color"], principled.inputs["Emission Color"])
+ principled.inputs["Emission Strength"].default_value = description.get("emission", 1)
+
+
def build_material(name, description, has_vertex_colors):
material = bpy.data.materials.new(name)
material.use_nodes = True
@@ -165,7 +333,9 @@ def build_material(name, description, has_vertex_colors):
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:
+ if "graph" in description:
+ add_graph(material, principled, description)
+ elif "map" in description:
add_texture(material, principled, description, has_vertex_colors)
elif has_vertex_colors:
add_vertex_colors(material, principled, description)
diff --git a/bench/reference/scenes.js b/bench/reference/scenes.js
index 35f9753d..26cca8c1 100644
--- a/bench/reference/scenes.js
+++ b/bench/reference/scenes.js
@@ -4,6 +4,7 @@ import { box, cylinder, sphere, torus } from '/src/geometry.js';
import { createEnvironmentMap, loadHdri } from '/src/hdri.js';
import { parseGltf } from '/src/gltf.js';
import { createTree, vegetationParts } from '/src/vegetation.js';
+import { materialPatternTextures, normalizeMaterialPattern } from '/src/material-patterns.js';
const HDRI_FILE = 'public/hdri/kloofendal_48d_partly_cloudy_puresky_1k.hdr';
const HDRI_URL = '/hdri/kloofendal_48d_partly_cloudy_puresky_1k.hdr';
@@ -48,7 +49,48 @@ function environment(lighting, { lightDirection = [-3, 6, 4], keyColor = [0, 0,
const SUN_COLOR = [3, 2.8, 2.5];
+// A wall of bricks written as a material graph: a triangle wave across each course for the mortar joints, half a brick of
+// shift on every second course, noise through a colour ramp for the brick tone. Blender gets the same graph as nodes.
+const BRICK_COLUMNS = 6;
+const BRICK_ROWS = 12;
+
+function brickGraph() {
+ const coordinate = axis => ({ uv: axis });
+ const oddCourse = { smoothstep: [0.49, 0.51, { wave: { frequency: BRICK_ROWS / 2, direction: 'v', shape: 'saw' } }] };
+ const shifted = { vec: [{ add: [coordinate('u'), { mul: [oddCourse, 0.5 / BRICK_COLUMNS] }] }, coordinate('v'), 0] };
+ const jointAcross = { smoothstep: [0.12, 0.3, { wave: { frequency: BRICK_COLUMNS, direction: 'u', shape: 'triangle', at: shifted } }] };
+ const jointAlong = { smoothstep: [0.08, 0.2, { wave: { frequency: BRICK_ROWS, direction: 'v', shape: 'triangle' } }] };
+ const body = { min: [jointAcross, jointAlong] };
+ const tone = { ramp: { value: { noise: { scale: 10, seed: 2, octaves: 3 } }, stops: [[0, [0.3, 0.09, 0.05]], [1, [0.58, 0.24, 0.14]]] } };
+ return { color: { mix: [[0.45, 0.42, 0.38], tone, body] }, height: body };
+}
+
+function wallQuad(width, height) {
+ const halfWidth = width / 2;
+ return {
+ positions: new Float32Array([-halfWidth, 0, 0, halfWidth, 0, 0, halfWidth, height, 0, -halfWidth, height, 0]),
+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
+ uvs: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),
+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
+ };
+}
+
export const REFERENCE_SCENES = {
+ async 'brick-graph'() {
+ const lighting = await skyLighting();
+ const pattern = normalizeMaterialPattern({ type: 'graph', graph: brickGraph(), mapping: 'uv', bump: 1, resolution: 512 });
+ const { map, normalMap, boxMapScale, boxMapAxis } = materialPatternTextures(pattern);
+ const wall = part('wall', wallQuad(6, 4), [0, 0, 0], [1, 1, 1], { color: [1, 1, 1], roughness: 0.85, map, normalMap, boxMapScale, boxMapAxis });
+ wall.material.graph = pattern.graph;
+ wall.material.graphBump = pattern.bump;
+ return {
+ parts: [floor([0.4, 0.38, 0.32]), wall], blenderWorld: lighting.blenderWorld,
+ environment: environment(lighting, { keyColor: SUN_COLOR }),
+ camera: { eye: [0, 2, 8.5], target: [0, 2, 0], up: [0, 1, 0], fov: 40, near: 0.1, far: 100 },
+ shadow: { eye: [-6, 10, 8], target: [0, 1, 0], up: [0, 1, 0], extent: 8, near: 0.1, far: 40 },
+ };
+ },
+
async 'material-spheres'() {
const lighting = await skyLighting();
const shared = sphere(64, 40);
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index dde83593..03675e94 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -29,13 +29,13 @@
"entry:clutter": 5300,
"entry:texture-set": 900,
"entry:agent-scene": 49200,
- "entry:agent-scene+lazy": 140600,
+ "entry:agent-scene+lazy": 141400,
"entry:agent-asset": 75600,
- "entry:agent-asset+lazy": 147700,
+ "entry:agent-asset+lazy": 148400,
"entry:hdri": 3300,
"scene:lit-box": 56000,
"scene:gltf-box": 75300,
"scene:agent-scene": 75700,
- "scene:agent-scene+lazy": 167100
+ "scene:agent-scene+lazy": 167400
}
}
diff --git a/docs/agent-scene.md b/docs/agent-scene.md
index 864b2bb2..f0c2eae0 100644
--- a/docs/agent-scene.md
+++ b/docs/agent-scene.md
@@ -119,7 +119,7 @@ Image textures and the other procedural material tags are outside this version.
| Field | Meaning |
| --- | --- |
-| `type` | `noise`, `wood`, `planks`, `bricks`, `tiles`, `marble`, `stone`, `concrete`, `metal`, `rust` or `fabric` |
+| `type` | `noise`, `wood`, `planks`, `bricks`, `tiles`, `marble`, `stone`, `concrete`, `metal`, `rust` or `fabric`, or `graph` (with `graph`) |
| `colors` | Two linear RGB colours to mix, darker first. `bricks` also takes a third, for the mortar. Each type has defaults |
| `size` | Metres per repeat of the texture, from 0.01 to 100 |
| `count` | Features per repeat, from 1 to 64: planks, bricks or tiles across, wood rings, or noise cells |
@@ -127,11 +127,12 @@ Image textures and the other procedural material tags are outside this version.
| `seed` | Nonnegative whole number. The same definition always bakes the same pixels |
| `axis` | Object axis the grain runs along: `x`, `y` (default) or `z` |
| `resolution` | Texture size: 256, 512 (default) or 1024 |
+| `mapping` | `box` (default) or `uv`: how the texture is placed. See Material graphs |
A pattern needs no UVs. The texture is projected along the object's three axes and blended by the surface normal, so it
works on every geometry type and after mesh edits. Coordinates are in metres on the object, after its node scale, so a
stretched box keeps the texture's real size and the pattern moves with the node. Corners between faces show where one
-projection meets another; `uv_unwrap` results are not used by patterns.
+projection meets another; set `mapping: "uv"` to follow `uv_unwrap` results instead (see Material graphs).
`color` defaults to white and tints the pattern. `roughness` and `metallic` scale what the pattern stores, so use
`roughness: 1` for its own surface and `metallic: 1` for `metal` and `rust` (rust stores where it is no longer metal).
@@ -141,6 +142,48 @@ share one. Each takes about 4 MiB of texture memory at 512. Measured in Node on
about 0.2 to 0.55 s per pattern, which happens when the scene first renders it. Changing a pattern rebuilds the
renderer.
+### Material graphs
+
+`pattern` with `type: "graph"` bakes your own node graph on the CPU into textures. A graph is plain JSON and never code:
+it is read against a fixed table of operators, checked against its limits before any pixel is computed, and turned into
+texture images, so no text from a recipe ever reaches the shader. The language shares the shape of the field expressions
+(one operator per object, numbers are constants, `[r, g, b]` is a constant vector).
+
+```json
+{ "id": "brick", "pattern": { "type": "graph", "mapping": "uv", "bump": 1.5, "graph": {
+ "color": { "ramp": { "value": { "noise": { "scale": 8, "seed": 3 } }, "stops": [[0, [0.15, 0.05, 0.03]], [1, [0.6, 0.25, 0.15]]] } },
+ "roughness": 0.9,
+ "height": { "noise": { "scale": 8, "seed": 3 } } } } }
+```
+
+| Graph output | Becomes |
+| --- | --- |
+| `color` | Base colour map, linear RGB (a number is grey). Without it the material `color` stands alone |
+| `roughness`, `metallic` | The metallic-roughness map. A material that has either output defaults the matching factor to 1 |
+| `emission` | The emissive map. The material `emission` defaults to 1 when the graph has it |
+| `height` | A normal map, so it gives bump. `bump` (0 to 4, default 1) scales the relief |
+
+Nodes: `uv` (`"u"`, `"v"` or `"both"`), `noise`, `voronoi` (`output`: `distance`, `edge` or `cell`, a random value per cell),
+`wave` (`sine`, `saw` or `triangle` along `u`, `v` or `diagonal`), `checker`, `gradient` (`u`, `v` or `radial`), `ramp`
+(2 to 8 stops of numbers or colours), `vec`, and the maths nodes `add`, `sub`, `mul`, `div`, `min`, `max`, `pow`, `abs`, `floor`,
+`fract`, `sqrt`, `invert`, `clamp`, `smoothstep` and `mix`. Maths nodes work on each component of a vector. Every texture
+node takes `at`, a vector expression such as `{ "add": [{ "uv": "both" }, { "mul": [{ "vec": [0.1, 0, 0] }, 1] }] }`, to warp
+it. Scales and counts are whole numbers (1 to 64, even for `checker`), so every texture node tiles.
+
+Limits, checked while the recipe is read: at most 64 nodes in all outputs, depth 12 (the field expression limits), at most 8 ramp
+stops, `resolution` of 256, 512 or 1024, and a work budget of 30 million units, where a plain node costs 1, a `noise` octave 3
+and a `voronoi` 8, per pixel and per pixel of the texture. A heavy graph at 1024 can be over it; use 512. A graph that is over a
+limit, holds an unknown operator or key, or holds any text other than the fixed names above is rejected with a message that
+names the problem. Baking the heaviest graph the budget allows took about 2 seconds in Node.
+
+#### Mapping
+
+`mapping` is `box` (default) or `uv`, and it applies to presets as well as graphs. `uv` samples the texture with the
+geometry's UVs, so a mesh with a `uv_unwrap` stack node (or `geometry.uvs`) carries it without box projection seams; the
+texture repeats outside 0 to 1 and tiles. `size` and `axis` only apply to `box`. A `uv` pattern on geometry without UVs
+fails at render and at `scene_export_glb` with a message that names `uv_unwrap`. GLB export writes the baked graph textures
+and the geometry UVs.
+
Nodes contain `id`, optional `label`, `parent`, `translation`, `rotation`, and `scale`.
Mesh nodes also require both `geometry` and `material` resource IDs.
Group nodes have neither resource reference.
diff --git a/docs/material-maps.md b/docs/material-maps.md
index db2c74e1..5b1444b5 100644
--- a/docs/material-maps.md
+++ b/docs/material-maps.md
@@ -138,6 +138,14 @@ Limits, stated plainly:
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.
+## Baked graphs and UV patterns
+
+A recipe material `pattern` of type `graph` bakes a bounded node graph into `map`, `normalMap` (from the graph's height),
+`metallicRoughnessMap` and `emissiveMap`, each only when the graph has that output. With `mapping: "uv"` the descriptors carry
+`boxMapScale: 0`, so the renderer samples every map, the emissive map included, with the geometry's UV channel 0, and GLB
+export writes the maps with the authored UVs. With the default `box` mapping the maps are projected along the object axes.
+The graph never becomes shader source: the shader gains no code per graph. See "Material graphs" in agent-scene.md.
+
## Limits
Texture transforms, UV channels beyond zero, and vertex alpha below one remain unsupported.
diff --git a/docs/parity.md b/docs/parity.md
index 2f59451f..d2efb643 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -197,13 +197,13 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| 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 |
| Rendering > Materials > Line Art | missing | No line rendering. | | |
| 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 > 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 > 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 |
-| Rendering > Shader Nodes > Utilities | missing | No node graph. | | #50 |
+| 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 |
+| Rendering > Shader Nodes > Utilities | partial | Maths on numbers and vectors: add, sub, mul, div, min, max, pow, abs, floor, fract, sqrt, clamp and smoothstep. There is no vector maths, mapping, map range or separate and combine nodes. | [material-graph](../tests/material-graph.test.js) | #50 |
| Rendering > Shader Nodes > Group | missing | No node graph. | | #50 |
| Rendering > Color Management | partial | ACES tone mapping and grading. There is no choice of color space or display. | [effects](../tests/effects.test.js) | |
| Rendering > Freestyle | missing | No line rendering. | | |
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 160af612..d7df9e9f 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -5,7 +5,7 @@ import { setPriority, constants } from 'node:os';
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_PATTERN_TYPES, MATERIAL_MAPPINGS, MATERIAL_GRAPH_OUTPUTS, MATERIAL_GRAPH_OPERATORS, MATERIAL_GRAPH_LIMITS } 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);
@@ -40,8 +40,12 @@ const instanceSpec = z.strictObject({
scale: z.tuple([z.number().min(0.001).max(1000), z.number().min(0.001).max(1000)]).optional().describe('Random uniform scale range [min, max].'),
}).describe('Exactly one of grid, scatter or surface. Expands at scene_create into a group node plus one child node per point (<id>.0, <id>.1, ...) that share geometry and material and draw as one instanced batch. At most 2048 candidate points.');
const nodeRecord = z.strictObject({ id: identifier, geometry: identifier.optional(), material: identifier.optional(), instances: instanceSpec.optional().describe('Repeat geometry and material at points; needs both ids. Only in the recipe given to scene_create, not in add-node.'), ...nodeFields });
+const graphNode = z.union([finite, vector3, z.record(z.string(), z.unknown())]);
+const materialGraph = z.strictObject(Object.fromEntries(MATERIAL_GRAPH_OUTPUTS.map(output => [output, graphNode.optional()]))).describe(`Node graph, plain JSON and never code or shader text, baked on the CPU into textures. One or more outputs: color (linear RGB; a number is grey), roughness, metallic, emission (colour; needs no emission field, it defaults to 1), height (becomes a normal map: bump gives relief). A node is a number, [x,y,z] or an object with one operator: ${MATERIAL_GRAPH_OPERATORS.join(' ')}. Textures: {"noise":{"scale":8,"seed":1,"octaves":4}}, {"voronoi":{"scale":6,"output":"distance"|"edge"|"cell"}}, {"wave":{"frequency":4,"direction":"u"|"v"|"diagonal","shape":"sine"|"saw"|"triangle"}}, {"checker":{"count":8}}, {"gradient":{"type":"u"|"v"|"radial"}}; each takes "at" (a vector such as {"uv":"both"}) to warp it, scales are whole numbers 1 to 64 so it tiles. {"uv":"u"|"v"|"both"} are the coordinates. {"ramp":{"value":node,"stops":[[0,[r,g,b]],[1,[r,g,b]]]}} maps a number to colours (2 to ${MATERIAL_GRAPH_LIMITS.maxStops} stops). Maths: add sub mul div min max pow take [a,b]; abs floor fract sqrt invert take one node; clamp smoothstep mix take [a,b,c]; {"vec":[r,g,b]}. Numbers combine with vectors per component. At most ${MATERIAL_GRAPH_LIMITS.maxNodes} nodes, depth ${MATERIAL_GRAPH_LIMITS.maxDepth}, and a work limit that wants a smaller resolution for a big graph. Example: {"color":{"ramp":{"value":{"noise":{"scale":8}},"stops":[[0,[0.1,0.05,0.02]],[1,[0.6,0.4,0.2]]]}},"height":{"noise":{"scale":8}}}`);
const materialPattern = z.strictObject({
- type: z.enum(MATERIAL_PATTERN_TYPES).describe('Surface look. Directional types (wood, planks, metal) run along axis.'),
+ type: z.enum([...MATERIAL_PATTERN_TYPES, 'graph']).describe('Surface look: a preset, or graph for your own node graph (give graph). Directional presets (wood, planks, metal) run along axis.'),
+ graph: materialGraph.optional().describe('Only with type graph.'),
+ mapping: z.enum(MATERIAL_MAPPINGS).optional().describe('box (default) projects along the object axes and needs no UVs; uv follows the geometry UVs, so the mesh needs a uv_unwrap node or geometry.uvs. size and axis only apply to box.'),
colors: z.array(color).min(2).max(3).optional().describe('Linear RGB colours to mix, darker first. Bricks take a third for the mortar. Each type has good defaults.'),
size: z.number().min(0.01).max(100).optional().describe('Metres per repeat of the texture, so it keeps its real size on any object and node scale.'),
count: z.number().int().min(1).max(64).optional().describe('Features per repeat: planks, bricks across, tiles across, wood rings or noise cells.'),
@@ -49,7 +53,7 @@ const materialPattern = z.strictObject({
seed: z.number().int().min(0).max(2147483647).optional(),
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.');
+}).describe('Procedural texture baked for this material. By default it needs no UVs and is projected along the object axes; mapping uv follows the geometry UVs instead. 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()
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 7c9f611c..68bdb11b 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -37,7 +37,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- A rigid accessory on a morphing or skinned surface uses optional `src/surface-attachment.js` and `docs/surface-attachment.md`.
- 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`.
+- 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`.
- 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. See "Inverse kinematics", "Constraints" and "Drivers" in the checkout's `docs/agent-motion.md`.
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 70fba010..438df36f 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -14,6 +14,15 @@ export const AGENT_SCENE_DEFAULT_LIMITS = Object.freeze({
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.
+export const MATERIAL_GRAPH_OUTPUTS = Object.freeze(['color', 'roughness', 'metallic', 'emission', 'height']);
+export const MATERIAL_GRAPH_OPERATORS = Object.freeze([
+ 'uv', 'vec', 'ramp', 'noise', 'voronoi', 'wave', 'checker', 'gradient',
+ 'add', 'sub', 'mul', 'div', 'min', 'max', 'pow', 'abs', 'floor', 'fract', 'sqrt', 'invert', 'clamp', 'smoothstep', 'mix',
+]);
+export const MATERIAL_GRAPH_LIMITS = Object.freeze({ maxNodes: MAX_FIELD_NODES, maxDepth: MAX_FIELD_DEPTH, maxStops: 8, maxWork: 30_000_000 });
+export const MATERIAL_MAPPINGS = Object.freeze(['box', 'uv']);
// Recipe textures are opaque patterns, so cutout masking has nothing to cut.
export const RECIPE_ALPHA_MODES = Object.freeze(['opaque', 'blend']);
@@ -36,6 +45,8 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam']),
alphaModes: RECIPE_ALPHA_MODES,
materialPatterns: MATERIAL_PATTERN_TYPES, maxMaterialPatterns: MAX_MATERIAL_PATTERNS,
+ materialMappings: MATERIAL_MAPPINGS,
+ materialGraph: Object.freeze({ outputs: MATERIAL_GRAPH_OUTPUTS, operators: MATERIAL_GRAPH_OPERATORS, ...MATERIAL_GRAPH_LIMITS }),
fixedResources: false, dynamicTopology: true, checkpoints: true, positiveScaleOnly: true,
authoredLook: true, maxPointLights: 8,
// Local lights: spot and rectangular area lights. Shadows share one 2048 x 3072 depth atlas of 24 tiles; a shadowed
diff --git a/src/agent-scene.js b/src/agent-scene.js
index f375a039..72e7a9bf 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -19,7 +19,7 @@ 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', ...MATERIAL_LAYER_FIELDS];
-const PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'boxMapScale', 'boxMapAxis'];
+const PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'emissiveMap', 'boxMapScale', 'boxMapAxis'];
const CAMERA_FIELDS = Object.keys(CAMERA_DEFAULTS);
const LOOK_OPERATION_FIELDS = Object.freeze({
'set-environment': 'environment',
@@ -193,8 +193,11 @@ 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.
const defaultColor = value.pattern === undefined ? [0.5, 0.5, 0.5] : [1, 1, 1];
+ const graph = value.pattern?.type === 'graph' ? value.pattern.graph : {};
+ // A graph that makes roughness, metallic or emission passes it through as written, so the factors default to 1.
+ const graphFactor = (output, fallback) => (Object.hasOwn(graph ?? {}, output) ? 1 : fallback);
const result = { id: value.id, tag: defaultValue(value.tag, 'surface'), color: vector(defaultValue(value.color, defaultColor), 3, 'color'),
- metallic: defaultValue(value.metallic, 0), roughness: defaultValue(value.roughness, 0.5), emission: defaultValue(value.emission, 0) };
+ metallic: defaultValue(value.metallic, graphFactor('metallic', 0)), roughness: defaultValue(value.roughness, graphFactor('roughness', 0.5)), emission: defaultValue(value.emission, graphFactor('emission', 0)) };
if (!AGENT_SCENE_CAPABILITIES.materialTags.includes(result.tag)) {
throw new RangeError(`Material tag must be one of ${AGENT_SCENE_CAPABILITIES.materialTags.join(', ')}.`);
}
diff --git a/src/material-graph.js b/src/material-graph.js
new file mode 100644
index 00000000..11a7290f
--- /dev/null
+++ b/src/material-graph.js
@@ -0,0 +1,366 @@
+import { MATERIAL_GRAPH_LIMITS, MATERIAL_GRAPH_OUTPUTS, MATERIAL_GRAPH_OPERATORS } from './agent-scene-capabilities.js';
+import { clampUnit, smoothStep, fractalNoise, cellularNoise, linearToSrgbByte, createImage, normalMapFromHeights } from './material-texture-kit.js';
+
+// A bounded material node graph. Like a field expression (src/mesh-fields.js), a graph is data and never code: it is
+// walked as plain objects against a fixed table of operators, checked against its limits before any pixel is
+// evaluated, and baked on the CPU into textures. Nothing here builds shader source, and the only strings accepted are
+// the fixed names listed below, so agent input can not reach the GPU as text. Issue 98 will merge this with the field
+// language; the shape (one operator per object, numbers are constants, [r, g, b] is a constant vector) already matches.
+//
+// { "color": { "ramp": { "value": { "noise": { "scale": 8 } }, "stops": [[0, [0.1, 0.05, 0.02]], [1, [0.6, 0.4, 0.2]]] } },
+// "height": { "noise": { "scale": 8 } } }
+//
+// Every texture node is periodic over the unit square, so a baked graph tiles. Values are numbers or vectors of three.
+
+const MAX_LITERAL = 1e6;
+const MAX_SEED = 0x7fffffff;
+const MAX_REPORTED_KEY_LENGTH = 24;
+const NOISE_SCALE_LIMIT = 64;
+const NOISE_OCTAVE_LIMIT = 6;
+// Work units per pixel for the nodes that cost more than a plain operator.
+const VORONOI_COST = 8;
+const NOISE_COST_PER_OCTAVE = 3;
+
+function graphError(message) {
+ return new TypeError(`Material graph: ${message}`);
+}
+
+function describeKey(key) {
+ const clipped = key.length > MAX_REPORTED_KEY_LENGTH ? `${key.slice(0, MAX_REPORTED_KEY_LENGTH)}...` : key;
+ return JSON.stringify(clipped);
+}
+
+function isPlainObject(value) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const prototype = Object.getPrototypeOf(value);
+ return prototype === Object.prototype || prototype === null;
+}
+
+function onlyKeys(node, allowed, label) {
+ for (const key of Object.keys(node)) {
+ if (!allowed.includes(key)) throw graphError(`${label} does not take ${describeKey(key)}; fields: ${allowed.join(', ')}.`);
+ }
+}
+
+function integerInRange(value, minimum, maximum, label) {
+ if (!Number.isInteger(value) || value < minimum || value > maximum) throw graphError(`${label} must be a whole number from ${minimum} to ${maximum}.`);
+ return value;
+}
+
+function oneOf(value, names, label) {
+ if (typeof value !== 'string' || !names.includes(value)) throw graphError(`${label} must be one of ${names.join(', ')}.`);
+ return value;
+}
+
+function finiteLiteral(value) {
+ return typeof value === 'number' && Number.isFinite(value) && Math.abs(value) <= MAX_LITERAL;
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// Compiled values take the pixel position: { kind: 'scalar', evaluate(u, v) } or { kind: 'vector', parts: [x, y, z] }.
+
+const scalarValue = evaluate => ({ kind: 'scalar', evaluate });
+const vectorValue = (partX, partY, partZ) => ({ kind: 'vector', parts: [partX, partY, partZ] });
+const partsOf = value => (value.kind === 'vector' ? value.parts : [value.evaluate, value.evaluate, value.evaluate]);
+
+function liftComponentwise(values, compute) {
+ if (values.every(value => value.kind === 'scalar')) {
+ const [first, second, third] = values.map(value => value.evaluate);
+ return scalarValue((u, v) => compute(first(u, v), second?.(u, v), third?.(u, v)));
+ }
+ const [first, second, third] = values.map(partsOf);
+ const channel = index => (u, v) => compute(first[index](u, v), second?.[index](u, v), third?.[index](u, v));
+ return vectorValue(channel(0), channel(1), channel(2));
+}
+
+const finiteOrZero = value => (Number.isFinite(value) ? value : 0);
+const fract = value => value - Math.floor(value);
+const mixNumbers = (start, end, factor) => start + (end - start) * factor;
+
+// name: [argument count, compute(first, second, third)]
+const MATH_OPERATORS = new Map([
+ ['add', [2, (a, b) => a + b]],
+ ['sub', [2, (a, b) => a - b]],
+ ['mul', [2, (a, b) => a * b]],
+ ['div', [2, (a, b) => (b === 0 ? 0 : a / b)]],
+ ['min', [2, (a, b) => Math.min(a, b)]],
+ ['max', [2, (a, b) => Math.max(a, b)]],
+ ['pow', [2, (a, b) => Math.abs(a) ** Math.min(Math.max(b, -16), 16)]],
+ ['abs', [1, Math.abs]],
+ ['floor', [1, Math.floor]],
+ ['fract', [1, fract]],
+ ['sqrt', [1, value => Math.sqrt(Math.max(value, 0))]],
+ ['invert', [1, value => 1 - value]],
+ ['clamp', [3, (value, low, high) => Math.min(Math.max(value, low), Math.max(low, high))]],
+ ['smoothstep', [3, (low, high, value) => (low === high ? (value < low ? 0 : 1) : smoothStep(low, high, value))]],
+ ['mix', [3, mixNumbers]],
+]);
+
+// ---------------------------------------------------------------------------------------------------------------
+// Compiling. The state counts nodes, the work each costs per pixel and the deepest nesting.
+
+function compileCoordinates(node) {
+ const axis = oneOf(node.uv, ['u', 'v', 'both'], 'uv');
+ if (Object.keys(node).length !== 1) throw graphError('uv takes no other fields.');
+ if (axis === 'u') return scalarValue(u => u);
+ if (axis === 'v') return scalarValue((u, v) => v);
+ return vectorValue(u => u, (u, v) => v, () => 0);
+}
+
+function compilePosition(settings, state, depth) {
+ if (settings.at === undefined) return [u => u, (u, v) => v];
+ const position = compileNode(settings.at, state, depth + 1);
+ if (position.kind !== 'vector') throw graphError('"at" needs a vector such as {"uv":"both"}.');
+ return position.parts;
+}
+
+function textureSettings(node, name, allowed) {
+ const settings = node[name];
+ if (!isPlainObject(settings) || Object.keys(node).length !== 1) throw graphError(`${name} takes { ${allowed.join(', ')} } and nothing else.`);
+ onlyKeys(settings, allowed, name);
+ return settings;
+}
+
+function compileNoise(node, state, depth) {
+ const settings = textureSettings(node, 'noise', ['scale', 'seed', 'octaves', 'at']);
+ const scale = integerInRange(settings.scale ?? 4, 1, NOISE_SCALE_LIMIT, 'noise scale');
+ const seed = integerInRange(settings.seed ?? 0, 0, MAX_SEED, 'noise seed');
+ const octaves = integerInRange(settings.octaves ?? 4, 1, NOISE_OCTAVE_LIMIT, 'noise octaves');
+ state.cost += octaves * NOISE_COST_PER_OCTAVE;
+ const [positionU, positionV] = compilePosition(settings, state, depth);
+ return scalarValue((u, v) => fractalNoise(positionU(u, v), positionV(u, v), scale, scale, seed, octaves) * 0.5 + 0.5);
+}
+
+const VORONOI_OUTPUTS = ['distance', 'edge', 'cell'];
+
+function compileVoronoi(node, state, depth) {
+ const settings = textureSettings(node, 'voronoi', ['scale', 'seed', 'output', 'at']);
+ const scale = integerInRange(settings.scale ?? 4, 1, NOISE_SCALE_LIMIT, 'voronoi scale');
+ const seed = integerInRange(settings.seed ?? 0, 0, MAX_SEED, 'voronoi seed');
+ const output = oneOf(settings.output ?? 'distance', VORONOI_OUTPUTS, 'voronoi output');
+ state.cost += VORONOI_COST;
+ const [positionU, positionV] = compilePosition(settings, state, depth);
+ return scalarValue((u, v) => {
+ const { nearest, second, cell } = cellularNoise(positionU(u, v), positionV(u, v), scale, seed);
+ if (output === 'cell') return cell / 4294967296;
+ return clampUnit(output === 'edge' ? second - nearest : nearest);
+ });
+}
+
+const WAVE_DIRECTIONS = ['u', 'v', 'diagonal'];
+const WAVE_SHAPES = ['sine', 'saw', 'triangle'];
+
+function compileWave(node, state, depth) {
+ const settings = textureSettings(node, 'wave', ['frequency', 'direction', 'shape', 'at']);
+ const frequency = integerInRange(settings.frequency ?? 4, 1, NOISE_SCALE_LIMIT, 'wave frequency');
+ const direction = oneOf(settings.direction ?? 'u', WAVE_DIRECTIONS, 'wave direction');
+ const shape = oneOf(settings.shape ?? 'sine', WAVE_SHAPES, 'wave shape');
+ const [positionU, positionV] = compilePosition(settings, state, depth);
+ return scalarValue((u, v) => {
+ const along = direction === 'u' ? positionU(u, v) : direction === 'v' ? positionV(u, v) : positionU(u, v) + positionV(u, v);
+ const phase = along * frequency;
+ if (shape === 'sine') return Math.sin(phase * Math.PI * 2) * 0.5 + 0.5;
+ return shape === 'saw' ? fract(phase) : 1 - Math.abs(fract(phase) * 2 - 1);
+ });
+}
+
+function compileChecker(node, state, depth) {
+ const settings = textureSettings(node, 'checker', ['count', 'at']);
+ const count = integerInRange(settings.count ?? 8, 2, NOISE_SCALE_LIMIT, 'checker count');
+ // An odd count would flip the pattern across the tiling seam.
+ if (count % 2 !== 0) throw graphError('checker count must be even so it tiles.');
+ const [positionU, positionV] = compilePosition(settings, state, depth);
+ return scalarValue((u, v) => (Math.floor(positionU(u, v) * count) + Math.floor(positionV(u, v) * count)) % 2 === 0 ? 0 : 1);
+}
+
+const GRADIENT_TYPES = ['u', 'v', 'radial'];
+
+function compileGradient(node, state, depth) {
+ const settings = textureSettings(node, 'gradient', ['type', 'at']);
+ const type = oneOf(settings.type ?? 'u', GRADIENT_TYPES, 'gradient type');
+ const [positionU, positionV] = compilePosition(settings, state, depth);
+ return scalarValue((u, v) => {
+ if (type === 'u') return clampUnit(positionU(u, v));
+ if (type === 'v') return clampUnit(positionV(u, v));
+ return clampUnit(1 - Math.hypot(positionU(u, v) - 0.5, positionV(u, v) - 0.5) * 2);
+ });
+}
+
+function checkedStop(stop, index, previousPosition) {
+ if (!Array.isArray(stop) || stop.length !== 2) throw graphError(`ramp stop ${index} must be [position, value].`);
+ const [position, value] = stop;
+ if (typeof position !== 'number' || !Number.isFinite(position) || position < 0 || position > 1 || position <= previousPosition) {
+ throw graphError('ramp stop positions must rise strictly from 0 to 1.');
+ }
+ const isVector = Array.isArray(value);
+ if (isVector ? value.length !== 3 || !value.every(finiteLiteral) : !finiteLiteral(value)) {
+ throw graphError(`ramp stop ${index} value must be a number or [r, g, b] of finite numbers.`);
+ }
+ return { position, value, isVector };
+}
+
+function compileRamp(node, state, depth) {
+ const settings = textureSettings(node, 'ramp', ['value', 'stops']);
+ const { stops: rawStops } = settings;
+ if (!Array.isArray(rawStops) || rawStops.length < 2 || rawStops.length > MATERIAL_GRAPH_LIMITS.maxStops) {
+ throw graphError(`ramp needs 2 to ${MATERIAL_GRAPH_LIMITS.maxStops} stops.`);
+ }
+ let previousPosition = -1;
+ const stops = rawStops.map((stop, index) => {
+ const checked = checkedStop(stop, index, previousPosition);
+ previousPosition = checked.position;
+ return checked;
+ });
+ if (!stops.every(stop => stop.isVector === stops[0].isVector)) throw graphError('ramp stops are all numbers or all [r, g, b].');
+ const input = compileNode(settings.value, state, depth + 1);
+ if (input.kind !== 'scalar') throw graphError('ramp "value" needs a number.');
+ const channelRamp = channel => (u, v) => {
+ const position = clampUnit(input.evaluate(u, v));
+ const valueOf = stop => (stop.isVector ? stop.value[channel] : stop.value);
+ if (position <= stops[0].position) return valueOf(stops[0]);
+ for (let index = 1; index < stops.length; index++) {
+ if (position <= stops[index].position) {
+ const from = stops[index - 1];
+ const to = stops[index];
+ return mixNumbers(valueOf(from), valueOf(to), (position - from.position) / (to.position - from.position));
+ }
+ }
+ return valueOf(stops[stops.length - 1]);
+ };
+ state.cost += 2;
+ return stops[0].isVector ? vectorValue(channelRamp(0), channelRamp(1), channelRamp(2)) : scalarValue(channelRamp(0));
+}
+
+function compileVector(node, state, depth) {
+ if (!Array.isArray(node.vec) || node.vec.length !== 3 || Object.keys(node).length !== 1) throw graphError('vec needs [x, y, z] in an array.');
+ const [partX, partY, partZ] = node.vec.map(part => {
+ const compiled = compileNode(part, state, depth + 1);
+ if (compiled.kind !== 'scalar') throw graphError('vec parts must be numbers.');
+ return compiled.evaluate;
+ });
+ return vectorValue(partX, partY, partZ);
+}
+
+function compileMath(name, node, state, depth) {
+ const [argumentCount, compute] = MATH_OPERATORS.get(name);
+ const operands = argumentCount === 1 && !Array.isArray(node[name]) ? [node[name]] : node[name];
+ if (!Array.isArray(operands) || operands.length !== argumentCount) throw graphError(`${name} needs ${argumentCount} argument${argumentCount === 1 ? '' : 's'}.`);
+ return liftComponentwise(operands.map(operand => compileNode(operand, state, depth + 1)), compute);
+}
+
+const TEXTURE_COMPILERS = new Map([
+ ['noise', compileNoise], ['voronoi', compileVoronoi], ['wave', compileWave], ['checker', compileChecker], ['gradient', compileGradient],
+]);
+
+function compileNode(node, state, depth) {
+ state.nodeCount++;
+ state.cost++;
+ if (state.nodeCount > MATERIAL_GRAPH_LIMITS.maxNodes) throw graphError(`more than ${MATERIAL_GRAPH_LIMITS.maxNodes} nodes.`);
+ if (depth > MATERIAL_GRAPH_LIMITS.maxDepth) throw graphError(`nesting deeper than ${MATERIAL_GRAPH_LIMITS.maxDepth}.`);
+ if (typeof node === 'number') {
+ if (!finiteLiteral(node)) throw graphError(`numbers must be finite and within ${MAX_LITERAL}.`);
+ return scalarValue(() => node);
+ }
+ if (Array.isArray(node)) {
+ if (node.length !== 3 || !node.every(finiteLiteral)) throw graphError('a vector literal is three finite numbers; build one from expressions with "vec".');
+ const [literalX, literalY, literalZ] = node;
+ return vectorValue(() => literalX, () => literalY, () => literalZ);
+ }
+ if (!isPlainObject(node)) throw graphError('each node is a number, a vector of three numbers or an object with one operator.');
+ const keys = Object.keys(node);
+ if (keys.length !== 1) throw graphError(`a node holds exactly one operator; got ${keys.length}.`);
+ const name = keys[0];
+ if (name === 'uv') return compileCoordinates(node);
+ if (name === 'vec') return compileVector(node, state, depth);
+ if (name === 'ramp') return compileRamp(node, state, depth);
+ if (TEXTURE_COMPILERS.has(name)) return TEXTURE_COMPILERS.get(name)(node, state, depth);
+ if (MATH_OPERATORS.has(name)) return compileMath(name, node, state, depth);
+ throw graphError(`unknown operator ${describeKey(name)}. Use one of ${MATERIAL_GRAPH_OPERATORS.join(', ')}.`);
+}
+
+const SCALAR_OUTPUTS = ['roughness', 'metallic', 'height'];
+
+/**
+ * Check a graph and compile each output. Limits on nodes, depth and work per pixel are enforced here, before any
+ * pixel is evaluated. Returns { outputs: { name: compiled }, nodeCount, cost }.
+ */
+export function compileMaterialGraph(graph) {
+ if (!isPlainObject(graph)) throw graphError(`graph must be an object with outputs: ${MATERIAL_GRAPH_OUTPUTS.join(', ')}.`);
+ onlyKeys(graph, MATERIAL_GRAPH_OUTPUTS, 'graph');
+ const names = Object.keys(graph);
+ if (names.length === 0) throw graphError(`graph needs at least one output: ${MATERIAL_GRAPH_OUTPUTS.join(', ')}.`);
+ const state = { nodeCount: 0, cost: 0 };
+ const outputs = {};
+ for (const name of names) {
+ outputs[name] = compileNode(graph[name], state, 0);
+ if (SCALAR_OUTPUTS.includes(name) && outputs[name].kind !== 'scalar') throw graphError(`${name} needs a number, not a vector.`);
+ }
+ return { outputs, nodeCount: state.nodeCount, cost: state.cost };
+}
+
+/** Throw when a graph is too costly to bake at this size. Called while normalizing, so a bad scene fails at once. */
+export function checkMaterialGraphWork(compiled, resolution) {
+ const work = compiled.cost * resolution * resolution;
+ if (work > MATERIAL_GRAPH_LIMITS.maxWork) {
+ throw new RangeError(`Material graph: ${compiled.cost} work units per pixel at ${resolution} by ${resolution} is over the limit of ${MATERIAL_GRAPH_LIMITS.maxWork}. Use fewer nodes or a smaller resolution.`);
+ }
+}
+
+/** Validate a graph and return a plain copy of it. A normalized graph normalizes to itself. */
+export function normalizeMaterialGraph(graph, resolution) {
+ const compiled = compileMaterialGraph(graph);
+ checkMaterialGraphWork(compiled, resolution);
+ return JSON.parse(JSON.stringify(graph));
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// Baking. Colours are linear RGB, as recipe colours are.
+
+function sampleChannels(compiled, u, v) {
+ if (compiled.kind === 'scalar') {
+ const value = finiteOrZero(compiled.evaluate(u, v));
+ return [value, value, value];
+ }
+ return [finiteOrZero(compiled.parts[0](u, v)), finiteOrZero(compiled.parts[1](u, v)), finiteOrZero(compiled.parts[2](u, v))];
+}
+
+function writeColor(data, offset, channels) {
+ for (let channel = 0; channel < 3; channel++) data[offset + channel] = linearToSrgbByte(channels[channel]);
+ data[offset + 3] = 255;
+}
+
+/** Bake a normalized graph into texture descriptors, one for each output the graph has. Deterministic. */
+export function bakeMaterialGraph(graph, { resolution, bump }) {
+ const compiled = compileMaterialGraph(graph);
+ checkMaterialGraphWork(compiled, resolution);
+ const { color, roughness, metallic, emission, height } = compiled.outputs;
+ const pixelCount = resolution * resolution;
+ const colorData = color ? new Uint8ClampedArray(pixelCount * 4) : null;
+ const emissionData = emission ? new Uint8ClampedArray(pixelCount * 4) : null;
+ const surfaceData = roughness || metallic ? new Uint8ClampedArray(pixelCount * 4) : null;
+ const heights = height ? new Float32Array(pixelCount) : null;
+ for (let row = 0; row < resolution; row++) {
+ for (let column = 0; column < resolution; column++) {
+ const pixel = row * resolution + column;
+ const u = (column + 0.5) / resolution;
+ const v = (row + 0.5) / resolution;
+ const offset = pixel * 4;
+ if (color) writeColor(colorData, offset, sampleChannels(color, u, v));
+ if (emission) writeColor(emissionData, offset, sampleChannels(emission, u, v));
+ if (heights) heights[pixel] = finiteOrZero(height.evaluate(u, v));
+ if (surfaceData) {
+ surfaceData[offset] = 255;
+ surfaceData[offset + 1] = roughness ? Math.round(clampUnit(finiteOrZero(roughness.evaluate(u, v))) * 255) : 255;
+ surfaceData[offset + 2] = metallic ? Math.round(clampUnit(finiteOrZero(metallic.evaluate(u, v))) * 255) : 255;
+ surfaceData[offset + 3] = 255;
+ }
+ }
+ }
+ const descriptor = (data, colorSpace) => (data ? { image: createImage(data, resolution, resolution), colorSpace } : undefined);
+ return {
+ map: descriptor(colorData, 'srgb'),
+ emissiveMap: descriptor(emissionData, 'srgb'),
+ metallicRoughnessMap: descriptor(surfaceData, 'linear'),
+ normalMap: descriptor(heights ? normalMapFromHeights(heights, resolution, bump) : null, 'linear'),
+ };
+}
diff --git a/src/material-patterns.js b/src/material-patterns.js
index f1f8259b..b0507cdc 100644
--- a/src/material-patterns.js
+++ b/src/material-patterns.js
@@ -1,103 +1,13 @@
-import { MATERIAL_PATTERN_TYPES } from './agent-scene-capabilities.js';
+import { MATERIAL_PATTERN_TYPES, MATERIAL_MAPPINGS } from './agent-scene-capabilities.js';
+import { bakeMaterialGraph, normalizeMaterialGraph } from './material-graph.js';
// Procedural surface patterns for recipe materials: seeded, tileable and baked on the CPU into the same texture
// descriptors a loaded material uses. Texture coordinates run 0 to 1 and every noise is periodic over that square, so
// a pattern repeats without a visible seam. Directional patterns (wood, planks, brushed metal) run along V.
-function hashCell(cellX, cellY, seed) {
- let hash = Math.imul(cellX, 0x27d4eb2d) ^ Math.imul(cellY, 0x165667b1) ^ Math.imul(seed, 0x9e3779b1);
- hash = Math.imul(hash ^ (hash >>> 15), 0x85ebca6b);
- hash = Math.imul(hash ^ (hash >>> 13), 0xc2b2ae35);
- return (hash ^ (hash >>> 16)) >>> 0;
-}
-
-const wrapCell = (cell, period) => ((cell % period) + period) % period;
-const smootherStep = value => value * value * value * (value * (value * 6 - 15) + 10);
-const clampUnit = value => Math.min(1, Math.max(0, value));
-const smoothStep = (minimum, maximum, value) => {
- const position = clampUnit((value - minimum) / (maximum - minimum));
- return position * position * (3 - 2 * position);
-};
-
-function cornerGradient(cellX, cellY, offsetX, offsetY, seed) {
- const angle = hashCell(cellX, cellY, seed) / 4294967296 * Math.PI * 2;
- return Math.cos(angle) * offsetX + Math.sin(angle) * offsetY;
-}
+import { hashCell, wrapCell, smoothStep, clampUnit, linearToSrgbByte, createImage, normalMapFromHeights, gradientNoise, fractalNoise, ridgedNoise, cellularNoise } from './material-texture-kit.js';
+export { gradientNoise, fractalNoise, ridgedNoise, cellularNoise };
-/** Gradient noise in about -1 to 1, periodic over [0, 1) with the given whole number of cells per axis. */
-export function gradientNoise(positionU, positionV, cellsU, cellsV, seed = 0) {
- const scaledU = positionU * cellsU;
- const scaledV = positionV * cellsV;
- const floorU = Math.floor(scaledU);
- const floorV = Math.floor(scaledV);
- const fractionU = scaledU - floorU;
- const fractionV = scaledV - floorV;
- const left = wrapCell(floorU, cellsU);
- const right = wrapCell(floorU + 1, cellsU);
- const bottom = wrapCell(floorV, cellsV);
- const top = wrapCell(floorV + 1, cellsV);
- const blendU = smootherStep(fractionU);
- const blendV = smootherStep(fractionV);
- const lower = cornerGradient(left, bottom, fractionU, fractionV, seed) * (1 - blendU)
- + cornerGradient(right, bottom, fractionU - 1, fractionV, seed) * blendU;
- const upper = cornerGradient(left, top, fractionU, fractionV - 1, seed) * (1 - blendU)
- + cornerGradient(right, top, fractionU - 1, fractionV - 1, seed) * blendU;
- return (lower * (1 - blendV) + upper * blendV) * 1.5;
-}
-
-/** Fractal sum of gradientNoise in about -1 to 1. Each octave doubles the cells, so it stays periodic. */
-export function fractalNoise(positionU, positionV, cellsU, cellsV, seed = 0, octaves = 5, gain = 0.5) {
- let total = 0;
- let amplitude = 1;
- let amplitudeSum = 0;
- for (let octave = 0; octave < octaves; octave++) {
- total += gradientNoise(positionU, positionV, cellsU << octave, cellsV << octave, seed + octave * 131) * amplitude;
- amplitudeSum += amplitude;
- amplitude *= gain;
- }
- return total / amplitudeSum;
-}
-
-/** Ridged fractal noise in 0 to 1: sharp crests where the gradient noise crosses zero. */
-export function ridgedNoise(positionU, positionV, cellsU, cellsV, seed = 0, octaves = 4) {
- let total = 0;
- let amplitude = 1;
- let amplitudeSum = 0;
- for (let octave = 0; octave < octaves; octave++) {
- const ridge = 1 - Math.abs(gradientNoise(positionU, positionV, cellsU << octave, cellsV << octave, seed + octave * 211));
- total += ridge * ridge * amplitude;
- amplitudeSum += amplitude;
- amplitude *= 0.5;
- }
- return total / amplitudeSum;
-}
-
-/** Periodic Worley noise: distances to the nearest and second nearest feature point, in cell units. */
-export function cellularNoise(positionU, positionV, cells, seed = 0) {
- const scaledU = positionU * cells;
- const scaledV = positionV * cells;
- const floorU = Math.floor(scaledU);
- const floorV = Math.floor(scaledV);
- let nearest = Infinity;
- let second = Infinity;
- for (let offsetV = -1; offsetV <= 1; offsetV++) {
- for (let offsetU = -1; offsetU <= 1; offsetU++) {
- const cellU = floorU + offsetU;
- const cellV = floorV + offsetV;
- const hash = hashCell(wrapCell(cellU, cells), wrapCell(cellV, cells), seed);
- const pointU = cellU + (hash & 0xffff) / 65536;
- const pointV = cellV + (hash >>> 16) / 65536;
- const distance = Math.hypot(pointU - scaledU, pointV - scaledV);
- if (distance < nearest) {
- second = nearest;
- nearest = distance;
- } else if (distance < second) {
- second = distance;
- }
- }
- }
- return { nearest, second };
-}
function unitHash(cellX, cellY, seed) {
return hashCell(cellX, cellY, seed) / 4294967296;
@@ -231,6 +141,10 @@ const PATTERN_DEFAULTS = {
const RESOLUTIONS = [256, 512, 1024];
const MAX_COUNT = 64;
+const GRAPH_TYPE = 'graph';
+const GRAPH_DEFAULTS = { size: 1, bump: 1 };
+const GRAPH_ONLY_FIELDS = ['colors', 'count', 'seed'];
+
function patternError(message) {
return new RangeError(`Material pattern ${message}`);
}
@@ -250,13 +164,38 @@ function checkedNumber(value, name, minimum, maximum) {
return value;
}
+function normalizeGraphPattern(value, mappingField) {
+ for (const field of GRAPH_ONLY_FIELDS) {
+ if (value[field] !== undefined) throw patternError(`of type graph does not take ${field}: the graph holds the colours and the noise seeds.`);
+ }
+ const axis = value.axis ?? 'y';
+ if (!['x', 'y', 'z'].includes(axis)) throw patternError('axis must be x, y or z: the object axis the texture V runs along.');
+ const resolution = value.resolution ?? 512;
+ if (!RESOLUTIONS.includes(resolution)) throw patternError(`resolution must be one of ${RESOLUTIONS.join(', ')}.`);
+ return {
+ type: GRAPH_TYPE,
+ graph: normalizeMaterialGraph(value.graph, resolution),
+ size: checkedNumber(value.size ?? GRAPH_DEFAULTS.size, 'size', 0.01, 100),
+ bump: checkedNumber(value.bump ?? GRAPH_DEFAULTS.bump, 'bump', 0, 4),
+ axis,
+ resolution,
+ ...mappingField,
+ };
+}
+
/** Validate a recipe pattern and fill in its defaults. A normalized pattern normalizes to itself. */
export function normalizeMaterialPattern(value) {
if (!value || typeof value !== 'object' || Array.isArray(value)) throw patternError(`must be an object such as { "type": "wood" }. Types: ${MATERIAL_PATTERN_TYPES.join(', ')}.`);
- const known = ['type', 'colors', 'size', 'count', 'bump', 'seed', 'axis', 'resolution'];
+ const known = ['type', 'colors', 'size', 'count', 'bump', 'seed', 'axis', 'resolution', 'mapping', 'graph'];
for (const key of Object.keys(value)) {
if (!known.includes(key)) throw patternError(`does not take ${key}. Fields: ${known.join(', ')}.`);
}
+ const mapping = value.mapping ?? 'box';
+ if (!MATERIAL_MAPPINGS.includes(mapping)) throw patternError(`mapping must be one of ${MATERIAL_MAPPINGS.join(', ')}: box projects along the object axes, uv follows the geometry's UVs.`);
+ // Box mapping is the default, so a preset that does not ask for UVs keeps exactly the shape it always had.
+ const mappingField = mapping === 'uv' ? { mapping } : {};
+ if (value.type === GRAPH_TYPE) return normalizeGraphPattern(value, mappingField);
+ if (value.graph !== undefined) throw patternError('does not take graph unless its type is graph.');
if (!Object.hasOwn(PATTERN_DEFAULTS, value.type ?? '')) throw patternError(`type must be one of ${MATERIAL_PATTERN_TYPES.join(', ')}.`);
const defaults = PATTERN_DEFAULTS[value.type];
const count = value.count ?? defaults.count;
@@ -276,22 +215,19 @@ export function normalizeMaterialPattern(value) {
seed,
axis,
resolution,
+ ...mappingField,
};
}
-function linearToSrgbByte(value) {
- const encoded = value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055;
- return Math.round(clampUnit(encoded) * 255);
-}
-
-function createImage(data, width, height) {
- // Browsers upload ImageData directly; Node only reads the pixels, as tests and tools do.
- return typeof ImageData === 'function' ? new ImageData(data, width, height) : { width, height, data };
-}
/** Bake a normalized pattern into { map, normalMap, metallicRoughnessMap } texture descriptors. Deterministic. */
export function bakeMaterialPattern(pattern) {
- const { resolution, type, seed, count, colors, bump, size } = pattern;
+ const placement = {
+ boxMapScale: pattern.mapping === 'uv' ? 0 : 1 / pattern.size,
+ boxMapAxis: ['x', 'y', 'z'].indexOf(pattern.axis),
+ };
+ if (pattern.type === GRAPH_TYPE) return { ...bakeMaterialGraph(pattern.graph, pattern), ...placement };
+ const { resolution, type, seed, count, colors, bump } = pattern;
const sampler = PATTERN_SAMPLERS[type];
const pixelCount = resolution * resolution;
const heights = new Float32Array(pixelCount);
@@ -318,31 +254,12 @@ export function bakeMaterialPattern(pattern) {
surfaceData[offset + 3] = 255;
}
}
- const normalData = new Uint8ClampedArray(pixelCount * 4);
- // Height differences are per texel; scale them so a bump of 1 reads the same at any resolution.
- const slopeScale = bump * resolution / 64;
- for (let row = 0; row < resolution; row++) {
- const rowAbove = (row + 1) % resolution;
- const rowBelow = (row + resolution - 1) % resolution;
- for (let column = 0; column < resolution; column++) {
- const columnRight = (column + 1) % resolution;
- const columnLeft = (column + resolution - 1) % resolution;
- const slopeU = (heights[row * resolution + columnRight] - heights[row * resolution + columnLeft]) * slopeScale;
- const slopeV = (heights[rowAbove * resolution + column] - heights[rowBelow * resolution + column]) * slopeScale;
- const length = Math.hypot(slopeU, slopeV, 1);
- const offset = (row * resolution + column) * 4;
- normalData[offset] = Math.round((-slopeU / length * 0.5 + 0.5) * 255);
- normalData[offset + 1] = Math.round((-slopeV / length * 0.5 + 0.5) * 255);
- normalData[offset + 2] = Math.round((1 / length * 0.5 + 0.5) * 255);
- normalData[offset + 3] = 255;
- }
- }
+ const normalData = normalMapFromHeights(heights, resolution, bump);
return {
map: { image: createImage(colorData, resolution, resolution), colorSpace: 'srgb' },
normalMap: { image: createImage(normalData, resolution, resolution), colorSpace: 'linear' },
metallicRoughnessMap: { image: createImage(surfaceData, resolution, resolution), colorSpace: 'linear' },
- boxMapScale: 1 / size,
- boxMapAxis: ['x', 'y', 'z'].indexOf(pattern.axis),
+ ...placement,
};
}
diff --git a/src/material-texture-kit.js b/src/material-texture-kit.js
new file mode 100644
index 00000000..19b1cc24
--- /dev/null
+++ b/src/material-texture-kit.js
@@ -0,0 +1,132 @@
+// Shared by material patterns and material graphs: seeded periodic noise, and the conversions that turn baked values
+// into texture descriptors. Texture coordinates run 0 to 1 and every noise is periodic over that square.
+
+export function hashCell(cellX, cellY, seed) {
+ let hash = Math.imul(cellX, 0x27d4eb2d) ^ Math.imul(cellY, 0x165667b1) ^ Math.imul(seed, 0x9e3779b1);
+ hash = Math.imul(hash ^ (hash >>> 15), 0x85ebca6b);
+ hash = Math.imul(hash ^ (hash >>> 13), 0xc2b2ae35);
+ return (hash ^ (hash >>> 16)) >>> 0;
+}
+
+export const wrapCell = (cell, period) => ((cell % period) + period) % period;
+export const smootherStep = value => value * value * value * (value * (value * 6 - 15) + 10);
+export const clampUnit = value => Math.min(1, Math.max(0, value));
+export const smoothStep = (minimum, maximum, value) => {
+ const position = clampUnit((value - minimum) / (maximum - minimum));
+ return position * position * (3 - 2 * position);
+};
+
+function cornerGradient(cellX, cellY, offsetX, offsetY, seed) {
+ const angle = hashCell(cellX, cellY, seed) / 4294967296 * Math.PI * 2;
+ return Math.cos(angle) * offsetX + Math.sin(angle) * offsetY;
+}
+
+/** Gradient noise in about -1 to 1, periodic over [0, 1) with the given whole number of cells per axis. */
+export function gradientNoise(positionU, positionV, cellsU, cellsV, seed = 0) {
+ const scaledU = positionU * cellsU;
+ const scaledV = positionV * cellsV;
+ const floorU = Math.floor(scaledU);
+ const floorV = Math.floor(scaledV);
+ const fractionU = scaledU - floorU;
+ const fractionV = scaledV - floorV;
+ const left = wrapCell(floorU, cellsU);
+ const right = wrapCell(floorU + 1, cellsU);
+ const bottom = wrapCell(floorV, cellsV);
+ const top = wrapCell(floorV + 1, cellsV);
+ const blendU = smootherStep(fractionU);
+ const blendV = smootherStep(fractionV);
+ const lower = cornerGradient(left, bottom, fractionU, fractionV, seed) * (1 - blendU)
+ + cornerGradient(right, bottom, fractionU - 1, fractionV, seed) * blendU;
+ const upper = cornerGradient(left, top, fractionU, fractionV - 1, seed) * (1 - blendU)
+ + cornerGradient(right, top, fractionU - 1, fractionV - 1, seed) * blendU;
+ return (lower * (1 - blendV) + upper * blendV) * 1.5;
+}
+
+/** Fractal sum of gradientNoise in about -1 to 1. Each octave doubles the cells, so it stays periodic. */
+export function fractalNoise(positionU, positionV, cellsU, cellsV, seed = 0, octaves = 5, gain = 0.5) {
+ let total = 0;
+ let amplitude = 1;
+ let amplitudeSum = 0;
+ for (let octave = 0; octave < octaves; octave++) {
+ total += gradientNoise(positionU, positionV, cellsU << octave, cellsV << octave, seed + octave * 131) * amplitude;
+ amplitudeSum += amplitude;
+ amplitude *= gain;
+ }
+ return total / amplitudeSum;
+}
+
+/** Ridged fractal noise in 0 to 1: sharp crests where the gradient noise crosses zero. */
+export function ridgedNoise(positionU, positionV, cellsU, cellsV, seed = 0, octaves = 4) {
+ let total = 0;
+ let amplitude = 1;
+ let amplitudeSum = 0;
+ for (let octave = 0; octave < octaves; octave++) {
+ const ridge = 1 - Math.abs(gradientNoise(positionU, positionV, cellsU << octave, cellsV << octave, seed + octave * 211));
+ total += ridge * ridge * amplitude;
+ amplitudeSum += amplitude;
+ amplitude *= 0.5;
+ }
+ return total / amplitudeSum;
+}
+
+/** Periodic Worley noise: distances to the nearest and second nearest feature point, in cell units, and a hash of the nearest cell. */
+export function cellularNoise(positionU, positionV, cells, seed = 0) {
+ const scaledU = positionU * cells;
+ const scaledV = positionV * cells;
+ const floorU = Math.floor(scaledU);
+ const floorV = Math.floor(scaledV);
+ let nearest = Infinity;
+ let second = Infinity;
+ let nearestCell = 0;
+ for (let offsetV = -1; offsetV <= 1; offsetV++) {
+ for (let offsetU = -1; offsetU <= 1; offsetU++) {
+ const cellU = floorU + offsetU;
+ const cellV = floorV + offsetV;
+ const hash = hashCell(wrapCell(cellU, cells), wrapCell(cellV, cells), seed);
+ const pointU = cellU + (hash & 0xffff) / 65536;
+ const pointV = cellV + (hash >>> 16) / 65536;
+ const distance = Math.hypot(pointU - scaledU, pointV - scaledV);
+ if (distance < nearest) {
+ second = nearest;
+ nearest = distance;
+ nearestCell = hash;
+ } else if (distance < second) {
+ second = distance;
+ }
+ }
+ }
+ return { nearest, second, cell: nearestCell };
+}
+
+export function linearToSrgbByte(value) {
+ const encoded = value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055;
+ return Math.round(clampUnit(encoded) * 255);
+}
+
+export function createImage(data, width, height) {
+ // Browsers upload ImageData directly; Node only reads the pixels, as tests and tools do.
+ return typeof ImageData === 'function' ? new ImageData(data, width, height) : { width, height, data };
+}
+
+/** Tangent-space normal map bytes from a height field. Height differences are per texel; scale them so a bump of 1 reads the same at any resolution. */
+export function normalMapFromHeights(heights, resolution, bump) {
+ const normalData = new Uint8ClampedArray(resolution * resolution * 4);
+ const slopeScale = bump * resolution / 64;
+ for (let row = 0; row < resolution; row++) {
+ const rowAbove = (row + 1) % resolution;
+ const rowBelow = (row + resolution - 1) % resolution;
+ for (let column = 0; column < resolution; column++) {
+ const columnRight = (column + 1) % resolution;
+ const columnLeft = (column + resolution - 1) % resolution;
+ const slopeU = (heights[row * resolution + columnRight] - heights[row * resolution + columnLeft]) * slopeScale;
+ const slopeV = (heights[rowAbove * resolution + column] - heights[rowBelow * resolution + column]) * slopeScale;
+ const length = Math.hypot(slopeU, slopeV, 1);
+ const offset = (row * resolution + column) * 4;
+ normalData[offset] = Math.round((-slopeU / length * 0.5 + 0.5) * 255);
+ normalData[offset + 1] = Math.round((-slopeV / length * 0.5 + 0.5) * 255);
+ normalData[offset + 2] = Math.round((1 / length * 0.5 + 0.5) * 255);
+ normalData[offset + 3] = 255;
+ }
+ }
+ return normalData;
+}
diff --git a/src/shaders.js b/src/shaders.js
index 8f708643..b0e13065 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -693,7 +693,7 @@ void main() {
}
float alpha = surfaceAlpha(textureAlpha);
vec3 emission = emissionColor * surface.z;
- if (USES_EMISSIVE_MAP) emission *= texture(emissiveMap, textureUV).rgb;
+ if (USES_EMISSIVE_MAP) emission *= (boxMapScale > 0.0 ? sampleBox(emissiveMap) : texture(emissiveMap, textureUV)).rgb;
if (TAG_UNLIT) {
vec3 radiance = color * exposure + emission;
outputColor = vec4(hdrEnabled > 0.5 ? radiance : pow(max(radiance, vec3(0)), vec3(1.0 / 2.2)), alpha);
diff --git a/tests/material-graph.test.js b/tests/material-graph.test.js
new file mode 100644
index 00000000..a630f33a
--- /dev/null
+++ b/tests/material-graph.test.js
@@ -0,0 +1,236 @@
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import test from 'node:test';
+import { bakeMaterialPattern, materialPatternTextures, normalizeMaterialPattern } from '../src/material-patterns.js';
+import { compileMaterialGraph } from '../src/material-graph.js';
+import { AGENT_SCENE_CAPABILITIES, MATERIAL_GRAPH_LIMITS, MATERIAL_GRAPH_OPERATORS } from '../src/agent-scene-capabilities.js';
+import { createAgentScene } from '../src/agent-scene.js';
+import { exportGlb } from '../src/export.js';
+
+const brickGraph = {
+ color: {
+ ramp: {
+ value: { add: [{ mul: [{ noise: { scale: 8, seed: 3 } }, 0.5] }, { mul: [{ wave: { frequency: 4, direction: 'v', shape: 'saw' } }, 0.5] }] },
+ stops: [[0, [0.15, 0.05, 0.03]], [1, [0.6, 0.25, 0.15]]],
+ },
+ },
+ roughness: { mix: [0.6, 0.95, { noise: { scale: 16, seed: 5 } }] },
+ height: { noise: { scale: 12, seed: 9 } },
+};
+
+const graphPattern = (overrides = {}) => ({ type: 'graph', graph: brickGraph, resolution: 256, ...overrides });
+
+function sha(baked) {
+ const hash = createHash('sha256');
+ for (const channel of ['map', 'normalMap', 'metallicRoughnessMap', 'emissiveMap']) {
+ if (baked[channel]) hash.update(Buffer.from(baked[channel].image.data));
+ }
+ return hash.digest('hex');
+}
+
+function glbJson(bytes) {
+ const array = new Uint8Array(bytes);
+ const view = new DataView(array.buffer, array.byteOffset, array.byteLength);
+ const length = view.getUint32(12, true);
+ return JSON.parse(new TextDecoder().decode(array.subarray(20, 20 + length)));
+}
+
+function checkerboardSum(image) {
+ let total = 0;
+ for (const byte of image.data) total += byte;
+ return total;
+}
+
+test('a graph bakes the outputs it has, and only those', () => {
+ const baked = bakeMaterialPattern(normalizeMaterialPattern(graphPattern()));
+ assert.equal(baked.map.colorSpace, 'srgb');
+ assert.equal(baked.metallicRoughnessMap.colorSpace, 'linear');
+ assert.equal(baked.normalMap.colorSpace, 'linear');
+ assert.equal(baked.emissiveMap, undefined);
+ const colorOnly = bakeMaterialPattern(normalizeMaterialPattern({ type: 'graph', graph: { color: [1, 0, 0] }, resolution: 256 }));
+ assert.equal(colorOnly.normalMap, undefined);
+ assert.equal(colorOnly.metallicRoughnessMap, undefined);
+ assert.equal(colorOnly.map.image.data[0], 255);
+ assert.equal(colorOnly.map.image.data[1], 0);
+});
+
+test('a baked graph is identical bytes every time', () => {
+ const first = sha(bakeMaterialPattern(normalizeMaterialPattern(graphPattern())));
+ const second = sha(bakeMaterialPattern(normalizeMaterialPattern(graphPattern())));
+ assert.equal(first, second);
+ const reseeded = structuredClone(brickGraph);
+ reseeded.height.noise.seed = 10;
+ assert.notEqual(sha(bakeMaterialPattern(normalizeMaterialPattern(graphPattern({ graph: reseeded })))), first);
+});
+
+test('height becomes a normal map: flat height is a flat normal, relief tilts it', () => {
+ const flat = bakeMaterialPattern(normalizeMaterialPattern({ type: 'graph', graph: { height: 0.5 }, resolution: 256 }));
+ assert.deepEqual(Array.from(flat.normalMap.image.data.slice(0, 3)), [128, 128, 255]);
+ const ridge = bakeMaterialPattern(normalizeMaterialPattern({ type: 'graph', graph: { height: { wave: { frequency: 4 } } }, resolution: 256, bump: 2 }));
+ const tilted = Array.from({ length: 256 }, (_, column) => ridge.normalMap.image.data[column * 4]);
+ assert.ok(Math.max(...tilted) - Math.min(...tilted) > 40);
+});
+
+test('every graph texture node tiles across the seam', () => {
+ const nodes = [{ noise: { scale: 6 } }, { voronoi: { scale: 5, output: 'edge' } }, { wave: { frequency: 3, direction: 'diagonal' } }, { checker: { count: 8 } }];
+ for (const node of nodes) {
+ const { outputs } = compileMaterialGraph({ height: node });
+ const evaluate = outputs.height.evaluate;
+ const step = 1 / 1024;
+ for (const row of [0.13, 0.5, 0.87]) {
+ const seam = Math.abs(evaluate(1 - step / 2, row) - evaluate(step / 2, row));
+ const interior = Math.abs(evaluate(0.5 + step / 2, row) - evaluate(0.5 - step / 2, row));
+ assert.ok(seam < 0.2 + interior, `${Object.keys(node)[0]} seam ${seam}`);
+ }
+ }
+});
+
+test('patterns with mapping uv use the geometry UVs from uv_unwrap instead of box projection', () => {
+ const recipe = {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'crate', type: 'mesh', base: { type: 'box', bevel: 0 }, stack: [{ op: 'uv_unwrap' }] }],
+ materials: [{ id: 'wall', pattern: graphPattern({ mapping: 'uv' }) }, { id: 'boxed', pattern: { type: 'wood', resolution: 256 } }],
+ nodes: [{ id: 'part', geometry: 'crate', material: 'wall' }],
+ };
+ const scene = createAgentScene(recipe);
+ const [part] = scene.parts;
+ assert.equal(part.material.boxMapScale, 0);
+ assert.equal(part.geometry.uvs.length, part.geometry.positions.length / 3 * 2);
+ assert.equal(scene.exportRecipe().materials[1].pattern.mapping, undefined);
+ assert.equal(scene.exportRecipe().materials[0].pattern.mapping, 'uv');
+ assert.ok(part.material.map && part.material.normalMap && part.material.metallicRoughnessMap);
+ assert.equal(part.material.roughness, 1);
+ const gltf = glbJson(exportGlb(scene.parts));
+ assert.equal(gltf.textures.length, 3);
+ assert.ok(gltf.meshes[0].primitives.every(primitive => primitive.attributes.TEXCOORD_0 !== undefined));
+ assert.ok(gltf.materials[0].normalTexture);
+});
+
+test('a graph that makes emission, roughness or metallic passes it through by default', () => {
+ const recipe = {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'block', type: 'box', bevel: 0 }],
+ materials: [{ id: 'lamp', pattern: { type: 'graph', graph: { emission: { checker: { count: 4 } }, metallic: 1 }, mapping: 'uv', resolution: 256 } }],
+ nodes: [{ id: 'part', geometry: 'block', material: 'lamp' }],
+ };
+ const { material } = createAgentScene(recipe).parts[0];
+ assert.equal(material.emission, 1);
+ assert.equal(material.metallic, 1);
+ assert.equal(material.emissiveMap.colorSpace, 'srgb');
+});
+
+test('graph and preset fields do not mix', () => {
+ assert.throws(() => normalizeMaterialPattern({ type: 'graph' }), /graph must be an object/);
+ assert.throws(() => normalizeMaterialPattern({ type: 'wood', graph: { height: 1 } }), /unless its type is graph/);
+ assert.throws(() => normalizeMaterialPattern({ type: 'graph', graph: { height: 1 }, colors: [[0, 0, 0], [1, 1, 1]] }), /does not take colors/);
+ assert.throws(() => normalizeMaterialPattern({ type: 'wood', mapping: 'planar' }), /mapping must be one of/);
+ const normalized = normalizeMaterialPattern(graphPattern({ mapping: 'uv' }));
+ assert.deepEqual(normalizeMaterialPattern(normalized), normalized);
+ assert.equal(Object.hasOwn(normalizeMaterialPattern({ type: 'wood' }), 'mapping'), false);
+});
+
+test('every capability operator compiles, and no other operator does', () => {
+ const samples = {
+ uv: { uv: 'u' }, vec: { vec: [1, 2, 3] }, ramp: { ramp: { value: 0.5, stops: [[0, 0], [1, 1]] } },
+ noise: { noise: {} }, voronoi: { voronoi: {} }, wave: { wave: {} }, checker: { checker: {} }, gradient: { gradient: {} },
+ };
+ for (const name of MATERIAL_GRAPH_OPERATORS) {
+ const node = samples[name] ?? (['abs', 'floor', 'fract', 'sqrt', 'invert'].includes(name) ? { [name]: 0.5 } : { [name]: [0.2, 0.4, 0.6].slice(0, ['clamp', 'smoothstep', 'mix'].includes(name) ? 3 : 2) });
+ assert.doesNotThrow(() => compileMaterialGraph({ color: node }), name);
+ }
+ assert.deepEqual(AGENT_SCENE_CAPABILITIES.materialGraph.operators, MATERIAL_GRAPH_OPERATORS);
+ assert.equal(AGENT_SCENE_CAPABILITIES.materialGraph.maxNodes, MATERIAL_GRAPH_LIMITS.maxNodes);
+});
+
+// ---------------------------------------------------------------------------------------------------------------
+// Boundary: a graph is data. Every hostile input is rejected before any pixel is evaluated, or is inert.
+
+function nested(depth) {
+ let node = 0.5;
+ for (let level = 0; level < depth; level++) node = { abs: node };
+ return node;
+}
+
+test('hostile graphs are rejected', () => {
+ const cycle = { abs: null };
+ cycle.abs = cycle;
+ const wide = { add: [0, 0] };
+ for (let index = 0; index < MATERIAL_GRAPH_LIMITS.maxNodes; index++) wide.add[0] = { add: [wide.add[0], 1] };
+ const hostile = {
+ 'proto key': JSON.parse('{"height":{"__proto__":{"abs":1}}}'),
+ 'proto output': JSON.parse('{"__proto__":{"height":1}}'),
+ 'constructor operator': { height: { constructor: [1, 2] } },
+ 'prototype operator': { height: { toString: [1] } },
+ 'inherited operator name': { height: { hasOwnProperty: 1 } },
+ 'cycle': { height: cycle },
+ 'deep nesting': { height: nested(MATERIAL_GRAPH_LIMITS.maxDepth + 5) },
+ 'too many nodes': { height: wide },
+ 'glsl as an operator': { height: { 'void main(){discard;}': 1 } },
+ 'glsl as a value': { height: 'void main() { gl_FragColor = vec4(1.0); }' },
+ 'glsl in an enum': { height: { wave: { direction: 'u; discard;' } } },
+ 'glsl as an output name': { 'gl_Position = vec4(0)': 1 },
+ 'shader injected in at': { height: { noise: { at: '1.0); evil(' } } },
+ 'function value': { height: () => 1 },
+ 'huge noise scale': { height: { noise: { scale: 1e9 } } },
+ 'fractional scale': { height: { noise: { scale: 2.5 } } },
+ 'octave bomb': { height: { noise: { octaves: 1000 } } },
+ 'odd checker': { height: { checker: { count: 7 } } },
+ 'huge literal': { height: 1e300 },
+ 'not a number': { height: Number.NaN },
+ 'infinite': { height: Number.POSITIVE_INFINITY },
+ 'vector for a scalar output': { height: [1, 2, 3] },
+ 'extra operator key': { height: { abs: 1, floor: 2 } },
+ 'ramp out of order': { color: { ramp: { value: 0.5, stops: [[0.8, 0], [0.2, 1]] } } },
+ 'ramp too long': { color: { ramp: { value: 0.5, stops: Array.from({ length: 40 }, (_, index) => [index / 40, 0]) } } },
+ 'empty': {},
+ 'array': [],
+ 'string graph': 'noise',
+ };
+ for (const [name, graph] of Object.entries(hostile)) {
+ assert.throws(() => normalizeMaterialPattern({ type: 'graph', graph, resolution: 256 }), Error, name);
+ }
+});
+
+test('hostile sizes and costs are rejected before any work', () => {
+ assert.throws(() => normalizeMaterialPattern({ type: 'graph', graph: { height: 1 }, resolution: 100000 }), /resolution must be one of/);
+ assert.throws(() => normalizeMaterialPattern({ type: 'graph', graph: { height: 1 }, resolution: '512' }), /resolution must be one of/);
+ const costly = { height: { voronoi: { scale: 8, at: { add: [{ uv: 'both' }, { mul: [{ vec: [{ noise: { octaves: 6 } }, { noise: { octaves: 6 } }, 0] }, 0.1] }] } } } };
+ let graph = costly.height;
+ for (let level = 0; level < 5; level++) graph = { add: [graph, { voronoi: { scale: 4, at: { vec: [graph, 0, 0] } } }] };
+ const started = Date.now();
+ assert.throws(() => normalizeMaterialPattern({ type: 'graph', graph: { height: graph }, resolution: 1024 }), /Material graph/);
+ assert.ok(Date.now() - started < 1000);
+});
+
+test('hostile strings never reach a texture, a recipe or a shader', () => {
+ const marker = 'discard;';
+ const accepted = normalizeMaterialPattern({ type: 'graph', graph: { height: { noise: { scale: 4 } } }, resolution: 256 });
+ assert.equal(JSON.stringify(accepted).includes(marker), false);
+ const recipe = {
+ format: '67js.scene', schemaVersion: 1, geometries: [{ id: 'block', type: 'box', bevel: 0 }],
+ materials: [{ id: 'bad', pattern: { type: 'graph', graph: { color: { wave: { direction: marker } } } } }],
+ nodes: [{ id: 'part', geometry: 'block', material: 'bad' }],
+ };
+ assert.throws(() => createAgentScene(recipe), /wave direction/);
+});
+
+test('math nodes compute the numbers they name, on numbers and on vectors', () => {
+ const value = node => compileMaterialGraph({ color: node }).outputs.color;
+ const scalarAt = node => value(node).evaluate(0.25, 0.75);
+ assert.equal(scalarAt({ min: [0.3, 0.2] }), 0.2);
+ assert.equal(scalarAt({ max: [0.3, 0.2] }), 0.3);
+ assert.equal(scalarAt({ add: [{ uv: 'u' }, { uv: 'v' }] }), 1);
+ assert.equal(scalarAt({ invert: 0.25 }), 0.75);
+ assert.equal(scalarAt({ fract: 2.75 }), 0.75);
+ assert.equal(scalarAt({ clamp: [5, 0, 1] }), 1);
+ assert.equal(scalarAt({ mix: [2, 4, 0.25] }), 2.5);
+ assert.equal(scalarAt({ div: [1, 0] }), 0);
+ const mixed = value({ mix: [[0, 0, 0], [1, 0.5, 0.25], 0.5] });
+ assert.deepEqual(mixed.parts.map(part => part(0, 0)), [0.5, 0.25, 0.125]);
+});
+
+test('the same graph shares one baked texture set across materials', () => {
+ const pattern = normalizeMaterialPattern(graphPattern());
+ assert.equal(materialPatternTextures(pattern), materialPatternTextures(pattern));
+ assert.ok(checkerboardSum(materialPatternTextures(pattern).map.image) > 0);
+});
diff --git a/tests/reference-baseline.test.js b/tests/reference-baseline.test.js
index 30178fca..9ae33c9d 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 = ['car-paint', 'character', 'fog', 'foliage', 'glass', 'lit-interior', 'material-spheres', 'metal', 'outdoor-hdri', 'spot-area'];
+const EXPECTED_SCENES = ['brick-graph', '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', () => {