Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
Add a periodic cellular (Worley) procedural layer (#312) (#329)
Matthew Kissinger558f23369ad4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a6732c70..05244f54 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,19 @@ does not publish a package.## Unreleased+- Procedural materials have a periodic cellular (Worley/Voronoi) layer (#312). `op: 'cellular'` is a+ V2 layer, so it also reaches V3 through `legacy-v2`: integer `cellsX`/`cellsY` per tile, a seed,+ per-axis `jitterX`/`jitterY` and `metricX`/`metricY`, and optional additive `weight`. Its `feature`+ maps onto `colorA`→`colorB`: `f1`, `f2`, `f2-f1`, a flat `cell` tone, `border` (joints opened by an+ order-independent hash of the two cell ids, with `borderOpen` and `borderWidth`) and `facet` (a+ tilted plane per cell, blended without a step, for height). The search is exact for every seed, by a+ stated bound that tests hold against an unbounded search. Golden pixel hashes pin each feature,+ because a V2 recipe hash has no compiler id. In V3 it is charged measured work, about 50 units per+ texel, instead of the flat 4: one default layer fits at 1024, and a `facet` or a stack is refused+ there and fits at 512. Existing recipes keep their hashes and compiler ids.+ `kiln discover --query voronoi` and `--query worley` find it, with `recipe:cellular-stone-v1` as a+ worked example. [Cellular layers](docs/rendering.md#cellular-layers) has the fields and the bound.+- The floating-parts warning and `GEO_PART_CONNECTIVITY` now see primitives merged into one mesh(#304). One mesh was one bounding box, so a welded component was never compared with the rest atany distance. Each mesh is now split into its connected components, through triangles and shareddiff --git a/dist/agent-run.mjs b/dist/agent-run.mjsindex 135372c4..bf94bd10 100644--- a/dist/agent-run.mjs+++ b/dist/agent-run.mjs@@ -3343,6 +3343,241 @@ var init_capture_cache = __esm(() => {init_capture_limits();});+// src/procedural-cellular.ts+function cellularSearchRadius(layer) {+ const { jitterX, jitterY, metricX, metricY, weight } = layer;+ const ownX = (1 + jitterX) / 2;+ const ownY = (1 + jitterY) / 2;+ const nearX = 1 + jitterX / 2;+ const nearY = 1 + jitterY / 2;+ const f1Bound = distanceOf(metricX * ownX, metricY * ownY) + weight;+ const f2Bound = Math.min(distanceOf(metricX * nearX, metricY * ownY), distanceOf(metricX * ownX, metricY * nearY)) + weight;+ const reach = layer.feature === "facet" ? Math.max(f2Bound, f1Bound + layer.facetBlend) : f2Bound;+ return {+ x: Math.max(1, Math.ceil(reach / metricX + ownX - 1)),+ y: Math.max(1, Math.ceil(reach / metricY + ownY - 1))+ };+}+function cellularWorkPerTexel(layer) {+ const { x, y } = cellularSearchRadius(layer);+ const search = 46 + Math.ceil((2 * x + 1) * (2 * y + 1) / 8) + (layer.weight > 0 ? 10 : 0);+ if (layer.feature === "border")+ return search + 8;+ if (layer.feature === "facet")+ return search + 32 + Math.ceil(layer.facetBlend * 30);+ return search;+}+function cellularFieldWork(layer) {+ return layer.cellsX * layer.cellsY * 12;+}+function cellularFieldBytes(layer) {+ return layer.cellsX * layer.cellsY * 48 + 4096;+}+function mix(value) {+ let h = value | 0;+ h ^= h >>> 16;+ h = Math.imul(h, 2246822507);+ h ^= h >>> 13;+ h = Math.imul(h, 3266489909);+ h ^= h >>> 16;+ return h >>> 0;+}+function centreOut(radius) {+ const order = new Int32Array(2 * radius + 1);+ for (let k = 1;k <= radius; k++) {+ order[2 * k - 1] = -k;+ order[2 * k] = k;+ }+ return order;+}+function wrapTable(cells, radius) {+ const table = new Int32Array(cells + 2 * radius + 1);+ for (let i = 0;i < table.length; i++) {+ table[i] = ((i - radius) % cells + cells) % cells;+ }+ return table;+}+function prepareCellularField(layer, radius = cellularSearchRadius(layer)) {+ const { cellsX, cellsY, seed, jitterX, jitterY, weight, feature } = layer;+ const count = cellsX * cellsY;+ const px = new Float64Array(count);+ const py = new Float64Array(count);+ const weights = new Float64Array(count);+ const tones = new Float64Array(feature === "cell" ? count : 0);+ const slopeX = new Float64Array(feature === "facet" ? count : 0);+ const slopeY = new Float64Array(feature === "facet" ? count : 0);+ for (let j = 0;j < cellsY; j++) {+ for (let i = 0;i < cellsX; i++) {+ const id = j * cellsX + i;+ const root = lattice(i, j, seed);+ px[id] = 0.5 + (stream(root, 0) - 0.5) * jitterX;+ py[id] = 0.5 + (stream(root, 1) - 0.5) * jitterY;+ weights[id] = stream(root, 2) * weight;+ if (feature === "cell")+ tones[id] = stream(root, 3);+ if (feature === "facet") {+ slopeX[id] = stream(root, 4) - 0.5;+ slopeY[id] = stream(root, 5) - 0.5;+ }+ }+ }+ return {+ layer,+ radius,+ px,+ py,+ weights,+ tones,+ slopeX,+ slopeY,+ wrapX: wrapTable(cellsX, radius.x),+ wrapY: wrapTable(cellsY, radius.y),+ orderX: centreOut(radius.x),+ orderY: centreOut(radius.y),+ squared: new Float64Array(2),+ found: new Int32Array(3)+ };+}+function scan(field, x, y) {+ const { layer, px, py, weights, wrapX, wrapY, orderX, orderY } = field;+ const { metricX, metricY, jitterX, jitterY, cellsX } = layer;+ const radiusX = field.radius.x;+ const radiusY = field.radius.y;+ const weighted = layer.weight > 0;+ const lowX = (1 - jitterX) / 2;+ const highX = (1 + jitterX) / 2;+ const lowY = (1 - jitterY) / 2;+ const highY = (1 + jitterY) / 2;+ const xi = Math.floor(x);+ const yi = Math.floor(y);+ const xf = x - xi;+ const yf = y - yi;+ let f1 = Infinity;+ let f2 = Infinity;+ let id1 = -1;+ let id2 = -1;+ let visited = 0;+ for (let n = 0;n < orderY.length; n++) {+ const dj = orderY[n];+ const gapY = dj > 0 ? (dj + lowY - yf) * metricY : dj < 0 ? (yf - dj - highY) * metricY : 0;+ const floorY = gapY * gapY;+ if (floorY >= f2)+ continue;+ const row = wrapY[yi + dj + radiusY] * cellsX;+ for (let m = 0;m < orderX.length; m++) {+ const di = orderX[m];+ const gapX = di > 0 ? (di + lowX - xf) * metricX : di < 0 ? (xf - di - highX) * metricX : 0;+ if (gapX * gapX + floorY >= f2)+ continue;+ const id = row + wrapX[xi + di + radiusX];+ visited++;+ const dx = (di + px[id] - xf) * metricX;+ const dy = (dj + py[id] - yf) * metricY;+ let d = dx * dx + dy * dy;+ if (d >= f2)+ continue;+ if (weighted) {+ const total = Math.sqrt(d) + weights[id];+ d = total * total;+ if (d >= f2)+ continue;+ }+ if (d < f1) {+ f2 = f1;+ id2 = id1;+ f1 = d;+ id1 = id;+ } else {+ f2 = d;+ id2 = id;+ }+ }+ }+ field.squared[0] = f1;+ field.squared[1] = f2;+ field.found[0] = id1;+ field.found[1] = id2;+ field.found[2] = visited;+}+function facetHeight(field, x, y, f1) {+ const { layer, px, py, weights, slopeX, slopeY, wrapX, wrapY, orderX, orderY } = field;+ const { metricX, metricY, jitterX, jitterY, cellsX, facetBlend, facetSlope } = layer;+ const radiusX = field.radius.x;+ const radiusY = field.radius.y;+ const limit = f1 + facetBlend;+ const limitSquared = limit * limit;+ const lowX = (1 - jitterX) / 2;+ const highX = (1 + jitterX) / 2;+ const lowY = (1 - jitterY) / 2;+ const highY = (1 + jitterY) / 2;+ const xi = Math.floor(x);+ const yi = Math.floor(y);+ const xf = x - xi;+ const yf = y - yi;+ let sum = 0;+ let total = 0;+ for (let n = 0;n < orderY.length; n++) {+ const dj = orderY[n];+ const gapY = dj > 0 ? (dj + lowY - yf) * metricY : dj < 0 ? (yf - dj - highY) * metricY : 0;+ const floorY = gapY * gapY;+ if (floorY >= limitSquared)+ continue;+ const row = wrapY[yi + dj + radiusY] * cellsX;+ for (let m = 0;m < orderX.length; m++) {+ const di = orderX[m];+ const gapX = di > 0 ? (di + lowX - xf) * metricX : di < 0 ? (xf - di - highX) * metricX : 0;+ if (gapX * gapX + floorY >= limitSquared)+ continue;+ const id = row + wrapX[xi + di + radiusX];+ const dx = (di + px[id] - xf) * metricX;+ const dy = (dj + py[id] - yf) * metricY;+ const d = Math.sqrt(dx * dx + dy * dy) + weights[id];+ if (d >= limit)+ continue;+ const falloff = 1 - (d - f1) / facetBlend;+ const blend = falloff * falloff;+ sum += blend * (slopeX[id] * dx + slopeY[id] * dy);+ total += blend;+ }+ }+ return Math.max(0, Math.min(1, 0.5 + facetSlope * sum / total));+}+function sampleCellularFeature(field, u, v) {+ const { layer } = field;+ const x = u * layer.cellsX;+ const y = v * layer.cellsY;+ scan(field, x, y);+ const f1 = Math.sqrt(field.squared[0]);+ switch (layer.feature) {+ case "f1":+ return Math.min(1, f1 / layer.range);+ case "f2":+ return Math.min(1, Math.sqrt(field.squared[1]) / layer.range);+ case "f2-f1":+ return Math.min(1, (Math.sqrt(field.squared[1]) - f1) / layer.range);+ case "cell":+ return Math.min(1, field.tones[field.found[0]] / layer.range);+ case "border": {+ const gap = (Math.sqrt(field.squared[1]) - f1) / layer.borderWidth;+ if (gap >= 1)+ return 0;+ const id1 = field.found[0];+ const id2 = field.found[1];+ const pair = lattice(Math.min(id1, id2), Math.max(id1, id2), layer.seed);+ if (mix(pair + 789269127) * TO_UNIT >= layer.borderOpen)+ return 0;+ return 1 - gap * gap * (3 - 2 * gap);+ }+ case "facet":+ return facetHeight(field, x, y, f1);+ }+}+var CELLULAR_FEATURES, MIN_CELLULAR_METRIC = 1, MAX_CELLULAR_METRIC = 4, MAX_CELLULAR_WEIGHT = 1, distanceOf = (x, y) => Math.sqrt(x * x + y * y), TO_UNIT, lattice = (x, y, seed) => Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(seed, 1274126177) | 0, stream = (root, index) => mix(root + Math.imul(index + 1, 2654435769)) * TO_UNIT;+var init_procedural_cellular = __esm(() => {+ CELLULAR_FEATURES = ["f1", "f2", "f2-f1", "cell", "border", "facet"];+ TO_UNIT = 1 / 4294967296;+});+// src/texture-contract.tsvar TEXTURE_USAGES;var init_texture_contract = __esm(() => {@@ -3578,6 +3813,23 @@ function blend(record, path) {}return value;}+function featureControl(record, path, feature, control, owners) {+ const { name, fallback, min, max } = control;+ const value = finite3(record[name], `${path}.${name}`, fallback, min, max);+ if (value !== fallback && !owners.includes(feature)) {+ const noun = owners.length > 1 ? "features" : "feature";+ const named = owners.length > 1 ? owners.join(", ") : JSON.stringify(owners[0]);+ throw new ProceduralTextureError(`${path}.${name} applies only to ${noun} ${named}, not ${JSON.stringify(feature)}. Remove it or change feature.`);+ }+ return value;+}+function cellularFeature(value, path) {+ const feature = value ?? "f1";+ if (!CELLULAR_FEATURES.includes(feature)) {+ throw new ProceduralTextureError(`${path}.feature ${JSON.stringify(feature)} is not one of ${CELLULAR_FEATURES.join(", ")}.`);+ }+ return feature;+}function canonicalLayer(value, index) {const path = `proceduralTexture.layers[${index}]`;const record = strictRecord(value, path);@@ -3646,6 +3898,50 @@ function canonicalLayer(value, index) {seed: integer(record["seed"], `${path}.seed`, 0, -2147483648, 2147483647),...common};+ case "cellular": {+ assertKeys(record, [+ "op",+ "colorA",+ "colorB",+ "cellsX",+ "cellsY",+ "seed",+ "jitterX",+ "jitterY",+ "metricX",+ "metricY",+ "weight",+ "feature",+ "range",+ "borderOpen",+ "borderWidth",+ "facetSlope",+ "facetBlend",+ "blend",+ "opacity"+ ], path);+ const feature = cellularFeature(record["feature"], path);+ return {+ op,+ colorA: color(record["colorA"], `${path}.colorA`),+ colorB: color(record["colorB"], `${path}.colorB`),+ cellsX: integer(record["cellsX"], `${path}.cellsX`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ cellsY: integer(record["cellsY"], `${path}.cellsY`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ seed: integer(record["seed"], `${path}.seed`, 0, -2147483648, 2147483647),+ jitterX: unit(record["jitterX"], `${path}.jitterX`, 1),+ jitterY: unit(record["jitterY"], `${path}.jitterY`, 1),+ metricX: finite3(record["metricX"], `${path}.metricX`, 1, MIN_CELLULAR_METRIC, MAX_CELLULAR_METRIC),+ metricY: finite3(record["metricY"], `${path}.metricY`, 1, MIN_CELLULAR_METRIC, MAX_CELLULAR_METRIC),+ weight: finite3(record["weight"], `${path}.weight`, 0, 0, MAX_CELLULAR_WEIGHT),+ feature,+ range: featureControl(record, path, feature, { name: "range", fallback: 1, min: 0.01, max: 8 }, ["f1", "f2", "f2-f1", "cell"]),+ borderOpen: featureControl(record, path, feature, { name: "borderOpen", fallback: 0.5, min: 0, max: 1 }, ["border"]),+ borderWidth: featureControl(record, path, feature, { name: "borderWidth", fallback: 0.05, min: 0.001, max: 1 }, ["border"]),+ facetSlope: featureControl(record, path, feature, { name: "facetSlope", fallback: 0.5, min: 0, max: 1 }, ["facet"]),+ facetBlend: featureControl(record, path, feature, { name: "facetBlend", fallback: 0.1, min: 0.001, max: 1 }, ["facet"]),+ ...common+ };+ }default:throw new ProceduralTextureError(`${path}.op is unsupported.`);}@@ -3855,6 +4151,7 @@ function canonicalizePortableMaterialSpecV2(input) {}var MAX_PROCEDURAL_SIZE = 1024, MIN_PROCEDURAL_SIZE = 4, MAX_PROCEDURAL_LAYERS = 8, MAX_NOISE_OCTAVES = 6, MAX_PROCEDURAL_NAME_LENGTH = 80, MAX_PROCEDURAL_PATTERN_COUNT = 256, MAX_PORTABLE_MATERIAL_TEXTURES = 5, MAX_PORTABLE_MATERIAL_TEXELS, ProceduralTextureError, OPS, BLENDS, FORBIDDEN_KEYS, SHA256_K, rotateRight = (value, bits) => value >>> bits | value << 32 - bits, MATERIAL_TEXTURE_USAGE;var init_procedural_material_v2 = __esm(() => {+ init_procedural_cellular();init_texture_contract();init_authoring_diagnostic();MAX_PORTABLE_MATERIAL_TEXELS = 4 * 1024 * 1024;@@ -3864,7 +4161,7 @@ var init_procedural_material_v2 = __esm(() => {this.name = "ProceduralTextureError";}};- OPS = ["solid", "checker", "stripes", "gradient", "bricks", "noise"];+ OPS = ["solid", "checker", "stripes", "gradient", "bricks", "noise", "cellular"];BLENDS = ["normal", "multiply", "screen", "overlay"];FORBIDDEN_KEYS = new Set(["__proto__", "prototype", "constructor"]);SHA256_K = new Uint32Array([@@ -4131,8 +4428,14 @@ function admitProceduralTextureSpecV3(input) {const spec = canonicalizeProceduralTextureSpecV2(legacyRecord);if (spec.size !== width || spec.size !== height || spec.usage !== usage)fail(`${path} legacy-v2 dimensions and usage must match the V3 surface.`);- work += texels * (1 + spec.layers.reduce((cost, layer) => cost + (layer.op === "noise" ? layer.octaves * 16 : 4), 0));+ work += texels * (1 + spec.layers.reduce((cost, layer) => cost + (layer.op === "noise" ? layer.octaves * 16 : layer.op === "cellular" ? cellularWorkPerTexel(layer) : 4), 0));legacyTransientBytes += texels * 4;+ for (const layer of spec.layers) {+ if (layer.op !== "cellular")+ continue;+ work += cellularFieldWork(layer);+ legacyTransientBytes += cellularFieldBytes(layer);+ }return {op: "legacy-v2",spec,@@ -4238,6 +4541,7 @@ ${canonicalProceduralTextureJsonV3(input)}`)}`;}var PROCEDURAL_TEXTURE_V3_COMPILER_ID = "kiln.procedural-rgba.v3.1", MAX_PROCEDURAL_V3_EDGE = 1024, MAX_PROCEDURAL_V3_TEXELS = 1048576, MAX_PROCEDURAL_V3_OPERATIONS = 64, MAX_PROCEDURAL_V3_VERTICES = 64, MAX_PROCEDURAL_V3_STAMPS = 256, MAX_PROCEDURAL_V3_PALETTE = 32, MAX_PROCEDURAL_V3_WORK = 64000000, MAX_PROCEDURAL_V3_TRANSIENT_BYTES, forbidden;var init_procedural_texture_v3_contract = __esm(() => {+ init_procedural_cellular();init_procedural_material_v2();init_texture_contract();MAX_PROCEDURAL_V3_TRANSIENT_BYTES = 64 * 1024 * 1024;@@ -4966,6 +5270,7 @@ var init_material_authoring_schema = __esm(() => {init_procedural_material_v2();init_procedural_texture_v3_contract();init_texture_atlas_contract();+ init_procedural_cellular();init_portable_sampler();init_texture_contract();canonicalLegacyV2FieldSchema = (() => {@@ -5015,6 +5320,26 @@ var init_material_authoring_schema = __esm(() => {octaves: z4.number().int().min(1).max(MAX_NOISE_OCTAVES),seed: z4.number().int().min(-2147483648).max(2147483647),...common+ }).strict(),+ z4.object({+ op: z4.literal("cellular"),+ colorA: color,+ colorB: color,+ cellsX: count,+ cellsY: count,+ seed: z4.number().int().min(-2147483648).max(2147483647),+ jitterX: unit,+ jitterY: unit,+ metricX: z4.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC),+ metricY: z4.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC),+ weight: z4.number().min(0).max(MAX_CELLULAR_WEIGHT),+ feature: z4.enum(CELLULAR_FEATURES),+ range: z4.number().min(0.01).max(8),+ borderOpen: unit,+ borderWidth: z4.number().min(0.001).max(1),+ facetSlope: unit,+ facetBlend: z4.number().min(0.001).max(1),+ ...common}).strict()])).min(1).max(MAX_PROCEDURAL_LAYERS)}).strict();@@ -5249,6 +5574,7 @@ var MATERIAL_LIBRARY_LIMITS, MATERIAL_LIBRARY_SLOTS, MATERIAL_LIBRARY_USAGE, slovar init_material_library = __esm(() => {init_procedural_material_v2();init_procedural_texture_v3_contract();+ init_procedural_cellular();init_portable_sampler();init_texture_atlas_contract();init_material_authoring_schema();@@ -5394,6 +5720,26 @@ var init_material_library = __esm(() => {octaves: z5.number().int().min(1).max(6).default(3),seed: z5.number().int().min(-2147483648).max(2147483647).default(0),...layerCommon+ }).strict(),+ z5.object({+ op: z5.literal("cellular"),+ colorA: color2,+ colorB: color2,+ cellsX: count2.default(8),+ cellsY: count2.default(8),+ seed: z5.number().int().min(-2147483648).max(2147483647).default(0),+ jitterX: z5.number().min(0).max(1).default(1),+ jitterY: z5.number().min(0).max(1).default(1),+ metricX: z5.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC).default(1),+ metricY: z5.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC).default(1),+ weight: z5.number().min(0).max(MAX_CELLULAR_WEIGHT).default(0),+ feature: z5.enum(CELLULAR_FEATURES).default("f1"),+ range: z5.number().min(0.01).max(8).default(1),+ borderOpen: z5.number().min(0).max(1).default(0.5),+ borderWidth: z5.number().min(0.001).max(1).default(0.05),+ facetSlope: z5.number().min(0).max(1).default(0.5),+ facetBlend: z5.number().min(0.001).max(1).default(0.1),+ ...layerCommon}).strict()])).min(1).max(8)}).strict();@@ -8663,7 +9009,7 @@ const mesh = new THREE.Mesh(unwrapped, bakedPbr);`category: "textures",description: "Builds a repeat-wrapped deterministic texture without an image file. V2 retains opaque pattern layers. Explicit V3 adds rectangular RGBA, pixel shapes/masks, color palettes and seeded stamps. Repeat wrapping alone does not prove seamless pixels. Baked to PNG and embedded in the GLB automatically.",example: "const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });",- promptNotes: "V2 layer fields by op: solid: { color }; checker: { colorA, colorB, squares? }; stripes: { colorA, colorB, count?, angleDeg? }; gradient: { from, to, angleDeg? }; bricks: { brick, mortar, rows?, cols?, mortarWidth?: 0..1 (fraction of a brick cell, default 0.06), stagger?: 0..1 (row offset fraction, default 0.5) }; noise: { colorA, colorB, scale?, octaves?, seed? }. V2 blend normal|multiply|screen|overlay; opacity 0..1; max 8 layers, counts 1..256, octaves 1..6. V3 operations: paint {shape,rgba,opacity?}; mask {shape,alpha?,invert?}; stamps {shape,rgba,count,seed,area,periodic?,opacity?}; legacy-v2 {spec,alpha?,opacity?} delegates an explicit V2 recipe with matching square dimensions/usage. RGBA is four bytes; V3 opacity/alpha are bytes0..255 default255. Shape kinds: rectangle/ellipse {x,y,width,height}; polygon {points:[[x,y],...]}; line {from:[x,y],to:[x,y],width}. Coordinates are integer pixel edges; centers define binary coverage, round line caps. Mask clears outside; invert keeps outside instead. area {x,y,width,height} sets seeded stamp translation offsets; periodic:true wraps copies explicitly. V3 background defaults transparent black, max64 ops,64 polygon vertices,256 expanded stamps (periodic counts9),32 palette colors,64million estimated work including edges. palette {colors:[RGB integers],dither?:'none'|'bayer4'} and stamps are albedo/emissive only. Zero alpha normalizes RGB to0. Sampler defaults remain repeat/linear/mips; alphaMode belongs to pbrMaterial. Sync; strict JSON rejects unknown/prototype fields and accessors. See docs/procedural-surfaces-v3.md for exact rounding and bounds."+ promptNotes: "V2 layer fields by op: solid: { color }; checker: { colorA, colorB, squares? }; stripes: { colorA, colorB, count?, angleDeg? }; gradient: { from, to, angleDeg? }; bricks: { brick, mortar, rows?, cols?, mortarWidth?: 0..1 (fraction of a brick cell, default 0.06), stagger?: 0..1 (row offset fraction, default 0.5) }; noise: { colorA, colorB, scale?, octaves?, seed? }; cellular: { colorA, colorB, cellsX?, cellsY?: 1..256 cells per tile, default 8; seed?; jitterX?, jitterY?: 0..1, default 1; metricX?, metricY?: 1..4, default 1, a larger metric thins joints across that axis; weight?: 0..1 additive cell weight drawn from the seed, default 0, curves borders and varies cell size; feature?: 'f1'|'f2'|'f2-f1'|'cell'|'border'|'facet', default f1; range?: 0.01..8 (f1, f2, f2-f1 and cell: the value that reaches colorB, default 1; below 1 on cell it leaves a sparse population of toned cells); borderOpen?: 0..1, default 0.5, borderWidth?: 0.001..1, default 0.05 (border: colorB in the opened joints); facetSlope?: 0..1, default 0.5, facetBlend?: 0.001..1, default 0.1 (facet: a tilted plane per cell, blended across borders, for height) }. A field the chosen feature ignores is an error. Reuse one layout and seed across layers and maps so joints line up. V2 blend normal|multiply|screen|overlay; opacity 0..1; max 8 layers, counts 1..256, octaves 1..6. V3 operations: paint {shape,rgba,opacity?}; mask {shape,alpha?,invert?}; stamps {shape,rgba,count,seed,area,periodic?,opacity?}; legacy-v2 {spec,alpha?,opacity?} delegates an explicit V2 recipe with matching square dimensions/usage. RGBA is four bytes; V3 opacity/alpha are bytes0..255 default255. Shape kinds: rectangle/ellipse {x,y,width,height}; polygon {points:[[x,y],...]}; line {from:[x,y],to:[x,y],width}. Coordinates are integer pixel edges; centers define binary coverage, round line caps. Mask clears outside; invert keeps outside instead. area {x,y,width,height} sets seeded stamp translation offsets; periodic:true wraps copies explicitly. V3 background defaults transparent black, max64 ops,64 polygon vertices,256 expanded stamps (periodic counts9),32 palette colors,64million estimated work including edges. palette {colors:[RGB integers],dither?:'none'|'bayer4'} and stamps are albedo/emissive only. Zero alpha normalizes RGB to0. Sampler defaults remain repeat/linear/mips; alphaMode belongs to pbrMaterial. Sync; strict JSON rejects unknown/prototype fields and accessors. See docs/procedural-surfaces-v3.md for exact rounding and bounds."},{name: "textureAtlas",@@ -10480,7 +10826,7 @@ function project(u, v, angleDeg) {const a = angleDeg * Math.PI / 180;return (u - 0.5) * Math.cos(a) + (v - 0.5) * Math.sin(a) + 0.5;}-function evalLayer(layer, u, v) {+function evalLayer(layer, u, v, field) {switch (layer.op) {case "solid":return rgbOf(layer.color);@@ -10513,6 +10859,12 @@ function evalLayer(layer, u, v) {const b = rgbOf(layer.colorB);return [lerp(a[0], b[0], n), lerp(a[1], b[1], n), lerp(a[2], b[2], n)];}+ case "cellular": {+ const n = sampleCellularFeature(field, u, v);+ const a = rgbOf(layer.colorA);+ const b = rgbOf(layer.colorB);+ return [lerp(a[0], b[0], n), lerp(a[1], b[1], n), lerp(a[2], b[2], n)];+ }}}function blendChannel(mode, base, top) {@@ -10538,6 +10890,7 @@ function compileProceduralTextureSpecV2(input) {const spec = canonicalizeProceduralTextureSpecV2(input);const { size, layers } = spec;const data = new Uint8Array(size * size * 4);+ const fields = layers.map((layer) => layer.op === "cellular" ? prepareCellularField(layer) : undefined);for (let y = 0;y < size; y++) {const v = (y + 0.5) / size;for (let x = 0;x < size; x++) {@@ -10546,7 +10899,7 @@ function compileProceduralTextureSpecV2(input) {let g = 0;let b = 0;for (const [i, layer] of layers.entries()) {- const [lr, lg, lb] = evalLayer(layer, u, v);+ const [lr, lg, lb] = evalLayer(layer, u, v, fields[i]);if (i === 0) {r = lr;g = lg;@@ -10577,6 +10930,7 @@ var smoothstep = (t) => t * t * (3 - 2 * t), rgbOf = (color) => [color & 255], lerp = (a, b, t) => a + (b - a) * t;var init_procedural_texture_v2_compiler = __esm(() => {+ init_procedural_cellular();init_procedural_material_v2();});@@ -45609,20 +45963,28 @@ define2("proceduralTexture", {"V3 paint/mask use integer pixel-edge shapes with binary center coverage and fixed integer source-over rounding. A mask clears outside its shape; invert keeps outside. Zero-alpha pixels are transparent black.","V3 color-only palette colors are 1..32 RGB integers, optional fixed Bayer4 dither. Stamps (any usage) use bounded Xorshift32 seed/area placement; periodic wrapping is explicit and at most 256 expanded copies. Legacy-v2 layers delegate unchanged square V2 patterns with matching usage.","Pattern counts 1..256 and noise octaves 1..6; seeded patterns are deterministic.",+ "The cellular layer is a periodic Worley/Voronoi field: integer cellsX/cellsY per tile, per-axis jitter, an anisotropic metric, optional additive weights, and a feature (f1, f2, f2-f1, cell, border, facet) mapped onto colorA..colorB. It tiles exactly at any size.","For stripes and gradient, angleDeg rotates the direction of color variation in UV space about the image center. At 0 degrees colors vary across U: stripe bands run along V. At 90 degrees colors vary across V: bands run along U. This does not rotate the mesh UVs.","Stripes count is the number of alternating bands across one unit of the projected coordinate, not the number of colorA/colorB pairs. Gradient runs from its from color to its to color along that coordinate and clamps outside 0..1.","Unknown keys, callbacks, paths, URLs and shader source are rejected."],preservation: ["Produces repeat-wrapped encoded texture content; color space follows usage."],- cost: "V2 retains pixel/layer budgets. V3 preflights at most 1,048,576 texels, 64million work units including polygon edges, palette comparisons and periodic copies, and 64MiB transient bytes."+ cost: "V2 retains pixel/layer budgets. V3 preflights at most 1,048,576 texels, 64million work units including polygon edges, palette comparisons and periodic copies, and 64MiB transient bytes. A cellular layer through legacy-v2 is charged about 50 units per texel, so one default layer fits at 1024 and a stack needs a smaller size."}, {references: ["src/procedural-texture.ts","src/procedural-texture-v3-contract.ts","docs/procedural-surfaces-v3.md"],- tags: ["texture", "procedural", "deterministic"],- aliases: ["generated texture", "noise texture", "layered pattern"],+ tags: ["texture", "procedural", "deterministic", "cellular", "Worley", "Voronoi"],+ aliases: [+ "generated texture",+ "noise texture",+ "layered pattern",+ "cellular noise",+ "worley noise",+ "voronoi noise"+ ],intents: ["generate a repeatable texture without external image files"],limitations: ["Repeat wrapping does not guarantee matching edge colors. Odd stripe counts, angled patterns and nonconstant gradients can show seams; inspect the chosen pattern at its repeat boundaries."@@ -46634,6 +46996,101 @@ function build() {"Verify the destination preserves texture direction, seams and cap treatment at useful viewing distances; a CPU geometry sheet cannot establish these."]}+ },+ {+ version: "kiln.catalog-entry.v1",+ id: "recipe:cellular-stone-v1",+ kind: "recipe",+ name: "Cellular stone: rubble, crystals and fractured rock",+ summary: "Build tiling stone from the periodic cellular (Worley/Voronoi) layer: one flat tone per stone or crystal, joints from the border distance, cracks opened per border, and faceted height for a derived normal. The example is bedded fractured rock; adapt the layout and features to the stone.",+ family: "materials",+ tags: [+ "cellular",+ "Worley",+ "Voronoi",+ "stone",+ "rock",+ "rubble",+ "granite",+ "tiling",+ "cracks"+ ],+ aliases: [+ "voronoi noise",+ "worley noise",+ "cellular noise",+ "crazy paving",+ "irregular stones",+ "crystal grain",+ "open joints"+ ],+ intents: [+ "make irregular rubble stones that tile",+ "make fractured rock with open and closed cracks",+ "give each crystal or stone its own tone"+ ],+ stability: "experimental",+ related: [+ { id: "operation:proceduralTexture", relation: "prerequisite" },+ { id: "operation:normalMapFromHeight", relation: "prerequisite" },+ { id: "operation:pbrMaterial", relation: "prerequisite" }+ ],+ references: ["src/procedural-cellular.ts", "docs/procedural-surfaces-v3.md"],+ limitations: [+ "The example is a starting layout, not a finished rock. Appearance needs GPU review at the viewing distance: a closed isotropic net of cells reads as crazy paving, however exact it is.",+ "The cell feature has hard edges with no antialiasing. A flat tone change with no joint over it reads as a pasted patch close up, so keep tonal contrast low between cells that share a closed border, or increase the texture size.",+ "Border width is in metric units, so a larger metric on one axis thins the joints that cross that axis. A strong metric gives hairline bed joints beside soft vertical ones.",+ "One saved texture repeats visibly at a distance. Tiling only removes the seam; it does not hide the period."+ ],+ recipe: {+ prerequisites: [+ "operation:proceduralTexture",+ "operation:normalMapFromHeight",+ "operation:pbrMaterial"+ ],+ steps: [+ "Choose the layout once: cellsX and cellsY per tile, seed, jitter, metric and weight. Share that object across every cellular layer of every map, so tone, joints and height agree.",+ "For beds, use low jitterY and a metricY above 1. For crystals, use full jitter, equal metrics and some weight to vary the crystal size.",+ "Colour: start from the cell feature for a flat tone per stone, overlay noise for the surface, and multiply a dark f2-f1 or border layer over it. On border, borderOpen below 1 leaves closed joints, so cracks end in T-junctions.",+ "Height: use f2-f1 for pillowed stones or facet for tilted fracture planes, multiply border over it for open cracks, and derive the normal from that height.",+ "Review on the GPU route at the intended distance and at a raking angle, across at least two repeats."+ ],+ example: `const meta = { name: 'CellularFracturedRock' };+function build() {+ const root = createRoot(meta.name);+ const beds = { cellsX: 6, cellsY: 12, seed: 83, jitterX: 0.9, jitterY: 0.45, metricY: 2, weight: 0.25 };+ const facets = { ...beds, feature: 'facet', facetSlope: 0.9, facetBlend: 0.3 };+ const joints = { ...beds, feature: 'border', borderOpen: 0.5, borderWidth: 0.06, blend: 'multiply' };+ const albedo = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', layers: [+ { op: 'cellular', ...beds, feature: 'cell', colorA: 0x6e6b65, colorB: 0x827e76 },+ { op: 'noise', colorA: 0x38362f, colorB: 0xc4c0b4, scale: 24, octaves: 5, seed: 84, blend: 'overlay', opacity: 0.6 },+ { op: 'cellular', ...facets, colorA: 0x606060, colorB: 0xffffff, blend: 'multiply', opacity: 0.5 },+ { op: 'cellular', ...joints, colorA: 0xffffff, colorB: 0x16130f },+ ] });+ const height = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', layers: [+ { op: 'cellular', ...facets, colorA: 0x000000, colorB: 0xffffff },+ { op: 'cellular', ...joints, colorA: 0xffffff, colorB: 0x000000 },+ ] });+ const packed = (roughness) => (255 << 16) | (roughness << 8);+ const metallicRoughness = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'metallicRoughness', layers: [+ { op: 'cellular', ...beds, feature: 'cell', colorA: packed(180), colorB: packed(235) },+ ] });+ const material = pbrMaterial({ albedo, normal: normalMapFromHeight(height, { strength: 5 }),+ metallicRoughness, roughness: 1, metalness: 1 });+ createPart('RockFace', planeGeo(2, 2), material, { parent: root });+ return root;+}`,+ adaptations: [+ "Rubble: cellsX 7, cellsY 11, jitterX 0.8, jitterY 0.3, metricY 1.5, weight 0.2. Cell for tone, a multiplied dark f2-f1 with range 0.14 for the joints, f2-f1 with range 0.42 for a pillowed height.",+ "Granite: full jitter, equal metrics, 64 cells and weight 0.5 for quartz. Add feldspar and biotite on other grids and seeds, with range on cell to leave a sparse population: range 0.16 keeps about a sixth of the cells dark.",+ "To save a reusable material, put these recipes in a material draft with derive normal-from-height on the normal slot, then export maps for a destination that takes plain images."+ ],+ checks: [+ "Read viewFidelity. A CPU geometry view cannot judge this: only a material-faithful GPU view shows whether the surface reads as stone.",+ "Look for the plaid and crazy-paving failures directly: straight joints running the whole tile, or every polygon closed and the same size.",+ "Numerically, each exported map should differ across its wrap edge by no more than interior neighbouring texels do. Repeat at two sizes, because a derived normal is resampled rather than regenerated."+ ]+ }}];diff --git a/dist/build.json b/dist/build.jsonindex 447b40b9..13fe130d 100644--- a/dist/build.json+++ b/dist/build.json@@ -2,10 +2,10 @@"schemaVersion": 1,"entries": {"worker": {- "identity": "sha256:fba6d13661be1de1d146fbaa6aa3e80b8ca6660614281617a516b26f4389bca8",+ "identity": "sha256:6e016f7b365827d8fda0fae3a864c3da4f1cde1a26ef6042e4c8c2d23367551c","engineVersion": "1.6.0","toolchain": "[email protected]",- "sourceHash": "3bfb596b14cd4f2ea462ffa606b90e88f1aafc24872176d4c21edb4665cd6d11",+ "sourceHash": "fbe285f483135cb3d6dc85650a05061094675e846c547a0b8667bb5121053ec0","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -37,13 +37,13 @@},"target": "node","file": "evaluator-worker.mjs",- "bundleHash": "sha256:eaba26a5f78ba7430675224d4f690344c4bafb0feeda387dc3831bbae80c7cca"+ "bundleHash": "sha256:df18308c79fd90fc2ab8af54027d160d75048c36e4b7e9f75aaa901be9060b03"},"agent-run": {- "identity": "sha256:fba6d13661be1de1d146fbaa6aa3e80b8ca6660614281617a516b26f4389bca8",+ "identity": "sha256:6e016f7b365827d8fda0fae3a864c3da4f1cde1a26ef6042e4c8c2d23367551c","engineVersion": "1.6.0","toolchain": "[email protected]",- "sourceHash": "3bfb596b14cd4f2ea462ffa606b90e88f1aafc24872176d4c21edb4665cd6d11",+ "sourceHash": "fbe285f483135cb3d6dc85650a05061094675e846c547a0b8667bb5121053ec0","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -75,13 +75,13 @@},"target": "node","file": "agent-run.mjs",- "bundleHash": "sha256:0865874dc38389b1af4f1327b6badea53c73c1f4e1f4ee69a7fc2088813ea6ff"+ "bundleHash": "sha256:c8336be791961778887f5757d0b62923f93631a139b74527ecdd7e21d7d87285"},"agent-providers": {- "identity": "sha256:fba6d13661be1de1d146fbaa6aa3e80b8ca6660614281617a516b26f4389bca8",+ "identity": "sha256:6e016f7b365827d8fda0fae3a864c3da4f1cde1a26ef6042e4c8c2d23367551c","engineVersion": "1.6.0","toolchain": "[email protected]",- "sourceHash": "3bfb596b14cd4f2ea462ffa606b90e88f1aafc24872176d4c21edb4665cd6d11",+ "sourceHash": "fbe285f483135cb3d6dc85650a05061094675e846c547a0b8667bb5121053ec0","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -116,10 +116,10 @@"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"},"mcp": {- "identity": "sha256:fba6d13661be1de1d146fbaa6aa3e80b8ca6660614281617a516b26f4389bca8",+ "identity": "sha256:6e016f7b365827d8fda0fae3a864c3da4f1cde1a26ef6042e4c8c2d23367551c","engineVersion": "1.6.0","toolchain": "[email protected]",- "sourceHash": "3bfb596b14cd4f2ea462ffa606b90e88f1aafc24872176d4c21edb4665cd6d11",+ "sourceHash": "fbe285f483135cb3d6dc85650a05061094675e846c547a0b8667bb5121053ec0","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -154,10 +154,10 @@"bundleHash": "sha256:ec8ccc0d1f25184650191131ad5dcd25e1434408f92bdf8d2ef150e1bf5f266b"},"cli": {- "identity": "sha256:fba6d13661be1de1d146fbaa6aa3e80b8ca6660614281617a516b26f4389bca8",+ "identity": "sha256:6e016f7b365827d8fda0fae3a864c3da4f1cde1a26ef6042e4c8c2d23367551c","engineVersion": "1.6.0","toolchain": "[email protected]",- "sourceHash": "3bfb596b14cd4f2ea462ffa606b90e88f1aafc24872176d4c21edb4665cd6d11",+ "sourceHash": "fbe285f483135cb3d6dc85650a05061094675e846c547a0b8667bb5121053ec0","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -189,13 +189,13 @@},"target": "node","file": "cli.mjs",- "bundleHash": "sha256:3edbacda3cec0596595bb93b02e34b32dd057aa8f7d2dae60b69597853a768e4"+ "bundleHash": "sha256:be27eea12bbb89c4ad325eaf66417c8cb6a1d010735af14cd958f58233e59228"},"engine": {- "identity": "sha256:fba6d13661be1de1d146fbaa6aa3e80b8ca6660614281617a516b26f4389bca8",+ "identity": "sha256:6e016f7b365827d8fda0fae3a864c3da4f1cde1a26ef6042e4c8c2d23367551c","engineVersion": "1.6.0","toolchain": "[email protected]",- "sourceHash": "3bfb596b14cd4f2ea462ffa606b90e88f1aafc24872176d4c21edb4665cd6d11",+ "sourceHash": "fbe285f483135cb3d6dc85650a05061094675e846c547a0b8667bb5121053ec0","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -227,7 +227,7 @@},"target": "node","file": "mcp-engine.mjs",- "bundleHash": "sha256:d2fc8cf72cb518bbc07fea0abf3c440f99c2d805cee100590e6e0361789fb6fe"+ "bundleHash": "sha256:1b307454900dcfcdd168c6619a8a6abe1b21b06d96d125bdf19483e6bf0db3bd"}}}diff --git a/dist/cli.mjs b/dist/cli.mjsindex faaaef33..1cf763b8 100644--- a/dist/cli.mjs+++ b/dist/cli.mjs@@ -2693,6 +2693,241 @@ async function renameDirectoryAtomically(source, destination, controls = {}) {}var init_atomic_directory = () => {};+// src/procedural-cellular.ts+function cellularSearchRadius(layer) {+ const { jitterX, jitterY, metricX, metricY, weight } = layer;+ const ownX = (1 + jitterX) / 2;+ const ownY = (1 + jitterY) / 2;+ const nearX = 1 + jitterX / 2;+ const nearY = 1 + jitterY / 2;+ const f1Bound = distanceOf(metricX * ownX, metricY * ownY) + weight;+ const f2Bound = Math.min(distanceOf(metricX * nearX, metricY * ownY), distanceOf(metricX * ownX, metricY * nearY)) + weight;+ const reach = layer.feature === "facet" ? Math.max(f2Bound, f1Bound + layer.facetBlend) : f2Bound;+ return {+ x: Math.max(1, Math.ceil(reach / metricX + ownX - 1)),+ y: Math.max(1, Math.ceil(reach / metricY + ownY - 1))+ };+}+function cellularWorkPerTexel(layer) {+ const { x, y } = cellularSearchRadius(layer);+ const search = 46 + Math.ceil((2 * x + 1) * (2 * y + 1) / 8) + (layer.weight > 0 ? 10 : 0);+ if (layer.feature === "border")+ return search + 8;+ if (layer.feature === "facet")+ return search + 32 + Math.ceil(layer.facetBlend * 30);+ return search;+}+function cellularFieldWork(layer) {+ return layer.cellsX * layer.cellsY * 12;+}+function cellularFieldBytes(layer) {+ return layer.cellsX * layer.cellsY * 48 + 4096;+}+function mix(value) {+ let h = value | 0;+ h ^= h >>> 16;+ h = Math.imul(h, 2246822507);+ h ^= h >>> 13;+ h = Math.imul(h, 3266489909);+ h ^= h >>> 16;+ return h >>> 0;+}+function centreOut(radius) {+ const order = new Int32Array(2 * radius + 1);+ for (let k = 1;k <= radius; k++) {+ order[2 * k - 1] = -k;+ order[2 * k] = k;+ }+ return order;+}+function wrapTable(cells, radius) {+ const table = new Int32Array(cells + 2 * radius + 1);+ for (let i = 0;i < table.length; i++) {+ table[i] = ((i - radius) % cells + cells) % cells;+ }+ return table;+}+function prepareCellularField(layer, radius = cellularSearchRadius(layer)) {+ const { cellsX, cellsY, seed, jitterX, jitterY, weight, feature } = layer;+ const count = cellsX * cellsY;+ const px = new Float64Array(count);+ const py = new Float64Array(count);+ const weights = new Float64Array(count);+ const tones = new Float64Array(feature === "cell" ? count : 0);+ const slopeX = new Float64Array(feature === "facet" ? count : 0);+ const slopeY = new Float64Array(feature === "facet" ? count : 0);+ for (let j = 0;j < cellsY; j++) {+ for (let i = 0;i < cellsX; i++) {+ const id = j * cellsX + i;+ const root = lattice(i, j, seed);+ px[id] = 0.5 + (stream(root, 0) - 0.5) * jitterX;+ py[id] = 0.5 + (stream(root, 1) - 0.5) * jitterY;+ weights[id] = stream(root, 2) * weight;+ if (feature === "cell")+ tones[id] = stream(root, 3);+ if (feature === "facet") {+ slopeX[id] = stream(root, 4) - 0.5;+ slopeY[id] = stream(root, 5) - 0.5;+ }+ }+ }+ return {+ layer,+ radius,+ px,+ py,+ weights,+ tones,+ slopeX,+ slopeY,+ wrapX: wrapTable(cellsX, radius.x),+ wrapY: wrapTable(cellsY, radius.y),+ orderX: centreOut(radius.x),+ orderY: centreOut(radius.y),+ squared: new Float64Array(2),+ found: new Int32Array(3)+ };+}+function scan(field, x, y) {+ const { layer, px, py, weights, wrapX, wrapY, orderX, orderY } = field;+ const { metricX, metricY, jitterX, jitterY, cellsX } = layer;+ const radiusX = field.radius.x;+ const radiusY = field.radius.y;+ const weighted = layer.weight > 0;+ const lowX = (1 - jitterX) / 2;+ const highX = (1 + jitterX) / 2;+ const lowY = (1 - jitterY) / 2;+ const highY = (1 + jitterY) / 2;+ const xi = Math.floor(x);+ const yi = Math.floor(y);+ const xf = x - xi;+ const yf = y - yi;+ let f1 = Infinity;+ let f2 = Infinity;+ let id1 = -1;+ let id2 = -1;+ let visited = 0;+ for (let n = 0;n < orderY.length; n++) {+ const dj = orderY[n];+ const gapY = dj > 0 ? (dj + lowY - yf) * metricY : dj < 0 ? (yf - dj - highY) * metricY : 0;+ const floorY = gapY * gapY;+ if (floorY >= f2)+ continue;+ const row = wrapY[yi + dj + radiusY] * cellsX;+ for (let m = 0;m < orderX.length; m++) {+ const di = orderX[m];+ const gapX = di > 0 ? (di + lowX - xf) * metricX : di < 0 ? (xf - di - highX) * metricX : 0;+ if (gapX * gapX + floorY >= f2)+ continue;+ const id = row + wrapX[xi + di + radiusX];+ visited++;+ const dx = (di + px[id] - xf) * metricX;+ const dy = (dj + py[id] - yf) * metricY;+ let d = dx * dx + dy * dy;+ if (d >= f2)+ continue;+ if (weighted) {+ const total = Math.sqrt(d) + weights[id];+ d = total * total;+ if (d >= f2)+ continue;+ }+ if (d < f1) {+ f2 = f1;+ id2 = id1;+ f1 = d;+ id1 = id;+ } else {+ f2 = d;+ id2 = id;+ }+ }+ }+ field.squared[0] = f1;+ field.squared[1] = f2;+ field.found[0] = id1;+ field.found[1] = id2;+ field.found[2] = visited;+}+function facetHeight(field, x, y, f1) {+ const { layer, px, py, weights, slopeX, slopeY, wrapX, wrapY, orderX, orderY } = field;+ const { metricX, metricY, jitterX, jitterY, cellsX, facetBlend, facetSlope } = layer;+ const radiusX = field.radius.x;+ const radiusY = field.radius.y;+ const limit = f1 + facetBlend;+ const limitSquared = limit * limit;+ const lowX = (1 - jitterX) / 2;+ const highX = (1 + jitterX) / 2;+ const lowY = (1 - jitterY) / 2;+ const highY = (1 + jitterY) / 2;+ const xi = Math.floor(x);+ const yi = Math.floor(y);+ const xf = x - xi;+ const yf = y - yi;+ let sum = 0;+ let total = 0;+ for (let n = 0;n < orderY.length; n++) {+ const dj = orderY[n];+ const gapY = dj > 0 ? (dj + lowY - yf) * metricY : dj < 0 ? (yf - dj - highY) * metricY : 0;+ const floorY = gapY * gapY;+ if (floorY >= limitSquared)+ continue;+ const row = wrapY[yi + dj + radiusY] * cellsX;+ for (let m = 0;m < orderX.length; m++) {+ const di = orderX[m];+ const gapX = di > 0 ? (di + lowX - xf) * metricX : di < 0 ? (xf - di - highX) * metricX : 0;+ if (gapX * gapX + floorY >= limitSquared)+ continue;+ const id = row + wrapX[xi + di + radiusX];+ const dx = (di + px[id] - xf) * metricX;+ const dy = (dj + py[id] - yf) * metricY;+ const d = Math.sqrt(dx * dx + dy * dy) + weights[id];+ if (d >= limit)+ continue;+ const falloff = 1 - (d - f1) / facetBlend;+ const blend = falloff * falloff;+ sum += blend * (slopeX[id] * dx + slopeY[id] * dy);+ total += blend;+ }+ }+ return Math.max(0, Math.min(1, 0.5 + facetSlope * sum / total));+}+function sampleCellularFeature(field, u, v) {+ const { layer } = field;+ const x = u * layer.cellsX;+ const y = v * layer.cellsY;+ scan(field, x, y);+ const f1 = Math.sqrt(field.squared[0]);+ switch (layer.feature) {+ case "f1":+ return Math.min(1, f1 / layer.range);+ case "f2":+ return Math.min(1, Math.sqrt(field.squared[1]) / layer.range);+ case "f2-f1":+ return Math.min(1, (Math.sqrt(field.squared[1]) - f1) / layer.range);+ case "cell":+ return Math.min(1, field.tones[field.found[0]] / layer.range);+ case "border": {+ const gap = (Math.sqrt(field.squared[1]) - f1) / layer.borderWidth;+ if (gap >= 1)+ return 0;+ const id1 = field.found[0];+ const id2 = field.found[1];+ const pair = lattice(Math.min(id1, id2), Math.max(id1, id2), layer.seed);+ if (mix(pair + 789269127) * TO_UNIT >= layer.borderOpen)+ return 0;+ return 1 - gap * gap * (3 - 2 * gap);+ }+ case "facet":+ return facetHeight(field, x, y, f1);+ }+}+var CELLULAR_FEATURES, MIN_CELLULAR_METRIC = 1, MAX_CELLULAR_METRIC = 4, MAX_CELLULAR_WEIGHT = 1, distanceOf = (x, y) => Math.sqrt(x * x + y * y), TO_UNIT, lattice = (x, y, seed) => Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(seed, 1274126177) | 0, stream = (root, index) => mix(root + Math.imul(index + 1, 2654435769)) * TO_UNIT;+var init_procedural_cellular = __esm(() => {+ CELLULAR_FEATURES = ["f1", "f2", "f2-f1", "cell", "border", "facet"];+ TO_UNIT = 1 / 4294967296;+});+// src/texture-contract.tsvar TEXTURE_USAGES;var init_texture_contract = __esm(() => {@@ -2819,6 +3054,23 @@ function blend(record, path) {}return value;}+function featureControl(record, path, feature, control, owners) {+ const { name, fallback, min, max } = control;+ const value = finite2(record[name], `${path}.${name}`, fallback, min, max);+ if (value !== fallback && !owners.includes(feature)) {+ const noun = owners.length > 1 ? "features" : "feature";+ const named = owners.length > 1 ? owners.join(", ") : JSON.stringify(owners[0]);+ throw new ProceduralTextureError(`${path}.${name} applies only to ${noun} ${named}, not ${JSON.stringify(feature)}. Remove it or change feature.`);+ }+ return value;+}+function cellularFeature(value, path) {+ const feature = value ?? "f1";+ if (!CELLULAR_FEATURES.includes(feature)) {+ throw new ProceduralTextureError(`${path}.feature ${JSON.stringify(feature)} is not one of ${CELLULAR_FEATURES.join(", ")}.`);+ }+ return feature;+}function canonicalLayer(value, index) {const path = `proceduralTexture.layers[${index}]`;const record = strictRecord(value, path);@@ -2887,6 +3139,50 @@ function canonicalLayer(value, index) {seed: integer(record["seed"], `${path}.seed`, 0, -2147483648, 2147483647),...common};+ case "cellular": {+ assertKeys(record, [+ "op",+ "colorA",+ "colorB",+ "cellsX",+ "cellsY",+ "seed",+ "jitterX",+ "jitterY",+ "metricX",+ "metricY",+ "weight",+ "feature",+ "range",+ "borderOpen",+ "borderWidth",+ "facetSlope",+ "facetBlend",+ "blend",+ "opacity"+ ], path);+ const feature = cellularFeature(record["feature"], path);+ return {+ op,+ colorA: color(record["colorA"], `${path}.colorA`),+ colorB: color(record["colorB"], `${path}.colorB`),+ cellsX: integer(record["cellsX"], `${path}.cellsX`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ cellsY: integer(record["cellsY"], `${path}.cellsY`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ seed: integer(record["seed"], `${path}.seed`, 0, -2147483648, 2147483647),+ jitterX: unit(record["jitterX"], `${path}.jitterX`, 1),+ jitterY: unit(record["jitterY"], `${path}.jitterY`, 1),+ metricX: finite2(record["metricX"], `${path}.metricX`, 1, MIN_CELLULAR_METRIC, MAX_CELLULAR_METRIC),+ metricY: finite2(record["metricY"], `${path}.metricY`, 1, MIN_CELLULAR_METRIC, MAX_CELLULAR_METRIC),+ weight: finite2(record["weight"], `${path}.weight`, 0, 0, MAX_CELLULAR_WEIGHT),+ feature,+ range: featureControl(record, path, feature, { name: "range", fallback: 1, min: 0.01, max: 8 }, ["f1", "f2", "f2-f1", "cell"]),+ borderOpen: featureControl(record, path, feature, { name: "borderOpen", fallback: 0.5, min: 0, max: 1 }, ["border"]),+ borderWidth: featureControl(record, path, feature, { name: "borderWidth", fallback: 0.05, min: 0.001, max: 1 }, ["border"]),+ facetSlope: featureControl(record, path, feature, { name: "facetSlope", fallback: 0.5, min: 0, max: 1 }, ["facet"]),+ facetBlend: featureControl(record, path, feature, { name: "facetBlend", fallback: 0.1, min: 0.001, max: 1 }, ["facet"]),+ ...common+ };+ }default:throw new ProceduralTextureError(`${path}.op is unsupported.`);}@@ -3096,6 +3392,7 @@ function canonicalizePortableMaterialSpecV2(input) {}var MAX_PROCEDURAL_SIZE = 1024, MIN_PROCEDURAL_SIZE = 4, MAX_PROCEDURAL_LAYERS = 8, MAX_NOISE_OCTAVES = 6, MAX_PROCEDURAL_NAME_LENGTH = 80, MAX_PROCEDURAL_PATTERN_COUNT = 256, MAX_PORTABLE_MATERIAL_TEXTURES = 5, MAX_PORTABLE_MATERIAL_TEXELS, ProceduralTextureError, OPS, BLENDS, FORBIDDEN_KEYS, SHA256_K, rotateRight = (value, bits) => value >>> bits | value << 32 - bits, MATERIAL_TEXTURE_USAGE;var init_procedural_material_v2 = __esm(() => {+ init_procedural_cellular();init_texture_contract();init_authoring_diagnostic();MAX_PORTABLE_MATERIAL_TEXELS = 4 * 1024 * 1024;@@ -3105,7 +3402,7 @@ var init_procedural_material_v2 = __esm(() => {this.name = "ProceduralTextureError";}};- OPS = ["solid", "checker", "stripes", "gradient", "bricks", "noise"];+ OPS = ["solid", "checker", "stripes", "gradient", "bricks", "noise", "cellular"];BLENDS = ["normal", "multiply", "screen", "overlay"];FORBIDDEN_KEYS = new Set(["__proto__", "prototype", "constructor"]);SHA256_K = new Uint32Array([@@ -3372,8 +3669,14 @@ function admitProceduralTextureSpecV3(input) {const spec = canonicalizeProceduralTextureSpecV2(legacyRecord);if (spec.size !== width || spec.size !== height || spec.usage !== usage)fail(`${path} legacy-v2 dimensions and usage must match the V3 surface.`);- work += texels * (1 + spec.layers.reduce((cost, layer) => cost + (layer.op === "noise" ? layer.octaves * 16 : 4), 0));+ work += texels * (1 + spec.layers.reduce((cost, layer) => cost + (layer.op === "noise" ? layer.octaves * 16 : layer.op === "cellular" ? cellularWorkPerTexel(layer) : 4), 0));legacyTransientBytes += texels * 4;+ for (const layer of spec.layers) {+ if (layer.op !== "cellular")+ continue;+ work += cellularFieldWork(layer);+ legacyTransientBytes += cellularFieldBytes(layer);+ }return {op: "legacy-v2",spec,@@ -3479,6 +3782,7 @@ ${canonicalProceduralTextureJsonV3(input)}`)}`;}var PROCEDURAL_TEXTURE_V3_COMPILER_ID = "kiln.procedural-rgba.v3.1", MAX_PROCEDURAL_V3_EDGE = 1024, MAX_PROCEDURAL_V3_TEXELS = 1048576, MAX_PROCEDURAL_V3_OPERATIONS = 64, MAX_PROCEDURAL_V3_VERTICES = 64, MAX_PROCEDURAL_V3_STAMPS = 256, MAX_PROCEDURAL_V3_PALETTE = 32, MAX_PROCEDURAL_V3_WORK = 64000000, MAX_PROCEDURAL_V3_TRANSIENT_BYTES, forbidden;var init_procedural_texture_v3_contract = __esm(() => {+ init_procedural_cellular();init_procedural_material_v2();init_texture_contract();MAX_PROCEDURAL_V3_TRANSIENT_BYTES = 64 * 1024 * 1024;@@ -4207,6 +4511,7 @@ var init_material_authoring_schema = __esm(() => {init_procedural_material_v2();init_procedural_texture_v3_contract();init_texture_atlas_contract();+ init_procedural_cellular();init_portable_sampler();init_texture_contract();canonicalLegacyV2FieldSchema = (() => {@@ -4256,6 +4561,26 @@ var init_material_authoring_schema = __esm(() => {octaves: z4.number().int().min(1).max(MAX_NOISE_OCTAVES),seed: z4.number().int().min(-2147483648).max(2147483647),...common+ }).strict(),+ z4.object({+ op: z4.literal("cellular"),+ colorA: color,+ colorB: color,+ cellsX: count,+ cellsY: count,+ seed: z4.number().int().min(-2147483648).max(2147483647),+ jitterX: unit,+ jitterY: unit,+ metricX: z4.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC),+ metricY: z4.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC),+ weight: z4.number().min(0).max(MAX_CELLULAR_WEIGHT),+ feature: z4.enum(CELLULAR_FEATURES),+ range: z4.number().min(0.01).max(8),+ borderOpen: unit,+ borderWidth: z4.number().min(0.001).max(1),+ facetSlope: unit,+ facetBlend: z4.number().min(0.001).max(1),+ ...common}).strict()])).min(1).max(MAX_PROCEDURAL_LAYERS)}).strict();@@ -4490,6 +4815,7 @@ var MATERIAL_LIBRARY_LIMITS, MATERIAL_LIBRARY_SLOTS, MATERIAL_LIBRARY_USAGE, slovar init_material_library = __esm(() => {init_procedural_material_v2();init_procedural_texture_v3_contract();+ init_procedural_cellular();init_portable_sampler();init_texture_atlas_contract();init_material_authoring_schema();@@ -4635,6 +4961,26 @@ var init_material_library = __esm(() => {octaves: z5.number().int().min(1).max(6).default(3),seed: z5.number().int().min(-2147483648).max(2147483647).default(0),...layerCommon+ }).strict(),+ z5.object({+ op: z5.literal("cellular"),+ colorA: color2,+ colorB: color2,+ cellsX: count2.default(8),+ cellsY: count2.default(8),+ seed: z5.number().int().min(-2147483648).max(2147483647).default(0),+ jitterX: z5.number().min(0).max(1).default(1),+ jitterY: z5.number().min(0).max(1).default(1),+ metricX: z5.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC).default(1),+ metricY: z5.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC).default(1),+ weight: z5.number().min(0).max(MAX_CELLULAR_WEIGHT).default(0),+ feature: z5.enum(CELLULAR_FEATURES).default("f1"),+ range: z5.number().min(0.01).max(8).default(1),+ borderOpen: z5.number().min(0).max(1).default(0.5),+ borderWidth: z5.number().min(0.001).max(1).default(0.05),+ facetSlope: z5.number().min(0).max(1).default(0.5),+ facetBlend: z5.number().min(0.001).max(1).default(0.1),+ ...layerCommon}).strict()])).min(1).max(8)}).strict();@@ -4888,7 +5234,7 @@ function project(u, v, angleDeg) {const a = angleDeg * Math.PI / 180;return (u - 0.5) * Math.cos(a) + (v - 0.5) * Math.sin(a) + 0.5;}-function evalLayer(layer, u, v) {+function evalLayer(layer, u, v, field) {switch (layer.op) {case "solid":return rgbOf(layer.color);@@ -4921,6 +5267,12 @@ function evalLayer(layer, u, v) {const b = rgbOf(layer.colorB);return [lerp(a[0], b[0], n), lerp(a[1], b[1], n), lerp(a[2], b[2], n)];}+ case "cellular": {+ const n = sampleCellularFeature(field, u, v);+ const a = rgbOf(layer.colorA);+ const b = rgbOf(layer.colorB);+ return [lerp(a[0], b[0], n), lerp(a[1], b[1], n), lerp(a[2], b[2], n)];+ }}}function blendChannel(mode, base, top) {@@ -4946,6 +5298,7 @@ function compileProceduralTextureSpecV2(input) {const spec = canonicalizeProceduralTextureSpecV2(input);const { size, layers } = spec;const data = new Uint8Array(size * size * 4);+ const fields = layers.map((layer) => layer.op === "cellular" ? prepareCellularField(layer) : undefined);for (let y = 0;y < size; y++) {const v = (y + 0.5) / size;for (let x = 0;x < size; x++) {@@ -4954,7 +5307,7 @@ function compileProceduralTextureSpecV2(input) {let g = 0;let b = 0;for (const [i, layer] of layers.entries()) {- const [lr, lg, lb] = evalLayer(layer, u, v);+ const [lr, lg, lb] = evalLayer(layer, u, v, fields[i]);if (i === 0) {r = lr;g = lg;@@ -4985,6 +5338,7 @@ var smoothstep = (t) => t * t * (3 - 2 * t), rgbOf = (color) => [color & 255], lerp = (a, b, t) => a + (b - a) * t;var init_procedural_texture_v2_compiler = __esm(() => {+ init_procedural_cellular();init_procedural_material_v2();});@@ -31863,7 +32217,7 @@ const mesh = new THREE.Mesh(unwrapped, bakedPbr);`category: "textures",description: "Builds a repeat-wrapped deterministic texture without an image file. V2 retains opaque pattern layers. Explicit V3 adds rectangular RGBA, pixel shapes/masks, color palettes and seeded stamps. Repeat wrapping alone does not prove seamless pixels. Baked to PNG and embedded in the GLB automatically.",example: "const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });",- promptNotes: "V2 layer fields by op: solid: { color }; checker: { colorA, colorB, squares? }; stripes: { colorA, colorB, count?, angleDeg? }; gradient: { from, to, angleDeg? }; bricks: { brick, mortar, rows?, cols?, mortarWidth?: 0..1 (fraction of a brick cell, default 0.06), stagger?: 0..1 (row offset fraction, default 0.5) }; noise: { colorA, colorB, scale?, octaves?, seed? }. V2 blend normal|multiply|screen|overlay; opacity 0..1; max 8 layers, counts 1..256, octaves 1..6. V3 operations: paint {shape,rgba,opacity?}; mask {shape,alpha?,invert?}; stamps {shape,rgba,count,seed,area,periodic?,opacity?}; legacy-v2 {spec,alpha?,opacity?} delegates an explicit V2 recipe with matching square dimensions/usage. RGBA is four bytes; V3 opacity/alpha are bytes0..255 default255. Shape kinds: rectangle/ellipse {x,y,width,height}; polygon {points:[[x,y],...]}; line {from:[x,y],to:[x,y],width}. Coordinates are integer pixel edges; centers define binary coverage, round line caps. Mask clears outside; invert keeps outside instead. area {x,y,width,height} sets seeded stamp translation offsets; periodic:true wraps copies explicitly. V3 background defaults transparent black, max64 ops,64 polygon vertices,256 expanded stamps (periodic counts9),32 palette colors,64million estimated work including edges. palette {colors:[RGB integers],dither?:'none'|'bayer4'} and stamps are albedo/emissive only. Zero alpha normalizes RGB to0. Sampler defaults remain repeat/linear/mips; alphaMode belongs to pbrMaterial. Sync; strict JSON rejects unknown/prototype fields and accessors. See docs/procedural-surfaces-v3.md for exact rounding and bounds."+ promptNotes: "V2 layer fields by op: solid: { color }; checker: { colorA, colorB, squares? }; stripes: { colorA, colorB, count?, angleDeg? }; gradient: { from, to, angleDeg? }; bricks: { brick, mortar, rows?, cols?, mortarWidth?: 0..1 (fraction of a brick cell, default 0.06), stagger?: 0..1 (row offset fraction, default 0.5) }; noise: { colorA, colorB, scale?, octaves?, seed? }; cellular: { colorA, colorB, cellsX?, cellsY?: 1..256 cells per tile, default 8; seed?; jitterX?, jitterY?: 0..1, default 1; metricX?, metricY?: 1..4, default 1, a larger metric thins joints across that axis; weight?: 0..1 additive cell weight drawn from the seed, default 0, curves borders and varies cell size; feature?: 'f1'|'f2'|'f2-f1'|'cell'|'border'|'facet', default f1; range?: 0.01..8 (f1, f2, f2-f1 and cell: the value that reaches colorB, default 1; below 1 on cell it leaves a sparse population of toned cells); borderOpen?: 0..1, default 0.5, borderWidth?: 0.001..1, default 0.05 (border: colorB in the opened joints); facetSlope?: 0..1, default 0.5, facetBlend?: 0.001..1, default 0.1 (facet: a tilted plane per cell, blended across borders, for height) }. A field the chosen feature ignores is an error. Reuse one layout and seed across layers and maps so joints line up. V2 blend normal|multiply|screen|overlay; opacity 0..1; max 8 layers, counts 1..256, octaves 1..6. V3 operations: paint {shape,rgba,opacity?}; mask {shape,alpha?,invert?}; stamps {shape,rgba,count,seed,area,periodic?,opacity?}; legacy-v2 {spec,alpha?,opacity?} delegates an explicit V2 recipe with matching square dimensions/usage. RGBA is four bytes; V3 opacity/alpha are bytes0..255 default255. Shape kinds: rectangle/ellipse {x,y,width,height}; polygon {points:[[x,y],...]}; line {from:[x,y],to:[x,y],width}. Coordinates are integer pixel edges; centers define binary coverage, round line caps. Mask clears outside; invert keeps outside instead. area {x,y,width,height} sets seeded stamp translation offsets; periodic:true wraps copies explicitly. V3 background defaults transparent black, max64 ops,64 polygon vertices,256 expanded stamps (periodic counts9),32 palette colors,64million estimated work including edges. palette {colors:[RGB integers],dither?:'none'|'bayer4'} and stamps are albedo/emissive only. Zero alpha normalizes RGB to0. Sampler defaults remain repeat/linear/mips; alphaMode belongs to pbrMaterial. Sync; strict JSON rejects unknown/prototype fields and accessors. See docs/procedural-surfaces-v3.md for exact rounding and bounds."},{name: "textureAtlas",@@ -49548,20 +49902,28 @@ var init_helper_contracts = __esm(() => {"V3 paint/mask use integer pixel-edge shapes with binary center coverage and fixed integer source-over rounding. A mask clears outside its shape; invert keeps outside. Zero-alpha pixels are transparent black.","V3 color-only palette colors are 1..32 RGB integers, optional fixed Bayer4 dither. Stamps (any usage) use bounded Xorshift32 seed/area placement; periodic wrapping is explicit and at most 256 expanded copies. Legacy-v2 layers delegate unchanged square V2 patterns with matching usage.","Pattern counts 1..256 and noise octaves 1..6; seeded patterns are deterministic.",+ "The cellular layer is a periodic Worley/Voronoi field: integer cellsX/cellsY per tile, per-axis jitter, an anisotropic metric, optional additive weights, and a feature (f1, f2, f2-f1, cell, border, facet) mapped onto colorA..colorB. It tiles exactly at any size.","For stripes and gradient, angleDeg rotates the direction of color variation in UV space about the image center. At 0 degrees colors vary across U: stripe bands run along V. At 90 degrees colors vary across V: bands run along U. This does not rotate the mesh UVs.","Stripes count is the number of alternating bands across one unit of the projected coordinate, not the number of colorA/colorB pairs. Gradient runs from its from color to its to color along that coordinate and clamps outside 0..1.","Unknown keys, callbacks, paths, URLs and shader source are rejected."],preservation: ["Produces repeat-wrapped encoded texture content; color space follows usage."],- cost: "V2 retains pixel/layer budgets. V3 preflights at most 1,048,576 texels, 64million work units including polygon edges, palette comparisons and periodic copies, and 64MiB transient bytes."+ cost: "V2 retains pixel/layer budgets. V3 preflights at most 1,048,576 texels, 64million work units including polygon edges, palette comparisons and periodic copies, and 64MiB transient bytes. A cellular layer through legacy-v2 is charged about 50 units per texel, so one default layer fits at 1024 and a stack needs a smaller size."}, {references: ["src/procedural-texture.ts","src/procedural-texture-v3-contract.ts","docs/procedural-surfaces-v3.md"],- tags: ["texture", "procedural", "deterministic"],- aliases: ["generated texture", "noise texture", "layered pattern"],+ tags: ["texture", "procedural", "deterministic", "cellular", "Worley", "Voronoi"],+ aliases: [+ "generated texture",+ "noise texture",+ "layered pattern",+ "cellular noise",+ "worley noise",+ "voronoi noise"+ ],intents: ["generate a repeatable texture without external image files"],limitations: ["Repeat wrapping does not guarantee matching edge colors. Odd stripe counts, angled patterns and nonconstant gradients can show seams; inspect the chosen pattern at its repeat boundaries."@@ -50578,6 +50940,101 @@ function build() {"Verify the destination preserves texture direction, seams and cap treatment at useful viewing distances; a CPU geometry sheet cannot establish these."]}+ },+ {+ version: "kiln.catalog-entry.v1",+ id: "recipe:cellular-stone-v1",+ kind: "recipe",+ name: "Cellular stone: rubble, crystals and fractured rock",+ summary: "Build tiling stone from the periodic cellular (Worley/Voronoi) layer: one flat tone per stone or crystal, joints from the border distance, cracks opened per border, and faceted height for a derived normal. The example is bedded fractured rock; adapt the layout and features to the stone.",+ family: "materials",+ tags: [+ "cellular",+ "Worley",+ "Voronoi",+ "stone",+ "rock",+ "rubble",+ "granite",+ "tiling",+ "cracks"+ ],+ aliases: [+ "voronoi noise",+ "worley noise",+ "cellular noise",+ "crazy paving",+ "irregular stones",+ "crystal grain",+ "open joints"+ ],+ intents: [+ "make irregular rubble stones that tile",+ "make fractured rock with open and closed cracks",+ "give each crystal or stone its own tone"+ ],+ stability: "experimental",+ related: [+ { id: "operation:proceduralTexture", relation: "prerequisite" },+ { id: "operation:normalMapFromHeight", relation: "prerequisite" },+ { id: "operation:pbrMaterial", relation: "prerequisite" }+ ],+ references: ["src/procedural-cellular.ts", "docs/procedural-surfaces-v3.md"],+ limitations: [+ "The example is a starting layout, not a finished rock. Appearance needs GPU review at the viewing distance: a closed isotropic net of cells reads as crazy paving, however exact it is.",+ "The cell feature has hard edges with no antialiasing. A flat tone change with no joint over it reads as a pasted patch close up, so keep tonal contrast low between cells that share a closed border, or increase the texture size.",+ "Border width is in metric units, so a larger metric on one axis thins the joints that cross that axis. A strong metric gives hairline bed joints beside soft vertical ones.",+ "One saved texture repeats visibly at a distance. Tiling only removes the seam; it does not hide the period."+ ],+ recipe: {+ prerequisites: [+ "operation:proceduralTexture",+ "operation:normalMapFromHeight",+ "operation:pbrMaterial"+ ],+ steps: [+ "Choose the layout once: cellsX and cellsY per tile, seed, jitter, metric and weight. Share that object across every cellular layer of every map, so tone, joints and height agree.",+ "For beds, use low jitterY and a metricY above 1. For crystals, use full jitter, equal metrics and some weight to vary the crystal size.",+ "Colour: start from the cell feature for a flat tone per stone, overlay noise for the surface, and multiply a dark f2-f1 or border layer over it. On border, borderOpen below 1 leaves closed joints, so cracks end in T-junctions.",+ "Height: use f2-f1 for pillowed stones or facet for tilted fracture planes, multiply border over it for open cracks, and derive the normal from that height.",+ "Review on the GPU route at the intended distance and at a raking angle, across at least two repeats."+ ],+ example: `const meta = { name: 'CellularFracturedRock' };+function build() {+ const root = createRoot(meta.name);+ const beds = { cellsX: 6, cellsY: 12, seed: 83, jitterX: 0.9, jitterY: 0.45, metricY: 2, weight: 0.25 };+ const facets = { ...beds, feature: 'facet', facetSlope: 0.9, facetBlend: 0.3 };+ const joints = { ...beds, feature: 'border', borderOpen: 0.5, borderWidth: 0.06, blend: 'multiply' };+ const albedo = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', layers: [+ { op: 'cellular', ...beds, feature: 'cell', colorA: 0x6e6b65, colorB: 0x827e76 },+ { op: 'noise', colorA: 0x38362f, colorB: 0xc4c0b4, scale: 24, octaves: 5, seed: 84, blend: 'overlay', opacity: 0.6 },+ { op: 'cellular', ...facets, colorA: 0x606060, colorB: 0xffffff, blend: 'multiply', opacity: 0.5 },+ { op: 'cellular', ...joints, colorA: 0xffffff, colorB: 0x16130f },+ ] });+ const height = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', layers: [+ { op: 'cellular', ...facets, colorA: 0x000000, colorB: 0xffffff },+ { op: 'cellular', ...joints, colorA: 0xffffff, colorB: 0x000000 },+ ] });+ const packed = (roughness) => (255 << 16) | (roughness << 8);+ const metallicRoughness = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'metallicRoughness', layers: [+ { op: 'cellular', ...beds, feature: 'cell', colorA: packed(180), colorB: packed(235) },+ ] });+ const material = pbrMaterial({ albedo, normal: normalMapFromHeight(height, { strength: 5 }),+ metallicRoughness, roughness: 1, metalness: 1 });+ createPart('RockFace', planeGeo(2, 2), material, { parent: root });+ return root;+}`,+ adaptations: [+ "Rubble: cellsX 7, cellsY 11, jitterX 0.8, jitterY 0.3, metricY 1.5, weight 0.2. Cell for tone, a multiplied dark f2-f1 with range 0.14 for the joints, f2-f1 with range 0.42 for a pillowed height.",+ "Granite: full jitter, equal metrics, 64 cells and weight 0.5 for quartz. Add feldspar and biotite on other grids and seeds, with range on cell to leave a sparse population: range 0.16 keeps about a sixth of the cells dark.",+ "To save a reusable material, put these recipes in a material draft with derive normal-from-height on the normal slot, then export maps for a destination that takes plain images."+ ],+ checks: [+ "Read viewFidelity. A CPU geometry view cannot judge this: only a material-faithful GPU view shows whether the surface reads as stone.",+ "Look for the plaid and crazy-paving failures directly: straight joints running the whole tile, or every polygon closed and the same size.",+ "Numerically, each exported map should differ across its wrap edge by no more than interior neighbouring texels do. Repeat at two sizes, because a derived normal is resampled rather than regenerated."+ ]+ }}];});diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjsindex 638cf2a2..f90b70e5 100644--- a/dist/evaluator-worker.mjs+++ b/dist/evaluator-worker.mjs@@ -3655,6 +3655,241 @@ var init_universal = __esm(() => {import * as THREE3 from "three";var init_gltf_texture_binding = () => {};+// src/procedural-cellular.ts+function cellularSearchRadius(layer) {+ const { jitterX, jitterY, metricX, metricY, weight } = layer;+ const ownX = (1 + jitterX) / 2;+ const ownY = (1 + jitterY) / 2;+ const nearX = 1 + jitterX / 2;+ const nearY = 1 + jitterY / 2;+ const f1Bound = distanceOf(metricX * ownX, metricY * ownY) + weight;+ const f2Bound = Math.min(distanceOf(metricX * nearX, metricY * ownY), distanceOf(metricX * ownX, metricY * nearY)) + weight;+ const reach = layer.feature === "facet" ? Math.max(f2Bound, f1Bound + layer.facetBlend) : f2Bound;+ return {+ x: Math.max(1, Math.ceil(reach / metricX + ownX - 1)),+ y: Math.max(1, Math.ceil(reach / metricY + ownY - 1))+ };+}+function cellularWorkPerTexel(layer) {+ const { x, y } = cellularSearchRadius(layer);+ const search = 46 + Math.ceil((2 * x + 1) * (2 * y + 1) / 8) + (layer.weight > 0 ? 10 : 0);+ if (layer.feature === "border")+ return search + 8;+ if (layer.feature === "facet")+ return search + 32 + Math.ceil(layer.facetBlend * 30);+ return search;+}+function cellularFieldWork(layer) {+ return layer.cellsX * layer.cellsY * 12;+}+function cellularFieldBytes(layer) {+ return layer.cellsX * layer.cellsY * 48 + 4096;+}+function mix(value) {+ let h = value | 0;+ h ^= h >>> 16;+ h = Math.imul(h, 2246822507);+ h ^= h >>> 13;+ h = Math.imul(h, 3266489909);+ h ^= h >>> 16;+ return h >>> 0;+}+function centreOut(radius) {+ const order = new Int32Array(2 * radius + 1);+ for (let k = 1;k <= radius; k++) {+ order[2 * k - 1] = -k;+ order[2 * k] = k;+ }+ return order;+}+function wrapTable(cells, radius) {+ const table = new Int32Array(cells + 2 * radius + 1);+ for (let i = 0;i < table.length; i++) {+ table[i] = ((i - radius) % cells + cells) % cells;+ }+ return table;+}+function prepareCellularField(layer, radius = cellularSearchRadius(layer)) {+ const { cellsX, cellsY, seed, jitterX, jitterY, weight, feature } = layer;+ const count = cellsX * cellsY;+ const px = new Float64Array(count);+ const py = new Float64Array(count);+ const weights = new Float64Array(count);+ const tones = new Float64Array(feature === "cell" ? count : 0);+ const slopeX = new Float64Array(feature === "facet" ? count : 0);+ const slopeY = new Float64Array(feature === "facet" ? count : 0);+ for (let j = 0;j < cellsY; j++) {+ for (let i = 0;i < cellsX; i++) {+ const id = j * cellsX + i;+ const root = lattice(i, j, seed);+ px[id] = 0.5 + (stream(root, 0) - 0.5) * jitterX;+ py[id] = 0.5 + (stream(root, 1) - 0.5) * jitterY;+ weights[id] = stream(root, 2) * weight;+ if (feature === "cell")+ tones[id] = stream(root, 3);+ if (feature === "facet") {+ slopeX[id] = stream(root, 4) - 0.5;+ slopeY[id] = stream(root, 5) - 0.5;+ }+ }+ }+ return {+ layer,+ radius,+ px,+ py,+ weights,+ tones,+ slopeX,+ slopeY,+ wrapX: wrapTable(cellsX, radius.x),+ wrapY: wrapTable(cellsY, radius.y),+ orderX: centreOut(radius.x),+ orderY: centreOut(radius.y),+ squared: new Float64Array(2),+ found: new Int32Array(3)+ };+}+function scan(field, x, y) {+ const { layer, px, py, weights, wrapX, wrapY, orderX, orderY } = field;+ const { metricX, metricY, jitterX, jitterY, cellsX } = layer;+ const radiusX = field.radius.x;+ const radiusY = field.radius.y;+ const weighted = layer.weight > 0;+ const lowX = (1 - jitterX) / 2;+ const highX = (1 + jitterX) / 2;+ const lowY = (1 - jitterY) / 2;+ const highY = (1 + jitterY) / 2;+ const xi = Math.floor(x);+ const yi = Math.floor(y);+ const xf = x - xi;+ const yf = y - yi;+ let f1 = Infinity;+ let f2 = Infinity;+ let id1 = -1;+ let id2 = -1;+ let visited = 0;+ for (let n = 0;n < orderY.length; n++) {+ const dj = orderY[n];+ const gapY = dj > 0 ? (dj + lowY - yf) * metricY : dj < 0 ? (yf - dj - highY) * metricY : 0;+ const floorY = gapY * gapY;+ if (floorY >= f2)+ continue;+ const row = wrapY[yi + dj + radiusY] * cellsX;+ for (let m = 0;m < orderX.length; m++) {+ const di = orderX[m];+ const gapX = di > 0 ? (di + lowX - xf) * metricX : di < 0 ? (xf - di - highX) * metricX : 0;+ if (gapX * gapX + floorY >= f2)+ continue;+ const id = row + wrapX[xi + di + radiusX];+ visited++;+ const dx = (di + px[id] - xf) * metricX;+ const dy = (dj + py[id] - yf) * metricY;+ let d = dx * dx + dy * dy;+ if (d >= f2)+ continue;+ if (weighted) {+ const total = Math.sqrt(d) + weights[id];+ d = total * total;+ if (d >= f2)+ continue;+ }+ if (d < f1) {+ f2 = f1;+ id2 = id1;+ f1 = d;+ id1 = id;+ } else {+ f2 = d;+ id2 = id;+ }+ }+ }+ field.squared[0] = f1;+ field.squared[1] = f2;+ field.found[0] = id1;+ field.found[1] = id2;+ field.found[2] = visited;+}+function facetHeight(field, x, y, f1) {+ const { layer, px, py, weights, slopeX, slopeY, wrapX, wrapY, orderX, orderY } = field;+ const { metricX, metricY, jitterX, jitterY, cellsX, facetBlend, facetSlope } = layer;+ const radiusX = field.radius.x;+ const radiusY = field.radius.y;+ const limit = f1 + facetBlend;+ const limitSquared = limit * limit;+ const lowX = (1 - jitterX) / 2;+ const highX = (1 + jitterX) / 2;+ const lowY = (1 - jitterY) / 2;+ const highY = (1 + jitterY) / 2;+ const xi = Math.floor(x);+ const yi = Math.floor(y);+ const xf = x - xi;+ const yf = y - yi;+ let sum = 0;+ let total = 0;+ for (let n = 0;n < orderY.length; n++) {+ const dj = orderY[n];+ const gapY = dj > 0 ? (dj + lowY - yf) * metricY : dj < 0 ? (yf - dj - highY) * metricY : 0;+ const floorY = gapY * gapY;+ if (floorY >= limitSquared)+ continue;+ const row = wrapY[yi + dj + radiusY] * cellsX;+ for (let m = 0;m < orderX.length; m++) {+ const di = orderX[m];+ const gapX = di > 0 ? (di + lowX - xf) * metricX : di < 0 ? (xf - di - highX) * metricX : 0;+ if (gapX * gapX + floorY >= limitSquared)+ continue;+ const id = row + wrapX[xi + di + radiusX];+ const dx = (di + px[id] - xf) * metricX;+ const dy = (dj + py[id] - yf) * metricY;+ const d = Math.sqrt(dx * dx + dy * dy) + weights[id];+ if (d >= limit)+ continue;+ const falloff = 1 - (d - f1) / facetBlend;+ const blend = falloff * falloff;+ sum += blend * (slopeX[id] * dx + slopeY[id] * dy);+ total += blend;+ }+ }+ return Math.max(0, Math.min(1, 0.5 + facetSlope * sum / total));+}+function sampleCellularFeature(field, u, v) {+ const { layer } = field;+ const x = u * layer.cellsX;+ const y = v * layer.cellsY;+ scan(field, x, y);+ const f1 = Math.sqrt(field.squared[0]);+ switch (layer.feature) {+ case "f1":+ return Math.min(1, f1 / layer.range);+ case "f2":+ return Math.min(1, Math.sqrt(field.squared[1]) / layer.range);+ case "f2-f1":+ return Math.min(1, (Math.sqrt(field.squared[1]) - f1) / layer.range);+ case "cell":+ return Math.min(1, field.tones[field.found[0]] / layer.range);+ case "border": {+ const gap = (Math.sqrt(field.squared[1]) - f1) / layer.borderWidth;+ if (gap >= 1)+ return 0;+ const id1 = field.found[0];+ const id2 = field.found[1];+ const pair = lattice(Math.min(id1, id2), Math.max(id1, id2), layer.seed);+ if (mix(pair + 789269127) * TO_UNIT >= layer.borderOpen)+ return 0;+ return 1 - gap * gap * (3 - 2 * gap);+ }+ case "facet":+ return facetHeight(field, x, y, f1);+ }+}+var CELLULAR_FEATURES, MIN_CELLULAR_METRIC = 1, MAX_CELLULAR_METRIC = 4, MAX_CELLULAR_WEIGHT = 1, distanceOf = (x, y) => Math.sqrt(x * x + y * y), TO_UNIT, lattice = (x, y, seed) => Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(seed, 1274126177) | 0, stream = (root, index) => mix(root + Math.imul(index + 1, 2654435769)) * TO_UNIT;+var init_procedural_cellular = __esm(() => {+ CELLULAR_FEATURES = ["f1", "f2", "f2-f1", "cell", "border", "facet"];+ TO_UNIT = 1 / 4294967296;+});+// src/texture-contract.tsvar TEXTURE_USAGES;var init_texture_contract = __esm(() => {@@ -3781,6 +4016,23 @@ function blend(record, path) {}return value;}+function featureControl(record, path, feature, control, owners) {+ const { name, fallback, min, max } = control;+ const value = finite2(record[name], `${path}.${name}`, fallback, min, max);+ if (value !== fallback && !owners.includes(feature)) {+ const noun = owners.length > 1 ? "features" : "feature";+ const named = owners.length > 1 ? owners.join(", ") : JSON.stringify(owners[0]);+ throw new ProceduralTextureError(`${path}.${name} applies only to ${noun} ${named}, not ${JSON.stringify(feature)}. Remove it or change feature.`);+ }+ return value;+}+function cellularFeature(value, path) {+ const feature = value ?? "f1";+ if (!CELLULAR_FEATURES.includes(feature)) {+ throw new ProceduralTextureError(`${path}.feature ${JSON.stringify(feature)} is not one of ${CELLULAR_FEATURES.join(", ")}.`);+ }+ return feature;+}function canonicalLayer(value, index) {const path = `proceduralTexture.layers[${index}]`;const record = strictRecord(value, path);@@ -3849,6 +4101,50 @@ function canonicalLayer(value, index) {seed: integer(record["seed"], `${path}.seed`, 0, -2147483648, 2147483647),...common};+ case "cellular": {+ assertKeys(record, [+ "op",+ "colorA",+ "colorB",+ "cellsX",+ "cellsY",+ "seed",+ "jitterX",+ "jitterY",+ "metricX",+ "metricY",+ "weight",+ "feature",+ "range",+ "borderOpen",+ "borderWidth",+ "facetSlope",+ "facetBlend",+ "blend",+ "opacity"+ ], path);+ const feature = cellularFeature(record["feature"], path);+ return {+ op,+ colorA: color(record["colorA"], `${path}.colorA`),+ colorB: color(record["colorB"], `${path}.colorB`),+ cellsX: integer(record["cellsX"], `${path}.cellsX`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ cellsY: integer(record["cellsY"], `${path}.cellsY`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ seed: integer(record["seed"], `${path}.seed`, 0, -2147483648, 2147483647),+ jitterX: unit(record["jitterX"], `${path}.jitterX`, 1),+ jitterY: unit(record["jitterY"], `${path}.jitterY`, 1),+ metricX: finite2(record["metricX"], `${path}.metricX`, 1, MIN_CELLULAR_METRIC, MAX_CELLULAR_METRIC),+ metricY: finite2(record["metricY"], `${path}.metricY`, 1, MIN_CELLULAR_METRIC, MAX_CELLULAR_METRIC),+ weight: finite2(record["weight"], `${path}.weight`, 0, 0, MAX_CELLULAR_WEIGHT),+ feature,+ range: featureControl(record, path, feature, { name: "range", fallback: 1, min: 0.01, max: 8 }, ["f1", "f2", "f2-f1", "cell"]),+ borderOpen: featureControl(record, path, feature, { name: "borderOpen", fallback: 0.5, min: 0, max: 1 }, ["border"]),+ borderWidth: featureControl(record, path, feature, { name: "borderWidth", fallback: 0.05, min: 0.001, max: 1 }, ["border"]),+ facetSlope: featureControl(record, path, feature, { name: "facetSlope", fallback: 0.5, min: 0, max: 1 }, ["facet"]),+ facetBlend: featureControl(record, path, feature, { name: "facetBlend", fallback: 0.1, min: 0.001, max: 1 }, ["facet"]),+ ...common+ };+ }default:throw new ProceduralTextureError(`${path}.op is unsupported.`);}@@ -4058,6 +4354,7 @@ function canonicalizePortableMaterialSpecV2(input) {}var MAX_PROCEDURAL_SIZE = 1024, MIN_PROCEDURAL_SIZE = 4, MAX_PROCEDURAL_LAYERS = 8, MAX_NOISE_OCTAVES = 6, MAX_PROCEDURAL_NAME_LENGTH = 80, MAX_PROCEDURAL_PATTERN_COUNT = 256, MAX_PORTABLE_MATERIAL_TEXTURES = 5, MAX_PORTABLE_MATERIAL_TEXELS, ProceduralTextureError, OPS, BLENDS, FORBIDDEN_KEYS, SHA256_K, rotateRight = (value, bits) => value >>> bits | value << 32 - bits, MATERIAL_TEXTURE_USAGE;var init_procedural_material_v2 = __esm(() => {+ init_procedural_cellular();init_texture_contract();init_authoring_diagnostic();MAX_PORTABLE_MATERIAL_TEXELS = 4 * 1024 * 1024;@@ -4067,7 +4364,7 @@ var init_procedural_material_v2 = __esm(() => {this.name = "ProceduralTextureError";}};- OPS = ["solid", "checker", "stripes", "gradient", "bricks", "noise"];+ OPS = ["solid", "checker", "stripes", "gradient", "bricks", "noise", "cellular"];BLENDS = ["normal", "multiply", "screen", "overlay"];FORBIDDEN_KEYS = new Set(["__proto__", "prototype", "constructor"]);SHA256_K = new Uint32Array([@@ -4380,8 +4677,14 @@ function admitProceduralTextureSpecV3(input) {const spec = canonicalizeProceduralTextureSpecV2(legacyRecord);if (spec.size !== width || spec.size !== height || spec.usage !== usage)fail(`${path} legacy-v2 dimensions and usage must match the V3 surface.`);- work += texels * (1 + spec.layers.reduce((cost, layer) => cost + (layer.op === "noise" ? layer.octaves * 16 : 4), 0));+ work += texels * (1 + spec.layers.reduce((cost, layer) => cost + (layer.op === "noise" ? layer.octaves * 16 : layer.op === "cellular" ? cellularWorkPerTexel(layer) : 4), 0));legacyTransientBytes += texels * 4;+ for (const layer of spec.layers) {+ if (layer.op !== "cellular")+ continue;+ work += cellularFieldWork(layer);+ legacyTransientBytes += cellularFieldBytes(layer);+ }return {op: "legacy-v2",spec,@@ -4487,6 +4790,7 @@ ${canonicalProceduralTextureJsonV3(input)}`)}`;}var PROCEDURAL_TEXTURE_V3_COMPILER_ID = "kiln.procedural-rgba.v3.1", MAX_PROCEDURAL_V3_EDGE = 1024, MAX_PROCEDURAL_V3_TEXELS = 1048576, MAX_PROCEDURAL_V3_OPERATIONS = 64, MAX_PROCEDURAL_V3_VERTICES = 64, MAX_PROCEDURAL_V3_STAMPS = 256, MAX_PROCEDURAL_V3_PALETTE = 32, MAX_PROCEDURAL_V3_WORK = 64000000, MAX_PROCEDURAL_V3_TRANSIENT_BYTES, forbidden;var init_procedural_texture_v3_contract = __esm(() => {+ init_procedural_cellular();init_procedural_material_v2();init_texture_contract();MAX_PROCEDURAL_V3_TRANSIENT_BYTES = 64 * 1024 * 1024;@@ -22479,7 +22783,7 @@ function project(u, v, angleDeg) {const a = angleDeg * Math.PI / 180;return (u - 0.5) * Math.cos(a) + (v - 0.5) * Math.sin(a) + 0.5;}-function evalLayer(layer, u, v) {+function evalLayer(layer, u, v, field) {switch (layer.op) {case "solid":return rgbOf(layer.color);@@ -22512,6 +22816,12 @@ function evalLayer(layer, u, v) {const b = rgbOf(layer.colorB);return [lerp(a[0], b[0], n), lerp(a[1], b[1], n), lerp(a[2], b[2], n)];}+ case "cellular": {+ const n = sampleCellularFeature(field, u, v);+ const a = rgbOf(layer.colorA);+ const b = rgbOf(layer.colorB);+ return [lerp(a[0], b[0], n), lerp(a[1], b[1], n), lerp(a[2], b[2], n)];+ }}}function blendChannel(mode, base, top) {@@ -22537,6 +22847,7 @@ function compileProceduralTextureSpecV2(input) {const spec = canonicalizeProceduralTextureSpecV2(input);const { size, layers } = spec;const data = new Uint8Array(size * size * 4);+ const fields = layers.map((layer) => layer.op === "cellular" ? prepareCellularField(layer) : undefined);for (let y = 0;y < size; y++) {const v = (y + 0.5) / size;for (let x = 0;x < size; x++) {@@ -22545,7 +22856,7 @@ function compileProceduralTextureSpecV2(input) {let g = 0;let b = 0;for (const [i, layer] of layers.entries()) {- const [lr, lg, lb] = evalLayer(layer, u, v);+ const [lr, lg, lb] = evalLayer(layer, u, v, fields[i]);if (i === 0) {r = lr;g = lg;@@ -22576,6 +22887,7 @@ var smoothstep2 = (t) => t * t * (3 - 2 * t), rgbOf = (color) => [color & 255], lerp = (a, b, t) => a + (b - a) * t;var init_procedural_texture_v2_compiler = __esm(() => {+ init_procedural_cellular();init_procedural_material_v2();});@@ -29483,7 +29795,7 @@ const mesh = new THREE.Mesh(unwrapped, bakedPbr);`category: "textures",description: "Builds a repeat-wrapped deterministic texture without an image file. V2 retains opaque pattern layers. Explicit V3 adds rectangular RGBA, pixel shapes/masks, color palettes and seeded stamps. Repeat wrapping alone does not prove seamless pixels. Baked to PNG and embedded in the GLB automatically.",example: "const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });",- promptNotes: "V2 layer fields by op: solid: { color }; checker: { colorA, colorB, squares? }; stripes: { colorA, colorB, count?, angleDeg? }; gradient: { from, to, angleDeg? }; bricks: { brick, mortar, rows?, cols?, mortarWidth?: 0..1 (fraction of a brick cell, default 0.06), stagger?: 0..1 (row offset fraction, default 0.5) }; noise: { colorA, colorB, scale?, octaves?, seed? }. V2 blend normal|multiply|screen|overlay; opacity 0..1; max 8 layers, counts 1..256, octaves 1..6. V3 operations: paint {shape,rgba,opacity?}; mask {shape,alpha?,invert?}; stamps {shape,rgba,count,seed,area,periodic?,opacity?}; legacy-v2 {spec,alpha?,opacity?} delegates an explicit V2 recipe with matching square dimensions/usage. RGBA is four bytes; V3 opacity/alpha are bytes0..255 default255. Shape kinds: rectangle/ellipse {x,y,width,height}; polygon {points:[[x,y],...]}; line {from:[x,y],to:[x,y],width}. Coordinates are integer pixel edges; centers define binary coverage, round line caps. Mask clears outside; invert keeps outside instead. area {x,y,width,height} sets seeded stamp translation offsets; periodic:true wraps copies explicitly. V3 background defaults transparent black, max64 ops,64 polygon vertices,256 expanded stamps (periodic counts9),32 palette colors,64million estimated work including edges. palette {colors:[RGB integers],dither?:'none'|'bayer4'} and stamps are albedo/emissive only. Zero alpha normalizes RGB to0. Sampler defaults remain repeat/linear/mips; alphaMode belongs to pbrMaterial. Sync; strict JSON rejects unknown/prototype fields and accessors. See docs/procedural-surfaces-v3.md for exact rounding and bounds."+ promptNotes: "V2 layer fields by op: solid: { color }; checker: { colorA, colorB, squares? }; stripes: { colorA, colorB, count?, angleDeg? }; gradient: { from, to, angleDeg? }; bricks: { brick, mortar, rows?, cols?, mortarWidth?: 0..1 (fraction of a brick cell, default 0.06), stagger?: 0..1 (row offset fraction, default 0.5) }; noise: { colorA, colorB, scale?, octaves?, seed? }; cellular: { colorA, colorB, cellsX?, cellsY?: 1..256 cells per tile, default 8; seed?; jitterX?, jitterY?: 0..1, default 1; metricX?, metricY?: 1..4, default 1, a larger metric thins joints across that axis; weight?: 0..1 additive cell weight drawn from the seed, default 0, curves borders and varies cell size; feature?: 'f1'|'f2'|'f2-f1'|'cell'|'border'|'facet', default f1; range?: 0.01..8 (f1, f2, f2-f1 and cell: the value that reaches colorB, default 1; below 1 on cell it leaves a sparse population of toned cells); borderOpen?: 0..1, default 0.5, borderWidth?: 0.001..1, default 0.05 (border: colorB in the opened joints); facetSlope?: 0..1, default 0.5, facetBlend?: 0.001..1, default 0.1 (facet: a tilted plane per cell, blended across borders, for height) }. A field the chosen feature ignores is an error. Reuse one layout and seed across layers and maps so joints line up. V2 blend normal|multiply|screen|overlay; opacity 0..1; max 8 layers, counts 1..256, octaves 1..6. V3 operations: paint {shape,rgba,opacity?}; mask {shape,alpha?,invert?}; stamps {shape,rgba,count,seed,area,periodic?,opacity?}; legacy-v2 {spec,alpha?,opacity?} delegates an explicit V2 recipe with matching square dimensions/usage. RGBA is four bytes; V3 opacity/alpha are bytes0..255 default255. Shape kinds: rectangle/ellipse {x,y,width,height}; polygon {points:[[x,y],...]}; line {from:[x,y],to:[x,y],width}. Coordinates are integer pixel edges; centers define binary coverage, round line caps. Mask clears outside; invert keeps outside instead. area {x,y,width,height} sets seeded stamp translation offsets; periodic:true wraps copies explicitly. V3 background defaults transparent black, max64 ops,64 polygon vertices,256 expanded stamps (periodic counts9),32 palette colors,64million estimated work including edges. palette {colors:[RGB integers],dither?:'none'|'bayer4'} and stamps are albedo/emissive only. Zero alpha normalizes RGB to0. Sampler defaults remain repeat/linear/mips; alphaMode belongs to pbrMaterial. Sync; strict JSON rejects unknown/prototype fields and accessors. See docs/procedural-surfaces-v3.md for exact rounding and bounds."},{name: "textureAtlas",@@ -32928,6 +33240,7 @@ var init_material_authoring_schema = __esm(() => {init_procedural_material_v2();init_procedural_texture_v3_contract();init_texture_atlas_contract();+ init_procedural_cellular();init_portable_sampler();init_texture_contract();canonicalLegacyV2FieldSchema = (() => {@@ -32977,6 +33290,26 @@ var init_material_authoring_schema = __esm(() => {octaves: z5.number().int().min(1).max(MAX_NOISE_OCTAVES),seed: z5.number().int().min(-2147483648).max(2147483647),...common+ }).strict(),+ z5.object({+ op: z5.literal("cellular"),+ colorA: color,+ colorB: color,+ cellsX: count,+ cellsY: count,+ seed: z5.number().int().min(-2147483648).max(2147483647),+ jitterX: unit,+ jitterY: unit,+ metricX: z5.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC),+ metricY: z5.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC),+ weight: z5.number().min(0).max(MAX_CELLULAR_WEIGHT),+ feature: z5.enum(CELLULAR_FEATURES),+ range: z5.number().min(0.01).max(8),+ borderOpen: unit,+ borderWidth: z5.number().min(0.001).max(1),+ facetSlope: unit,+ facetBlend: z5.number().min(0.001).max(1),+ ...common}).strict()])).min(1).max(MAX_PROCEDURAL_LAYERS)}).strict();@@ -33181,6 +33514,7 @@ var MATERIAL_LIBRARY_LIMITS, MATERIAL_LIBRARY_SLOTS, MATERIAL_LIBRARY_USAGE, slovar init_material_library = __esm(() => {init_procedural_material_v2();init_procedural_texture_v3_contract();+ init_procedural_cellular();init_portable_sampler();init_texture_atlas_contract();init_material_authoring_schema();@@ -33326,6 +33660,26 @@ var init_material_library = __esm(() => {octaves: z6.number().int().min(1).max(6).default(3),seed: z6.number().int().min(-2147483648).max(2147483647).default(0),...layerCommon+ }).strict(),+ z6.object({+ op: z6.literal("cellular"),+ colorA: color2,+ colorB: color2,+ cellsX: count4.default(8),+ cellsY: count4.default(8),+ seed: z6.number().int().min(-2147483648).max(2147483647).default(0),+ jitterX: z6.number().min(0).max(1).default(1),+ jitterY: z6.number().min(0).max(1).default(1),+ metricX: z6.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC).default(1),+ metricY: z6.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC).default(1),+ weight: z6.number().min(0).max(MAX_CELLULAR_WEIGHT).default(0),+ feature: z6.enum(CELLULAR_FEATURES).default("f1"),+ range: z6.number().min(0.01).max(8).default(1),+ borderOpen: z6.number().min(0).max(1).default(0.5),+ borderWidth: z6.number().min(0.001).max(1).default(0.05),+ facetSlope: z6.number().min(0).max(1).default(0.5),+ facetBlend: z6.number().min(0.001).max(1).default(0.1),+ ...layerCommon}).strict()])).min(1).max(8)}).strict();diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjsindex 6c9264eb..696371c3 100644--- a/dist/mcp-engine.mjs+++ b/dist/mcp-engine.mjs@@ -51,6 +51,241 @@ var init_background = __esm(() => {GRID_BACKGROUND_HEX = BACKDROPS[DEFAULT_BACKDROP_ID].hex;});+// src/procedural-cellular.ts+function cellularSearchRadius(layer) {+ const { jitterX, jitterY, metricX, metricY, weight } = layer;+ const ownX = (1 + jitterX) / 2;+ const ownY = (1 + jitterY) / 2;+ const nearX = 1 + jitterX / 2;+ const nearY = 1 + jitterY / 2;+ const f1Bound = distanceOf(metricX * ownX, metricY * ownY) + weight;+ const f2Bound = Math.min(distanceOf(metricX * nearX, metricY * ownY), distanceOf(metricX * ownX, metricY * nearY)) + weight;+ const reach = layer.feature === "facet" ? Math.max(f2Bound, f1Bound + layer.facetBlend) : f2Bound;+ return {+ x: Math.max(1, Math.ceil(reach / metricX + ownX - 1)),+ y: Math.max(1, Math.ceil(reach / metricY + ownY - 1))+ };+}+function cellularWorkPerTexel(layer) {+ const { x, y } = cellularSearchRadius(layer);+ const search = 46 + Math.ceil((2 * x + 1) * (2 * y + 1) / 8) + (layer.weight > 0 ? 10 : 0);+ if (layer.feature === "border")+ return search + 8;+ if (layer.feature === "facet")+ return search + 32 + Math.ceil(layer.facetBlend * 30);+ return search;+}+function cellularFieldWork(layer) {+ return layer.cellsX * layer.cellsY * 12;+}+function cellularFieldBytes(layer) {+ return layer.cellsX * layer.cellsY * 48 + 4096;+}+function mix(value) {+ let h = value | 0;+ h ^= h >>> 16;+ h = Math.imul(h, 2246822507);+ h ^= h >>> 13;+ h = Math.imul(h, 3266489909);+ h ^= h >>> 16;+ return h >>> 0;+}+function centreOut(radius) {+ const order = new Int32Array(2 * radius + 1);+ for (let k = 1;k <= radius; k++) {+ order[2 * k - 1] = -k;+ order[2 * k] = k;+ }+ return order;+}+function wrapTable(cells, radius) {+ const table = new Int32Array(cells + 2 * radius + 1);+ for (let i = 0;i < table.length; i++) {+ table[i] = ((i - radius) % cells + cells) % cells;+ }+ return table;+}+function prepareCellularField(layer, radius = cellularSearchRadius(layer)) {+ const { cellsX, cellsY, seed, jitterX, jitterY, weight, feature } = layer;+ const count = cellsX * cellsY;+ const px = new Float64Array(count);+ const py = new Float64Array(count);+ const weights = new Float64Array(count);+ const tones = new Float64Array(feature === "cell" ? count : 0);+ const slopeX = new Float64Array(feature === "facet" ? count : 0);+ const slopeY = new Float64Array(feature === "facet" ? count : 0);+ for (let j = 0;j < cellsY; j++) {+ for (let i = 0;i < cellsX; i++) {+ const id = j * cellsX + i;+ const root = lattice(i, j, seed);+ px[id] = 0.5 + (stream(root, 0) - 0.5) * jitterX;+ py[id] = 0.5 + (stream(root, 1) - 0.5) * jitterY;+ weights[id] = stream(root, 2) * weight;+ if (feature === "cell")+ tones[id] = stream(root, 3);+ if (feature === "facet") {+ slopeX[id] = stream(root, 4) - 0.5;+ slopeY[id] = stream(root, 5) - 0.5;+ }+ }+ }+ return {+ layer,+ radius,+ px,+ py,+ weights,+ tones,+ slopeX,+ slopeY,+ wrapX: wrapTable(cellsX, radius.x),+ wrapY: wrapTable(cellsY, radius.y),+ orderX: centreOut(radius.x),+ orderY: centreOut(radius.y),+ squared: new Float64Array(2),+ found: new Int32Array(3)+ };+}+function scan(field, x, y) {+ const { layer, px, py, weights, wrapX, wrapY, orderX, orderY } = field;+ const { metricX, metricY, jitterX, jitterY, cellsX } = layer;+ const radiusX = field.radius.x;+ const radiusY = field.radius.y;+ const weighted = layer.weight > 0;+ const lowX = (1 - jitterX) / 2;+ const highX = (1 + jitterX) / 2;+ const lowY = (1 - jitterY) / 2;+ const highY = (1 + jitterY) / 2;+ const xi = Math.floor(x);+ const yi = Math.floor(y);+ const xf = x - xi;+ const yf = y - yi;+ let f1 = Infinity;+ let f2 = Infinity;+ let id1 = -1;+ let id2 = -1;+ let visited = 0;+ for (let n = 0;n < orderY.length; n++) {+ const dj = orderY[n];+ const gapY = dj > 0 ? (dj + lowY - yf) * metricY : dj < 0 ? (yf - dj - highY) * metricY : 0;+ const floorY = gapY * gapY;+ if (floorY >= f2)+ continue;+ const row = wrapY[yi + dj + radiusY] * cellsX;+ for (let m = 0;m < orderX.length; m++) {+ const di = orderX[m];+ const gapX = di > 0 ? (di + lowX - xf) * metricX : di < 0 ? (xf - di - highX) * metricX : 0;+ if (gapX * gapX + floorY >= f2)+ continue;+ const id = row + wrapX[xi + di + radiusX];+ visited++;+ const dx = (di + px[id] - xf) * metricX;+ const dy = (dj + py[id] - yf) * metricY;+ let d = dx * dx + dy * dy;+ if (d >= f2)+ continue;+ if (weighted) {+ const total = Math.sqrt(d) + weights[id];+ d = total * total;+ if (d >= f2)+ continue;+ }+ if (d < f1) {+ f2 = f1;+ id2 = id1;+ f1 = d;+ id1 = id;+ } else {+ f2 = d;+ id2 = id;+ }+ }+ }+ field.squared[0] = f1;+ field.squared[1] = f2;+ field.found[0] = id1;+ field.found[1] = id2;+ field.found[2] = visited;+}+function facetHeight(field, x, y, f1) {+ const { layer, px, py, weights, slopeX, slopeY, wrapX, wrapY, orderX, orderY } = field;+ const { metricX, metricY, jitterX, jitterY, cellsX, facetBlend, facetSlope } = layer;+ const radiusX = field.radius.x;+ const radiusY = field.radius.y;+ const limit = f1 + facetBlend;+ const limitSquared = limit * limit;+ const lowX = (1 - jitterX) / 2;+ const highX = (1 + jitterX) / 2;+ const lowY = (1 - jitterY) / 2;+ const highY = (1 + jitterY) / 2;+ const xi = Math.floor(x);+ const yi = Math.floor(y);+ const xf = x - xi;+ const yf = y - yi;+ let sum = 0;+ let total = 0;+ for (let n = 0;n < orderY.length; n++) {+ const dj = orderY[n];+ const gapY = dj > 0 ? (dj + lowY - yf) * metricY : dj < 0 ? (yf - dj - highY) * metricY : 0;+ const floorY = gapY * gapY;+ if (floorY >= limitSquared)+ continue;+ const row = wrapY[yi + dj + radiusY] * cellsX;+ for (let m = 0;m < orderX.length; m++) {+ const di = orderX[m];+ const gapX = di > 0 ? (di + lowX - xf) * metricX : di < 0 ? (xf - di - highX) * metricX : 0;+ if (gapX * gapX + floorY >= limitSquared)+ continue;+ const id = row + wrapX[xi + di + radiusX];+ const dx = (di + px[id] - xf) * metricX;+ const dy = (dj + py[id] - yf) * metricY;+ const d = Math.sqrt(dx * dx + dy * dy) + weights[id];+ if (d >= limit)+ continue;+ const falloff = 1 - (d - f1) / facetBlend;+ const blend = falloff * falloff;+ sum += blend * (slopeX[id] * dx + slopeY[id] * dy);+ total += blend;+ }+ }+ return Math.max(0, Math.min(1, 0.5 + facetSlope * sum / total));+}+function sampleCellularFeature(field, u, v) {+ const { layer } = field;+ const x = u * layer.cellsX;+ const y = v * layer.cellsY;+ scan(field, x, y);+ const f1 = Math.sqrt(field.squared[0]);+ switch (layer.feature) {+ case "f1":+ return Math.min(1, f1 / layer.range);+ case "f2":+ return Math.min(1, Math.sqrt(field.squared[1]) / layer.range);+ case "f2-f1":+ return Math.min(1, (Math.sqrt(field.squared[1]) - f1) / layer.range);+ case "cell":+ return Math.min(1, field.tones[field.found[0]] / layer.range);+ case "border": {+ const gap = (Math.sqrt(field.squared[1]) - f1) / layer.borderWidth;+ if (gap >= 1)+ return 0;+ const id1 = field.found[0];+ const id2 = field.found[1];+ const pair = lattice(Math.min(id1, id2), Math.max(id1, id2), layer.seed);+ if (mix(pair + 789269127) * TO_UNIT >= layer.borderOpen)+ return 0;+ return 1 - gap * gap * (3 - 2 * gap);+ }+ case "facet":+ return facetHeight(field, x, y, f1);+ }+}+var CELLULAR_FEATURES, MIN_CELLULAR_METRIC = 1, MAX_CELLULAR_METRIC = 4, MAX_CELLULAR_WEIGHT = 1, distanceOf = (x, y) => Math.sqrt(x * x + y * y), TO_UNIT, lattice = (x, y, seed) => Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(seed, 1274126177) | 0, stream = (root, index) => mix(root + Math.imul(index + 1, 2654435769)) * TO_UNIT;+var init_procedural_cellular = __esm(() => {+ CELLULAR_FEATURES = ["f1", "f2", "f2-f1", "cell", "border", "facet"];+ TO_UNIT = 1 / 4294967296;+});+// src/texture-contract.tsvar TEXTURE_USAGES;var init_texture_contract = __esm(() => {@@ -286,6 +521,23 @@ function blend(record, path) {}return value;}+function featureControl(record, path, feature, control, owners) {+ const { name, fallback, min, max } = control;+ const value = finite(record[name], `${path}.${name}`, fallback, min, max);+ if (value !== fallback && !owners.includes(feature)) {+ const noun = owners.length > 1 ? "features" : "feature";+ const named = owners.length > 1 ? owners.join(", ") : JSON.stringify(owners[0]);+ throw new ProceduralTextureError(`${path}.${name} applies only to ${noun} ${named}, not ${JSON.stringify(feature)}. Remove it or change feature.`);+ }+ return value;+}+function cellularFeature(value, path) {+ const feature = value ?? "f1";+ if (!CELLULAR_FEATURES.includes(feature)) {+ throw new ProceduralTextureError(`${path}.feature ${JSON.stringify(feature)} is not one of ${CELLULAR_FEATURES.join(", ")}.`);+ }+ return feature;+}function canonicalLayer(value, index) {const path = `proceduralTexture.layers[${index}]`;const record = strictRecord(value, path);@@ -354,6 +606,50 @@ function canonicalLayer(value, index) {seed: integer(record["seed"], `${path}.seed`, 0, -2147483648, 2147483647),...common};+ case "cellular": {+ assertKeys(record, [+ "op",+ "colorA",+ "colorB",+ "cellsX",+ "cellsY",+ "seed",+ "jitterX",+ "jitterY",+ "metricX",+ "metricY",+ "weight",+ "feature",+ "range",+ "borderOpen",+ "borderWidth",+ "facetSlope",+ "facetBlend",+ "blend",+ "opacity"+ ], path);+ const feature = cellularFeature(record["feature"], path);+ return {+ op,+ colorA: color(record["colorA"], `${path}.colorA`),+ colorB: color(record["colorB"], `${path}.colorB`),+ cellsX: integer(record["cellsX"], `${path}.cellsX`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ cellsY: integer(record["cellsY"], `${path}.cellsY`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ seed: integer(record["seed"], `${path}.seed`, 0, -2147483648, 2147483647),+ jitterX: unit(record["jitterX"], `${path}.jitterX`, 1),+ jitterY: unit(record["jitterY"], `${path}.jitterY`, 1),+ metricX: finite(record["metricX"], `${path}.metricX`, 1, MIN_CELLULAR_METRIC, MAX_CELLULAR_METRIC),+ metricY: finite(record["metricY"], `${path}.metricY`, 1, MIN_CELLULAR_METRIC, MAX_CELLULAR_METRIC),+ weight: finite(record["weight"], `${path}.weight`, 0, 0, MAX_CELLULAR_WEIGHT),+ feature,+ range: featureControl(record, path, feature, { name: "range", fallback: 1, min: 0.01, max: 8 }, ["f1", "f2", "f2-f1", "cell"]),+ borderOpen: featureControl(record, path, feature, { name: "borderOpen", fallback: 0.5, min: 0, max: 1 }, ["border"]),+ borderWidth: featureControl(record, path, feature, { name: "borderWidth", fallback: 0.05, min: 0.001, max: 1 }, ["border"]),+ facetSlope: featureControl(record, path, feature, { name: "facetSlope", fallback: 0.5, min: 0, max: 1 }, ["facet"]),+ facetBlend: featureControl(record, path, feature, { name: "facetBlend", fallback: 0.1, min: 0.001, max: 1 }, ["facet"]),+ ...common+ };+ }default:throw new ProceduralTextureError(`${path}.op is unsupported.`);}@@ -563,6 +859,7 @@ function canonicalizePortableMaterialSpecV2(input) {}var MAX_PROCEDURAL_SIZE = 1024, MIN_PROCEDURAL_SIZE = 4, MAX_PROCEDURAL_LAYERS = 8, MAX_NOISE_OCTAVES = 6, MAX_PROCEDURAL_NAME_LENGTH = 80, MAX_PROCEDURAL_PATTERN_COUNT = 256, MAX_PORTABLE_MATERIAL_TEXTURES = 5, MAX_PORTABLE_MATERIAL_TEXELS, ProceduralTextureError, OPS, BLENDS, FORBIDDEN_KEYS, SHA256_K, rotateRight = (value, bits) => value >>> bits | value << 32 - bits, MATERIAL_TEXTURE_USAGE;var init_procedural_material_v2 = __esm(() => {+ init_procedural_cellular();init_texture_contract();init_authoring_diagnostic();MAX_PORTABLE_MATERIAL_TEXELS = 4 * 1024 * 1024;@@ -572,7 +869,7 @@ var init_procedural_material_v2 = __esm(() => {this.name = "ProceduralTextureError";}};- OPS = ["solid", "checker", "stripes", "gradient", "bricks", "noise"];+ OPS = ["solid", "checker", "stripes", "gradient", "bricks", "noise", "cellular"];BLENDS = ["normal", "multiply", "screen", "overlay"];FORBIDDEN_KEYS = new Set(["__proto__", "prototype", "constructor"]);SHA256_K = new Uint32Array([@@ -839,8 +1136,14 @@ function admitProceduralTextureSpecV3(input) {const spec = canonicalizeProceduralTextureSpecV2(legacyRecord);if (spec.size !== width || spec.size !== height || spec.usage !== usage)fail(`${path} legacy-v2 dimensions and usage must match the V3 surface.`);- work += texels * (1 + spec.layers.reduce((cost, layer) => cost + (layer.op === "noise" ? layer.octaves * 16 : 4), 0));+ work += texels * (1 + spec.layers.reduce((cost, layer) => cost + (layer.op === "noise" ? layer.octaves * 16 : layer.op === "cellular" ? cellularWorkPerTexel(layer) : 4), 0));legacyTransientBytes += texels * 4;+ for (const layer of spec.layers) {+ if (layer.op !== "cellular")+ continue;+ work += cellularFieldWork(layer);+ legacyTransientBytes += cellularFieldBytes(layer);+ }return {op: "legacy-v2",spec,@@ -946,6 +1249,7 @@ ${canonicalProceduralTextureJsonV3(input)}`)}`;}var PROCEDURAL_TEXTURE_V3_COMPILER_ID = "kiln.procedural-rgba.v3.1", MAX_PROCEDURAL_V3_EDGE = 1024, MAX_PROCEDURAL_V3_TEXELS = 1048576, MAX_PROCEDURAL_V3_OPERATIONS = 64, MAX_PROCEDURAL_V3_VERTICES = 64, MAX_PROCEDURAL_V3_STAMPS = 256, MAX_PROCEDURAL_V3_PALETTE = 32, MAX_PROCEDURAL_V3_WORK = 64000000, MAX_PROCEDURAL_V3_TRANSIENT_BYTES, forbidden;var init_procedural_texture_v3_contract = __esm(() => {+ init_procedural_cellular();init_procedural_material_v2();init_texture_contract();MAX_PROCEDURAL_V3_TRANSIENT_BYTES = 64 * 1024 * 1024;@@ -1674,6 +1978,7 @@ var init_material_authoring_schema = __esm(() => {init_procedural_material_v2();init_procedural_texture_v3_contract();init_texture_atlas_contract();+ init_procedural_cellular();init_portable_sampler();init_texture_contract();canonicalLegacyV2FieldSchema = (() => {@@ -1723,6 +2028,26 @@ var init_material_authoring_schema = __esm(() => {octaves: z.number().int().min(1).max(MAX_NOISE_OCTAVES),seed: z.number().int().min(-2147483648).max(2147483647),...common+ }).strict(),+ z.object({+ op: z.literal("cellular"),+ colorA: color,+ colorB: color,+ cellsX: count,+ cellsY: count,+ seed: z.number().int().min(-2147483648).max(2147483647),+ jitterX: unit,+ jitterY: unit,+ metricX: z.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC),+ metricY: z.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC),+ weight: z.number().min(0).max(MAX_CELLULAR_WEIGHT),+ feature: z.enum(CELLULAR_FEATURES),+ range: z.number().min(0.01).max(8),+ borderOpen: unit,+ borderWidth: z.number().min(0.001).max(1),+ facetSlope: unit,+ facetBlend: z.number().min(0.001).max(1),+ ...common}).strict()])).min(1).max(MAX_PROCEDURAL_LAYERS)}).strict();@@ -1957,6 +2282,7 @@ var MATERIAL_LIBRARY_LIMITS, MATERIAL_LIBRARY_SLOTS, MATERIAL_LIBRARY_USAGE, slovar init_material_library = __esm(() => {init_procedural_material_v2();init_procedural_texture_v3_contract();+ init_procedural_cellular();init_portable_sampler();init_texture_atlas_contract();init_material_authoring_schema();@@ -2102,6 +2428,26 @@ var init_material_library = __esm(() => {octaves: z2.number().int().min(1).max(6).default(3),seed: z2.number().int().min(-2147483648).max(2147483647).default(0),...layerCommon+ }).strict(),+ z2.object({+ op: z2.literal("cellular"),+ colorA: color2,+ colorB: color2,+ cellsX: count.default(8),+ cellsY: count.default(8),+ seed: z2.number().int().min(-2147483648).max(2147483647).default(0),+ jitterX: z2.number().min(0).max(1).default(1),+ jitterY: z2.number().min(0).max(1).default(1),+ metricX: z2.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC).default(1),+ metricY: z2.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC).default(1),+ weight: z2.number().min(0).max(MAX_CELLULAR_WEIGHT).default(0),+ feature: z2.enum(CELLULAR_FEATURES).default("f1"),+ range: z2.number().min(0.01).max(8).default(1),+ borderOpen: z2.number().min(0).max(1).default(0.5),+ borderWidth: z2.number().min(0.001).max(1).default(0.05),+ facetSlope: z2.number().min(0).max(1).default(0.5),+ facetBlend: z2.number().min(0.001).max(1).default(0.1),+ ...layerCommon}).strict()])).min(1).max(8)}).strict();@@ -2569,7 +2915,7 @@ function project(u, v, angleDeg) {const a = angleDeg * Math.PI / 180;return (u - 0.5) * Math.cos(a) + (v - 0.5) * Math.sin(a) + 0.5;}-function evalLayer(layer, u, v) {+function evalLayer(layer, u, v, field) {switch (layer.op) {case "solid":return rgbOf(layer.color);@@ -2602,6 +2948,12 @@ function evalLayer(layer, u, v) {const b = rgbOf(layer.colorB);return [lerp(a[0], b[0], n), lerp(a[1], b[1], n), lerp(a[2], b[2], n)];}+ case "cellular": {+ const n = sampleCellularFeature(field, u, v);+ const a = rgbOf(layer.colorA);+ const b = rgbOf(layer.colorB);+ return [lerp(a[0], b[0], n), lerp(a[1], b[1], n), lerp(a[2], b[2], n)];+ }}}function blendChannel(mode, base, top) {@@ -2627,6 +2979,7 @@ function compileProceduralTextureSpecV2(input) {const spec = canonicalizeProceduralTextureSpecV2(input);const { size, layers } = spec;const data = new Uint8Array(size * size * 4);+ const fields = layers.map((layer) => layer.op === "cellular" ? prepareCellularField(layer) : undefined);for (let y = 0;y < size; y++) {const v = (y + 0.5) / size;for (let x = 0;x < size; x++) {@@ -2635,7 +2988,7 @@ function compileProceduralTextureSpecV2(input) {let g = 0;let b = 0;for (const [i, layer] of layers.entries()) {- const [lr, lg, lb] = evalLayer(layer, u, v);+ const [lr, lg, lb] = evalLayer(layer, u, v, fields[i]);if (i === 0) {r = lr;g = lg;@@ -2666,6 +3019,7 @@ var smoothstep = (t) => t * t * (3 - 2 * t), rgbOf = (color) => [color & 255], lerp = (a, b, t) => a + (b - a) * t;var init_procedural_texture_v2_compiler = __esm(() => {+ init_procedural_cellular();init_procedural_material_v2();});@@ -32960,7 +33314,7 @@ const mesh = new THREE.Mesh(unwrapped, bakedPbr);`category: "textures",description: "Builds a repeat-wrapped deterministic texture without an image file. V2 retains opaque pattern layers. Explicit V3 adds rectangular RGBA, pixel shapes/masks, color palettes and seeded stamps. Repeat wrapping alone does not prove seamless pixels. Baked to PNG and embedded in the GLB automatically.",example: "const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });",- promptNotes: "V2 layer fields by op: solid: { color }; checker: { colorA, colorB, squares? }; stripes: { colorA, colorB, count?, angleDeg? }; gradient: { from, to, angleDeg? }; bricks: { brick, mortar, rows?, cols?, mortarWidth?: 0..1 (fraction of a brick cell, default 0.06), stagger?: 0..1 (row offset fraction, default 0.5) }; noise: { colorA, colorB, scale?, octaves?, seed? }. V2 blend normal|multiply|screen|overlay; opacity 0..1; max 8 layers, counts 1..256, octaves 1..6. V3 operations: paint {shape,rgba,opacity?}; mask {shape,alpha?,invert?}; stamps {shape,rgba,count,seed,area,periodic?,opacity?}; legacy-v2 {spec,alpha?,opacity?} delegates an explicit V2 recipe with matching square dimensions/usage. RGBA is four bytes; V3 opacity/alpha are bytes0..255 default255. Shape kinds: rectangle/ellipse {x,y,width,height}; polygon {points:[[x,y],...]}; line {from:[x,y],to:[x,y],width}. Coordinates are integer pixel edges; centers define binary coverage, round line caps. Mask clears outside; invert keeps outside instead. area {x,y,width,height} sets seeded stamp translation offsets; periodic:true wraps copies explicitly. V3 background defaults transparent black, max64 ops,64 polygon vertices,256 expanded stamps (periodic counts9),32 palette colors,64million estimated work including edges. palette {colors:[RGB integers],dither?:'none'|'bayer4'} and stamps are albedo/emissive only. Zero alpha normalizes RGB to0. Sampler defaults remain repeat/linear/mips; alphaMode belongs to pbrMaterial. Sync; strict JSON rejects unknown/prototype fields and accessors. See docs/procedural-surfaces-v3.md for exact rounding and bounds."+ promptNotes: "V2 layer fields by op: solid: { color }; checker: { colorA, colorB, squares? }; stripes: { colorA, colorB, count?, angleDeg? }; gradient: { from, to, angleDeg? }; bricks: { brick, mortar, rows?, cols?, mortarWidth?: 0..1 (fraction of a brick cell, default 0.06), stagger?: 0..1 (row offset fraction, default 0.5) }; noise: { colorA, colorB, scale?, octaves?, seed? }; cellular: { colorA, colorB, cellsX?, cellsY?: 1..256 cells per tile, default 8; seed?; jitterX?, jitterY?: 0..1, default 1; metricX?, metricY?: 1..4, default 1, a larger metric thins joints across that axis; weight?: 0..1 additive cell weight drawn from the seed, default 0, curves borders and varies cell size; feature?: 'f1'|'f2'|'f2-f1'|'cell'|'border'|'facet', default f1; range?: 0.01..8 (f1, f2, f2-f1 and cell: the value that reaches colorB, default 1; below 1 on cell it leaves a sparse population of toned cells); borderOpen?: 0..1, default 0.5, borderWidth?: 0.001..1, default 0.05 (border: colorB in the opened joints); facetSlope?: 0..1, default 0.5, facetBlend?: 0.001..1, default 0.1 (facet: a tilted plane per cell, blended across borders, for height) }. A field the chosen feature ignores is an error. Reuse one layout and seed across layers and maps so joints line up. V2 blend normal|multiply|screen|overlay; opacity 0..1; max 8 layers, counts 1..256, octaves 1..6. V3 operations: paint {shape,rgba,opacity?}; mask {shape,alpha?,invert?}; stamps {shape,rgba,count,seed,area,periodic?,opacity?}; legacy-v2 {spec,alpha?,opacity?} delegates an explicit V2 recipe with matching square dimensions/usage. RGBA is four bytes; V3 opacity/alpha are bytes0..255 default255. Shape kinds: rectangle/ellipse {x,y,width,height}; polygon {points:[[x,y],...]}; line {from:[x,y],to:[x,y],width}. Coordinates are integer pixel edges; centers define binary coverage, round line caps. Mask clears outside; invert keeps outside instead. area {x,y,width,height} sets seeded stamp translation offsets; periodic:true wraps copies explicitly. V3 background defaults transparent black, max64 ops,64 polygon vertices,256 expanded stamps (periodic counts9),32 palette colors,64million estimated work including edges. palette {colors:[RGB integers],dither?:'none'|'bayer4'} and stamps are albedo/emissive only. Zero alpha normalizes RGB to0. Sampler defaults remain repeat/linear/mips; alphaMode belongs to pbrMaterial. Sync; strict JSON rejects unknown/prototype fields and accessors. See docs/procedural-surfaces-v3.md for exact rounding and bounds."},{name: "textureAtlas",@@ -49917,20 +50271,28 @@ define2("proceduralTexture", {"V3 paint/mask use integer pixel-edge shapes with binary center coverage and fixed integer source-over rounding. A mask clears outside its shape; invert keeps outside. Zero-alpha pixels are transparent black.","V3 color-only palette colors are 1..32 RGB integers, optional fixed Bayer4 dither. Stamps (any usage) use bounded Xorshift32 seed/area placement; periodic wrapping is explicit and at most 256 expanded copies. Legacy-v2 layers delegate unchanged square V2 patterns with matching usage.","Pattern counts 1..256 and noise octaves 1..6; seeded patterns are deterministic.",+ "The cellular layer is a periodic Worley/Voronoi field: integer cellsX/cellsY per tile, per-axis jitter, an anisotropic metric, optional additive weights, and a feature (f1, f2, f2-f1, cell, border, facet) mapped onto colorA..colorB. It tiles exactly at any size.","For stripes and gradient, angleDeg rotates the direction of color variation in UV space about the image center. At 0 degrees colors vary across U: stripe bands run along V. At 90 degrees colors vary across V: bands run along U. This does not rotate the mesh UVs.","Stripes count is the number of alternating bands across one unit of the projected coordinate, not the number of colorA/colorB pairs. Gradient runs from its from color to its to color along that coordinate and clamps outside 0..1.","Unknown keys, callbacks, paths, URLs and shader source are rejected."],preservation: ["Produces repeat-wrapped encoded texture content; color space follows usage."],- cost: "V2 retains pixel/layer budgets. V3 preflights at most 1,048,576 texels, 64million work units including polygon edges, palette comparisons and periodic copies, and 64MiB transient bytes."+ cost: "V2 retains pixel/layer budgets. V3 preflights at most 1,048,576 texels, 64million work units including polygon edges, palette comparisons and periodic copies, and 64MiB transient bytes. A cellular layer through legacy-v2 is charged about 50 units per texel, so one default layer fits at 1024 and a stack needs a smaller size."}, {references: ["src/procedural-texture.ts","src/procedural-texture-v3-contract.ts","docs/procedural-surfaces-v3.md"],- tags: ["texture", "procedural", "deterministic"],- aliases: ["generated texture", "noise texture", "layered pattern"],+ tags: ["texture", "procedural", "deterministic", "cellular", "Worley", "Voronoi"],+ aliases: [+ "generated texture",+ "noise texture",+ "layered pattern",+ "cellular noise",+ "worley noise",+ "voronoi noise"+ ],intents: ["generate a repeatable texture without external image files"],limitations: ["Repeat wrapping does not guarantee matching edge colors. Odd stripe counts, angled patterns and nonconstant gradients can show seams; inspect the chosen pattern at its repeat boundaries."@@ -50942,6 +51304,101 @@ function build() {"Verify the destination preserves texture direction, seams and cap treatment at useful viewing distances; a CPU geometry sheet cannot establish these."]}+ },+ {+ version: "kiln.catalog-entry.v1",+ id: "recipe:cellular-stone-v1",+ kind: "recipe",+ name: "Cellular stone: rubble, crystals and fractured rock",+ summary: "Build tiling stone from the periodic cellular (Worley/Voronoi) layer: one flat tone per stone or crystal, joints from the border distance, cracks opened per border, and faceted height for a derived normal. The example is bedded fractured rock; adapt the layout and features to the stone.",+ family: "materials",+ tags: [+ "cellular",+ "Worley",+ "Voronoi",+ "stone",+ "rock",+ "rubble",+ "granite",+ "tiling",+ "cracks"+ ],+ aliases: [+ "voronoi noise",+ "worley noise",+ "cellular noise",+ "crazy paving",+ "irregular stones",+ "crystal grain",+ "open joints"+ ],+ intents: [+ "make irregular rubble stones that tile",+ "make fractured rock with open and closed cracks",+ "give each crystal or stone its own tone"+ ],+ stability: "experimental",+ related: [+ { id: "operation:proceduralTexture", relation: "prerequisite" },+ { id: "operation:normalMapFromHeight", relation: "prerequisite" },+ { id: "operation:pbrMaterial", relation: "prerequisite" }+ ],+ references: ["src/procedural-cellular.ts", "docs/procedural-surfaces-v3.md"],+ limitations: [+ "The example is a starting layout, not a finished rock. Appearance needs GPU review at the viewing distance: a closed isotropic net of cells reads as crazy paving, however exact it is.",+ "The cell feature has hard edges with no antialiasing. A flat tone change with no joint over it reads as a pasted patch close up, so keep tonal contrast low between cells that share a closed border, or increase the texture size.",+ "Border width is in metric units, so a larger metric on one axis thins the joints that cross that axis. A strong metric gives hairline bed joints beside soft vertical ones.",+ "One saved texture repeats visibly at a distance. Tiling only removes the seam; it does not hide the period."+ ],+ recipe: {+ prerequisites: [+ "operation:proceduralTexture",+ "operation:normalMapFromHeight",+ "operation:pbrMaterial"+ ],+ steps: [+ "Choose the layout once: cellsX and cellsY per tile, seed, jitter, metric and weight. Share that object across every cellular layer of every map, so tone, joints and height agree.",+ "For beds, use low jitterY and a metricY above 1. For crystals, use full jitter, equal metrics and some weight to vary the crystal size.",+ "Colour: start from the cell feature for a flat tone per stone, overlay noise for the surface, and multiply a dark f2-f1 or border layer over it. On border, borderOpen below 1 leaves closed joints, so cracks end in T-junctions.",+ "Height: use f2-f1 for pillowed stones or facet for tilted fracture planes, multiply border over it for open cracks, and derive the normal from that height.",+ "Review on the GPU route at the intended distance and at a raking angle, across at least two repeats."+ ],+ example: `const meta = { name: 'CellularFracturedRock' };+function build() {+ const root = createRoot(meta.name);+ const beds = { cellsX: 6, cellsY: 12, seed: 83, jitterX: 0.9, jitterY: 0.45, metricY: 2, weight: 0.25 };+ const facets = { ...beds, feature: 'facet', facetSlope: 0.9, facetBlend: 0.3 };+ const joints = { ...beds, feature: 'border', borderOpen: 0.5, borderWidth: 0.06, blend: 'multiply' };+ const albedo = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', layers: [+ { op: 'cellular', ...beds, feature: 'cell', colorA: 0x6e6b65, colorB: 0x827e76 },+ { op: 'noise', colorA: 0x38362f, colorB: 0xc4c0b4, scale: 24, octaves: 5, seed: 84, blend: 'overlay', opacity: 0.6 },+ { op: 'cellular', ...facets, colorA: 0x606060, colorB: 0xffffff, blend: 'multiply', opacity: 0.5 },+ { op: 'cellular', ...joints, colorA: 0xffffff, colorB: 0x16130f },+ ] });+ const height = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', layers: [+ { op: 'cellular', ...facets, colorA: 0x000000, colorB: 0xffffff },+ { op: 'cellular', ...joints, colorA: 0xffffff, colorB: 0x000000 },+ ] });+ const packed = (roughness) => (255 << 16) | (roughness << 8);+ const metallicRoughness = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'metallicRoughness', layers: [+ { op: 'cellular', ...beds, feature: 'cell', colorA: packed(180), colorB: packed(235) },+ ] });+ const material = pbrMaterial({ albedo, normal: normalMapFromHeight(height, { strength: 5 }),+ metallicRoughness, roughness: 1, metalness: 1 });+ createPart('RockFace', planeGeo(2, 2), material, { parent: root });+ return root;+}`,+ adaptations: [+ "Rubble: cellsX 7, cellsY 11, jitterX 0.8, jitterY 0.3, metricY 1.5, weight 0.2. Cell for tone, a multiplied dark f2-f1 with range 0.14 for the joints, f2-f1 with range 0.42 for a pillowed height.",+ "Granite: full jitter, equal metrics, 64 cells and weight 0.5 for quartz. Add feldspar and biotite on other grids and seeds, with range on cell to leave a sparse population: range 0.16 keeps about a sixth of the cells dark.",+ "To save a reusable material, put these recipes in a material draft with derive normal-from-height on the normal slot, then export maps for a destination that takes plain images."+ ],+ checks: [+ "Read viewFidelity. A CPU geometry view cannot judge this: only a material-faithful GPU view shows whether the surface reads as stone.",+ "Look for the plaid and crazy-paving failures directly: straight joints running the whole tile, or every polygon closed and the same size.",+ "Numerically, each exported map should differ across its wrap edge by no more than interior neighbouring texels do. Repeat at two sizes, because a derived normal is resampled rather than regenerated."+ ]+ }}];diff --git a/docs/procedural-surfaces-v3.md b/docs/procedural-surfaces-v3.mdindex 9b37ac3e..01d0727d 100644--- a/docs/procedural-surfaces-v3.md+++ b/docs/procedural-surfaces-v3.md@@ -147,6 +147,37 @@ transient pixel buffers stay below 64MiB. The compiler creates one RGBA output;legacy layers temporarily create matching RGBA outputs and palette metadata isbounded. These limits do not raise legacy or portable-material budgets.+A [cellular](rendering.md#cellular-layers) layer through `legacy-v2` is charged per texel, on the+scale where one noise octave costs 16:++```+46 + ceil(windowCells / 8) + (weight > 0 ? 10 : 0)+ + (border ? 8 : 0) + (facet ? 32 + ceil(facetBlend * 30) : 0)+```++where `windowCells` is `(2·Rx + 1)(2·Ry + 1)` for the exact search radius, plus 12 units per cell+for its table and 48 bytes per cell plus 4 KiB of transient allocation. This is fitted to the real+compile path against noise, as CPU time under Node and Bun on a loaded 8-core machine, where one+unit is about 9 to 14 ns and repeat runs vary by about 15%. The search prunes, so it reads about 6+to 11 cells a texel whatever the window, and the window adds little:++| Layer | Window | Measured units | Charged |+| --- | --- | --- | --- |+| No jitter | 9 | 35 to 45 | 48 |+| Default `f1`, `f2-f1`, `cell` | 25 | 44 to 62 | 50 |+| Default `border` | 25 | 48 to 51 | 58 |+| Beds: `metricY: 3`, `jitterY: 0.3`, `weight: 0.3` | 21 | 41 to 43 | 59 |+| `weight: 0.5` to `1` | 49 | 55 to 64 | 63 |+| `metricY: 4` | 55 | 51 | 53 |+| `metricY: 4`, `weight: 1` | 65 | 57 to 77 | 65 |+| Default `facet` | 25 | 79 to 98 | 85 |+| `facet`, `facetBlend: 1` | 49 | 116 to 130 | 115 |+| `facet`, `metricY: 4`, `weight: 1`, `facetBlend: 1` | 75 | 110 to 121 | 128 |++At 1024 square the budget leaves 59 units per texel after the output and the legacy result, so one+default, `border` or bedded layer fits. Any `weight` at full jitter, any `facet` or a stack is refused+there and fits at 512, which leaves 242. A V2 recipe compiled directly has no work budget.+The compiler ID is `kiln.procedural-rgba.v3.1`. V3 recipe hashes are SHA-256 of`compilerId + '\n' + canonicalJson`; property order and omitted defaults producethe same canonical result. A changed pixel algorithm requires a new compiler ID.diff --git a/docs/rendering.md b/docs/rendering.mdindex c5418d30..02617247 100644--- a/docs/rendering.md+++ b/docs/rendering.md@@ -294,9 +294,46 @@ The layer operations are strict objects; fields from another operation are error| `gradient` | `from`, `to` | `angleDeg` || `bricks` | `brick`, `mortar` | `rows`, `cols`, `mortarWidth`, `stagger` || `noise` | `colorA`, `colorB` | `scale`, `octaves`, `seed` |+| `cellular` | `colorA`, `colorB` | `cellsX`, `cellsY`, `seed`, `jitterX`, `jitterY`, `metricX`, `metricY`, `weight`, `feature`, `range`, `borderOpen`, `borderWidth`, `facetSlope`, `facetBlend` |Every layer also accepts `blend` (`normal`, `multiply`, `screen`, or `overlay`) and `opacity` from 0 to 1. Pattern counts are integers from 1 to 256; noise octaves are 1 to 6. Seeded noise is tileable and reproducible. Call `kiln_discover({ ids: ["proceduralTexture"] })` to retrieve this contract and an executable example.+### Cellular layers++`cellular` is a periodic Worley (Voronoi) field that tiles exactly, because it wraps the cell index rather than the sample point. Use it for anything made of separate pieces: stones, crystals, cracked rock. `kiln_discover({ ids: ["recipe:cellular-stone-v1"] })` has a worked fractured-rock program with rubble and granite adaptations.++Distances are in cell units, where one cell is 1 × 1 whatever `cellsX` and `cellsY` make it in UV. A cell's point sits in the box `0.5 ± jitter/2` on each axis, and the distance to it is `sqrt((metricX·dx)² + (metricY·dy)²) + w`.++| Field | Range and default | Meaning |+| --- | --- | --- |+| `cellsX`, `cellsY` | 1 to 256, default 8 | Cells per tile on each axis |+| `seed` | signed 32-bit, default 0 | Draws every cell's values |+| `jitterX`, `jitterY` | 0 to 1, default 1 | How far a point strays. Low `jitterY` keeps cells in rows |+| `metricX`, `metricY` | 1 to 4, default 1 | A larger metric flattens borders against that axis and thins the joints that cross it |+| `weight` | 0 to 1, default 0 | Upper limit of an additive per-cell weight drawn from the seed. It curves borders and varies cell size |+| `feature` | default `f1` | What maps onto `colorA`→`colorB`, below |+| `range` | 0.01 to 8, default 1 | `f1`, `f2`, `f2-f1`, `cell`: the value that reaches `colorB` |+| `borderOpen` | 0 to 1, default 0.5 | `border`: fraction of borders that are open |+| `borderWidth` | 0.001 to 1, default 0.05 | `border`: width in distance units |+| `facetSlope` | 0 to 1, default 0.5 | `facet`: how far each cell's plane can tilt |+| `facetBlend` | 0.001 to 1, default 0.1 | `facet`: how far a plane reaches across its border |++| `feature` | Value in 0..1 |+| --- | --- |+| `f1`, `f2` | Distance to the nearest and second nearest cell point, divided by `range` |+| `f2-f1` | Their difference divided by `range`: 0 on a border, rising into the cell. It is not a true Euclidean distance |+| `cell` | One flat random tone per cell, divided by `range`. A `range` below 1 saturates most cells at `colorB`, which leaves a sparse population: `range: 0.16` keeps about a sixth of the cells toned |+| `border` | 1 at the centre of an open border, falling to 0 at `borderWidth`. Open borders are chosen by a hash of the two cell ids in either order, so both sides agree, and a crack can end where it meets a closed border |+| `facet` | A tilted plane per cell, for height. It blends over every cell within `facetBlend` of the nearest, so it has no step anywhere, including near corners |++A field the chosen feature ignores is an error rather than something silently dropped, which keeps one meaning to each recipe hash. Reuse one layout object and seed across the layers and maps of a material so that its tone, joints and height line up.++`cell` has hard edges with no antialiasing. A flat tone change with no joint over it reads as a pasted patch close up, so keep contrast low between cells that share a closed border, or raise the size. A closed isotropic net reads as crazy paving, however exact it is: review on the GPU route, and use low `jitterY`, a `metricY` above 1 and a `borderOpen` below 1 to get bedded rock.++The search is exact for every seed. A sample's own point is at most `(1 + jitter)/2` away on an axis, and a neighbour on the nearer side at most `1 + jitter/2`, so those two cells bound F2 from above. An image `k` rings out is at least `k - (1 + jitter)/2` away, scaled by that axis' metric, and weights only add. The search radius is the first ring whose lower bound reaches F2's upper bound, extended by `facetBlend` for `facet`: two rings at the default, and at most seven rings by two at the extremes. Full jitter makes the usual 3 × 3 window miss true neighbours. Tests hold this against an unbounded search, including layouts with every point planted at an extreme of its box.++Golden pixel hashes pin each feature. A V2 recipe hash has no compiler id, so changing this algorithm would move pixels under an unchanged hash: a change in behaviour needs a new field or op, not a new pin. V2 has size and layer limits but no work budget. Through V3 `legacy-v2`, a cellular layer is charged its own cost; see [admission](procedural-surfaces-v3.md#admission-and-identity).+The bundled scanned library contains Poly Haven CC0 material families with recorded provenance. Use catalog IDs rather than file paths or URLs. Assets embed their textures and do not fetch them at runtime.Procedural layers suit regular patterns such as brickwork and painted stripes. Scanned materials can provide irregular surfaces such as bark, soil, or leather. Choose based on the requested appearance and check the result in a material-faithful view.diff --git a/skills/kiln-author-asset/references/geometry-recipes.md b/skills/kiln-author-asset/references/geometry-recipes.mdindex 505ca427..ddf52354 100644--- a/skills/kiln-author-asset/references/geometry-recipes.md+++ b/skills/kiln-author-asset/references/geometry-recipes.md@@ -289,6 +289,13 @@ merge returns one geometry, so one primitive per frond with each copy's UVs keptthree.js runtime export. Do not hand-build hundreds of leaflets with `meshGeo`.Grass clumps and shrubs can use `crossedQuadsGeo` cards.+For stone made of separate pieces, discover `recipe:cellular-stone-v1` rather than+overlaying `bricks`, which reads as plaid. The `cellular` layer gives one flat tone per+stone, joints and faceted height from one shared layout. A closed isotropic net of+cells reads as crazy paving: low `jitterY`, a `metricY` above 1 and a `borderOpen`+below 1 keep rock in beds, with cracks that end in T-junctions. Judge it on a+material-faithful view at the viewing distance and across two repeats.+For original cutouts, `proceduralTexture` V3 authors rectangular RGBA pixels;`textureAtlas` combines named fixed regions from V3 recipes or exact saved maprevisions. Discover their full contracts before authoring. Atlas regions do notdiff --git a/src/__tests__/__snapshots__/prompt-api.test.ts.snap b/src/__tests__/__snapshots__/prompt-api.test.ts.snapindex 758be360..527f94d6 100644--- a/src/__tests__/__snapshots__/prompt-api.test.ts.snap+++ b/src/__tests__/__snapshots__/prompt-api.test.ts.snap@@ -773,8 +773,18 @@ proceduralTexture({ schemaVersion: 2, size?: 4..1024 pow2, usage?, name?, layers// stripes: { colorA, colorB, count?, angleDeg? }; gradient: { from, to, angleDeg? }; bricks:// { brick, mortar, rows?, cols?, mortarWidth?: 0..1 (fraction of a brick cell, default 0.06),// stagger?: 0..1 (row offset fraction, default 0.5) }; noise: { colorA, colorB, scale?,- // octaves?, seed? }. V2 blend normal|multiply|screen|overlay; opacity 0..1; max 8 layers,- // counts 1..256, octaves 1..6. V3 operations: paint {shape,rgba,opacity?}; mask+ // octaves?, seed? }; cellular: { colorA, colorB, cellsX?, cellsY?: 1..256 cells per tile,+ // default 8; seed?; jitterX?, jitterY?: 0..1, default 1; metricX?, metricY?: 1..4, default 1,+ // a larger metric thins joints across that axis; weight?: 0..1 additive cell weight drawn+ // from the seed, default 0, curves borders and varies cell size; feature?:+ // 'f1'|'f2'|'f2-f1'|'cell'|'border'|'facet', default f1; range?: 0.01..8 (f1, f2, f2-f1 and+ // cell: the value that reaches colorB, default 1; below 1 on cell it leaves a sparse+ // population of toned cells); borderOpen?: 0..1, default 0.5, borderWidth?: 0.001..1, default+ // 0.05 (border: colorB in the opened joints); facetSlope?: 0..1, default 0.5, facetBlend?:+ // 0.001..1, default 0.1 (facet: a tilted plane per cell, blended across borders, for height)+ // }. A field the chosen feature ignores is an error. Reuse one layout and seed across layers+ // and maps so joints line up. V2 blend normal|multiply|screen|overlay; opacity 0..1; max 8+ // layers, counts 1..256, octaves 1..6. V3 operations: paint {shape,rgba,opacity?}; mask// {shape,alpha?,invert?}; stamps {shape,rgba,count,seed,area,periodic?,opacity?}; legacy-v2// {spec,alpha?,opacity?} delegates an explicit V2 recipe with matching square// dimensions/usage. RGBA is four bytes; V3 opacity/alpha are bytes0..255 default255. Shapediff --git a/src/__tests__/procedural-cellular.test.ts b/src/__tests__/procedural-cellular.test.tsnew file mode 100644index 00000000..c44094f1--- /dev/null+++ b/src/__tests__/procedural-cellular.test.ts@@ -0,0 +1,665 @@+import { createHash } from 'node:crypto';+import { describe, expect, test } from 'bun:test';++import {+ CELLULAR_FEATURES,+ type CanonicalCellularLayer,+ type CellularField,+ cellularFieldBytes,+ cellularSearchRadius,+ cellularWorkPerTexel,+ prepareCellularField,+ sampleCellularFeature,+ searchCellular,+} from '../procedural-cellular';+import {+ type ProceduralLayer,+ ProceduralTextureError,+ canonicalProceduralTextureJsonV2,+ canonicalizeProceduralTextureSpecV2,+ compileProceduralTextureSpecV2,+ hashProceduralTextureSpecV2,+ proceduralTexture,+} from '../procedural-texture';+import { compileProceduralTextureSpecV3 } from '../procedural-texture-v3';+import { admitProceduralTextureSpecV3 } from '../procedural-texture-v3-contract';++type CellularInput = Extract<ProceduralLayer, { op: 'cellular' }>;++const cellular = (fields: Partial<CellularInput> = {}): CellularInput => ({+ op: 'cellular',+ colorA: 0x000000,+ colorB: 0xffffff,+ ...fields,+});++const spec = (layer: ProceduralLayer, size = 64) => ({+ schemaVersion: 2 as const,+ size,+ usage: 'albedo' as const,+ layers: [layer],+});++const canonicalLayer = (fields: Partial<CellularInput> = {}): CanonicalCellularLayer =>+ canonicalizeProceduralTextureSpecV2(spec(cellular(fields))).layers[0] as CanonicalCellularLayer;++const sha = (pixels: Uint8Array): string => createHash('sha256').update(pixels).digest('hex');++/** Every image of every cell inside a generous box, with no pruning and no search radius. */+function oracle(field: CellularField, x: number, y: number): { f1: number; f2: number } {+ const { layer, px, py, weights } = field;+ const reach = Math.max(cellularSearchRadius(layer).x, cellularSearchRadius(layer).y) + 3;+ let f1 = Infinity;+ let f2 = Infinity;+ for (let j = Math.floor(y) - reach; j <= Math.floor(y) + reach; j++) {+ for (let i = Math.floor(x) - reach; i <= Math.floor(x) + reach; i++) {+ const wi = ((i % layer.cellsX) + layer.cellsX) % layer.cellsX;+ const wj = ((j % layer.cellsY) + layer.cellsY) % layer.cellsY;+ const k = wj * layer.cellsX + wi;+ const dx = (i + px[k]! - x) * layer.metricX;+ const dy = (j + py[k]! - y) * layer.metricY;+ const d = Math.sqrt(dx * dx + dy * dy) + weights[k]!;+ if (d < f1) {+ f2 = f1;+ f1 = d;+ } else if (d < f2) {+ f2 = d;+ }+ }+ }+ return { f1, f2 };+}++/** Largest search error over a grid of samples, against the unbounded oracle. */+function searchError(layer: CanonicalCellularLayer, field = prepareCellularField(layer)): number {+ let worst = 0;+ const steps = 12;+ for (let sy = 0; sy < steps; sy++) {+ for (let sx = 0; sx < steps; sx++) {+ // Include samples hard against a cell edge, where the worst case lives.+ const u = (sx + (sx % 2 === 0 ? 1e-6 : 0.5)) / steps;+ const v = (sy + (sy % 2 === 0 ? 1e-6 : 0.5)) / steps;+ const found = searchCellular(field, u, v);+ const truth = oracle(field, u * layer.cellsX, v * layer.cellsY);+ worst = Math.max(worst, Math.abs(found.f1 - truth.f1), Math.abs(found.f2 - truth.f2));+ }+ }+ return worst;+}++/** Plant every cell point at one extreme of its jitter box, the adversarial layout. */+function adversarial(layer: CanonicalCellularLayer, cornerX: number, cornerY: number) {+ const field = prepareCellularField(layer);+ const px = field.px as Float64Array;+ const py = field.py as Float64Array;+ const weights = field.weights as Float64Array;+ for (let k = 0; k < px.length; k++) {+ px[k] = 0.5 + (cornerX - 0.5) * layer.jitterX;+ py[k] = 0.5 + (cornerY - 0.5) * layer.jitterY;+ weights[k] = layer.weight;+ }+ return field;+}++describe('cellular layer contract', () => {+ test('canonicalization applies defaults and makes explicit defaults byte-identical', () => {+ const implicit = spec(cellular());+ const explicit = spec(+ cellular({+ cellsX: 8,+ cellsY: 8,+ seed: 0,+ jitterX: 1,+ jitterY: 1,+ metricX: 1,+ metricY: 1,+ weight: 0,+ feature: 'f1',+ range: 1,+ borderOpen: 0.5,+ borderWidth: 0.05,+ facetSlope: 0.5,+ facetBlend: 0.1,+ }),+ );+ expect(canonicalProceduralTextureJsonV2(implicit)).toBe(+ canonicalProceduralTextureJsonV2(explicit),+ );+ expect(hashProceduralTextureSpecV2(implicit)).toBe(hashProceduralTextureSpecV2(explicit));+ // A canonical spec is a fixed point, because hashing re-canonicalizes it.+ const canonical = canonicalizeProceduralTextureSpecV2(implicit);+ expect(canonicalizeProceduralTextureSpecV2(canonical)).toEqual(canonical);+ });++ const refusals: Array<[string, Partial<CellularInput> | Record<string, unknown>, RegExp]> = [+ ['cellsX below one', { cellsX: 0 }, /cellsX must be a whole number between 1 and 256/],+ ['cellsY above the cap', { cellsY: 257 }, /cellsY must be a whole number between 1 and 256/],+ ['fractional cells', { cellsX: 2.5 }, /cellsX must be a whole number/],+ ['jitter above one', { jitterX: 1.5 }, /jitterX must be a finite number between 0 and 1/],+ ['negative jitter', { jitterY: -0.1 }, /jitterY must be a finite number between 0 and 1/],+ ['metric below one', { metricX: 0.5 }, /metricX must be a finite number between 1 and 4/],+ ['metric above four', { metricY: 5 }, /metricY must be a finite number between 1 and 4/],+ ['weight above range', { weight: 1.5 }, /weight must be a finite number between 0 and 1/],+ ['unknown feature', { feature: 'f3' }, /feature "f3" is not one of f1, f2, f2-f1, cell/],+ ['non-finite range', { range: Number.NaN }, /range must be a finite number/],+ ['zero range', { range: 0 }, /range must be a finite number between 0.01 and 8/],+ ['seed out of range', { seed: 2 ** 31 }, /seed must be a whole number/],+ ['unknown field', { octaves: 3 }, /has unknown key "octaves"/],+ [+ 'open fraction out of range',+ { feature: 'border', borderOpen: 1.5 },+ /borderOpen must be a finite number between 0 and 1/,+ ],+ [+ 'zero border width',+ { feature: 'border', borderWidth: 0 },+ /borderWidth must be a finite number between 0.001 and 1/,+ ],+ [+ 'slope out of range',+ { feature: 'facet', facetSlope: 1.5 },+ /facetSlope must be a finite number between 0 and 1/,+ ],+ [+ 'zero blend',+ { feature: 'facet', facetBlend: 0 },+ /facetBlend must be a finite number between 0.001 and 1/,+ ],+ [+ 'a field the feature ignores',+ { feature: 'f1', borderOpen: 0.25 },+ /borderOpen applies only to feature "border", not "f1"/,+ ],+ [+ 'range on a feature with no ramp',+ { feature: 'border', range: 2 },+ /range applies only to features f1, f2, f2-f1, cell, not "border"/,+ ],+ [+ 'facet control on a border',+ { feature: 'border', facetBlend: 0.5 },+ /facetBlend applies only to feature "facet", not "border"/,+ ],+ ];+ for (const [name, fields, message] of refusals) {+ test(`refuses ${name} with a message naming the rule`, () => {+ const compile = (): unknown =>+ compileProceduralTextureSpecV2(spec(cellular(fields as Partial<CellularInput>)));+ expect(compile).toThrow(ProceduralTextureError);+ expect(compile).toThrow(message);+ });+ }++ test('reaches the ordinary texture path and survives the strict V3 boundary', () => {+ const texture = proceduralTexture(spec(cellular({ feature: 'cell' }), 16));+ expect(texture.image.width).toBe(16);+ expect(() =>+ compileProceduralTextureSpecV3({+ schemaVersion: 3,+ width: 16,+ height: 16,+ usage: 'albedo',+ operations: [{ op: 'legacy-v2', spec: spec(cellular({ cellsX: 2 }), 16) }],+ }),+ ).not.toThrow();+ });+});++describe('exact neighbour search', () => {+ test('the search radius follows the stated bound', () => {+ // Full jitter, unit metric: a point can sit a whole cell from its own cell's far edge, so+ // F2 can reach sqrt(1.5^2 + 1^2) = 1.80 and a 3x3 window would miss a true neighbour.+ expect(cellularSearchRadius(canonicalLayer())).toEqual({ x: 2, y: 2 });+ // No jitter is a plain grid: F2 is at most sqrt(1 + .25), one ring is enough.+ expect(cellularSearchRadius(canonicalLayer({ jitterX: 0, jitterY: 0 }))).toEqual({+ x: 1,+ y: 1,+ });+ // A strong metric on one axis makes the other axis' neighbours relatively closer.+ expect(cellularSearchRadius(canonicalLayer({ metricY: 4 }))).toEqual({ x: 5, y: 2 });+ expect(cellularSearchRadius(canonicalLayer({ metricY: 4, weight: 1 }))).toEqual({+ x: 6,+ y: 2,+ });+ });++ const corners: Array<Partial<CellularInput>> = [];+ for (const jitterX of [0, 0.35, 1])+ for (const jitterY of [0, 1])+ for (const [metricX, metricY] of [+ [1, 1],+ [1, 4],+ [4, 1],+ [2.5, 1],+ ] as const)+ for (const weight of [0, 1]) corners.push({ jitterX, jitterY, metricX, metricY, weight });++ test('agrees with an unbounded search on seeded layouts at every parameter corner', () => {+ for (const corner of corners) {+ for (const [cellsX, cellsY] of [+ [1, 1],+ [2, 5],+ [7, 3],+ ] as const) {+ const layer = canonicalLayer({ ...corner, cellsX, cellsY, seed: cellsX * 31 + cellsY });+ expect(searchError(layer)).toBeLessThan(1e-9);+ }+ }+ });++ test('agrees with an unbounded search when every point is at an extreme of its box', () => {+ for (const corner of corners) {+ for (const [cornerX, cornerY] of [+ [0, 0],+ [1, 0],+ [0, 1],+ [1, 1],+ ] as const) {+ const layer = canonicalLayer({ ...corner, cellsX: 6, cellsY: 6 });+ expect(searchError(layer, adversarial(layer, cornerX, cornerY))).toBeLessThan(1e-9);+ }+ }+ });++ test('negative control: one ring fewer than the bound misses the true nearest cell', () => {+ // Every point within one ring of the sample is at least 1.116 away, and the point two columns+ // along is 1.002 away. This proves the oracle can see a miss and the 5x5 default is not slack.+ const layer = canonicalLayer({ cellsX: 8, cellsY: 8 });+ const plant = (field: CellularField): CellularField => {+ for (let j = 0; j < 8; j++) {+ for (let i = 0; i < 8; i++) {+ (field.px as Float64Array)[j * 8 + i] = i === 0 || i === 2 ? 0.001 : 0.999;+ (field.py as Float64Array)[j * 8 + i] = j === 4 ? 0.999 : 0.001;+ }+ }+ (field.py as Float64Array)[3 * 8 + 2] = 0.5;+ return field;+ };+ const u = 0.999 / 8;+ const v = 3.5 / 8;+ const full = plant(prepareCellularField(layer));+ expect(searchCellular(full, u, v).f1).toBeCloseTo(1.002, 9);+ expect(searchCellular(full, u, v).f1).toBeCloseTo(oracle(full, u * 8, v * 8).f1, 9);+ const narrow = plant(prepareCellularField(layer, { x: 1, y: 1 }));+ expect(searchCellular(narrow, u, v).f1).toBeGreaterThan(1.11);+ });++ test('ordinary seeded layouts stay exact while pruning most of the window', () => {+ const layer = canonicalLayer({ cellsX: 16, cellsY: 16, seed: 3 });+ const field = prepareCellularField(layer);+ let cells = 0;+ const steps = 128;+ for (let y = 0; y < steps; y++) {+ for (let x = 0; x < steps; x++) {+ cells += searchCellular(field, (x + 0.5) / steps, (y + 0.5) / steps).visited;+ }+ }+ expect(cells / (steps * steps)).toBeLessThan(10);+ });+});++describe('features', () => {+ test('every feature is deterministic and changes with the seed', () => {+ for (const feature of CELLULAR_FEATURES) {+ const one = compileProceduralTextureSpecV2(spec(cellular({ feature, seed: 11 })));+ const again = compileProceduralTextureSpecV2(spec(cellular({ feature, seed: 11 })));+ const other = compileProceduralTextureSpecV2(spec(cellular({ feature, seed: 12 })));+ expect(sha(again.pixels)).toBe(sha(one.pixels));+ expect(again.recipeHash).toBe(one.recipeHash);+ expect(sha(other.pixels)).not.toBe(sha(one.pixels));+ expect(other.recipeHash).not.toBe(one.recipeHash);+ }+ });++ test('pixels are pinned, because the recipe hash carries no compiler id', () => {+ // These hashes are the algorithm's identity. A change here moves pixels under an unchanged+ // recipe hash, so it needs a new op or field rather than a re-pin.+ const golden = Object.fromEntries(+ CELLULAR_FEATURES.map((feature) => [+ feature,+ sha(+ compileProceduralTextureSpecV2(+ spec(+ cellular({+ feature,+ seed: 1234,+ cellsX: 7,+ cellsY: 11,+ jitterX: 0.8,+ jitterY: 0.4,+ metricY: 2,+ weight: 0.25,+ colorA: 0x102030,+ colorB: 0xe0d0c0,+ }),+ 128,+ ),+ ).pixels,+ ),+ ]),+ );+ expect(golden).toEqual(GOLDEN_PIXELS);+ });++ test('cell gives one flat tone per cell', () => {+ const layer = canonicalLayer({ feature: 'cell', cellsX: 5, cellsY: 5, seed: 8 });+ const field = prepareCellularField(layer);+ const tone = new Map<number, number>();+ for (let y = 0; y < 96; y++) {+ for (let x = 0; x < 96; x++) {+ const u = (x + 0.5) / 96;+ const v = (y + 0.5) / 96;+ const id = searchCellular(field, u, v).id1;+ const value = sampleCellularFeature(field, u, v);+ expect(tone.get(id) ?? value).toBe(value);+ tone.set(id, value);+ }+ }+ expect(new Set(tone.values()).size).toBeGreaterThan(15);+ });++ test('range on cell picks out a sparse population of flat tones', () => {+ // A linear ramp alone cannot make a few dark crystals among many pale ones. Saturating the+ // tone can: about a fifth of the cells keep a tone and the rest reach colorB exactly.+ const pixels = compileProceduralTextureSpecV2(+ spec(cellular({ feature: 'cell', range: 0.2, cellsX: 32, cellsY: 32, seed: 4 }), 256),+ ).pixels;+ let saturated = 0;+ for (let i = 0; i < pixels.length; i += 4) if (pixels[i] === 255) saturated++;+ const fraction = saturated / (256 * 256);+ expect(fraction).toBeGreaterThan(0.7);+ expect(fraction).toBeLessThan(0.9);+ });++ test('a border is opened by a hash that does not depend on which side you stand', () => {+ // Walk across a whole tile and check that every observed pair gets one state, in either order.+ const layer = canonicalLayer({ feature: 'border', cellsX: 9, cellsY: 9, seed: 21 });+ const field = prepareCellularField(layer);+ const state = new Map<string, number>();+ let swapped = 0;+ for (let y = 0; y < 256; y++) {+ for (let x = 0; x < 256; x++) {+ const u = (x + 0.5) / 256;+ const v = (y + 0.5) / 256;+ const { id1, id2, f1, f2 } = searchCellular(field, u, v);+ const key = `${Math.min(id1, id2)}:${Math.max(id1, id2)}`;+ const value = sampleCellularFeature(field, u, v);+ if (f2 - f1 < layer.borderWidth * 0.25) {+ const open = value > 0 ? 1 : 0;+ if (state.has(key) && id1 > id2) swapped++;+ expect(state.get(key) ?? open).toBe(open);+ state.set(key, open);+ }+ }+ }+ expect(swapped).toBeGreaterThan(0);+ const open = [...state.values()].filter(Boolean).length;+ expect(open / state.size).toBeGreaterThan(0.3);+ expect(open / state.size).toBeLessThan(0.7);+ });++ test('borderOpen 0 closes every border and 1 opens every border', () => {+ const closed = compileProceduralTextureSpecV2(+ spec(cellular({ feature: 'border', borderOpen: 0, seed: 2 })),+ );+ expect(Math.max(...closed.pixels.filter((_, i) => i % 4 === 0))).toBe(0);+ const layer = canonicalLayer({ feature: 'border', borderOpen: 1, seed: 2 });+ const field = prepareCellularField(layer);+ let checked = 0;+ for (let y = 0; y < 128; y++) {+ for (let x = 0; x < 128; x++) {+ const u = (x + 0.5) / 128;+ const v = (y + 0.5) / 128;+ const { f1, f2 } = searchCellular(field, u, v);+ if (f2 - f1 < layer.borderWidth * 0.25) {+ expect(sampleCellularFeature(field, u, v)).toBeGreaterThan(0.5);+ checked++;+ }+ }+ }+ expect(checked).toBeGreaterThan(0);+ });++ test('an open border can end at a closed one, which is what stops crazy paving', () => {+ const layer = canonicalLayer({ feature: 'border', cellsX: 12, cellsY: 12, seed: 5 });+ const field = prepareCellularField(layer);+ // A cell with both an open and a closed border has a crack that stops at its corner.+ const open = new Map<number, Set<number>>();+ for (let y = 0; y < 256; y++) {+ for (let x = 0; x < 256; x++) {+ const u = (x + 0.5) / 256;+ const v = (y + 0.5) / 256;+ const { id1, f1, f2 } = searchCellular(field, u, v);+ if (f2 - f1 < layer.borderWidth * 0.25) {+ const states = open.get(id1) ?? new Set<number>();+ states.add(sampleCellularFeature(field, u, v) > 0 ? 1 : 0);+ open.set(id1, states);+ }+ }+ }+ const mixed = [...open.values()].filter((states) => states.size === 2).length;+ expect(mixed / open.size).toBeGreaterThan(0.5);+ });++ test('facets are continuous everywhere, including where a second neighbour changes', () => {+ // A plane pair blended only across F1/F2 jumps on the line where F2 and F3 swap, near each+ // corner. The largest step between adjacent samples must shrink with the sample spacing.+ const layer = canonicalLayer({+ feature: 'facet',+ cellsX: 6,+ cellsY: 6,+ seed: 17,+ facetSlope: 1,+ facetBlend: 0.15,+ });+ const field = prepareCellularField(layer);+ const largestStep = (steps: number): number => {+ let largest = 0;+ let previousRow: number[] = [];+ for (let y = 0; y < steps; y++) {+ const row: number[] = [];+ for (let x = 0; x < steps; x++) {+ const value = sampleCellularFeature(field, (x + 0.5) / steps, (y + 0.5) / steps);+ row.push(value);+ if (x > 0) largest = Math.max(largest, Math.abs(value - row[x - 1]!));+ if (y > 0) largest = Math.max(largest, Math.abs(value - previousRow[x]!));+ }+ previousRow = row;+ }+ return largest;+ };+ const coarse = largestStep(256);+ const fine = largestStep(1024);+ expect(fine).toBeLessThan(coarse * 0.45);+ });++ test('a narrow facet blend keeps a flat plane inside each cell', () => {+ const layer = canonicalLayer({+ feature: 'facet',+ cellsX: 4,+ cellsY: 4,+ seed: 3,+ facetSlope: 0.5,+ facetBlend: 0.05,+ });+ const field = prepareCellularField(layer);+ // Far from any border, a second difference along a line is zero: the surface is a plane.+ let measured = 0;+ for (let y = 8; y < 248; y += 8) {+ for (let x = 8; x < 248; x += 8) {+ const u = x / 256;+ const v = y / 256;+ const e = 1 / 2048;+ const near = [u - e, u, u + e].map((p) => searchCellular(field, p, v));+ if (near.some(({ f1, f2 }) => f2 - f1 < layer.facetBlend + 0.01)) continue;+ if (near[0]!.id1 !== near[2]!.id1) continue;+ const [a, b, c] = [u - e, u, u + e].map((p) => sampleCellularFeature(field, p, v));+ expect(Math.abs(a! - 2 * b! + c!)).toBeLessThan(1e-9);+ measured++;+ }+ }+ expect(measured).toBeGreaterThan(50);+ });+});++describe('tiling', () => {+ // A wrap difference must be inside what the interior already does, on every channel.+ const wrapWithinInterior = (pixels: Uint8Array, size: number): void => {+ const at = (x: number, y: number): number => pixels[(y * size + x) * 4]!;+ let interior = 0;+ for (let y = 0; y < size; y++)+ for (let x = 0; x + 1 < size; x++) {+ interior = Math.max(interior, Math.abs(at(x, y) - at(x + 1, y)));+ }+ for (let y = 0; y + 1 < size; y++)+ for (let x = 0; x < size; x++) {+ interior = Math.max(interior, Math.abs(at(x, y) - at(x, y + 1)));+ }+ for (let i = 0; i < size; i++) {+ expect(Math.abs(at(size - 1, i) - at(0, i))).toBeLessThanOrEqual(interior);+ expect(Math.abs(at(i, size - 1) - at(i, 0))).toBeLessThanOrEqual(interior);+ }+ };++ for (const feature of CELLULAR_FEATURES) {+ test(`${feature} is one period: a shifted lattice gives the same pixels`, () => {+ for (const [cellsX, cellsY] of [+ [1, 1],+ [3, 5],+ [8, 8],+ ] as const) {+ const layer = canonicalLayer({ feature, cellsX, cellsY, seed: 9, weight: 0.5 });+ const field = prepareCellularField(layer);+ for (let i = 0; i < 40; i++) {+ // Sample just inside and just outside each wrap edge. Outside the tile, the wrapped+ // lattice index must see the same cells, so the value is continuous through the edge.+ const v = (i + 0.5) / 40;+ const seam = Math.abs(+ sampleCellularFeature(field, 1e-9, v) - sampleCellularFeature(field, 1 - 1e-9, v),+ );+ const across = Math.abs(+ sampleCellularFeature(field, v, 1e-9) - sampleCellularFeature(field, v, 1 - 1e-9),+ );+ const ceiling = feature === 'cell' || feature === 'border' ? 1 : 1e-6;+ expect(seam).toBeLessThanOrEqual(ceiling);+ expect(across).toBeLessThanOrEqual(ceiling);+ }+ wrapWithinInterior(+ compileProceduralTextureSpecV2(spec(cellular({ feature, cellsX, cellsY, seed: 9 }), 128))+ .pixels,+ 128,+ );+ }+ });+ }++ test('a one-cell tile still has a border, between a cell and its own image', () => {+ const layer = canonicalLayer({ feature: 'f2-f1', cellsX: 1, cellsY: 1, seed: 6 });+ const field = prepareCellularField(layer);+ const found = searchCellular(field, 0.5, 0.5);+ expect(found.id1).toBe(0);+ expect(found.id2).toBe(0);+ expect(found.f2).toBeGreaterThan(found.f1);+ });+});++describe('V3 work and allocation budgets', () => {+ const legacy = (layer: ProceduralLayer, size: number) => ({+ schemaVersion: 3 as const,+ width: size,+ height: size,+ usage: 'albedo' as const,+ operations: [{ op: 'legacy-v2', spec: spec(layer, size) }],+ });++ test('a cellular layer is charged its own cost, not the flat pattern cost', () => {+ const layer = canonicalLayer({ cellsX: 8, cellsY: 8 });+ const admitted = admitProceduralTextureSpecV3(legacy(cellular({ cellsX: 8, cellsY: 8 }), 64));+ const texels = 64 * 64;+ expect(admitted.estimatedWorkUnits).toBe(+ texels + texels * (1 + cellularWorkPerTexel(layer)) + 8 * 8 * 12,+ );+ expect(cellularWorkPerTexel(layer)).toBeGreaterThan(4);+ expect(admitted.conservativePixelAllocationBytes).toBe(texels * 8 + cellularFieldBytes(layer));+ });++ test('cost grows with the window, and the widest window costs the most', () => {+ const narrow = cellularWorkPerTexel(canonicalLayer({ jitterX: 0, jitterY: 0 }));+ const wide = cellularWorkPerTexel(canonicalLayer({ metricY: 4, weight: 1 }));+ const facet = cellularWorkPerTexel(+ canonicalLayer({ metricY: 4, weight: 1, feature: 'facet', facetBlend: 1 }),+ );+ const tone = cellularWorkPerTexel(canonicalLayer({ feature: 'cell' }));+ expect(narrow).toBeLessThan(wide);+ expect(wide).toBeLessThan(facet);+ expect(tone).toBeLessThanOrEqual(cellularWorkPerTexel(canonicalLayer()));+ });++ test('a default layer fits at 1024, and a stack that does not is refused by the budget rule', () => {+ expect(() => admitProceduralTextureSpecV3(legacy(cellular(), 1024))).not.toThrow();+ const layers = Array.from({ length: 4 }, () => cellular({ blend: 'multiply', opacity: 0.5 }));+ expect(() =>+ admitProceduralTextureSpecV3({+ schemaVersion: 3,+ width: 1024,+ height: 1024,+ usage: 'albedo',+ operations: [+ {+ op: 'legacy-v2',+ spec: { schemaVersion: 2, size: 1024, usage: 'albedo', layers },+ },+ ],+ }),+ ).toThrow(/estimated work budget \d+ exceeds 64000000/);+ // The same stack is admitted at a size that fits.+ expect(() =>+ admitProceduralTextureSpecV3({+ schemaVersion: 3,+ width: 256,+ height: 256,+ usage: 'albedo',+ operations: [+ { op: 'legacy-v2', spec: { schemaVersion: 2, size: 256, usage: 'albedo', layers } },+ ],+ }),+ ).not.toThrow();+ });++ test('through V3 the pixels are the V2 pixels', () => {+ const layer = cellular({ cellsX: 5, cellsY: 3, feature: 'facet', seed: 4 });+ const v2 = compileProceduralTextureSpecV2(spec(layer, 32));+ const v3 = compileProceduralTextureSpecV3({+ schemaVersion: 3,+ width: 32,+ height: 32,+ usage: 'albedo',+ background: [0, 0, 0, 255],+ operations: [{ op: 'legacy-v2', spec: spec(layer, 32) }],+ });+ expect(sha(v3.pixels)).toBe(sha(v2.pixels));+ });++ test('V2 itself keeps its size and layer limits and no work budget', () => {+ const layers = Array.from({ length: 8 }, () => cellular({ cellsX: 4, cellsY: 4 }));+ expect(() =>+ canonicalizeProceduralTextureSpecV2({ schemaVersion: 2, size: 1024, layers }),+ ).not.toThrow();+ expect(() =>+ canonicalizeProceduralTextureSpecV2({+ schemaVersion: 2,+ size: 1024,+ layers: [...layers, cellular()],+ }),+ ).toThrow(/exceeds the maximum of 8/);+ });+});++const GOLDEN_PIXELS: Record<string, string> = {+ f1: '668e8eea5f94eedee007eccf72378edf48ef90c08f4e0a59060e98554151c54a',+ f2: 'a454aea66bd942924e153e56489d519893245845cf62a595c393258b7a851042',+ 'f2-f1': 'bb9f582fd0ff490004d2f38cc0aa43205843410a8a7f2009a1b0f0dcd3ff534b',+ cell: '7daaa6f9fac8fc9d02aa9c38a7e2cb3a118d6a38ede17fa84fae0e59b34795c5',+ border: '11b3e399c4964e358951dd106eb32fb0650305c2b18a2637039c39e988b98a54',+ facet: '08b32693f2bac4657cfe73323a18399a58d4f49e45fdd612bcd805ab6abae84d',+};diff --git a/src/discovery/helper-contracts.ts b/src/discovery/helper-contracts.tsindex b17cfd4a..e1e2a63c 100644--- a/src/discovery/helper-contracts.ts+++ b/src/discovery/helper-contracts.ts@@ -2779,12 +2779,13 @@ define('V3 paint/mask use integer pixel-edge shapes with binary center coverage and fixed integer source-over rounding. A mask clears outside its shape; invert keeps outside. Zero-alpha pixels are transparent black.','V3 color-only palette colors are 1..32 RGB integers, optional fixed Bayer4 dither. Stamps (any usage) use bounded Xorshift32 seed/area placement; periodic wrapping is explicit and at most 256 expanded copies. Legacy-v2 layers delegate unchanged square V2 patterns with matching usage.','Pattern counts 1..256 and noise octaves 1..6; seeded patterns are deterministic.',+ 'The cellular layer is a periodic Worley/Voronoi field: integer cellsX/cellsY per tile, per-axis jitter, an anisotropic metric, optional additive weights, and a feature (f1, f2, f2-f1, cell, border, facet) mapped onto colorA..colorB. It tiles exactly at any size.','For stripes and gradient, angleDeg rotates the direction of color variation in UV space about the image center. At 0 degrees colors vary across U: stripe bands run along V. At 90 degrees colors vary across V: bands run along U. This does not rotate the mesh UVs.','Stripes count is the number of alternating bands across one unit of the projected coordinate, not the number of colorA/colorB pairs. Gradient runs from its from color to its to color along that coordinate and clamps outside 0..1.','Unknown keys, callbacks, paths, URLs and shader source are rejected.',],preservation: ['Produces repeat-wrapped encoded texture content; color space follows usage.'],- cost: 'V2 retains pixel/layer budgets. V3 preflights at most 1,048,576 texels, 64million work units including polygon edges, palette comparisons and periodic copies, and 64MiB transient bytes.',+ cost: 'V2 retains pixel/layer budgets. V3 preflights at most 1,048,576 texels, 64million work units including polygon edges, palette comparisons and periodic copies, and 64MiB transient bytes. A cellular layer through legacy-v2 is charged about 50 units per texel, so one default layer fits at 1024 and a stack needs a smaller size.',},{references: [@@ -2792,8 +2793,15 @@ define('src/procedural-texture-v3-contract.ts','docs/procedural-surfaces-v3.md',],- tags: ['texture', 'procedural', 'deterministic'],- aliases: ['generated texture', 'noise texture', 'layered pattern'],+ tags: ['texture', 'procedural', 'deterministic', 'cellular', 'Worley', 'Voronoi'],+ aliases: [+ 'generated texture',+ 'noise texture',+ 'layered pattern',+ 'cellular noise',+ 'worley noise',+ 'voronoi noise',+ ],intents: ['generate a repeatable texture without external image files'],limitations: ['Repeat wrapping does not guarantee matching edge colors. Odd stripe counts, angled patterns and nonconstant gradients can show seams; inspect the chosen pattern at its repeat boundaries.',diff --git a/src/discovery/helper-specs.ts b/src/discovery/helper-specs.tsindex 807be2b5..1a87e78d 100644--- a/src/discovery/helper-specs.ts+++ b/src/discovery/helper-specs.ts@@ -1165,7 +1165,7 @@ const PRIMITIVES: HelperSpec[] = [example:"const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });",promptNotes:- "V2 layer fields by op: solid: { color }; checker: { colorA, colorB, squares? }; stripes: { colorA, colorB, count?, angleDeg? }; gradient: { from, to, angleDeg? }; bricks: { brick, mortar, rows?, cols?, mortarWidth?: 0..1 (fraction of a brick cell, default 0.06), stagger?: 0..1 (row offset fraction, default 0.5) }; noise: { colorA, colorB, scale?, octaves?, seed? }. V2 blend normal|multiply|screen|overlay; opacity 0..1; max 8 layers, counts 1..256, octaves 1..6. V3 operations: paint {shape,rgba,opacity?}; mask {shape,alpha?,invert?}; stamps {shape,rgba,count,seed,area,periodic?,opacity?}; legacy-v2 {spec,alpha?,opacity?} delegates an explicit V2 recipe with matching square dimensions/usage. RGBA is four bytes; V3 opacity/alpha are bytes0..255 default255. Shape kinds: rectangle/ellipse {x,y,width,height}; polygon {points:[[x,y],...]}; line {from:[x,y],to:[x,y],width}. Coordinates are integer pixel edges; centers define binary coverage, round line caps. Mask clears outside; invert keeps outside instead. area {x,y,width,height} sets seeded stamp translation offsets; periodic:true wraps copies explicitly. V3 background defaults transparent black, max64 ops,64 polygon vertices,256 expanded stamps (periodic counts9),32 palette colors,64million estimated work including edges. palette {colors:[RGB integers],dither?:'none'|'bayer4'} and stamps are albedo/emissive only. Zero alpha normalizes RGB to0. Sampler defaults remain repeat/linear/mips; alphaMode belongs to pbrMaterial. Sync; strict JSON rejects unknown/prototype fields and accessors. See docs/procedural-surfaces-v3.md for exact rounding and bounds.",+ "V2 layer fields by op: solid: { color }; checker: { colorA, colorB, squares? }; stripes: { colorA, colorB, count?, angleDeg? }; gradient: { from, to, angleDeg? }; bricks: { brick, mortar, rows?, cols?, mortarWidth?: 0..1 (fraction of a brick cell, default 0.06), stagger?: 0..1 (row offset fraction, default 0.5) }; noise: { colorA, colorB, scale?, octaves?, seed? }; cellular: { colorA, colorB, cellsX?, cellsY?: 1..256 cells per tile, default 8; seed?; jitterX?, jitterY?: 0..1, default 1; metricX?, metricY?: 1..4, default 1, a larger metric thins joints across that axis; weight?: 0..1 additive cell weight drawn from the seed, default 0, curves borders and varies cell size; feature?: 'f1'|'f2'|'f2-f1'|'cell'|'border'|'facet', default f1; range?: 0.01..8 (f1, f2, f2-f1 and cell: the value that reaches colorB, default 1; below 1 on cell it leaves a sparse population of toned cells); borderOpen?: 0..1, default 0.5, borderWidth?: 0.001..1, default 0.05 (border: colorB in the opened joints); facetSlope?: 0..1, default 0.5, facetBlend?: 0.001..1, default 0.1 (facet: a tilted plane per cell, blended across borders, for height) }. A field the chosen feature ignores is an error. Reuse one layout and seed across layers and maps so joints line up. V2 blend normal|multiply|screen|overlay; opacity 0..1; max 8 layers, counts 1..256, octaves 1..6. V3 operations: paint {shape,rgba,opacity?}; mask {shape,alpha?,invert?}; stamps {shape,rgba,count,seed,area,periodic?,opacity?}; legacy-v2 {spec,alpha?,opacity?} delegates an explicit V2 recipe with matching square dimensions/usage. RGBA is four bytes; V3 opacity/alpha are bytes0..255 default255. Shape kinds: rectangle/ellipse {x,y,width,height}; polygon {points:[[x,y],...]}; line {from:[x,y],to:[x,y],width}. Coordinates are integer pixel edges; centers define binary coverage, round line caps. Mask clears outside; invert keeps outside instead. area {x,y,width,height} sets seeded stamp translation offsets; periodic:true wraps copies explicitly. V3 background defaults transparent black, max64 ops,64 polygon vertices,256 expanded stamps (periodic counts9),32 palette colors,64million estimated work including edges. palette {colors:[RGB integers],dither?:'none'|'bayer4'} and stamps are albedo/emissive only. Zero alpha normalizes RGB to0. Sampler defaults remain repeat/linear/mips; alphaMode belongs to pbrMaterial. Sync; strict JSON rejects unknown/prototype fields and accessors. See docs/procedural-surfaces-v3.md for exact rounding and bounds.",},{name: 'textureAtlas',diff --git a/src/discovery/lexical-index.test.ts b/src/discovery/lexical-index.test.tsindex d47fc51d..34193f9a 100644--- a/src/discovery/lexical-index.test.ts+++ b/src/discovery/lexical-index.test.ts@@ -152,4 +152,9 @@ test('Cove authoring words reach welding, crease, packed-roughness and V3 shapeexpect(await first('roughness map')).toBe('operation:pbrMaterial');expect(await first('packed roughness metalness texture')).toBe('operation:pbrMaterial');expect(await first('V3 texture ellipse polygon shape')).toBe('operation:proceduralTexture');+ // #312: the op is `cellular`, and authors search for it by these names.+ for (const name of ['voronoi', 'worley', 'cellular noise'])+ expect(['operation:proceduralTexture', 'recipe:cellular-stone-v1']).toContain(+ (await first(name)) ?? '',+ );});diff --git a/src/discovery/recipes.test.ts b/src/discovery/recipes.test.tsindex 3776149f..e4f25792 100644--- a/src/discovery/recipes.test.ts+++ b/src/discovery/recipes.test.ts@@ -47,6 +47,8 @@ test('recipe retrieval finds related ordinary language without changing host pol['attached raised vein seam', 'recipe:surface-detail-v1'],['alpha leaf card cutout', 'recipe:foliage-cutout-v1'],['stripes follow a curved rail', 'recipe:directional-sweep-v1'],+ ['fractured rock with open cracks', 'recipe:cellular-stone-v1'],+ ['rubble stones voronoi', 'recipe:cellular-stone-v1'],] as const) {const result = await query({ query: text, kind: 'recipe' });expect(result.entries.slice(0, 6).map((e) => e.id)).toContain(id);@@ -131,6 +133,18 @@ function constructionExample(id: string): string {return entry!.recipe.example;}+test('cellular stone recipe builds tiling colour and a matching height-derived normal', async () => {+ const source = constructionExample('recipe:cellular-stone-v1');+ const { root } = await executeKilnCode(source);+ const doc = await new WebIO().readBinary(+ (await renderSceneToGLB(root, { optimize: 'off' })).bytes,+ );+ const material = doc.getRoot().listMaterials()[0]!;+ expect(material.getBaseColorTexture()).not.toBeNull();+ expect(material.getNormalTexture()).not.toBeNull();+ expect(material.getMetallicRoughnessTexture()).not.toBeNull();+});+test('cutout recipe exports alpha-bearing material and UVs without treating its placeholder as production foliage', async () => {const source = constructionExample('recipe:foliage-cutout-v1');const { root } = await executeKilnCode(source);diff --git a/src/discovery/surface-recipes.ts b/src/discovery/surface-recipes.tsindex 9d66c0f7..3b712ba8 100644--- a/src/discovery/surface-recipes.ts+++ b/src/discovery/surface-recipes.ts@@ -127,4 +127,100 @@ function build() {],},},+ {+ version: 'kiln.catalog-entry.v1',+ id: 'recipe:cellular-stone-v1',+ kind: 'recipe',+ name: 'Cellular stone: rubble, crystals and fractured rock',+ summary:+ 'Build tiling stone from the periodic cellular (Worley/Voronoi) layer: one flat tone per stone or crystal, joints from the border distance, cracks opened per border, and faceted height for a derived normal. The example is bedded fractured rock; adapt the layout and features to the stone.',+ family: 'materials',+ tags: [+ 'cellular',+ 'Worley',+ 'Voronoi',+ 'stone',+ 'rock',+ 'rubble',+ 'granite',+ 'tiling',+ 'cracks',+ ],+ aliases: [+ 'voronoi noise',+ 'worley noise',+ 'cellular noise',+ 'crazy paving',+ 'irregular stones',+ 'crystal grain',+ 'open joints',+ ],+ intents: [+ 'make irregular rubble stones that tile',+ 'make fractured rock with open and closed cracks',+ 'give each crystal or stone its own tone',+ ],+ stability: 'experimental',+ related: [+ { id: 'operation:proceduralTexture', relation: 'prerequisite' },+ { id: 'operation:normalMapFromHeight', relation: 'prerequisite' },+ { id: 'operation:pbrMaterial', relation: 'prerequisite' },+ ],+ references: ['src/procedural-cellular.ts', 'docs/procedural-surfaces-v3.md'],+ limitations: [+ 'The example is a starting layout, not a finished rock. Appearance needs GPU review at the viewing distance: a closed isotropic net of cells reads as crazy paving, however exact it is.',+ 'The cell feature has hard edges with no antialiasing. A flat tone change with no joint over it reads as a pasted patch close up, so keep tonal contrast low between cells that share a closed border, or increase the texture size.',+ 'Border width is in metric units, so a larger metric on one axis thins the joints that cross that axis. A strong metric gives hairline bed joints beside soft vertical ones.',+ 'One saved texture repeats visibly at a distance. Tiling only removes the seam; it does not hide the period.',+ ],+ recipe: {+ prerequisites: [+ 'operation:proceduralTexture',+ 'operation:normalMapFromHeight',+ 'operation:pbrMaterial',+ ],+ steps: [+ 'Choose the layout once: cellsX and cellsY per tile, seed, jitter, metric and weight. Share that object across every cellular layer of every map, so tone, joints and height agree.',+ 'For beds, use low jitterY and a metricY above 1. For crystals, use full jitter, equal metrics and some weight to vary the crystal size.',+ 'Colour: start from the cell feature for a flat tone per stone, overlay noise for the surface, and multiply a dark f2-f1 or border layer over it. On border, borderOpen below 1 leaves closed joints, so cracks end in T-junctions.',+ 'Height: use f2-f1 for pillowed stones or facet for tilted fracture planes, multiply border over it for open cracks, and derive the normal from that height.',+ 'Review on the GPU route at the intended distance and at a raking angle, across at least two repeats.',+ ],+ example: `const meta = { name: 'CellularFracturedRock' };+function build() {+ const root = createRoot(meta.name);+ const beds = { cellsX: 6, cellsY: 12, seed: 83, jitterX: 0.9, jitterY: 0.45, metricY: 2, weight: 0.25 };+ const facets = { ...beds, feature: 'facet', facetSlope: 0.9, facetBlend: 0.3 };+ const joints = { ...beds, feature: 'border', borderOpen: 0.5, borderWidth: 0.06, blend: 'multiply' };+ const albedo = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', layers: [+ { op: 'cellular', ...beds, feature: 'cell', colorA: 0x6e6b65, colorB: 0x827e76 },+ { op: 'noise', colorA: 0x38362f, colorB: 0xc4c0b4, scale: 24, octaves: 5, seed: 84, blend: 'overlay', opacity: 0.6 },+ { op: 'cellular', ...facets, colorA: 0x606060, colorB: 0xffffff, blend: 'multiply', opacity: 0.5 },+ { op: 'cellular', ...joints, colorA: 0xffffff, colorB: 0x16130f },+ ] });+ const height = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', layers: [+ { op: 'cellular', ...facets, colorA: 0x000000, colorB: 0xffffff },+ { op: 'cellular', ...joints, colorA: 0xffffff, colorB: 0x000000 },+ ] });+ const packed = (roughness) => (255 << 16) | (roughness << 8);+ const metallicRoughness = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'metallicRoughness', layers: [+ { op: 'cellular', ...beds, feature: 'cell', colorA: packed(180), colorB: packed(235) },+ ] });+ const material = pbrMaterial({ albedo, normal: normalMapFromHeight(height, { strength: 5 }),+ metallicRoughness, roughness: 1, metalness: 1 });+ createPart('RockFace', planeGeo(2, 2), material, { parent: root });+ return root;+}`,+ adaptations: [+ 'Rubble: cellsX 7, cellsY 11, jitterX 0.8, jitterY 0.3, metricY 1.5, weight 0.2. Cell for tone, a multiplied dark f2-f1 with range 0.14 for the joints, f2-f1 with range 0.42 for a pillowed height.',+ 'Granite: full jitter, equal metrics, 64 cells and weight 0.5 for quartz. Add feldspar and biotite on other grids and seeds, with range on cell to leave a sparse population: range 0.16 keeps about a sixth of the cells dark.',+ 'To save a reusable material, put these recipes in a material draft with derive normal-from-height on the normal slot, then export maps for a destination that takes plain images.',+ ],+ checks: [+ 'Read viewFidelity. A CPU geometry view cannot judge this: only a material-faithful GPU view shows whether the surface reads as stone.',+ 'Look for the plaid and crazy-paving failures directly: straight joints running the whole tile, or every polygon closed and the same size.',+ 'Numerically, each exported map should differ across its wrap edge by no more than interior neighbouring texels do. Repeat at two sizes, because a derived normal is resampled rather than regenerated.',+ ],+ },+ },];diff --git a/src/material-authoring-schema.ts b/src/material-authoring-schema.tsindex e30f47c3..d5d48ddc 100644--- a/src/material-authoring-schema.ts+++ b/src/material-authoring-schema.ts@@ -22,6 +22,12 @@ import {TEXTURE_ATLAS_LIMITS_V1_2,TEXTURE_ATLAS_PACK_EDGES,} from './texture-atlas-contract';+import {+ CELLULAR_FEATURES,+ MAX_CELLULAR_METRIC,+ MAX_CELLULAR_WEIGHT,+ MIN_CELLULAR_METRIC,+} from './procedural-cellular';import {PORTABLE_MIN_FILTERS_V1,PORTABLE_MAG_FILTERS_V1,@@ -91,6 +97,28 @@ export const canonicalLegacyV2FieldSchema = (() => {...common,}).strict(),+ z+ .object({+ op: z.literal('cellular'),+ colorA: color,+ colorB: color,+ cellsX: count,+ cellsY: count,+ seed: z.number().int().min(-2147483648).max(2147483647),+ jitterX: unit,+ jitterY: unit,+ metricX: z.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC),+ metricY: z.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC),+ weight: z.number().min(0).max(MAX_CELLULAR_WEIGHT),+ feature: z.enum(CELLULAR_FEATURES),+ range: z.number().min(0.01).max(8),+ borderOpen: unit,+ borderWidth: z.number().min(0.001).max(1),+ facetSlope: unit,+ facetBlend: z.number().min(0.001).max(1),+ ...common,+ })+ .strict(),]),).min(1)diff --git a/src/material-cellular.test.ts b/src/material-cellular.test.tsnew file mode 100644index 00000000..c3951512--- /dev/null+++ b/src/material-cellular.test.ts@@ -0,0 +1,429 @@+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import sharp from 'sharp';+import type { MaterialRecordV1 } from './material-library';+import {+ createMaterialRecordV1,+ exportMaterialMaps,+ type MaterialDraftV1,+ verifyMaterialRecordV1,+} from './material-library-node';+import type { ProceduralLayer } from './procedural-material-v2';+import { compileProceduralTextureSpecV2 } from './procedural-texture';++const packed = (roughness: number): number => (255 << 16) | (roughness << 8);+const source = {+ id: 'authored',+ kind: 'procedural' as const,+ provider: 'Cellular worked example',+ creator: 'Kiln',+ license: {+ spdx: 'CC0-1.0',+ url: 'https://creativecommons.org/publicdomain/zero/1.0/',+ attribution: '',+ },+ originalFiles: [],+};++type Usage = 'albedo' | 'normal' | 'metallicRoughness';+const recipe = (usage: Usage, layers: ProceduralLayer[]) => ({+ schemaVersion: 2 as const,+ size: 256,+ usage,+ layers,+});++function draft(+ materialId: string,+ meters: number,+ albedo: ProceduralLayer[],+ height: ProceduralLayer[],+ strength: number,+ rough: ProceduralLayer[],+): MaterialDraftV1 {+ return {+ materialId,+ name: materialId,+ tags: ['rock', 'procedural'],+ tileable: true,+ physicalSizeMeters: { width: meters, height: meters },+ parameters: { metalness: 1, roughness: 1 },+ sources: [source],+ maps: [+ {+ slot: 'baseColor',+ sourceId: 'authored',+ transforms: [],+ procedural: recipe('albedo', albedo),+ },+ {+ slot: 'normal',+ sourceId: 'authored',+ transforms: [],+ procedural: recipe('normal', height),+ derive: { kind: 'normal-from-height', strength },+ },+ {+ slot: 'metallicRoughness',+ sourceId: 'authored',+ transforms: [],+ procedural: recipe('metallicRoughness', rough),+ },+ ],+ };+}++const cell = (fields: Record<string, unknown>, colorA: number, colorB: number): ProceduralLayer =>+ ({ op: 'cellular', ...fields, colorA, colorB }) as ProceduralLayer;++// One seed and one cell layout through every layer of every map, so the joints line up.+const stones = {+ cellsX: 7,+ cellsY: 11,+ seed: 41,+ jitterX: 0.8,+ jitterY: 0.3,+ metricY: 1.5,+ weight: 0.2,+};+const rubble = draft(+ 'cellular-rubble',+ 2,+ [+ cell({ ...stones, feature: 'cell' }, 0x6a6358, 0xb3a892),+ {+ op: 'noise',+ colorA: 0x3c3a36,+ colorB: 0xc8c4bc,+ scale: 32,+ octaves: 4,+ seed: 41,+ blend: 'overlay',+ opacity: 0.55,+ },+ cell({ ...stones, feature: 'f2-f1', range: 0.14, blend: 'multiply' }, 0x2b2722, 0xffffff),+ ],+ [+ cell({ ...stones, feature: 'f2-f1', range: 0.42 }, 0x000000, 0xe0e0e0),+ {+ op: 'noise',+ colorA: 0x404040,+ colorB: 0xc0c0c0,+ scale: 32,+ octaves: 4,+ seed: 42,+ blend: 'overlay',+ opacity: 0.35,+ },+ ],+ 3,+ [+ cell({ ...stones, feature: 'cell' }, packed(170), packed(225)),+ {+ op: 'noise',+ colorA: packed(120),+ colorB: packed(210),+ scale: 32,+ octaves: 3,+ seed: 43,+ blend: 'overlay',+ opacity: 0.5,+ },+ ],+);++// One flat tone per crystal. `range` on `cell` leaves about a sixth of the biotite grid dark.+const quartz = { cellsX: 64, cellsY: 64, seed: 7, weight: 0.5 };+const feldspar = { cellsX: 38, cellsY: 38, seed: 12, weight: 0.7 };+const biotite = { cellsX: 72, cellsY: 72, seed: 19, weight: 0.6, feature: 'cell', range: 0.16 };+const granite = draft(+ 'cellular-granite',+ 1,+ [+ cell({ ...quartz, feature: 'cell' }, 0x9a9794, 0xe4dfda),+ cell({ ...feldspar, feature: 'cell', range: 0.5, blend: 'multiply' }, 0xc4a999, 0xffffff),+ cell({ ...biotite, blend: 'multiply' }, 0x08080a, 0xffffff),+ ],+ [+ cell({ ...quartz, feature: 'facet', facetSlope: 0.9, facetBlend: 0.05 }, 0x404040, 0xc0c0c0),+ cell({ ...biotite, blend: 'multiply' }, 0xd8d8d8, 0xffffff),+ ],+ 1,+ [+ cell({ ...quartz, feature: 'cell' }, packed(60), packed(140)),+ cell({ ...biotite, blend: 'multiply' }, packed(90), packed(255)),+ ],+);++// Blocks kept in beds by low vertical jitter and a vertical metric, tilted per cell, with about+// half the joints opened so that cracks end in T-junctions instead of closing every polygon.+const beds = {+ cellsX: 6,+ cellsY: 12,+ seed: 83,+ jitterX: 0.9,+ jitterY: 0.45,+ metricY: 2,+ weight: 0.25,+};+const facets = { ...beds, feature: 'facet', facetSlope: 0.9, facetBlend: 0.3 };+const joints = {+ ...beds,+ feature: 'border',+ borderOpen: 0.5,+ borderWidth: 0.06,+ blend: 'multiply',+};+const rock = draft(+ 'cellular-fractured-rock',+ 3,+ [+ cell({ ...beds, feature: 'cell' }, 0x6e6b65, 0x827e76),+ {+ op: 'noise',+ colorA: 0x38362f,+ colorB: 0xc4c0b4,+ scale: 24,+ octaves: 5,+ seed: 84,+ blend: 'overlay',+ opacity: 0.6,+ },+ cell({ ...facets, blend: 'multiply', opacity: 0.5 }, 0x606060, 0xffffff),+ cell(joints, 0xffffff, 0x16130f),+ ],+ [+ cell(facets, 0x000000, 0xffffff),+ cell(joints, 0xffffff, 0x000000),+ {+ op: 'noise',+ colorA: 0x505050,+ colorB: 0xb0b0b0,+ scale: 24,+ octaves: 5,+ seed: 85,+ blend: 'overlay',+ opacity: 0.3,+ },+ ],+ 5,+ [+ cell({ ...beds, feature: 'cell' }, packed(180), packed(235)),+ {+ op: 'noise',+ colorA: packed(150),+ colorB: packed(235),+ scale: 24,+ octaves: 3,+ seed: 86,+ blend: 'overlay',+ opacity: 0.4,+ },+ ],+);++const EXAMPLES = [rubble, granite, rock];++interface Raster {+ data: Uint8Array;+ width: number;+ height: number;+ channels: number;+}++async function read(path: string): Promise<Raster> {+ const { data, info } = await sharp(path).raw().toBuffer({ resolveWithObject: true });+ return { data, width: info.width, height: info.height, channels: info.channels };+}++/**+ * Per channel and axis: the largest and mean difference across the wrap edge, against the same+ * statistics of every interior neighbouring line. A seam shows up as a wrap line unlike any other.+ */+function seamReport(raster: Raster): Array<{+ channel: number;+ axis: 'x' | 'y';+ wrapMax: number;+ interiorMax: number;+ wrapMean: number;+ interiorMeanMax: number;+}> {+ const { data, width, height, channels } = raster;+ const at = (x: number, y: number, c: number): number => data[(y * width + x) * channels + c]!;+ const lines = (axis: 'x' | 'y', c: number, line: number): { max: number; mean: number } => {+ const length = axis === 'x' ? height : width;+ const size = axis === 'x' ? width : height;+ let max = 0;+ let sum = 0;+ for (let i = 0; i < length; i++) {+ const a = axis === 'x' ? at(line, i, c) : at(i, line, c);+ const next = (line + 1) % size;+ const b = axis === 'x' ? at(next, i, c) : at(i, next, c);+ const difference = Math.abs(a - b);+ max = Math.max(max, difference);+ sum += difference;+ }+ return { max, mean: sum / length };+ };+ const report = [];+ for (let channel = 0; channel < Math.min(channels, 3); channel++) {+ for (const axis of ['x', 'y'] as const) {+ const size = axis === 'x' ? width : height;+ let interiorMax = 0;+ let interiorMeanMax = 0;+ for (let line = 0; line + 1 < size; line++) {+ const { max, mean } = lines(axis, channel, line);+ interiorMax = Math.max(interiorMax, max);+ interiorMeanMax = Math.max(interiorMeanMax, mean);+ }+ const wrap = lines(axis, channel, size - 1);+ report.push({+ channel,+ axis,+ wrapMax: wrap.max,+ interiorMax,+ wrapMean: wrap.mean,+ interiorMeanMax,+ });+ }+ }+ return report;+}++const records = new Map<string, MaterialRecordV1>();+let root: string;+beforeAll(async () => {+ root = await mkdtemp(join(tmpdir(), 'kiln-cellular-materials-'));+ for (const example of EXAMPLES) {+ records.set(example.materialId, await createMaterialRecordV1(example));+ }+});+afterAll(async () => {+ await rm(root, { recursive: true, force: true });+});++describe.each(EXAMPLES.map((example) => [example.materialId, example] as const))(+ '%s worked example',+ (materialId, example) => {+ test('saves as a recipe-only revision with base colour, a derived normal and metallicRoughness', () => {+ const { manifest } = records.get(materialId)!;+ expect(manifest.maps.map((map) => map.slot).sort()).toEqual([+ 'baseColor',+ 'metallicRoughness',+ 'normal',+ ]);+ for (const map of manifest.maps) {+ expect(map.procedural?.compiler).toBe('kiln.procedural-texture.v2');+ }+ const normal = manifest.maps.find((map) => map.slot === 'normal')!;+ expect(normal.procedural?.derive?.kind).toBe('normal-from-height');+ expect(manifest.sources[0]!.originalFiles).toEqual([]);+ });++ test('the same recipe and seed give the same hashes, and verification recompiles the bytes', async () => {+ const first = records.get(materialId)!;+ const again = await createMaterialRecordV1(example);+ expect(again.manifest.revisionId).toBe(first.manifest.revisionId);+ expect(again.manifest.maps.map((map) => map.procedural?.recipeHash)).toEqual(+ first.manifest.maps.map((map) => map.procedural?.recipeHash),+ );+ expect(again.manifest.maps.map((map) => map.procedural?.pixelHash)).toEqual(+ first.manifest.maps.map((map) => map.procedural?.pixelHash),+ );+ await verifyMaterialRecordV1(first);+ });++ for (const size of [256, 128]) {+ test(`--maps at ${size}: every slot tiles, as judged from the exported files`, async () => {+ const outDir = join(root, `${materialId}-${size}`);+ const { sidecar } = await exportMaterialMaps(records.get(materialId)!, {+ outDir,+ size,+ repeatMeters: 2,+ });+ expect(sidecar.maps).toHaveLength(3);+ for (const map of sidecar.maps) {+ const raster = await read(join(outDir, `${materialId}.${map.slot}.png`));+ expect([raster.width, raster.height]).toEqual([size, size]);+ for (const line of seamReport(raster)) {+ expect(line.wrapMax).toBeLessThanOrEqual(line.interiorMax);+ // Beds cluster joints on cell rows, and the wrap edge is always a row boundary sampled+ // dead-centre, so its average can lead its peers by a little (measured 13%). The+ // same-phase test below holds it to no margin at all.+ expect(line.wrapMean).toBeLessThanOrEqual(line.interiorMeanMax * 1.25);+ }+ }+ });+ }+ },+);++test('with every cell boundary in the same sampling phase, the wrap edge is one of its peers', async () => {+ // 16 cells on 256 texels puts every boundary between two texels, exactly like the wrap edge, so+ // the wrap line gets no phase advantage and has nothing to explain.+ const layout = { cellsX: 16, cellsY: 16, seed: 41, jitterX: 0.8, jitterY: 0.3, metricY: 1.5 };+ for (const fields of [+ { feature: 'f2-f1', range: 0.3 },+ { feature: 'cell' },+ { feature: 'border', borderOpen: 1 },+ { feature: 'facet', facetSlope: 1 },+ ]) {+ const { pixels } = compileProceduralTextureSpecV2({+ schemaVersion: 2,+ size: 256,+ usage: 'albedo',+ layers: [cell({ ...layout, ...fields }, 0x000000, 0xffffff)],+ });+ const across = (line: number): number => {+ const next = (line + 1) % 256;+ let sum = 0;+ for (let x = 0; x < 256; x++) {+ sum += Math.abs(pixels[(line * 256 + x) * 4]! - pixels[(next * 256 + x) * 4]!);+ }+ return sum;+ };+ const peers = Array.from({ length: 15 }, (_, k) => across((k + 1) * 16 - 1));+ expect(across(255)).toBeLessThanOrEqual(Math.max(...peers));+ }+});++test('negative control: the same check refuses a seam', async () => {+ // A linear ramp is the plainest non-tiling map: every interior step is small, the wrap is not.+ const seamed = await createMaterialRecordV1({+ materialId: 'seamed-ramp',+ name: 'Seamed ramp',+ tags: [],+ tileable: true,+ physicalSizeMeters: { width: 1, height: 1 },+ parameters: { metalness: 1, roughness: 1 },+ sources: [source],+ maps: [+ {+ slot: 'baseColor',+ sourceId: 'authored',+ transforms: [],+ procedural: recipe('albedo', [+ { op: 'gradient', from: 0x000000, to: 0xffffff, angleDeg: 0 },+ ]),+ },+ ],+ });+ const outDir = join(root, 'seamed');+ await exportMaterialMaps(seamed, { outDir, size: 64, repeatMeters: 1 });+ const lines = seamReport(await read(join(outDir, 'seamed-ramp.baseColor.png')));+ expect(lines.some((line) => line.wrapMax > line.interiorMax)).toBe(true);+ expect(lines.some((line) => line.wrapMean > line.interiorMeanMax * 1.25)).toBe(true);+});++test('a tampered stored map is refused by the recompile', async () => {+ const record = records.get('cellular-rubble')!;+ const name = record.manifest.maps[0]!.file;+ const bytes = Uint8Array.from(record.files[name]!);+ // Flip a byte inside the PNG's image data. Any change must fail, whichever check catches it.+ bytes[bytes.length - 40]! ^= 0xff;+ await expect(+ verifyMaterialRecordV1({ ...record, files: { ...record.files, [name]: bytes } }),+ ).rejects.toThrow();+});diff --git a/src/material-library.ts b/src/material-library.tsindex 396b4efc..b857b26b 100644--- a/src/material-library.ts+++ b/src/material-library.ts@@ -8,6 +8,12 @@ import {canonicalizeProceduralTextureSpecV3,PROCEDURAL_TEXTURE_V3_COMPILER_ID,} from './procedural-texture-v3-contract';+import {+ CELLULAR_FEATURES,+ MAX_CELLULAR_METRIC,+ MAX_CELLULAR_WEIGHT,+ MIN_CELLULAR_METRIC,+} from './procedural-cellular';import { canonicalizePortableSamplerV1 } from './portable-sampler';import type { CanonicalPortableMaterialSpecV3 } from './procedural-material-v3';import {@@ -212,6 +218,28 @@ export const materialProceduralSpecSchema = z...layerCommon,}).strict(),+ z+ .object({+ op: z.literal('cellular'),+ colorA: color,+ colorB: color,+ cellsX: count.default(8),+ cellsY: count.default(8),+ seed: z.number().int().min(-2147483648).max(2147483647).default(0),+ jitterX: z.number().min(0).max(1).default(1),+ jitterY: z.number().min(0).max(1).default(1),+ metricX: z.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC).default(1),+ metricY: z.number().min(MIN_CELLULAR_METRIC).max(MAX_CELLULAR_METRIC).default(1),+ weight: z.number().min(0).max(MAX_CELLULAR_WEIGHT).default(0),+ feature: z.enum(CELLULAR_FEATURES).default('f1'),+ range: z.number().min(0.01).max(8).default(1),+ borderOpen: z.number().min(0).max(1).default(0.5),+ borderWidth: z.number().min(0.001).max(1).default(0.05),+ facetSlope: z.number().min(0).max(1).default(0.5),+ facetBlend: z.number().min(0.001).max(1).default(0.1),+ ...layerCommon,+ })+ .strict(),]),).min(1)diff --git a/src/procedural-cellular.ts b/src/procedural-cellular.tsnew file mode 100644index 00000000..13f2b80d--- /dev/null+++ b/src/procedural-cellular.ts@@ -0,0 +1,338 @@+/**+ * Periodic cellular (Worley) field behind the V2 `cellular` layer. Browser-safe, with no Three.js+ * state, and imported by the V3 contract for its cost, so it stays free of the pixel compiler.+ *+ * Coordinates are cell units: one cell is 1 x 1, whatever `cellsX` and `cellsY` make it in UV. A+ * cell's point sits in the box `0.5 +- jitter/2` on each axis. Distance is+ * `sqrt((metricX*dx)^2 + (metricY*dy)^2) + w`, where `w` is that cell's additive weight, drawn+ * from `[0, weight]`.+ *+ * Output bytes must match on every platform and forever, because a V2 recipe hash carries no+ * compiler id: only integer hashing and `sqrt` here, never `Math.pow`, `sin` or `random`.+ */+import type { CanonicalProceduralLayerV2 } from './procedural-material-v2';++export const CELLULAR_FEATURES = ['f1', 'f2', 'f2-f1', 'cell', 'border', 'facet'] as const;+export type CellularFeature = (typeof CELLULAR_FEATURES)[number];++export const MIN_CELLULAR_METRIC = 1;+export const MAX_CELLULAR_METRIC = 4;+export const MAX_CELLULAR_WEIGHT = 1;++export type CanonicalCellularLayer = Extract<CanonicalProceduralLayerV2, { op: 'cellular' }>;++const distanceOf = (x: number, y: number): number => Math.sqrt(x * x + y * y);++/**+ * How many rings of neighbours keep the search exact, for any seed.+ *+ * A sample is somewhere in its own cell, so its own point is at most `(1 + jitter) / 2` away on an+ * axis. A neighbour on the nearer side of an axis is at most `1 + jitter / 2` away on that axis.+ * Those two cells bound F2 from above, taking the cheaper axis for the neighbour. An image `k`+ * rings out is at least `k - (1 + jitter) / 2` away, scaled by that axis' metric, and weights only+ * add, so once a ring's lower bound reaches F2's upper bound nothing beyond it can be nearest or+ * second nearest. Facets also read every cell within `facetBlend` of F1, so they extend the reach.+ */+export function cellularSearchRadius(layer: CanonicalCellularLayer): { x: number; y: number } {+ const { jitterX, jitterY, metricX, metricY, weight } = layer;+ const ownX = (1 + jitterX) / 2;+ const ownY = (1 + jitterY) / 2;+ const nearX = 1 + jitterX / 2;+ const nearY = 1 + jitterY / 2;+ const f1Bound = distanceOf(metricX * ownX, metricY * ownY) + weight;+ const f2Bound =+ Math.min(+ distanceOf(metricX * nearX, metricY * ownY),+ distanceOf(metricX * ownX, metricY * nearY),+ ) + weight;+ const reach = layer.feature === 'facet' ? Math.max(f2Bound, f1Bound + layer.facetBlend) : f2Bound;+ return {+ x: Math.max(1, Math.ceil(reach / metricX + ownX - 1)),+ y: Math.max(1, Math.ceil(reach / metricY + ownY - 1)),+ };+}++/**+ * V3 work units per texel, where one noise octave costs 16. Fitted to the real compile path against+ * noise; docs/procedural-surfaces-v3.md records the measurements. The search prunes, so it reads+ * about the same few cells whatever the window, and the window adds little. This charges what a+ * layer costs, not a worst case that no seed reaches, the same way noise and bricks are charged.+ */+export function cellularWorkPerTexel(layer: CanonicalCellularLayer): number {+ const { x, y } = cellularSearchRadius(layer);+ const search = 46 + Math.ceil(((2 * x + 1) * (2 * y + 1)) / 8) + (layer.weight > 0 ? 10 : 0);+ if (layer.feature === 'border') return search + 8;+ if (layer.feature === 'facet') return search + 32 + Math.ceil(layer.facetBlend * 30);+ return search;+}++/** One-time hashing of the cell table: at most three hashes per cell, on the same scale. */+export function cellularFieldWork(layer: CanonicalCellularLayer): number {+ return layer.cellsX * layer.cellsY * 12;+}++/** Conservative table allocation: six doubles per cell plus the small wrap and order tables. */+export function cellularFieldBytes(layer: CanonicalCellularLayer): number {+ return layer.cellsX * layer.cellsY * 48 + 4096;+}++// A strong finalizer, not `hash2`: cells draw several values from one id, so neighbouring ids and+// neighbouring streams must not correlate. It is never compared with noise.+function mix(value: number): number {+ let h = value | 0;+ h ^= h >>> 16;+ h = Math.imul(h, 0x85ebca6b);+ h ^= h >>> 13;+ h = Math.imul(h, 0xc2b2ae35);+ h ^= h >>> 16;+ return h >>> 0;+}++const TO_UNIT = 1 / 4294967296;+const lattice = (x: number, y: number, seed: number): number =>+ (Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(seed, 1274126177)) | 0;+const stream = (root: number, index: number): number =>+ mix(root + Math.imul(index + 1, 0x9e3779b9)) * TO_UNIT;++/** Nearest cells first, so F2 tightens early and the rest of the window prunes. */+function centreOut(radius: number): Int32Array {+ const order = new Int32Array(2 * radius + 1);+ for (let k = 1; k <= radius; k++) {+ order[2 * k - 1] = -k;+ order[2 * k] = k;+ }+ return order;+}++function wrapTable(cells: number, radius: number): Int32Array {+ const table = new Int32Array(cells + 2 * radius + 1);+ for (let i = 0; i < table.length; i++) {+ // Wrapping the cell index, not the sample point, is what makes the field tile.+ table[i] = (((i - radius) % cells) + cells) % cells;+ }+ return table;+}++export interface CellularField {+ readonly layer: CanonicalCellularLayer;+ readonly radius: { readonly x: number; readonly y: number };+ readonly px: Float64Array;+ readonly py: Float64Array;+ readonly weights: Float64Array;+ readonly tones: Float64Array;+ readonly slopeX: Float64Array;+ readonly slopeY: Float64Array;+ readonly wrapX: Int32Array;+ readonly wrapY: Int32Array;+ readonly orderX: Int32Array;+ readonly orderY: Int32Array;+ /** F1, F2 of the latest scan, squared. Typed arrays keep the hot writes unboxed. */+ readonly squared: Float64Array;+ /** Nearest id, second nearest id and cells read by the latest scan. */+ readonly found: Int32Array;+}++/** Draw every cell's values once. `radius` is only for proving the bound matters in tests. */+export function prepareCellularField(+ layer: CanonicalCellularLayer,+ radius: { x: number; y: number } = cellularSearchRadius(layer),+): CellularField {+ const { cellsX, cellsY, seed, jitterX, jitterY, weight, feature } = layer;+ const count = cellsX * cellsY;+ const px = new Float64Array(count);+ const py = new Float64Array(count);+ const weights = new Float64Array(count);+ const tones = new Float64Array(feature === 'cell' ? count : 0);+ const slopeX = new Float64Array(feature === 'facet' ? count : 0);+ const slopeY = new Float64Array(feature === 'facet' ? count : 0);+ for (let j = 0; j < cellsY; j++) {+ for (let i = 0; i < cellsX; i++) {+ const id = j * cellsX + i;+ const root = lattice(i, j, seed);+ px[id] = 0.5 + (stream(root, 0) - 0.5) * jitterX;+ py[id] = 0.5 + (stream(root, 1) - 0.5) * jitterY;+ weights[id] = stream(root, 2) * weight;+ if (feature === 'cell') tones[id] = stream(root, 3);+ if (feature === 'facet') {+ slopeX[id] = stream(root, 4) - 0.5;+ slopeY[id] = stream(root, 5) - 0.5;+ }+ }+ }+ return {+ layer,+ radius,+ px,+ py,+ weights,+ tones,+ slopeX,+ slopeY,+ wrapX: wrapTable(cellsX, radius.x),+ wrapY: wrapTable(cellsY, radius.y),+ orderX: centreOut(radius.x),+ orderY: centreOut(radius.y),+ squared: new Float64Array(2),+ found: new Int32Array(3),+ };+}++/**+ * Find the nearest and second nearest images around a sample. Rows and columns whose closest+ * possible point is already past F2 are skipped; weights only add, so the unweighted lower bound+ * is safe. `sqrt` is taken only for a weighted candidate that survives.+ */+function scan(field: CellularField, x: number, y: number): void {+ const { layer, px, py, weights, wrapX, wrapY, orderX, orderY } = field;+ const { metricX, metricY, jitterX, jitterY, cellsX } = layer;+ const radiusX = field.radius.x;+ const radiusY = field.radius.y;+ const weighted = layer.weight > 0;+ const lowX = (1 - jitterX) / 2;+ const highX = (1 + jitterX) / 2;+ const lowY = (1 - jitterY) / 2;+ const highY = (1 + jitterY) / 2;+ const xi = Math.floor(x);+ const yi = Math.floor(y);+ const xf = x - xi;+ const yf = y - yi;+ let f1 = Infinity;+ let f2 = Infinity;+ let id1 = -1;+ let id2 = -1;+ let visited = 0;+ for (let n = 0; n < orderY.length; n++) {+ const dj = orderY[n]!;+ const gapY = dj > 0 ? (dj + lowY - yf) * metricY : dj < 0 ? (yf - dj - highY) * metricY : 0;+ const floorY = gapY * gapY;+ if (floorY >= f2) continue;+ const row = wrapY[yi + dj + radiusY]! * cellsX;+ for (let m = 0; m < orderX.length; m++) {+ const di = orderX[m]!;+ const gapX = di > 0 ? (di + lowX - xf) * metricX : di < 0 ? (xf - di - highX) * metricX : 0;+ if (gapX * gapX + floorY >= f2) continue;+ const id = row + wrapX[xi + di + radiusX]!;+ visited++;+ const dx = (di + px[id]! - xf) * metricX;+ const dy = (dj + py[id]! - yf) * metricY;+ let d = dx * dx + dy * dy;+ if (d >= f2) continue;+ if (weighted) {+ const total = Math.sqrt(d) + weights[id]!;+ d = total * total;+ if (d >= f2) continue;+ }+ if (d < f1) {+ f2 = f1;+ id2 = id1;+ f1 = d;+ id1 = id;+ } else {+ f2 = d;+ id2 = id;+ }+ }+ }+ field.squared[0] = f1;+ field.squared[1] = f2;+ field.found[0] = id1;+ field.found[1] = id2;+ field.found[2] = visited;+}++export interface CellularNearest {+ f1: number;+ f2: number;+ id1: number;+ id2: number;+ visited: number;+}++/** F1, F2 and the two nearest cell ids at a UV sample. */+export function searchCellular(field: CellularField, u: number, v: number): CellularNearest {+ scan(field, u * field.layer.cellsX, v * field.layer.cellsY);+ return {+ f1: Math.sqrt(field.squared[0]!),+ f2: Math.sqrt(field.squared[1]!),+ id1: field.found[0]!,+ id2: field.found[1]!,+ visited: field.found[2]!,+ };+}++/**+ * A tilted plane per cell, weighted across every cell within `facetBlend` of F1. Each weight falls+ * to zero at that limit, so no cell enters or leaves with a step. Blending only F1 and F2 would+ * jump on the line near a corner where F2 and F3 swap.+ */+function facetHeight(field: CellularField, x: number, y: number, f1: number): number {+ const { layer, px, py, weights, slopeX, slopeY, wrapX, wrapY, orderX, orderY } = field;+ const { metricX, metricY, jitterX, jitterY, cellsX, facetBlend, facetSlope } = layer;+ const radiusX = field.radius.x;+ const radiusY = field.radius.y;+ const limit = f1 + facetBlend;+ const limitSquared = limit * limit;+ const lowX = (1 - jitterX) / 2;+ const highX = (1 + jitterX) / 2;+ const lowY = (1 - jitterY) / 2;+ const highY = (1 + jitterY) / 2;+ const xi = Math.floor(x);+ const yi = Math.floor(y);+ const xf = x - xi;+ const yf = y - yi;+ let sum = 0;+ let total = 0;+ for (let n = 0; n < orderY.length; n++) {+ const dj = orderY[n]!;+ const gapY = dj > 0 ? (dj + lowY - yf) * metricY : dj < 0 ? (yf - dj - highY) * metricY : 0;+ const floorY = gapY * gapY;+ if (floorY >= limitSquared) continue;+ const row = wrapY[yi + dj + radiusY]! * cellsX;+ for (let m = 0; m < orderX.length; m++) {+ const di = orderX[m]!;+ const gapX = di > 0 ? (di + lowX - xf) * metricX : di < 0 ? (xf - di - highX) * metricX : 0;+ if (gapX * gapX + floorY >= limitSquared) continue;+ const id = row + wrapX[xi + di + radiusX]!;+ const dx = (di + px[id]! - xf) * metricX;+ const dy = (dj + py[id]! - yf) * metricY;+ const d = Math.sqrt(dx * dx + dy * dy) + weights[id]!;+ if (d >= limit) continue;+ const falloff = 1 - (d - f1) / facetBlend;+ const blend = falloff * falloff;+ sum += blend * (slopeX[id]! * dx + slopeY[id]! * dy);+ total += blend;+ }+ }+ return Math.max(0, Math.min(1, 0.5 + (facetSlope * sum) / total));+}++/** The selected feature at a UV sample, in 0..1, mapped by the caller onto colorA..colorB. */+export function sampleCellularFeature(field: CellularField, u: number, v: number): number {+ const { layer } = field;+ const x = u * layer.cellsX;+ const y = v * layer.cellsY;+ scan(field, x, y);+ const f1 = Math.sqrt(field.squared[0]!);+ switch (layer.feature) {+ case 'f1':+ return Math.min(1, f1 / layer.range);+ case 'f2':+ return Math.min(1, Math.sqrt(field.squared[1]!) / layer.range);+ case 'f2-f1':+ return Math.min(1, (Math.sqrt(field.squared[1]!) - f1) / layer.range);+ case 'cell':+ return Math.min(1, field.tones[field.found[0]!]! / layer.range);+ case 'border': {+ const gap = (Math.sqrt(field.squared[1]!) - f1) / layer.borderWidth;+ if (gap >= 1) return 0;+ const id1 = field.found[0]!;+ const id2 = field.found[1]!;+ // Order-independent, so both sides of a border agree on whether it is open.+ const pair = lattice(Math.min(id1, id2), Math.max(id1, id2), layer.seed);+ if (mix(pair + 0x2f0b4a87) * TO_UNIT >= layer.borderOpen) return 0;+ return 1 - gap * gap * (3 - 2 * gap);+ }+ case 'facet':+ return facetHeight(field, x, y, f1);+ }+}diff --git a/src/procedural-material-v2.ts b/src/procedural-material-v2.tsindex 573f1654..7bc01081 100644--- a/src/procedural-material-v2.ts+++ b/src/procedural-material-v2.ts@@ -8,6 +8,13 @@* the pixel compiler allocates an output buffer.*/+import {+ CELLULAR_FEATURES,+ type CellularFeature,+ MAX_CELLULAR_METRIC,+ MAX_CELLULAR_WEIGHT,+ MIN_CELLULAR_METRIC,+} from './procedural-cellular';import { TEXTURE_USAGES, type TextureUsage } from './texture-contract';import {AuthoringDiagnosticError,@@ -57,6 +64,25 @@ export type ProceduralLayer = LayerCommon &octaves?: number;seed?: number;}+ | {+ op: 'cellular';+ colorA: number;+ colorB: number;+ cellsX?: number;+ cellsY?: number;+ seed?: number;+ jitterX?: number;+ jitterY?: number;+ metricX?: number;+ metricY?: number;+ weight?: number;+ feature?: CellularFeature;+ range?: number;+ borderOpen?: number;+ borderWidth?: number;+ facetSlope?: number;+ facetBlend?: number;+ });/** Historical source shape. Absence of schemaVersion means V1. */@@ -108,6 +134,25 @@ export type CanonicalProceduralLayerV2 = CanonicalLayerCommon &octaves: number;seed: number;}+ | {+ op: 'cellular';+ colorA: number;+ colorB: number;+ cellsX: number;+ cellsY: number;+ seed: number;+ jitterX: number;+ jitterY: number;+ metricX: number;+ metricY: number;+ weight: number;+ feature: CellularFeature;+ range: number;+ borderOpen: number;+ borderWidth: number;+ facetSlope: number;+ facetBlend: number;+ });export interface CanonicalProceduralTextureSpecV2 {@@ -175,7 +220,7 @@ export class ProceduralTextureError extends AuthoringDiagnosticError {}}-const OPS = ['solid', 'checker', 'stripes', 'gradient', 'bricks', 'noise'] as const;+const OPS = ['solid', 'checker', 'stripes', 'gradient', 'bricks', 'noise', 'cellular'] as const;const BLENDS: readonly ProceduralBlend[] = ['normal', 'multiply', 'screen', 'overlay'];const FORBIDDEN_KEYS = new Set(['__proto__', 'prototype', 'constructor']);@@ -339,6 +384,36 @@ function blend(record: Record<string, unknown>, path: string): ProceduralBlend {return value as ProceduralBlend;}+/** A control one feature reads. Any other feature has it at its default, so the hash is stable. */+function featureControl(+ record: Record<string, unknown>,+ path: string,+ feature: CellularFeature,+ control: { name: string; fallback: number; min: number; max: number },+ owners: readonly CellularFeature[],+): number {+ const { name, fallback, min, max } = control;+ const value = finite(record[name], `${path}.${name}`, fallback, min, max);+ if (value !== fallback && !owners.includes(feature)) {+ const noun = owners.length > 1 ? 'features' : 'feature';+ const named = owners.length > 1 ? owners.join(', ') : JSON.stringify(owners[0]);+ throw new ProceduralTextureError(+ `${path}.${name} applies only to ${noun} ${named}, not ${JSON.stringify(feature)}. Remove it or change feature.`,+ );+ }+ return value;+}++function cellularFeature(value: unknown, path: string): CellularFeature {+ const feature = value ?? 'f1';+ if (!(CELLULAR_FEATURES as readonly unknown[]).includes(feature)) {+ throw new ProceduralTextureError(+ `${path}.feature ${JSON.stringify(feature)} is not one of ${CELLULAR_FEATURES.join(', ')}.`,+ );+ }+ return feature as CellularFeature;+}+function canonicalLayer(value: unknown, index: number): CanonicalProceduralLayerV2 {const path = `proceduralTexture.layers[${index}]`;const record = strictRecord(value, path);@@ -419,6 +494,96 @@ function canonicalLayer(value: unknown, index: number): CanonicalProceduralLayerseed: integer(record['seed'], `${path}.seed`, 0, -0x80000000, 0x7fffffff),...common,};+ case 'cellular': {+ assertKeys(+ record,+ [+ 'op',+ 'colorA',+ 'colorB',+ 'cellsX',+ 'cellsY',+ 'seed',+ 'jitterX',+ 'jitterY',+ 'metricX',+ 'metricY',+ 'weight',+ 'feature',+ 'range',+ 'borderOpen',+ 'borderWidth',+ 'facetSlope',+ 'facetBlend',+ 'blend',+ 'opacity',+ ],+ path,+ );+ const feature = cellularFeature(record['feature'], path);+ return {+ op,+ colorA: color(record['colorA'], `${path}.colorA`),+ colorB: color(record['colorB'], `${path}.colorB`),+ cellsX: integer(record['cellsX'], `${path}.cellsX`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ cellsY: integer(record['cellsY'], `${path}.cellsY`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ seed: integer(record['seed'], `${path}.seed`, 0, -0x80000000, 0x7fffffff),+ jitterX: unit(record['jitterX'], `${path}.jitterX`, 1),+ jitterY: unit(record['jitterY'], `${path}.jitterY`, 1),+ metricX: finite(+ record['metricX'],+ `${path}.metricX`,+ 1,+ MIN_CELLULAR_METRIC,+ MAX_CELLULAR_METRIC,+ ),+ metricY: finite(+ record['metricY'],+ `${path}.metricY`,+ 1,+ MIN_CELLULAR_METRIC,+ MAX_CELLULAR_METRIC,+ ),+ weight: finite(record['weight'], `${path}.weight`, 0, 0, MAX_CELLULAR_WEIGHT),+ feature,+ range: featureControl(+ record,+ path,+ feature,+ { name: 'range', fallback: 1, min: 0.01, max: 8 },+ ['f1', 'f2', 'f2-f1', 'cell'],+ ),+ borderOpen: featureControl(+ record,+ path,+ feature,+ { name: 'borderOpen', fallback: 0.5, min: 0, max: 1 },+ ['border'],+ ),+ borderWidth: featureControl(+ record,+ path,+ feature,+ { name: 'borderWidth', fallback: 0.05, min: 0.001, max: 1 },+ ['border'],+ ),+ facetSlope: featureControl(+ record,+ path,+ feature,+ { name: 'facetSlope', fallback: 0.5, min: 0, max: 1 },+ ['facet'],+ ),+ facetBlend: featureControl(+ record,+ path,+ feature,+ { name: 'facetBlend', fallback: 0.1, min: 0.001, max: 1 },+ ['facet'],+ ),+ ...common,+ };+ }default:throw new ProceduralTextureError(`${path}.op is unsupported.`);}diff --git a/src/procedural-texture-v2-compiler.ts b/src/procedural-texture-v2-compiler.tsindex 564da4ca..9cd4b20c 100644--- a/src/procedural-texture-v2-compiler.ts+++ b/src/procedural-texture-v2-compiler.ts@@ -1,4 +1,9 @@/** Legacy V1/V2 pixel compiler. Extraction preserves arithmetic and recipe identity. */+import {+ type CellularField,+ prepareCellularField,+ sampleCellularFeature,+} from './procedural-cellular';import {type CanonicalProceduralLayerV2,type CanonicalProceduralTextureSpecV2,@@ -93,6 +98,7 @@ function evalLayer(layer: CanonicalProceduralLayerV2,u: number,v: number,+ field: CellularField | undefined,): [number, number, number] {switch (layer.op) {case 'solid':@@ -136,6 +142,13 @@ function evalLayer(const b = rgbOf(layer.colorB);return [lerp(a[0], b[0], n), lerp(a[1], b[1], n), lerp(a[2], b[2], n)];}++ case 'cellular': {+ const n = sampleCellularFeature(field!, u, v);+ const a = rgbOf(layer.colorA);+ const b = rgbOf(layer.colorB);+ return [lerp(a[0], b[0], n), lerp(a[1], b[1], n), lerp(a[2], b[2], n)];+ }}}@@ -196,6 +209,9 @@ export function compileProceduralTextureSpecV2(input: unknown): CompiledProcedurconst spec = canonicalizeProceduralTextureSpecV2(input);const { size, layers } = spec;const data = new Uint8Array(size * size * 4);+ const fields = layers.map((layer) =>+ layer.op === 'cellular' ? prepareCellularField(layer) : undefined,+ );for (let y = 0; y < size; y++) {// Sample at texel centers so a pattern with N divisions lands on exact// boundaries instead of drifting half a texel.@@ -206,7 +222,7 @@ export function compileProceduralTextureSpecV2(input: unknown): CompiledProcedurlet g = 0;let b = 0;for (const [i, layer] of layers.entries()) {- const [lr, lg, lb] = evalLayer(layer, u, v);+ const [lr, lg, lb] = evalLayer(layer, u, v, fields[i]);if (i === 0) {r = lr;g = lg;diff --git a/src/procedural-texture-v3-contract.ts b/src/procedural-texture-v3-contract.tsindex 54ca0663..1e202714 100644--- a/src/procedural-texture-v3-contract.ts+++ b/src/procedural-texture-v3-contract.ts@@ -1,4 +1,5 @@/** Bounded JSON and identity contract; no pixel allocations or Three.js dependency. */+import { cellularFieldBytes, cellularFieldWork, cellularWorkPerTexel } from './procedural-cellular';import {canonicalizeProceduralTextureSpecV2,type CanonicalProceduralTextureSpecV2,@@ -318,11 +319,22 @@ export function admitProceduralTextureSpecV3(input: unknown): ProceduralTextureAtexels *(1 +spec.layers.reduce(- (cost, layer) => cost + (layer.op === 'noise' ? layer.octaves * 16 : 4),+ (cost, layer) =>+ cost ++ (layer.op === 'noise'+ ? layer.octaves * 16+ : layer.op === 'cellular'+ ? cellularWorkPerTexel(layer)+ : 4),0,));// Count every legacy result conservatively, even if GC retains prior buffers.legacyTransientBytes += texels * 4;+ for (const layer of spec.layers) {+ if (layer.op !== 'cellular') continue;+ work += cellularFieldWork(layer);+ legacyTransientBytes += cellularFieldBytes(layer);+ }return {op: 'legacy-v2',spec,