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
feat(sandbox): seededRandom for reproducible, cacheable variation (#244)
Matt Kissinger1ba3b08864be
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9d728c3f..13ff855e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -53,6 +53,15 @@ does not publish a package.positions. With float positions, `KHR_mesh_quantization` is still declared for thequantized normals and texture coordinates([#197](https://github.com/instruktlabs/kiln/issues/197)).+- Add the `seededRandom(seed)` sandbox global for reproducible random variation+ ([#244](https://github.com/instruktlabs/kiln/issues/244)). It takes a finite number or a+ non-empty string and returns `next()`, `range(min, max)`, `int(min, max)` (both ends+ included, like `THREE.MathUtils.randInt`), `pick(array)` and `fork(label)`, an+ independent stream derived from the seed and label rather than from how many draws were+ made, so a variant can replay a parent's draws. Seeds are hashed with FNV-1a and drawn+ with mulberry32, the generator scene layout and material presets already used. Builds+ that use it stay cacheable; `Math.random` still bypasses build reuse. Discovery finds it+ for "seeded random".## 1.4.0 (2026-10-23)diff --git a/docs/programs.md b/docs/programs.mdindex 0dfc0b5f..297f03dd 100644--- a/docs/programs.md+++ b/docs/programs.md@@ -140,9 +140,11 @@ These support the design; they do not prove one interface is best for every modeSource references avoid sending the program again. Build caching separately avoidsrunning unchanged source again. The public tool registry reuses successful builds-when the source, evaluator identity and evaluation options match. Packaged Node-CLI/MCP runs can reuse builds on disk when the runtime bundle and installed dependency-files have a verifiable identity. Source-development runs use a process-local cache.+when the source, evaluator identity and evaluation options match. Source that reads+`Math.random`, `Date` or other ambient inputs is never reused; draw from the+`seededRandom(seed)` sandbox global instead, whose `fork(label)` streams let a variant+replay a parent's draws. Packaged Node CLI/MCP runs can reuse builds on disk when+the runtime bundle and installed dependency files have a verifiable identity. Source-development runs use a process-local cache.Camera changes can reuse geometry, but each image also depends on its renderer,camera and capture settings. A source reference alone never identifies a rendereddiff --git a/docs/runtime.md b/docs/runtime.mdindex 1b7c3a7a..70e721a0 100644--- a/docs/runtime.md+++ b/docs/runtime.md@@ -212,7 +212,7 @@ cannot promise reproducible output. Function-bearing material resolvers bypassgeneric caching unless encapsulated by a host evaluator with a complete dependencyidentity.-The cache bypasses known ambient time and random APIs, including `Date`, `performance`, `crypto`, `Math.random` and Three.js random helpers. This conservative source check is not a proof that arbitrary JavaScript is pure. Prefer an explicit seed and ordinary deterministic functions when reproducible revisions matter.+The cache bypasses known ambient time and random APIs, including `Date`, `performance`, `crypto`, `Math.random` and Three.js random helpers. This conservative source check is not a proof that arbitrary JavaScript is pure. Prefer an explicit seed and ordinary deterministic functions when reproducible revisions matter. The sandbox global `seededRandom(seed)` is such a generator: its draws depend only on the source, so builds that use it stay cacheable.`buildCache.hit` reports a completed build reuse. The CLI prints `build reused` or `build created`. Camera changes reuse the same compatible GLB. Edits, changed build options and changed runtime identities produce different keys. Simultaneous requests without cancellation can share a build; cancellable misses own independent workers.diff --git a/skills/kiln-author-asset/references/program-contract.md b/skills/kiln-author-asset/references/program-contract.mdindex 73ea994a..236702d9 100644--- a/skills/kiln-author-asset/references/program-contract.md+++ b/skills/kiln-author-asset/references/program-contract.md@@ -37,7 +37,7 @@ To review that motion, `kiln_screenshot_animation` needs the clip **by name** --Custom `THREE.BufferGeometry` is available. `meshGeo` helps validate flat positions, indices, normals, UV0, and tangents. Read export warnings for unsupported attributes; arbitrary Three.js features do not automatically survive GLB export. The host may select `geometryPolicy: 'strict'` to reject unsupported attributes instead of dropping them with warnings. In a local runtime, `KILN_GEOMETRY_POLICY=strict` configures this host policy; generated source and tool arguments cannot weaken it.-Use deterministic equations or explicit seeded recipes when repeatable builds matter. Avoid ambient state in reusable geometry functions.+Use deterministic equations or explicit seeded recipes when repeatable builds matter. Avoid ambient state in reusable geometry functions. For random variation call `seededRandom(seed)` instead of `Math.random`, which makes every build uncached; give each varied feature its own `fork(label)` so a variant with the same seed and label replays those draws.The source policy rejects host-global access, network access, dynamic imports/evaluation, constructor chains, and raw `THREE.DataTexture`, `ShaderMaterial`, or `RawShaderMaterial`. Use approved texture/material helpers. Generated code runs in strict mode: `this` is allowed inside object-literal and class methods (an object whose `add` method reads `this.parts`), not at the top level or in a plain function; an assignment to an undeclared name, `with` or a legacy octal literal is an error. Source checks are not an operating-system sandbox; evaluator process boundaries belong to the host.diff --git a/src/__tests__/__snapshots__/prompt-api.test.ts.snap b/src/__tests__/__snapshots__/prompt-api.test.ts.snapindex 9258cffe..adb9cbe2 100644--- a/src/__tests__/__snapshots__/prompt-api.test.ts.snap+++ b/src/__tests__/__snapshots__/prompt-api.test.ts.snap@@ -874,5 +874,14 @@ countTriangles(root: Object3D)countMaterials(root: Object3D) // Unique material count (by reference) across the subtree.// e.g. const mats = countMaterials(root);getJointNames(root: Object3D) // All node names beginning with \`Joint_\`. Use to sanity-check animation targets.- // e.g. const joints = getJointNames(root);"+ // e.g. const joints = getJointNames(root);+seededRandom(seed: number | string)+ // Deterministic random numbers from a seed: the same seed gives the same draws, so builds+ // stay cacheable (Math.random marks a build ambient and uncached). fork(label) is an+ // independent stream from the seed and label, not from how many draws were made.+ // NOTE: Use instead of Math.random. Give each varied feature its own fork(label) so adding a+ // draw elsewhere does not shift it; a variant that reuses the seed and label replays the+ // stream.+ // e.g. const rng = seededRandom('palm-3'); const crown = rng.fork('crown'); const lean =+ // rng.range(-8, 8); const fronds = crown.int(7, 9); const look = rng.pick(['fan', 'droop']);"`;diff --git a/src/__tests__/build-cache-review.test.ts b/src/__tests__/build-cache-review.test.tsindex 4c6136b4..2a6ba238 100644--- a/src/__tests__/build-cache-review.test.ts+++ b/src/__tests__/build-cache-review.test.ts@@ -32,6 +32,29 @@ test('does not reuse source that explicitly depends on ambient randomness or timawait port.render(deterministic);expect(calls).toBe(11);});+test('a program using seededRandom builds deterministically and stays cacheable', async () => {+ // #244: Math.random marks a build ambient; the seeded sandbox generator must not.+ const seeded =+ "const meta={name:'seeded-review'};function build(){const r=createRoot('Root');const rng=seededRandom('palm');const crown=rng.fork('crown');const m=gameMaterial('#888888');for(let i=0;i<4;i++){createPart('Leaf'+i,boxGeo(rng.range(0.2,0.6),0.1,crown.range(0.5,1)),m,{parent:r,position:[rng.int(-3,3),0,crown.next()]});}return r;}";+ const first = await renderGLBInProcess(seeded);+ const second = await renderGLBInProcess(seeded);+ expect(Buffer.from(second.glb).equals(Buffer.from(first.glb))).toBe(true);+ let calls = 0;+ const port = createCachedEvaluatorPort(+ {+ render: async (code, options) => {+ calls++;+ return renderGLBInProcess(code, options);+ },+ },+ { cache: new MemoryBuildCache(), identity: () => 'seeded-review' },+ );+ const built = await port.render(seeded);+ const reused = await port.render(seeded);+ expect(calls).toBe(1);+ expect(Buffer.from(reused.glb).equals(Buffer.from(built.glb))).toBe(true);+ expect(Buffer.from(built.glb).equals(Buffer.from(first.glb))).toBe(true);+});test('cache is optional for a successful result containing non-cloneable metadata', async () => {const code = source.replace("name:'cache-review'", "name:'cache-review',note:()=>1");const original = await renderGLBInProcess(code);diff --git a/src/__tests__/primitives.test.ts b/src/__tests__/primitives.test.tsindex 4eca8032..9dbb888f 100644--- a/src/__tests__/primitives.test.ts+++ b/src/__tests__/primitives.test.ts@@ -918,6 +918,7 @@ describe('buildSandboxGlobals', () => {'countMaterials','getJointNames','materialBudgetAdvisory',+ 'seededRandom','Math','console',];diff --git a/src/__tests__/seeded-random.test.ts b/src/__tests__/seeded-random.test.tsnew file mode 100644index 00000000..0adaa266--- /dev/null+++ b/src/__tests__/seeded-random.test.ts@@ -0,0 +1,149 @@+import { describe, expect, test } from 'bun:test';++import { buildSandboxGlobals } from '../primitives';+import { mulberry32 as shared, seededRandom, type SeededRandom } from '../seeded-random';++// Independent reference for the documented algorithm: FNV-1a (32-bit) over the seed's+// UTF-8 bytes, then mulberry32, the generator src/composer/layout.ts already uses.+function fnv1a(text: string): number {+ let hash = 0x811c9dc5;+ for (const byte of new TextEncoder().encode(text)) {+ hash ^= byte;+ hash = Math.imul(hash, 0x01000193) >>> 0;+ }+ return hash;+}+function mulberry32(seed: number): () => number {+ let s = seed >>> 0;+ return () => {+ s = (s + 0x6d2b79f5) >>> 0;+ let t = Math.imul(s ^ (s >>> 15), 1 | s);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}+const draws = (rng: SeededRandom, n: number) => Array.from({ length: n }, () => rng.next());++describe('seededRandom', () => {+ test('hashes the seed with FNV-1a and draws with mulberry32', () => {+ expect(fnv1a('')).toBe(0x811c9dc5);+ expect(fnv1a('a')).toBe(0xe40c292c);+ expect(fnv1a('foobar')).toBe(0xbf9cf968);+ // The engine's layout and material presets share this exact generator.+ for (const seed of [0, 1, 123, 0xffffffff])+ expect(Array.from({ length: 8 }, shared(seed))).toEqual(+ Array.from({ length: 8 }, mulberry32(seed)),+ );+ const reference = mulberry32(fnv1a('palm'));+ expect(draws(seededRandom('palm'), 8)).toEqual(Array.from({ length: 8 }, reference));+ // A number seed is hashed from its canonical decimal text, so 7 and '7' match.+ expect(draws(seededRandom(7), 4)).toEqual(draws(seededRandom('7'), 4));+ expect(draws(seededRandom(-0), 4)).toEqual(draws(seededRandom(0), 4));+ });++ test('the same seed gives the same sequence and different seeds differ', () => {+ expect(draws(seededRandom(42), 32)).toEqual(draws(seededRandom(42), 32));+ expect(draws(seededRandom('island'), 32)).toEqual(draws(seededRandom('island'), 32));+ expect(draws(seededRandom(42), 8)).not.toEqual(draws(seededRandom(43), 8));+ expect(draws(seededRandom('a'), 8)).not.toEqual(draws(seededRandom('b'), 8));+ for (const value of draws(seededRandom(1), 1000)) {+ expect(value).toBeGreaterThanOrEqual(0);+ expect(value).toBeLessThan(1);+ }+ });++ test('fork(label) is stable per label and independent of parent draws', () => {+ const fresh = seededRandom('palm');+ const advanced = seededRandom('palm');+ draws(advanced, 17);+ advanced.int(0, 9);+ expect(draws(advanced.fork('crown'), 12)).toEqual(draws(fresh.fork('crown'), 12));+ expect(draws(fresh.fork('crown'), 12)).toEqual(draws(seededRandom('palm').fork('crown'), 12));+ // Forking does not consume or disturb the parent's own stream.+ const parent = seededRandom('palm');+ parent.fork('crown');+ expect(draws(parent, 6)).toEqual(draws(seededRandom('palm'), 6));+ // Labels and parent seeds select different streams; nested forks are deterministic.+ expect(draws(fresh.fork('crown'), 6)).not.toEqual(draws(fresh.fork('trunk'), 6));+ expect(draws(fresh.fork('crown'), 6)).not.toEqual(draws(seededRandom('reef').fork('crown'), 6));+ expect(draws(fresh.fork('crown'), 6)).not.toEqual(draws(seededRandom('palm'), 6));+ expect(draws(fresh.fork('a').fork('b'), 6)).toEqual(+ draws(seededRandom('palm').fork('a').fork('b'), 6),+ );+ expect(draws(fresh.fork('a').fork('b'), 6)).not.toEqual(draws(fresh.fork('b').fork('a'), 6));+ });++ test('range is half-open and int includes both ends like THREE.MathUtils.randInt', () => {+ const rng = seededRandom('bounds');+ const ints = new Set<number>();+ for (let i = 0; i < 2000; i++) {+ const r = rng.range(-2, 3);+ expect(r).toBeGreaterThanOrEqual(-2);+ expect(r).toBeLessThan(3);+ const n = rng.int(-1, 2);+ expect(Number.isInteger(n)).toBe(true);+ ints.add(n);+ }+ expect([...ints].sort((a, b) => a - b)).toEqual([-1, 0, 1, 2]);+ expect(rng.range(4, 4)).toBe(4);+ expect(rng.int(5, 5)).toBe(5);+ // Each helper consumes exactly one draw from the same stream.+ const a = seededRandom(9);+ const b = seededRandom(9);+ expect(a.range(10, 20)).toBe(10 + 10 * b.next());+ expect(a.int(0, 9)).toBe(Math.floor(b.next() * 10));+ });++ test('pick returns an element chosen by one draw', () => {+ const items = ['fan', 'spike', 'droop'] as const;+ const rng = seededRandom('pick');+ const twin = seededRandom('pick');+ const seen = new Set<string>();+ for (let i = 0; i < 200; i++) {+ const choice = rng.pick(items);+ expect(choice).toBe(items[twin.int(0, items.length - 1)]!);+ seen.add(choice);+ }+ expect(seen.size).toBe(3);+ });++ test('rejects invalid seeds, labels and bounds with named errors', () => {+ const bad = (fn: () => unknown, kind: typeof TypeError | typeof RangeError, text: RegExp) => {+ expect(fn).toThrow(kind);+ expect(fn).toThrow(text);+ };+ const call = seededRandom as unknown as (...args: unknown[]) => SeededRandom;+ bad(+ () => call(),+ TypeError,+ /seededRandom: seed must be a finite number or a non-empty string/,+ );+ bad(() => call(null), TypeError, /seed must be/);+ bad(() => call({}), TypeError, /seed must be/);+ bad(() => call(1n), TypeError, /seed must be/);+ bad(() => call(Number.NaN), RangeError, /seed must be finite/);+ bad(() => call(Infinity), RangeError, /seed must be finite/);+ bad(() => call(''), RangeError, /seed must be a non-empty string/);+ bad(() => call('x'.repeat(257)), RangeError, /at most 256/);+ bad(() => call(1, 2), TypeError, /exactly one seed/);+ const rng = seededRandom(1) as unknown as Record<string, (...args: unknown[]) => unknown>;+ bad(() => rng.fork!(''), RangeError, /fork: label must be a non-empty string/);+ bad(() => rng.fork!(3), TypeError, /fork: label must be/);+ bad(() => rng.range!(2, 1), RangeError, /range: min must not exceed max/);+ bad(() => rng.range!(0, Infinity), RangeError, /range: bounds must be finite numbers/);+ bad(() => rng.int!(0.5, 2), RangeError, /int: bounds must be safe integers/);+ bad(() => rng.int!(3, 2), RangeError, /int: min must not exceed max/);+ bad(() => rng.int!(0, 2 ** 32), RangeError, /int: at most 4294967296 values/);+ bad(() => rng.pick!([]), RangeError, /pick: array must not be empty/);+ bad(() => rng.pick!('abc'), TypeError, /pick: expects an array/);+ });++ test('is a sandbox global that programs can call', () => {+ const usage: Record<string, number> = {};+ const globals = buildSandboxGlobals(usage);+ const make = globals.seededRandom as typeof seededRandom;+ expect(typeof make).toBe('function');+ expect(draws(make('x'), 4)).toEqual(draws(seededRandom('x'), 4));+ expect(usage.seededRandom).toBe(1);+ });+});diff --git a/src/composer/layout.ts b/src/composer/layout.tsindex 0ba9a522..08122e81 100644--- a/src/composer/layout.ts+++ b/src/composer/layout.ts@@ -25,6 +25,7 @@* the tool surface; the overlap validator gates every result (`overlaps` is* empty by construction — global min-distance covers inter-anchor clearance).*/+import { mulberry32 } from '../seeded-random';import { flatGround, type GroundSampler } from './ground';import {findPlacementOverlaps,@@ -105,17 +106,6 @@ const TO_RAD = Math.PI / 180;const ROLE_RANK: Record<ItemRole, number> = { hero: 0, support: 1, fill: 2 };const round1 = (n: number): number => Math.round(n * 10) / 10;-/** Deterministic PRNG (mulberry32) — no Math.random, so scenes are reproducible. */-function makeRng(seed: number): () => number {- let s = seed >>> 0;- return () => {- s = (s + 0x6d2b79f5) >>> 0;- let t = Math.imul(s ^ (s >>> 15), 1 | s);- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;- };-}-interface Prepared {item: LayoutItem;scale: number;@@ -273,7 +263,8 @@ export function layoutScene(items: LayoutItem[], opts: LayoutOptions = {}): Layoconst ground = opts.ground ?? flatGround(0);const sceneCenter: Vec2 = opts.sceneCenter ?? [0, 0];const facing = opts.facing ?? 'scene-in';- const rng = makeRng(opts.seed ?? 1);+ // Deterministic PRNG (mulberry32): no Math.random, so scenes are reproducible.+ const rng = mulberry32(opts.seed ?? 1);const anchors: Anchor[] = opts.anchors?.length? opts.anchors: [{ id: '__root', center: [0, 0] }];diff --git a/src/discovery/helper-contracts.ts b/src/discovery/helper-contracts.tsindex caaa3f62..6e56387a 100644--- a/src/discovery/helper-contracts.ts+++ b/src/discovery/helper-contracts.ts@@ -2970,6 +2970,52 @@ define(},);+define(+ 'seededRandom',+ {+ units: 'Unitless numbers; range and int use the caller units of their bounds.',+ axes: 'Not applicable.',+ origin: 'Not applicable.',+ ownership: 'Returns a new frozen generator object; it holds only its own 32-bit state.',+ coordinates: 'Not applicable; no scene or transform is read.',+ parameters: [+ 'seed is a finite number or a non-empty string of at most 256 characters; a number is hashed from its decimal text, so 7 and "7" are the same seed. Other values throw.',+ 'next() returns a float in [0, 1). range(min, max) returns min + (max - min) * next(), in [min, max); bounds are finite and min <= max.',+ 'int(min, max) returns an integer from min to max with both ends included (like THREE.MathUtils.randInt); bounds are safe integers, min <= max, at most 2^32 values.',+ 'pick(array) returns one element of a non-empty array.',+ 'fork(label) takes a non-empty string of at most 256 characters and returns an independent generator.',+ ],+ topology: [noMesh],+ preservation: ['Reads and changes no scene state.'],+ semantics: [+ 'Seeds are hashed with FNV-1a (32-bit) over UTF-8; draws use mulberry32. next, range, int and pick each consume exactly one draw.',+ 'fork(label) derives its seed from the parent seed and the label only. It does not consume or depend on parent draws, so the same seed and label always replay the same stream.',+ 'The output depends only on the program source, so a build using seededRandom remains eligible for build reuse; Math.random, Date and THREE.MathUtils random helpers bypass it.',+ ],+ cost: 'Constant time per draw; hashing is linear in seed or label length.',+ },+ {+ references: ['src/seeded-random.ts', 'src/build-cache.ts'],+ tags: ['random', 'seed', 'deterministic', 'variation'],+ aliases: [+ 'seeded random',+ 'random number generator',+ 'random numbers',+ 'deterministic random',+ 'PRNG',+ ],+ intents: [+ 'reproducible random variants',+ 'replay a parent asset random draws in a variant',+ 'random variation that keeps builds cacheable',+ ],+ limitations: [+ 'Not cryptographic. 32-bit state: streams are reproducible, not statistically perfect.',+ 'Ranges with very large magnitude and tiny span can round up to max.',+ ],+ },+);+/** Every retained helper must be explicitly listed; missing facts fail catalog construction. */const assemblyAccess: Facts = {units: lengthUnits,diff --git a/src/discovery/helper-specs.ts b/src/discovery/helper-specs.tsindex e95f1d7c..4d4d3303 100644--- a/src/discovery/helper-specs.ts+++ b/src/discovery/helper-specs.ts@@ -1236,6 +1236,19 @@ const PRIMITIVES: HelperSpec[] = [description: 'All node names beginning with `Joint_`. Use to sanity-check animation targets.',example: 'const joints = getJointNames(root);',},+ {+ name: 'seededRandom',+ signature: 'seededRandom(seed: number | string)',+ returns:+ '{ next(): [0,1), range(min, max): [min,max), int(min, max): min..max inclusive, pick(array), fork(label) }',+ category: 'utility',+ description:+ 'Deterministic random numbers from a seed: the same seed gives the same draws, so builds stay cacheable (Math.random marks a build ambient and uncached). fork(label) is an independent stream from the seed and label, not from how many draws were made.',+ example:+ "const rng = seededRandom('palm-3');\nconst crown = rng.fork('crown');\nconst lean = rng.range(-8, 8);\nconst fronds = crown.int(7, 9);\nconst look = rng.pick(['fan', 'droop']);",+ promptNotes:+ 'Use instead of Math.random. Give each varied feature its own fork(label) so adding a draw elsewhere does not shift it; a variant that reuses the seed and label replays the stream.',+ },];/**diff --git a/src/discovery/lexical-index.test.ts b/src/discovery/lexical-index.test.tsindex 1ba82f64..d47fc51d 100644--- a/src/discovery/lexical-index.test.ts+++ b/src/discovery/lexical-index.test.ts@@ -100,6 +100,25 @@ test('foliage wording reaches the repetition and card helpers', async () => {expect(await top('many identical leaves instanced')).toContain('operation:repeatInstances');});+test('seeded random wording reaches the seededRandom helper', async () => {+ // #244: "seeded random" returned only proceduralTexture; programs had no seeded generator.+ const run = createDiscoveryService(+ entries,+ createLexicalDiscoveryIndex(entries),+ async () => ({}),+ );+ const top = async (query: string) =>+ (await run({ query })).entries.slice(0, 3).map((entry) => entry.id);+ for (const query of [+ 'seeded random',+ 'random numbers',+ 'reproducible random variants',+ 'deterministic random generator',+ ])+ expect(await top(query)).toContain('operation:seededRandom');+ expect((await run({ ids: ['seededRandom'] })).text).toContain('fork(label)');+});+test('everyday object words reach the reviewed structure and material entries', async () => {// Dogfood run C (C-A2): "bench" found nothing and "cast iron" expanded to cost/caster.const run = createDiscoveryService(diff --git a/src/material-presets.ts b/src/material-presets.tsindex 30fc7c18..4628d797 100644--- a/src/material-presets.ts+++ b/src/material-presets.ts@@ -7,6 +7,7 @@ import {type ProceduralMaterialDraftV2,} from './material-library';import type { MaterialDraftV1 } from './material-library-node';+import { mulberry32 } from './seeded-random';import type { ProceduralLayer, ProceduralTextureSpecV2 } from './procedural-material-v2';const catalog = [@@ -469,24 +470,12 @@ export function createMaterialPresetDraftAny(};}-/** Deterministic 32-bit generator for preset geometry; never Math.random. */-function presetRandom(seed: number) {- let state = seed >>> 0;- return () => {- state = (state + 0x6d2b79f5) >>> 0;- let t = state;- t = Math.imul(t ^ (t >>> 15), t | 1);- t ^= t + Math.imul(t ^ (t >>> 7), t | 61);- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;- };-}-/*** V3 RGBA frond silhouette: a rachis up the image centre from the bottom edge, with paired* leaflets that shorten and narrow toward the tip. Everything else is fully transparent.*/function frondCutout(size: number, seed: number) {- const random = presetRandom(seed);+ const random = mulberry32(seed); // deterministic; never Math.randomconst unit = size / 64;const centre = Math.round(size / 2);const inside = (value: number) => Math.min(size - 2, Math.max(1, Math.round(value)));diff --git a/src/primitives.ts b/src/primitives.tsindex d7cd3a99..8d499874 100644--- a/src/primitives.ts+++ b/src/primitives.ts@@ -73,6 +73,7 @@ export * from './geometry';import * as profile from './profile';import * as solids from './solids';import * as proceduralTextures from './procedural-texture';+import { seededRandom } from './seeded-random';import * as textures from './textures';import { textureAtlas, remapUVToAtlas } from './texture-atlas';import type { TextureResolver } from './texture-resolver';@@ -2453,6 +2454,7 @@ export function buildSandboxGlobals(countMaterials: wrap('countMaterials', countMaterials),getJointNames: wrap('getJointNames', getJointNames),materialBudgetAdvisory: wrap('materialBudgetAdvisory', materialBudgetAdvisory),+ seededRandom: wrap('seededRandom', seededRandom),// THREE namespace is exposed so agents can `new THREE.Mesh(geo, mat)`// as operands to CSG and other ops that expect Object3D inputs.THREE,diff --git a/src/seeded-random.ts b/src/seeded-random.tsnew file mode 100644index 00000000..23149580--- /dev/null+++ b/src/seeded-random.ts@@ -0,0 +1,107 @@+/**+ * Seeded random numbers for generated programs and engine code.+ *+ * One algorithm for the whole engine: mulberry32, a 32-bit generator. Program seeds are+ * hashed with FNV-1a (32-bit) over their UTF-8 bytes. The output depends only on the seed+ * and the calls made, so a build that draws from `seededRandom` stays cacheable, unlike+ * `Math.random`. Pure: no Date.now(), Math.random() or host state.+ */++/** mulberry32: returns floats in [0, 1) as k / 2^32 from a 32-bit seed. */+export function mulberry32(seed: number): () => number {+ let state = seed >>> 0;+ return () => {+ state = (state + 0x6d2b79f5) >>> 0;+ let t = Math.imul(state ^ (state >>> 15), state | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/** FNV-1a (32-bit) over the UTF-8 bytes of `text`. */+export function fnv1a32(text: string): number {+ let hash = 0x811c9dc5;+ for (const byte of new TextEncoder().encode(text)) {+ hash ^= byte;+ hash = Math.imul(hash, 0x01000193) >>> 0;+ }+ return hash;+}++/** A deterministic generator returned by `seededRandom`. */+export interface SeededRandom {+ /** A float in [0, 1). */+ next(): number;+ /** A float in [min, max): min + (max - min) * next(). */+ range(min: number, max: number): number;+ /** An integer from min to max, both included (like THREE.MathUtils.randInt). */+ int(min: number, max: number): number;+ /** One element of a non-empty array, chosen with one draw. */+ pick<T>(items: readonly T[]): T;+ /** An independent stream from this generator's seed and `label`; never from its draws. */+ fork(label: string): SeededRandom;+}++const MAX_TEXT = 256;+const MAX_INT_VALUES = 2 ** 32;++function text(value: unknown, what: string): string {+ if (typeof value !== 'string')+ throw new TypeError(`seededRandom: ${what} must be a finite number or a non-empty string`);+ if (value.length === 0) throw new RangeError(`seededRandom: ${what} must be a non-empty string`);+ if (value.length > MAX_TEXT)+ throw new RangeError(`seededRandom: ${what} must be at most ${MAX_TEXT} characters`);+ return value;+}++function generator(seed32: number): SeededRandom {+ const draw = mulberry32(seed32);+ const rng: SeededRandom = {+ next: () => draw(),+ range(min: number, max: number): number {+ if (!Number.isFinite(min) || !Number.isFinite(max))+ throw new RangeError('seededRandom.range: bounds must be finite numbers');+ if (min > max) throw new RangeError('seededRandom.range: min must not exceed max');+ return min + (max - min) * draw();+ },+ int(min: number, max: number): number {+ if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max))+ throw new RangeError('seededRandom.int: bounds must be safe integers');+ if (min > max) throw new RangeError('seededRandom.int: min must not exceed max');+ const count = max - min + 1;+ if (count > MAX_INT_VALUES)+ throw new RangeError(`seededRandom.int: at most ${MAX_INT_VALUES} values (max - min + 1)`);+ return min + Math.floor(draw() * count);+ },+ pick<T>(items: readonly T[]): T {+ if (!Array.isArray(items)) throw new TypeError('seededRandom.pick: expects an array');+ if (items.length === 0) throw new RangeError('seededRandom.pick: array must not be empty');+ return items[Math.floor(draw() * items.length)] as T;+ },+ fork(label: string): SeededRandom {+ if (typeof label !== 'string')+ throw new TypeError('seededRandom.fork: label must be a non-empty string');+ if (label.length === 0)+ throw new RangeError('seededRandom.fork: label must be a non-empty string');+ if (label.length > MAX_TEXT)+ throw new RangeError(`seededRandom.fork: label must be at most ${MAX_TEXT} characters`);+ return generator(fnv1a32(`${seed32}/${label}`));+ },+ };+ return Object.freeze(rng);+}++/**+ * Deterministic generator for a number or string seed. A number seed is hashed from its+ * canonical decimal text (`7` and `'7'` are the same seed).+ */+export function seededRandom(...args: [seed: number | string]): SeededRandom {+ if (args.length > 1)+ throw new TypeError('seededRandom: pass exactly one seed (a finite number or a string)');+ const [seed] = args;+ if (typeof seed === 'number') {+ if (!Number.isFinite(seed)) throw new RangeError('seededRandom: seed must be finite');+ return generator(fnv1a32(String(seed)));+ }+ return generator(fnv1a32(text(seed, 'seed')));+}