Skip to content

3D engine that AI agents drive

Add a vertexGroup node to the material graph (#1957)

Nguyen Xuan An9b971856d111
diff --git a/changes/1957.md b/changes/1957.md
new file mode 100644
index 00000000..cce0ac40
--- /dev/null
+++ b/changes/1957.md
@@ -0,0 +1 @@
+- A material graph has a `vertexGroup` node: the weight of a mesh vertex group, drawn into UV space per mesh and baked like any other node, so the rasterizer and both path tracers read it (#1957)
diff --git a/changes/1957.size.md b/changes/1957.size.md
new file mode 100644
index 00000000..4ce997e3
--- /dev/null
+++ b/changes/1957.size.md
@@ -0,0 +1,3 @@
+- scene:agent-scene: 185 bytes gzip for the vertexGroup graph node and its per-mesh weight-map rasterizer, which lets a graph mix a vertex group with noise and layers on every backend
+- scene:agent-scene+lazy: 1773 bytes gzip for the same node, its weight-map rasterizer and the per-mesh material view, which is the only way a vertex group reaches the path tracers
+- goal:agent-scene: 185 bytes gzip for the vertexGroup graph node, an agent-facing capability that mixes a mesh vertex group into a material graph; the tracers read it only through the per-mesh baked texture
diff --git a/docs/agent-scene.md b/docs/agent-scene.md
index 1c8765ec..b901bed9 100644
--- a/docs/agent-scene.md
+++ b/docs/agent-scene.md
@@ -194,7 +194,9 @@ Placement and pattern nodes:
- `coord` (`"generated"`, `"object"` or `"world"`) is a vector for `at`. `generated` is the unit tile, `object` and `world` are metres across the tile (texture u and v times the pattern `size`). A baked texture is projected onto the mesh, so it knows only the two axes of that projection and the third is 0; `object` and `world` are the same because box mapping reads the placed, scaled position.
- `mapping` (`vector`, default `{ "coord": "generated" }`; `scale` a number or `[x, y, z]`; `rotate` radians around Z; `offset` `[x, y, z]`) scales, turns and moves a vector, as Blender's Mapping node does. Feed it to `at`.
-These make a material work on a mesh without UVs: box mapping (the default) projects the baked graph along the object axes, so a brick wall or a noise pattern needs no unwrap. `vertex_color` on a mesh already multiplies the baked colour. Not in graphs yet: ambient occlusion, bevel and curvature masks, fresnel anywhere but as an emission factor, and a vertex group node (they need per-vertex or per-pixel data that a bake from `u` and `v` alone does not have).
+These make a material work on a mesh without UVs: box mapping (the default) projects the baked graph along the object axes, so a brick wall or a noise pattern needs no unwrap. `vertex_color` on a mesh already multiplies the baked colour. Not in graphs yet: ambient occlusion, bevel and curvature masks, and fresnel anywhere but as an emission factor (they need per-pixel data that a bake from `u` and `v` alone does not have).
+
+`vertexGroup` (`{ "vertexGroup": { "name": "edge" } }`) is a number from 0 to 1: the weight of that vertex group of the mesh. The host draws each group the graph names into a map in UV space (every triangle filled at its UVs with the blend of its three vertex weights, spread a few texels past island edges) and bakes the graph with it, so the weight mixes with noise, ramps and `layer` like any other node: `"color": { "layer": { "base": [0.5, 0.5, 0.5], "top": [0.9, 0.6, 0.2], "mask": { "vertexGroup": { "name": "edge" } } } }`. The pattern needs `"mapping": "uv"` (box mapping has no `u` and `v` to match), and the mesh needs UVs and the group, or building the part fails and lists the groups it has. The result is an ordinary baked texture, so the rasterizer and the CPU and GPU path tracers read it the same way. A material used on two meshes bakes one set of textures for each mesh; one used on a single mesh bakes once. `material.wear` is separate: it needs no UVs and blends per pixel in the rasterizer only.
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
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 4c9e755d..a10b8095 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -55,7 +55,7 @@ export const MATERIAL_GRAPH_OUTPUTS = Object.freeze(['color', 'roughness', 'meta
export const MATERIAL_GRAPH_OPERATORS = Object.freeze([
'uv', 'coord', 'mapping', 'vec', 'ramp', 'image', 'noise', 'whiteNoise', 'brick', 'voronoi', 'wave', 'checker', 'gradient',
'add', 'sub', 'mul', 'div', 'min', 'max', 'pow', 'abs', 'floor', 'fract', 'sqrt', 'invert', 'clamp', 'smoothstep', 'mix',
- 'layer', 'hue', 'curve', 'fresnel',
+ 'layer', 'hue', 'curve', 'fresnel', 'vertexGroup',
]);
export const MATERIAL_GRAPH_LIMITS = Object.freeze({ maxNodes: MAX_FIELD_NODES, maxDepth: MAX_FIELD_DEPTH, maxStops: 8, maxWork: 30_000_000 });
// Curve and text geometry. A text geometry is bounded by vertices per curve segment: the bundled font stays under
@@ -85,9 +85,10 @@ export const MATERIAL_GRAPH_NODES = Object.freeze({
note: 'Each takes "at", a vector such as {"uv":"both"}. Scales are whole numbers 1-64.',
}),
uv: '{"uv":"u"|"v"|"both"} coordinates.',
- coordinates: '{"coord":"generated"|"object"|"world"} vector of where the texel sits: generated is the unit tile, object and world are metres across the tile (u * size); the third axis is 0 because a baked texture is projected. {"mapping":{"vector":node,"scale":n|[x,y,z],"offset":[x,y,z],"rotate":radians}} scales, turns around Z and moves a vector (default: generated). Feed either to "at". Meshes without UVs use box mapping; vertex_color already multiplies the baked colour. In graphs: fresnel, only as an emission factor. Not in graphs: vertexGroup, AO, bevel, curvature (per-pixel data a bake lacks).',
+ coordinates: '{"coord":"generated"|"object"|"world"} vector of where the texel sits: generated is the unit tile, object and world are metres across the tile (u * size); the third axis is 0 because a baked texture is projected. {"mapping":{"vector":node,"scale":n|[x,y,z],"offset":[x,y,z],"rotate":radians}} scales, turns around Z and moves a vector (default: generated). Feed either to "at". Meshes without UVs use box mapping; vertex_color already multiplies the baked colour. In graphs: fresnel, only as an emission factor. Not in graphs: AO, bevel, curvature (per-pixel data a bake lacks).',
ramp: '{"ramp":{"value":node,"stops":[[0,[r,g,b]],[1,[r,g,b]]]}} 2-8 stops rising from 0 to 1.',
fresnel: '{"fresnel":{"ior":1.5}} ior 1.01-3. View dependent, so only as a factor of emission, alone or {"mul":[node,{"fresnel":{...}}]}: emission rises toward grazing angles, rendered per pixel by the rasterizer and the CPU path tracer.',
+ vertexGroup: '{"vertexGroup":{"name":"edge"}} a number 0-1: the weight of that vertex group of the mesh, drawn into UV space and read at the texel, so it mixes with noise, ramps and layers. Needs pattern mapping "uv" and a mesh with UVs and the group (make it with a vertex_group mesh edit); every backend reads the baked texture. A material used on two meshes bakes once per mesh.',
mixing: '{"layer":{"base","top","mask","edge","softness"}}; {"hue":{"color","shift","saturation","value"}}; {"curve":{"value","points":[[x,y]]}}.',
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]}.',
mapping: 'box (default) projects along object axes, no UVs; uv follows geometry UVs. size and axis only apply to box.',
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 628c864a..65fd85e8 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -1765,10 +1765,12 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
const usesVisibility = recipeUsesVisibility(recipe);
const nextParts = recipe.nodes.filter(node => node.geometry !== undefined).map(node => {
const binding = skinBindings.get(node.id);
- const material = materialHandles.get(node.material).output;
+ const recipeMaterial = materialHandles.get(node.material);
const sourceGeometry = binding?.geometry ?? geometries.get(node.geometry);
- const foamGeometry = sourceGeometry.vertexGroups?.foam ? agentSceneModule('mesh').waterFoamGeometry(sourceGeometry, material) : sourceGeometry;
- const geometry = material.wear ? geometryWithSurfaceMasks(foamGeometry, material.wear, node.id) : foamGeometry;
+ const foamGeometry = sourceGeometry.vertexGroups?.foam ? agentSceneModule('mesh').waterFoamGeometry(sourceGeometry, recipeMaterial.output) : sourceGeometry;
+ const geometry = recipeMaterial.output.wear ? geometryWithSurfaceMasks(foamGeometry, recipeMaterial.output.wear, node.id) : foamGeometry;
+ // A graph with a vertexGroup node bakes with this mesh's weights, so its textures belong to the mesh.
+ const material = recipeMaterial.output.pattern?.graph ? agentSceneModule('patterns').materialViewForGeometry(recipeMaterial.output, geometry, node.id, recipeMaterial.holder.images) : recipeMaterial.output;
const assetExtras = assetRuntime.partExtras.get(node.id);
// Shape keys of a recipe mesh are morph targets with their own weights per part; an imported asset brings its own pose.
const shapeKeyMorph = geometry.morphTargetValues && !assetExtras?.morph ? { weights: Float32Array.from(geometry.morphTargetValues) } : undefined;
diff --git a/src/material-graph.js b/src/material-graph.js
index 5a72f2dc..9cd83ce6 100644
--- a/src/material-graph.js
+++ b/src/material-graph.js
@@ -609,7 +609,45 @@ function splitEmissionFresnel(node) {
return { base: operands[1 - fresnelSlot], ior: readFresnelIor(operands[fresnelSlot]) };
}
+// A vertex group is mesh data, which a graph baked from u and v does not have. The host rasterizes each group a graph
+// names into a weight map in UV space for one mesh (material-vertex-group-map.js) and bakes the graph with those maps, so
+// the node reads its weight at the texel's own u and v. Validating a graph needs no mesh, so without maps only the name
+// is checked; a pattern with the node must use uv mapping, since box mapping has no u and v to match.
+const VERTEX_GROUP_COST = 2;
+const VERTEX_GROUP_NAME_LIMIT = 128;
+
+function readVertexGroupName(node) {
+ const settings = textureSettings(node, 'vertexGroup', ['name']);
+ const { name } = settings;
+ if (typeof name !== 'string' || name === '' || name.length > VERTEX_GROUP_NAME_LIMIT) {
+ throw graphError('vertexGroup needs the name of a vertex group of the mesh, such as {"vertexGroup":{"name":"edge"}}; make the group with a vertex_group mesh edit.');
+ }
+ return name;
+}
+
+function compileVertexGroup(node, state) {
+ const name = readVertexGroupName(node);
+ state.cost += VERTEX_GROUP_COST;
+ if (!state.groups) return scalarValue(() => 0);
+ const map = state.groups.get(name);
+ if (!map) throw graphError(`vertexGroup ${describeKey(name)} was not rasterized for this mesh. Bake the material through a part whose mesh has the group.`);
+ return scalarValue((u, v) => sampleImageChannel(map, u, v, 0, byte => byte / 255));
+}
+
+/** The vertex group names a graph reads with `vertexGroup` nodes, in the order they first appear. */
+export function graphVertexGroupNames(graph) {
+ const names = new Set();
+ const visit = (value, depth) => {
+ if (!value || typeof value !== 'object' || depth > MATERIAL_GRAPH_LIMITS.maxDepth * 3) return;
+ if (!Array.isArray(value) && isPlainObject(value.vertexGroup) && typeof value.vertexGroup.name === 'string') names.add(value.vertexGroup.name);
+ for (const child of Array.isArray(value) ? value : Object.values(value)) visit(child, depth + 1);
+ };
+ visit(graph, 0);
+ return [...names];
+}
+
const TEXTURE_COMPILERS = new Map([
+ ['vertexGroup', compileVertexGroup],
['image', compileImage], ['noise', compileNoise], ['whiteNoise', compileWhiteNoise], ['brick', compileBrick], ['voronoi', compileVoronoi], ['wave', compileWave], ['checker', compileChecker], ['gradient', compileGradient],
]);
@@ -651,12 +689,12 @@ const SCALAR_OUTPUTS = ['roughness', 'metallic', 'height', 'opacity', 'clearcoat
* Check a graph and compile each output. `size` is the metres one texture tile covers, which object and world coordinates report. Limits on nodes, depth and work per pixel are enforced here, before any
* pixel is evaluated. Returns { outputs: { name: compiled }, emissionFresnel (an IOR, or undefined), nodeCount, cost }.
*/
-export function compileMaterialGraph(graph, { size = 1, images } = {}) {
+export function compileMaterialGraph(graph, { size = 1, images, groups } = {}) {
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, size, images };
+ const state = { nodeCount: 0, cost: 0, size, images, groups };
const outputs = Object.create(null);
let emissionFresnel;
for (const name of MATERIAL_GRAPH_OUTPUTS) {
@@ -731,8 +769,8 @@ export function graphImageData(graph, pool) {
}
/** Bake a normalized graph into texture descriptors, one for each output the graph has. Deterministic. */
-export function bakeMaterialGraph(graph, { resolution, bump, size = 1 }, images) {
- const compiled = compileMaterialGraph(graph, { size, images: imagePoolMap(images) });
+export function bakeMaterialGraph(graph, { resolution, bump, size = 1 }, images, groups) {
+ const compiled = compileMaterialGraph(graph, { size, images: imagePoolMap(images), groups: groups ? imagePoolMap(groups) : undefined });
checkMaterialGraphWork(compiled, resolution);
const { color, roughness, metallic, emission, height, opacity, clearcoat, transmission, aov } = compiled.outputs;
const pixelCount = resolution * resolution;
diff --git a/src/material-patterns.js b/src/material-patterns.js
index e22e0b1f..4950a4b6 100644
--- a/src/material-patterns.js
+++ b/src/material-patterns.js
@@ -1,5 +1,6 @@
import { MATERIAL_PATTERN_TYPES, MATERIAL_MAPPINGS } from './agent-scene-capabilities.js';
-import { bakeMaterialGraph, graphImageData, normalizeMaterialGraph } from './material-graph.js';
+import { bakeMaterialGraph, graphImageData, graphVertexGroupNames, normalizeMaterialGraph } from './material-graph.js';
+import { vertexGroupMap } from './material-vertex-group-map.js';
import { kernelKey, runKernel } from './kernel-offload.js';
// Procedural surface patterns for recipe materials: seeded, tileable and baked on the CPU into the same texture
@@ -173,9 +174,13 @@ function normalizeGraphPattern(value, mappingField) {
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(', ')}.`);
+ const graph = normalizeMaterialGraph(value.graph, resolution);
+ if (graphVertexGroupNames(graph).length > 0 && mappingField.mapping !== 'uv') {
+ throw patternError('uses a vertexGroup node, which reads the mesh in UV space: set "mapping": "uv" on the pattern (the mesh needs UVs).');
+ }
return {
type: GRAPH_TYPE,
- graph: normalizeMaterialGraph(value.graph, resolution),
+ graph,
size: checkedNumber(value.size ?? GRAPH_DEFAULTS.size, 'size', 0.01, 100),
bump: checkedNumber(value.bump ?? GRAPH_DEFAULTS.bump, 'bump', 0, 4),
axis,
@@ -222,12 +227,12 @@ export function normalizeMaterialPattern(value) {
/** Bake a normalized pattern into { map, normalMap, metallicRoughnessMap } texture descriptors. Deterministic. */
-export function bakeMaterialPattern(pattern, images) {
+export function bakeMaterialPattern(pattern, images, groups) {
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, images), ...placement };
+ if (pattern.type === GRAPH_TYPE) return { ...bakeMaterialGraph(pattern.graph, pattern, images, groups), ...placement };
const { resolution, type, seed, count, colors, bump } = pattern;
if (!Object.hasOwn(PATTERN_SAMPLERS, type)) throw patternError(`type must be one of ${MATERIAL_PATTERN_TYPES.join(', ')}.`);
const sampler = PATTERN_SAMPLERS[type];
@@ -271,10 +276,14 @@ const MAX_BAKED_PATTERNS = 32;
// keeps the same descriptors alive for as long as a material holds them, because a renderer rejects changed textures.
const bakedByPatternObject = new WeakMap();
-/** The baked textures of a pattern, shared by every material with the same definition. */
-export function materialPatternTextures(pattern, imagePool) {
+/**
+ * The baked textures of a pattern, shared by every material with the same definition. `groups` holds the weight maps
+ * of the vertex groups its graph reads, for one mesh (see materialViewForGeometry); the key then covers their bytes.
+ */
+export function materialPatternTextures(pattern, imagePool, groups) {
const images = pattern.graph ? graphImageData(pattern.graph, imagePool) : {};
const hasImages = Object.keys(images).length > 0;
+ if (groups) return bakeWithGroups(pattern, images, groups);
const remembered = bakedByPatternObject.get(pattern);
// An image graph is remembered only for the very frames it was baked from, so another pool with the same asset ID
// but different pixels bakes again.
@@ -293,9 +302,77 @@ export function materialPatternTextures(pattern, imagePool) {
return baked;
}
+function bakeWithGroups(pattern, images, groups) {
+ const arguments_ = [pattern, images, groups];
+ const key = kernelKey('pattern', arguments_);
+ let baked = bakedPatterns.get(key);
+ if (baked) {
+ bakedPatterns.delete(key);
+ } else {
+ baked = runKernel('pattern', arguments_, bakeMaterialPattern);
+ if (bakedPatterns.size >= MAX_BAKED_PATTERNS) bakedPatterns.delete(bakedPatterns.keys().next().value);
+ }
+ bakedPatterns.set(key, baked);
+ return baked;
+}
+
+const viewsByGeometry = new WeakMap();
+const groupNamesByPattern = new WeakMap();
+
+function vertexGroupNamesOf(pattern) {
+ if (!pattern?.graph) return [];
+ let names = groupNamesByPattern.get(pattern);
+ if (!names) {
+ names = graphVertexGroupNames(pattern.graph);
+ groupNamesByPattern.set(pattern, names);
+ }
+ return names;
+}
+
+function groupMapsOf(pattern, geometry, nodeId) {
+ const maps = {};
+ for (const name of vertexGroupNamesOf(pattern)) maps[name] = vertexGroupMap(geometry, name, pattern.resolution, nodeId);
+ return maps;
+}
+
+/**
+ * The material a part of `geometry` renders with. A material whose graph has no `vertexGroup` node is returned as it
+ * is. Otherwise the result is a view of it whose baked textures come from the graph baked with this mesh's vertex
+ * group weights, cached per geometry and material so the renderer sees the same textures on every rebuild.
+ */
+export function materialViewForGeometry(material, geometry, nodeId, imagePool) {
+ const pattern = material.pattern;
+ if (vertexGroupNamesOf(pattern).length === 0) return material;
+ // The groups are checked now, so a mesh without UVs or without the group fails when the part is built.
+ const groups = groupMapsOf(pattern, geometry, nodeId);
+ let views = viewsByGeometry.get(geometry);
+ if (!views) {
+ views = new WeakMap();
+ viewsByGeometry.set(geometry, views);
+ }
+ let view = views.get(material);
+ if (view) return view;
+ const output = {};
+ for (const field of Object.keys(material)) {
+ Object.defineProperty(output, field, { enumerable: true, configurable: true, get: () => material[field] });
+ }
+ let baked;
+ const bakedTextures = () => {
+ baked ??= materialPatternTextures(material.pattern, imagePool, groupMapsOf(material.pattern, geometry, nodeId));
+ return baked;
+ };
+ for (const field of Object.keys(material).filter(name => PATTERN_TEXTURE_FIELDS.includes(name))) {
+ Object.defineProperty(output, field, { enumerable: true, configurable: true, get: () => bakedTextures()[field] });
+ }
+ view = Object.freeze(output);
+ views.set(material, view);
+ return view;
+}
+
function sameFrames(rememberedImages, images) {
const ids = Object.keys(images);
return ids.length === Object.keys(rememberedImages).length && ids.every(id => rememberedImages[id]?.data === images[id].data);
}
export { PATTERN_DEFAULTS };
+const PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'emissiveMap', 'layerMaps', 'transmissionMap', 'aovMap', 'emissionFresnel', 'boxMapScale', 'boxMapAxis'];
diff --git a/src/material-vertex-group-map.js b/src/material-vertex-group-map.js
new file mode 100644
index 00000000..0b565998
--- /dev/null
+++ b/src/material-vertex-group-map.js
@@ -0,0 +1,111 @@
+import { invalidField } from './field-error.js';
+
+// The weights of one vertex group drawn into UV space, so a material graph can read them as a texture. Every triangle is
+// filled at its UVs with the barycentric blend of its three vertex weights, then the filled texels spread a few texels
+// outward so bilinear reads next to a UV island edge do not blend with empty texels. Row 0 is v = 0, as in a baked graph.
+
+const DILATION_PASSES = 4;
+const INSIDE_TOLERANCE = 1e-6;
+
+function groupWeights(geometry, name, nodeId) {
+ if (!geometry.uvs) {
+ throw invalidField('vertexGroup', name, `a mesh with UVs (node ${nodeId} has none); add UVs with a uv mesh edit, or use box mapping and material.wear for per-pixel wear`);
+ }
+ const weights = geometry.vertexGroups?.[name];
+ if (!weights) {
+ const known = Object.keys(geometry.vertexGroups ?? {});
+ throw invalidField('vertexGroup', name, `a vertex group of the mesh of node ${nodeId} (known groups: ${known.join(', ') || 'none'}); make one with a vertex_group mesh edit`);
+ }
+ return weights;
+}
+
+function fillTriangle(texels, covered, resolution, uvs, weights, corners) {
+ const points = corners.map(corner => [uvs[corner * 2] * resolution, uvs[corner * 2 + 1] * resolution]);
+ const [[ax, ay], [bx, by], [cx, cy]] = points;
+ const area = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
+ if (Math.abs(area) < INSIDE_TOLERANCE) return;
+ const firstColumn = Math.max(0, Math.floor(Math.min(ax, bx, cx) - 1));
+ const lastColumn = Math.min(resolution - 1, Math.ceil(Math.max(ax, bx, cx)));
+ const firstRow = Math.max(0, Math.floor(Math.min(ay, by, cy) - 1));
+ const lastRow = Math.min(resolution - 1, Math.ceil(Math.max(ay, by, cy)));
+ for (let row = firstRow; row <= lastRow; row++) {
+ for (let column = firstColumn; column <= lastColumn; column++) {
+ const pointX = column + 0.5;
+ const pointY = row + 0.5;
+ const weightB = ((pointX - ax) * (cy - ay) - (cx - ax) * (pointY - ay)) / area;
+ const weightC = ((bx - ax) * (pointY - ay) - (pointX - ax) * (by - ay)) / area;
+ const weightA = 1 - weightB - weightC;
+ if (weightA < -INSIDE_TOLERANCE || weightB < -INSIDE_TOLERANCE || weightC < -INSIDE_TOLERANCE) continue;
+ const value = weightA * weights[corners[0]] + weightB * weights[corners[1]] + weightC * weights[corners[2]];
+ const pixel = row * resolution + column;
+ texels[pixel] = Math.min(255, Math.max(0, Math.round(value * 255)));
+ covered[pixel] = 1;
+ }
+ }
+}
+
+function dilate(texels, covered, resolution) {
+ for (let pass = 0; pass < DILATION_PASSES; pass++) {
+ const spread = [];
+ for (let row = 0; row < resolution; row++) {
+ for (let column = 0; column < resolution; column++) {
+ const pixel = row * resolution + column;
+ if (covered[pixel]) continue;
+ let sum = 0;
+ let count = 0;
+ for (let rowOffset = -1; rowOffset <= 1; rowOffset++) {
+ for (let columnOffset = -1; columnOffset <= 1; columnOffset++) {
+ const neighbourRow = row + rowOffset;
+ const neighbourColumn = column + columnOffset;
+ if (neighbourRow < 0 || neighbourColumn < 0 || neighbourRow >= resolution || neighbourColumn >= resolution) continue;
+ const neighbour = neighbourRow * resolution + neighbourColumn;
+ if (!covered[neighbour]) continue;
+ sum += texels[neighbour];
+ count++;
+ }
+ }
+ if (count > 0) spread.push([pixel, Math.round(sum / count)]);
+ }
+ }
+ for (const [pixel, value] of spread) {
+ texels[pixel] = value;
+ covered[pixel] = 1;
+ }
+ }
+}
+
+const mapsByGeometry = new WeakMap();
+
+/**
+ * One group of a render geometry as `{ width, height, data }` RGBA bytes with the weight (0 to 255) in the red channel.
+ * Cached per geometry, group and resolution, so a part keeps the same map between rebuilds. Throws, with what to pass
+ * instead, when the mesh has no UVs or no such group.
+ */
+export function vertexGroupMap(geometry, name, resolution, nodeId) {
+ const weights = groupWeights(geometry, name, nodeId);
+ let maps = mapsByGeometry.get(geometry);
+ if (!maps) {
+ maps = new Map();
+ mapsByGeometry.set(geometry, maps);
+ }
+ const key = `${name}|${resolution}`;
+ const remembered = maps.get(key);
+ if (remembered) return remembered;
+ const texels = new Uint8Array(resolution * resolution);
+ const covered = new Uint8Array(resolution * resolution);
+ const { indices, uvs } = geometry;
+ const cornerCount = indices ? indices.length : weights.length;
+ for (let corner = 0; corner + 2 < cornerCount; corner += 3) {
+ const corners = indices ? [indices[corner], indices[corner + 1], indices[corner + 2]] : [corner, corner + 1, corner + 2];
+ fillTriangle(texels, covered, resolution, uvs, weights, corners);
+ }
+ dilate(texels, covered, resolution);
+ const data = new Uint8ClampedArray(resolution * resolution * 4);
+ for (let pixel = 0; pixel < texels.length; pixel++) {
+ data[pixel * 4] = texels[pixel];
+ data[pixel * 4 + 3] = 255;
+ }
+ const map = Object.freeze({ width: resolution, height: resolution, data });
+ maps.set(key, map);
+ return map;
+}
diff --git a/tests/material-graph-vertex-group.test.js b/tests/material-graph-vertex-group.test.js
new file mode 100644
index 00000000..bbd9bf81
--- /dev/null
+++ b/tests/material-graph-vertex-group.test.js
@@ -0,0 +1,88 @@
+import './support/load-agent-scene-modules.mjs';
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createAgentScene } from '../src/agent-scene.js';
+import { compileMaterialGraph } from '../src/material-graph.js';
+import { bakeMaterialPattern, normalizeMaterialPattern } from '../src/material-patterns.js';
+import { vertexGroupMap } from '../src/material-vertex-group-map.js';
+
+const EDGE_GRAPH = { color: { mul: [[1, 1, 1], { vertexGroup: { name: 'edge' } }] } };
+
+function recipeWith({ edits, pattern, geometryId = 'hatch' }) {
+ return {
+ format: 'crucible.scene',
+ schemaVersion: 1,
+ geometries: [{
+ id: geometryId,
+ type: 'mesh',
+ base: { type: 'box', bevel: 0, subdivisions: 1 },
+ edits: [
+ { op: 'subdivide_edges', edges: { all: true }, cuts: 3 },
+ { op: 'vertex_group', name: 'edge', measure: 'edge', angle: 45 },
+ ...edits,
+ ],
+ }],
+ materials: [{ id: 'paint', pattern }],
+ nodes: [{ id: 'hatch', geometry: geometryId, material: 'paint' }],
+ };
+}
+
+const withUvs = [{ op: 'uv_project', mode: 'cube' }];
+const graphPattern = (graph, extra = {}) => ({ type: 'graph', mapping: 'uv', resolution: 256, graph, ...extra });
+
+function redChannel(texture) {
+ const { data } = texture.image;
+ const values = [];
+ for (let offset = 0; offset < data.length; offset += 4) values.push(data[offset]);
+ return values;
+}
+
+test('vertexGroup validates its name without a mesh and costs work units', () => {
+ assert.ok(compileMaterialGraph(EDGE_GRAPH).outputs.color);
+ for (const bad of [{ vertexGroup: {} }, { vertexGroup: { name: '' } }, { vertexGroup: { name: 4 } }, { vertexGroup: { name: 'edge', extra: 1 } }]) {
+ assert.throws(() => compileMaterialGraph({ roughness: bad }), /vertexGroup/);
+ }
+});
+
+test('a graph with vertexGroup needs uv mapping', () => {
+ assert.throws(() => normalizeMaterialPattern({ type: 'graph', graph: EDGE_GRAPH }), /vertexGroup.*"mapping": "uv"/);
+ assert.ok(normalizeMaterialPattern(graphPattern(EDGE_GRAPH)));
+});
+
+test('the weight map holds the triangle blend of the vertex weights and spreads past the island edge', () => {
+ const geometry = {
+ indices: Uint32Array.from([0, 1, 2]),
+ uvs: Float32Array.from([0.25, 0.25, 0.75, 0.25, 0.25, 0.75]),
+ vertexGroups: { edge: Float32Array.from([0, 1, 1]) },
+ };
+ const map = vertexGroupMap(geometry, 'edge', 256, 'quad');
+ const at = (column, row) => map.data[(row * 256 + column) * 4];
+ assert.ok(Math.abs(at(100, 100) - 147) <= 2, 'the blend at (0.3945, 0.3945) is 1 - barycentric weight of the weight-0 corner');
+ assert.ok(at(100, 120) > at(100, 100), 'weight rises toward the weight-1 corners');
+ assert.ok(at(62, 100) > 0, 'dilation fills the texel just outside the triangle');
+ assert.equal(at(50, 100), 0, 'texels beyond the spread stay empty');
+ assert.equal(at(250, 250), 0, 'texels far from any island stay empty');
+ assert.equal(vertexGroupMap(geometry, 'edge', 256, 'quad'), map, 'the map is cached per geometry');
+});
+
+test('a mesh without UVs or without the group is refused with what to pass', () => {
+ assert.throws(() => createAgentScene(recipeWith({ edits: [], pattern: graphPattern(EDGE_GRAPH) })), /vertexGroup: got "edge"; expected a mesh with UVs \(node hatch has none\)/);
+ const missing = graphPattern({ color: { vertexGroup: { name: 'rust' } } });
+ assert.throws(() => createAgentScene(recipeWith({ edits: withUvs, pattern: missing })), /got "rust".*known groups: edge/);
+});
+
+test('the part bakes the graph with its own mesh weights; a graph without the node is unchanged', () => {
+ const scene = createAgentScene(recipeWith({ edits: withUvs, pattern: graphPattern(EDGE_GRAPH) }));
+ const [part] = scene.parts;
+ const baked = redChannel(part.material.map);
+ assert.ok(baked.some(value => value > 200), 'texels at the edge group are bright');
+ assert.ok(baked.some(value => value < 40), 'texels away from it are dark');
+ assert.equal(part.material.map, part.material.map, 'the texture is stable between reads');
+ const rebuilt = createAgentScene(recipeWith({ edits: withUvs, pattern: graphPattern(EDGE_GRAPH) })).parts[0];
+ assert.deepEqual(redChannel(rebuilt.material.map), baked, 'baking is deterministic');
+
+ const plainPattern = graphPattern({ color: [0.4, 0.5, 0.6] });
+ const plain = createAgentScene(recipeWith({ edits: withUvs, pattern: plainPattern })).parts[0];
+ const direct = bakeMaterialPattern(normalizeMaterialPattern(plainPattern));
+ assert.deepEqual(redChannel(plain.material.map), redChannel(direct.map), 'a graph without the node bakes exactly as before');
+});
diff --git a/tests/material-graph.test.js b/tests/material-graph.test.js
index f29b5d30..7ebaa51b 100644
--- a/tests/material-graph.test.js
+++ b/tests/material-graph.test.js
@@ -178,7 +178,7 @@ test('graph and preset fields do not mix', () => {
test('every capability operator compiles, and no other operator does', () => {
const samples = {
uv: { uv: 'u' }, image: { image: { asset: 'a'.repeat(64) } }, coord: { coord: 'object' }, mapping: { mapping: {} }, whiteNoise: { whiteNoise: {} }, brick: { brick: {} }, vec: { vec: [1, 2, 3] }, ramp: { ramp: { value: 0.5, stops: [[0, 0], [1, 1]] } },
- fresnel: { fresnel: {} }, noise: { noise: {} }, voronoi: { voronoi: {} }, wave: { wave: {} }, checker: { checker: {} }, gradient: { gradient: {} },
+ fresnel: { fresnel: {} }, vertexGroup: { vertexGroup: { name: 'edge' } }, noise: { noise: {} }, voronoi: { voronoi: {} }, wave: { wave: {} }, checker: { checker: {} }, gradient: { gradient: {} },
layer: { layer: { base: [0, 0, 0], top: [1, 1, 1], mask: 0.5 } }, hue: { hue: { color: [1, 0, 0], shift: 0.1 } }, curve: { curve: { value: 0.5, points: [[0, 0], [1, 1]] } },
};
for (const name of MATERIAL_GRAPH_OPERATORS) {
@@ -298,9 +298,9 @@ test('graph errors name the valid options, and scene_capabilities lists the node
}
});
-test('scene_capabilities says fresnel exists only as an emission factor and lists what is missing', () => {
+test('scene_capabilities says fresnel exists only as an emission factor and lists what is missing, vertexGroup no longer among it', () => {
const coordinates = AGENT_SCENE_CAPABILITIES.materialGraph.nodes.coordinates;
assert.match(coordinates, /In graphs: fresnel, only as an emission factor/);
- assert.match(coordinates, /Not in graphs: vertexGroup, AO, bevel, curvature/);
+ assert.match(coordinates, /Not in graphs: AO, bevel, curvature/);
assert.doesNotMatch(coordinates, /Not in graphs yet: AO, bevel, curvature, fresnel/);
});