Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Run heavy scene kernels on a worker in the MCP preview

Nguyen Xuan An2ad3b3694a95
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e11aca4e..da74e028 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
## Unreleased
+- Run the heavy scene kernels on a worker in the MCP preview (part of issue #38; the Chrome long-task measurement and the live edit path are not done). The light bake, the cloth solver, `uv_unwrap` and pattern textures are pure functions of their input, so `runKernel` in the new `src/kernel-offload.js` computes them inline as before, or, inside `buildWithKernels`, throws `KernelDeferred`, lets a module worker (`kernel-worker.js`, a package entry like the path tracer's) compute the result, caches it by a hash of the input bytes and runs the synchronous build again. The preview builds `scene_create` that way when the page has `Worker`; Node and every other caller keep the synchronous path and the same bytes (a test builds one scene cold in a separate process both ways and compares a digest of geometry, textures and the bake report). A worker error comes back with its class and message, a worker that cannot start or dies leaves the job to the inline path, and an `AbortSignal` ends the build and the worker. Measured in Node on the demo recipe: the `uv_unwrap` stack takes 3.6 s, the draft light bake 7.5 s and the standard bake passes the 20 s limit on this machine, cloth at the 10 s limit takes 3.4 s, a 1024 pattern takes 1 to 7 s, a boolean 0.12 s. Total build time does not fall (the kernels run one after another); the page stays free. `scene_apply` edits still run on the main thread. Core did not grow (`entry:core`, `lit-box` unchanged); the lazy entries rose by about 900 bytes gzip.
- Add ragdolls (part of issue #96): `physics.ragdoll` in a recipe with armatures and `physics` in an asset recipe (`set-physics`) bind a capsule body to every bone or joint and play the fall back as the pose of those bones, the same bytes for the same seek. New `src/ragdoll.js`, loaded with the physics code only. New suite task `robot-ragdoll`. The lazy budgets of `agent-scene+lazy` and `agent-asset+lazy` rise by 100 and 800 bytes gzip for it; the core entries did not grow from this. Joints have no swing limits yet.
- Add terrain holes and a recipe `terrain` geometry (part of issue #64; layers beyond four and the navmesh are not built). `createTerrain({ holes: [{ center: [x, z], radius }] })` leaves no surface where a cell centre is inside a circle, and `terrain.isHole(x, z)` answers for a point; without `holes` the seeded meshes are byte-identical (a digest test). A recipe geometry `{ type: "terrain", size, resolution, seed, amplitude, holes }` builds one seeded ground mesh with the same holes; it loads on demand through the new `terrain` module (core did not grow), the tool schema entry is one line with the fields in `scene_capabilities` `terrain`, and the schema total budget did not change (scene_create and scene_apply rose by a few hundred bytes, mesh_edit fell by the same amount). New suite task `terrain-hole-walk` (ground with a 3 m opening and a walker that has to go around it) with the checks `groundRelief` and `walkPath`. Measured: Haiku passed it 2 of 2 (9 and 6 tool calls, $0.29 in all) and both exported recipes used the `terrain` geometry; there was no control run without the feature, so this shows agents find it, not how many could do without.
- Bake patterned, textured and emissive parts, and skip hair hosts (part of issue #128). A recipe `bake` used to skip every part with a pattern, a map or emission (31 parts, the floor and every wall, in the demo room) and failed `scene_create` with "Textured geometry requires UV channel 0" on a node that hosts hair. Those parts now keep `uvs` and their look and take the bounced light through a new `lightMap` material slot on a second UV set (`geometry.lightUvs`); the fragment shader adds `color * (1 - metallic) * lightMap * lightMapScale`, so a brick pattern tints its own bounced light. Hair and particle host nodes are skipped and listed in `report.skipped`. The shader branch compiles out of scenes with no light map; the renderer carries about 650 bytes of gzip for it in `entry:core` (see `docs/light-bake.md` for the measured sizes). GLB export writes `TEXCOORD_1` and the light map as the emissive texture (an approximation: glTF has no light map slot). The path tracer ignores baked maps by design. New reference scene `brick-room` (a recipe-built closed brick room).
diff --git a/docs/parity.md b/docs/parity.md
index 16bfffe2..543b8de2 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -240,7 +240,7 @@ The goal also needs this work, and no page in the Blender manual covers it.
| --- | --- | --- | --- |
| Parity evidence | partial | This ledger exists. The Blender comparisons do not. | #24, #25, #26 |
| Bundle size | partial | `npm run size` checks a budget for each entry, and the package has a 1 MiB limit. three.js is gone from the library; only the benchmark page imports it. | #27, #33, #34, #35, #36 |
-| Runtime speed | partial | `bench/runtime` compares 8 scenes, and three.js wins most of the 7 older ones. Frustum culling per part and per instance group is on by default, `lods` from `generateGeometryLods` pick a level per instance by pixel error (`docs/culling-lod.md`), and `createGpuTimer` plus `createAdaptiveResolution` give live viewers GPU timing and a bounded resolution scale. On `large-outdoor` 67js is 1.55 ms against 6.0 ms for three.js on an RTX 3060. Part of #37: recipes have no way to declare `lods` yet, shadow passes are not culled, and bakes run on the main thread. | #28, #37, #38, #74 |
+| Runtime speed | partial | `bench/runtime` compares 8 scenes, and three.js wins most of the 7 older ones. Frustum culling per part and per instance group is on by default, `lods` from `generateGeometryLods` pick a level per instance by pixel error (`docs/culling-lod.md`), and `createGpuTimer` plus `createAdaptiveResolution` give live viewers GPU timing and a bounded resolution scale. On `large-outdoor` 67js is 1.55 ms against 6.0 ms for three.js on an RTX 3060. Part of #37: recipes have no way to declare `lods` yet and shadow passes are not culled. Part of #38: the MCP preview builds `scene_create` with the light bake, cloth, `uv_unwrap` and pattern kernels on a worker (`src/kernel-offload.js`); `scene_apply` edits, the browser site and the Chrome long-task measurement are not done. | #28, #37, #38, #74 |
| Agent measurement | partial | A task suite runs on one model and reads recipes only. | #29, #30, #31, #69 |
| Pull request checks | partial | The `Test` workflow reports a status and does not block a merge. | #32 |
| Relations between parts | partial | The agent version of snapping: node `relations` (`attach`, `gap`, `flush`, `align`, `centered`) over world bounds or a tagged region, solved again on every edit, cycles rejected. Tests in [part-relations](../tests/part-relations.test.js); suite tasks `kettle-resize` and `desk-resize` with plain twins (no gain in calls measured on Sonnet). No snapping to edges or vertices, no relation on the part's own tagged region. | #44 |
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index ed5726ab..07110c6b 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -1,3 +1,4 @@
+import { buildWithKernels, kernelWorkersAvailable } from '../src/kernel-offload.js';
import { createAgentScene, loadAllAgentSceneModules, allAgentSceneModulesLoaded, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader, needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader } from '../src/agent-scene.js';
import { Renderer67 } from '../src/renderer.js';
import { installCameraEffects } from '../src/camera-effects.js';
@@ -240,6 +241,19 @@ function afterMeshBooleans(value, run) {
return Promise.all(loads).then(run);
}
+// Heavy kernels (light bake, cloth, uv_unwrap, pattern textures) compute on a worker while the page stays responsive;
+// the scene is built from the same bytes as on one thread. Reading each part's maps here makes pattern bakes run in the
+// same pass, so the renderer later finds them baked.
+function buildSceneOffMainThread(recipe) {
+ return buildWithKernels(() => {
+ const scene = createAgentScene(recipe);
+ for (const part of scene.parts) {
+ void part.material.map;
+ }
+ return scene;
+ });
+}
+
function seekForExport(record, motionTime) {
if (record.asset) record.scene.sampleFrame({ motionTime });
else record.scene.sampleMotion(motionTime);
@@ -486,7 +500,12 @@ window.__agentPreview = {
},
create(input) {
if (active) throw new Error('Dispose the current scene before creating another.');
- return afterMeshBooleans(input.recipe, () => createPreview(createAgentScene(input.recipe), input));
+ return afterMeshBooleans(input.recipe, () => {
+ if (!kernelWorkersAvailable()) {
+ return createPreview(createAgentScene(input.recipe), input);
+ }
+ return buildSceneOffMainThread(input.recipe).then(scene => createPreview(scene, input));
+ });
},
async createAsset(input) {
if (active) throw new Error('Dispose the current scene before creating another.');
diff --git a/src/agent-bake.js b/src/agent-bake.js
index c95b3d5f..ec9560f4 100644
--- a/src/agent-bake.js
+++ b/src/agent-bake.js
@@ -1,4 +1,5 @@
import { bakeLightmaps } from './light-bake.js';
+import { runKernel } from './kernel-offload.js';
import { knownKeys, finiteNumber } from './agent-recipe-checks.js';
import { BAKE_PRESETS, BAKE_RANGES, BAKE_MAXIMUM_SECONDS } from './agent-scene-capabilities.js';
@@ -42,6 +43,21 @@ function liveBakedMaterial(liveMaterial, bakedMaterial) {
return Object.freeze(output);
}
+/**
+ * The light bake as a worker kernel: only the parts the bake changed travel back, as [index, part] pairs, because a
+ * part that was left alone is the caller's own object and has nothing to send.
+ */
+export function bakeChangedParts(snapshots, lighting, options) {
+ const { parts, report } = bakeLightmaps(snapshots, lighting, options);
+ const changed = [];
+ parts.forEach((part, index) => {
+ if (part !== snapshots[index]) {
+ changed.push([index, part]);
+ }
+ });
+ return { changed, report };
+}
+
/**
* Bakes the parts at the world matrices given by name (a retained part's own matrix is only refreshed after a commit).
* Returns the new parts, which share the originals' matrices so poses still move them, and a report: texels,
@@ -61,7 +77,11 @@ export function bakeAgentParts(parts, worldMatrices, environment, settings, gene
material: { ...part.material },
generatesGeometry: generatedGeometryNames.has(part.name),
}));
- const { parts: bakedSnapshots, report } = bakeLightmaps(snapshots, lighting, { ...settings, maxSeconds: BAKE_MAXIMUM_SECONDS });
+ const { changed, report } = runKernel('lightBake', [snapshots, lighting, { ...settings, maxSeconds: BAKE_MAXIMUM_SECONDS }], bakeChangedParts);
+ const bakedSnapshots = snapshots.slice();
+ for (const [index, part] of changed) {
+ bakedSnapshots[index] = part;
+ }
const bakedParts = parts.map((part, index) => {
if (bakedSnapshots[index] === snapshots[index]) {
return part;
diff --git a/src/agent-cloth.js b/src/agent-cloth.js
index eaf1fa6c..9fc81ba7 100644
--- a/src/agent-cloth.js
+++ b/src/agent-cloth.js
@@ -1,4 +1,5 @@
import { mat4 } from 'gl-matrix';
+import { runKernel } from './kernel-offload.js';
import { bakeCloth, sampleClothFrames, weldVertices } from './cloth.js';
import { recomputeNormals } from './geometry-normals.js';
import { bakingContext, boundedArray, finiteNumber, knownKeys, rootNodeWithGeometry, vectorOfThree } from './agent-recipe-checks.js';
@@ -133,12 +134,12 @@ function bakeSheet(sheet, cloth, node, geometry, colliders, frameCount) {
}
worldPositions.set(world, particle * 3);
});
- const recording = bakeCloth(worldPositions, welded.triangles, {
+ const recording = Object.freeze({ ...runKernel('cloth', [worldPositions, welded.triangles, {
pinned: pinnedParticles(geometry.positions, welded.representatives, sheet.pin),
gravity: cloth.gravity, wind: cloth.wind, stiffness: sheet.stiffness, bend: sheet.bend,
density: sheet.density, damping: sheet.damping, friction: sheet.friction, thickness: sheet.thickness,
colliders, frameCount, framesPerSecond: FRAMES_PER_SECOND,
- });
+ }], bakeCloth) });
return { recording, welded, inverse: mat4.invert(mat4.create(), matrix), geometry, particleScratch: new Float32Array(recording.particleCount * 3) };
}
diff --git a/src/kernel-offload.js b/src/kernel-offload.js
new file mode 100644
index 00000000..246be83b
--- /dev/null
+++ b/src/kernel-offload.js
@@ -0,0 +1,224 @@
+// Heavy pure computations (light bake, cloth solver, material pattern bake, uv_unwrap) can run on a worker while the
+// page stays responsive. Scene building is synchronous, so the worker result reaches it through a cache:
+//
+// 1. `buildWithKernels(build)` runs the synchronous build with a session open.
+// 2. A kernel that has no cached result throws `KernelDeferred` instead of computing.
+// 3. The session computes that kernel on a worker, caches the result by a hash of its input, and runs the build again.
+//
+// Without a session `runKernel` computes inline, so every caller that never opted in behaves exactly as before and a
+// host without workers (Node) produces the same bytes through the same code. This module is only imported by the
+// on-demand scene modules, never by the scene core.
+
+// Held in a constant so the bundler leaves the URL alone: the worker is its own package entry, built beside this file.
+const KERNEL_WORKER_FILE = './kernel-worker.js';
+
+const RECONSTRUCTED_ERRORS = { RangeError, TypeError, SyntaxError, ReferenceError };
+
+// More distinct heavy kernels than any real scene holds: past it the build finishes inline.
+const MAXIMUM_DEFERRALS = 256;
+
+let activeSession = null;
+
+/** Thrown by `runKernel` inside a session when a kernel's result has to be computed on the worker first. */
+export class KernelDeferred {
+ constructor(job) {
+ this.job = job;
+ }
+}
+
+function isPlainObject(value) {
+ const prototype = Object.getPrototypeOf(value);
+ return prototype === Object.prototype || prototype === null;
+}
+
+const HASH_PRIMES = [0x01000193, 0x85ebca6b];
+
+function createHasher() {
+ return { states: [0x811c9dc5, 0x9747b28c], length: 0 };
+}
+
+function mixBytes(hasher, bytes) {
+ for (let index = 0; index < bytes.length; index++) {
+ for (let lane = 0; lane < 2; lane++) {
+ hasher.states[lane] = Math.imul(hasher.states[lane] ^ bytes[index], HASH_PRIMES[lane]) >>> 0;
+ }
+ }
+ hasher.length += bytes.length;
+}
+
+const textEncoder = new TextEncoder();
+
+function mixText(hasher, text) {
+ mixBytes(hasher, textEncoder.encode(text));
+}
+
+function mixNamedValue(hasher, key, value) {
+ mixText(hasher, `${key}=`);
+ return mixValue(hasher, value);
+}
+
+/** Feeds a value into the hasher; returns false for anything that is not plain, cloneable data. */
+function mixValue(hasher, value) {
+ if (value === null || value === undefined || typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {
+ mixText(hasher, `${typeof value}:${String(value)};`);
+ return true;
+ }
+ if (ArrayBuffer.isView(value)) {
+ mixText(hasher, `${value.constructor.name}:${value.byteLength};`);
+ mixBytes(hasher, new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
+ return true;
+ }
+ if (Array.isArray(value)) {
+ mixText(hasher, `[${value.length}:`);
+ return value.every(item => mixValue(hasher, item));
+ }
+ if (typeof value === 'object' && isPlainObject(value)) {
+ const keys = Object.keys(value);
+ mixText(hasher, `{${keys.length}:`);
+ return keys.every(key => mixNamedValue(hasher, key, value[key]));
+ }
+ return false;
+}
+
+/** A key that identifies a kernel call by its name and the bytes of its input, or null when the input is not plain data. */
+export function kernelKey(name, args) {
+ const hasher = createHasher();
+ mixText(hasher, `${name}:`);
+ if (!mixValue(hasher, args)) {
+ return null;
+ }
+ return `${name}:${hasher.length}:${hasher.states.map(state => state.toString(16)).join('')}`;
+}
+
+/**
+ * Runs `compute(...args)`. Inside a `buildWithKernels` session the call returns the worker's cached result, or throws
+ * `KernelDeferred` so the session can fetch it. Everywhere else it computes inline. A call site that catches errors
+ * must rethrow `KernelDeferred`.
+ */
+export function runKernel(name, args, compute) {
+ if (!activeSession) {
+ return compute(...args);
+ }
+ const key = kernelKey(name, args);
+ if (key === null || activeSession.inlineAll || activeSession.inlineKeys.has(key)) {
+ return compute(...args);
+ }
+ if (activeSession.results.has(key)) {
+ const entry = activeSession.results.get(key);
+ if (entry.thrown) {
+ throw entry.thrown;
+ }
+ return entry.value;
+ }
+ throw new KernelDeferred({ name, args, key });
+}
+
+function rebuildError({ name, message }) {
+ const ErrorClass = RECONSTRUCTED_ERRORS[name] ?? Error;
+ return new ErrorClass(message);
+}
+
+function defaultWorkerFactory() {
+ return new Worker(new URL(KERNEL_WORKER_FILE, import.meta.url), { type: 'module' });
+}
+
+/** Whether this host can start the kernel worker. */
+export function kernelWorkersAvailable() {
+ return typeof Worker === 'function';
+}
+
+function abortError(signal) {
+ return signal.reason ?? new DOMException('The build was cancelled.', 'AbortError');
+}
+
+/** One job on one worker: resolves with the worker's answer, or rejects when the worker itself fails. */
+function requestKernel(worker, job, signal) {
+ return new Promise((resolve, reject) => {
+ const cleanUp = () => signal?.removeEventListener('abort', onAbort);
+ const onAbort = () => {
+ cleanUp();
+ reject(abortError(signal));
+ };
+ signal?.addEventListener('abort', onAbort, { once: true });
+ worker.onmessage = event => {
+ cleanUp();
+ resolve(event.data);
+ };
+ worker.onerror = event => {
+ cleanUp();
+ reject(new Error(`Kernel worker failed: ${event.message}`));
+ };
+ try {
+ worker.postMessage({ name: job.name, args: job.args });
+ } catch (error) {
+ cleanUp();
+ reject(error);
+ }
+ });
+}
+
+/**
+ * Runs a synchronous scene build while its heavy kernels compute on a worker. The result is the build's own result,
+ * built from identical bytes. `createWorker` replaces the browser Worker (tests, other hosts); `signal` cancels the
+ * build and ends the worker. Hosts without workers just run the build.
+ */
+export async function buildWithKernels(build, { createWorker = defaultWorkerFactory, signal, available = kernelWorkersAvailable() } = {}) {
+ if (!available || activeSession) {
+ return build();
+ }
+ const session = { results: new Map(), inlineKeys: new Set(), inlineAll: false, deferrals: 0 };
+ let worker = null;
+ try {
+ for (;;) {
+ if (signal?.aborted) {
+ throw abortError(signal);
+ }
+ activeSession = session;
+ try {
+ return build();
+ } catch (error) {
+ if (!(error instanceof KernelDeferred)) {
+ throw error;
+ }
+ activeSession = null;
+ session.deferrals++;
+ // A build whose inputs change on every run would never find its cached result; computing inline ends the loop.
+ session.inlineAll = session.deferrals > MAXIMUM_DEFERRALS;
+ worker ??= createWorkerOrNull(createWorker);
+ await computeOnWorker(session, worker, error.job, signal);
+ } finally {
+ activeSession = null;
+ }
+ }
+ } finally {
+ worker?.terminate();
+ }
+}
+
+function createWorkerOrNull(createWorker) {
+ try {
+ return createWorker();
+ } catch {
+ return null;
+ }
+}
+
+// A worker that cannot start or dies leaves the job to the inline path, which then does the work and raises its own
+// errors, so a failure never depends on the worker.
+async function computeOnWorker(session, worker, job, signal) {
+ if (!worker) {
+ session.inlineKeys.add(job.key);
+ return;
+ }
+ let answer;
+ try {
+ answer = await requestKernel(worker, job, signal);
+ } catch (error) {
+ if (signal?.aborted) {
+ throw error;
+ }
+ session.inlineKeys.add(job.key);
+ return;
+ }
+ session.results.set(job.key, answer.error ? { thrown: rebuildError(answer.error) } : { value: answer.value });
+}
diff --git a/src/kernel-registry.js b/src/kernel-registry.js
new file mode 100644
index 00000000..fc59a9bb
--- /dev/null
+++ b/src/kernel-registry.js
@@ -0,0 +1,40 @@
+import { bakeChangedParts } from './agent-bake.js';
+import { bakeCloth } from './cloth.js';
+import { bakeMaterialPattern } from './material-patterns.js';
+import { unwrapUv } from './mesh-uv.js';
+
+// The kernels a worker can run, by the name the call sites give `runKernel`. Each is the same function the call site
+// computes inline with, so the worker and the inline path return identical data.
+const KERNELS = {
+ lightBake: bakeChangedParts,
+ cloth: bakeCloth,
+ pattern: bakeMaterialPattern,
+ uvUnwrap: unwrapUv,
+};
+
+function collectBuffers(value, buffers) {
+ if (ArrayBuffer.isView(value)) {
+ buffers.add(value.buffer);
+ return;
+ }
+ if (value && typeof value === 'object') {
+ for (const child of Array.isArray(value) ? value : Object.values(value)) {
+ collectBuffers(child, buffers);
+ }
+ }
+}
+
+/**
+ * Answers one worker request: `{ response, transfer }`. A kernel that throws answers with the error's class name and
+ * message, so the page raises the same error the inline path would.
+ */
+export function answerKernelRequest({ name, args }) {
+ try {
+ const value = KERNELS[name](...args);
+ const buffers = new Set();
+ collectBuffers(value, buffers);
+ return { response: { value }, transfer: [...buffers] };
+ } catch (error) {
+ return { response: { error: { name: error?.constructor?.name ?? 'Error', message: String(error?.message ?? error) } }, transfer: [] };
+ }
+}
diff --git a/src/kernel-worker.js b/src/kernel-worker.js
new file mode 100644
index 00000000..685ef5a1
--- /dev/null
+++ b/src/kernel-worker.js
@@ -0,0 +1,7 @@
+import { answerKernelRequest } from './kernel-registry.js';
+
+// One thread of heavy scene computation: receives a kernel name and its input, answers with the result.
+self.onmessage = (event) => {
+ const { response, transfer } = answerKernelRequest(event.data);
+ self.postMessage(response, transfer);
+};
diff --git a/src/material-patterns.js b/src/material-patterns.js
index b0507cdc..2654aea9 100644
--- a/src/material-patterns.js
+++ b/src/material-patterns.js
@@ -1,5 +1,6 @@
import { MATERIAL_PATTERN_TYPES, MATERIAL_MAPPINGS } from './agent-scene-capabilities.js';
import { bakeMaterialGraph, normalizeMaterialGraph } from './material-graph.js';
+import { runKernel } from './kernel-offload.js';
// Procedural surface patterns for recipe materials: seeded, tileable and baked on the CPU into the same texture
// descriptors a loaded material uses. Texture coordinates run 0 to 1 and every noise is periodic over that square, so
@@ -278,7 +279,7 @@ export function materialPatternTextures(pattern) {
if (baked) {
bakedPatterns.delete(key);
} else {
- baked = bakeMaterialPattern(pattern);
+ baked = runKernel('pattern', [pattern], bakeMaterialPattern);
if (bakedPatterns.size >= MAX_BAKED_PATTERNS) bakedPatterns.delete(bakedPatterns.keys().next().value);
}
bakedPatterns.set(key, baked);
diff --git a/src/mesh-recipe.js b/src/mesh-recipe.js
index bdf75c2e..397fd91f 100644
--- a/src/mesh-recipe.js
+++ b/src/mesh-recipe.js
@@ -11,6 +11,7 @@ import { bevelEdges } from './mesh-bevel.js';
import { loopCut } from './mesh-loopcut.js';
import { CUT_OPERATIONS, normalizeCutEdit, runCutEdit, checkCutBudget } from './mesh-cut-edits.js';
import { unwrapUv } from './mesh-uv.js';
+import { runKernel, KernelDeferred } from './kernel-offload.js';
import { validateField } from './mesh-fields.js';
import { setPosition, displaceMesh, DISPLACE_DIRECTIONS } from './mesh-field-edits.js';
import { subdivideMesh, subdivisionSize, MAX_SUBDIVISION_LEVELS, MAX_CREASE_SHARPNESS } from './mesh-subdivide.js';
@@ -406,8 +407,12 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
if (edit.op === 'uv_unwrap') {
let outcome;
try {
- outcome = unwrapUv(current, edit);
+ const unwrapped = runKernel('uvUnwrap', [current, edit], unwrapUv);
+ outcome = { ...unwrapped, mesh: createMeshData(unwrapped.mesh) };
} catch (error) {
+ if (error instanceof KernelDeferred) {
+ throw error;
+ }
throw new error.constructor(`Mesh edit ${index} (uv_unwrap): ${error.message}`);
}
result.islands = outcome.islands;
diff --git a/tests/kernel-offload.test.js b/tests/kernel-offload.test.js
new file mode 100644
index 00000000..562d584d
--- /dev/null
+++ b/tests/kernel-offload.test.js
@@ -0,0 +1,99 @@
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import test from 'node:test';
+import { createAgentScene } from '../src/agent-scene.js';
+import { buildWithKernels, kernelKey, runKernel } from '../src/kernel-offload.js';
+import { answerKernelRequest } from '../src/kernel-registry.js';
+import { kernelRoom, sceneDigest } from './support/kernel-offload-fixture.mjs';
+
+const BUILD_SCRIPT = new URL('./support/kernel-offload-build.mjs', import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1');
+const LOADER = new URL('./support/load-agent-scene-modules.mjs', import.meta.url).href;
+
+// Each build runs in its own process so that nothing an earlier build cached (mesh evaluation, pattern textures) can
+// stand in for the kernel under test.
+function coldBuild(mode) {
+ const output = execFileSync(process.execPath, ['--import', LOADER, BUILD_SCRIPT, mode], { encoding: 'utf8' });
+ return JSON.parse(output.trim().split('\n').at(-1));
+}
+
+const inlineBuild = coldBuild('inline');
+
+test('the same recipe builds to the same bytes on one thread and with kernels on a worker', () => {
+ const workerBuild = coldBuild('worker');
+ assert.equal(workerBuild.digest, inlineBuild.digest);
+ for (const kernel of ['uvUnwrap', 'lightBake', 'cloth', 'pattern']) {
+ assert.ok(workerBuild.requestedKernels.includes(kernel), `the ${kernel} kernel ran on the worker`);
+ }
+ assert.deepEqual(inlineBuild.requestedKernels, []);
+});
+
+test('a host without workers builds inline', async () => {
+ const requested = [];
+ const scene = await buildWithKernels(() => createAgentScene(kernelRoom()), {
+ createWorker: () => { requested.push('started'); return {}; },
+ available: false,
+ });
+ assert.deepEqual(requested, []);
+ assert.equal(sceneDigest(scene), inlineBuild.digest);
+});
+
+test('a worker that cannot start leaves the work to the inline path with the same result', async () => {
+ const scene = await buildWithKernels(() => createAgentScene(kernelRoom()), {
+ createWorker: () => { throw new Error('no workers here'); },
+ available: true,
+ });
+ assert.equal(sceneDigest(scene), inlineBuild.digest);
+});
+
+test('a worker that dies mid-job leaves the work to the inline path with the same result', async () => {
+ const dying = {
+ postMessage() {
+ setTimeout(() => dying.onerror?.({ message: 'crashed' }), 0);
+ },
+ terminate() {},
+ };
+ const scene = await buildWithKernels(() => createAgentScene(kernelRoom()), { createWorker: () => dying, available: true });
+ assert.equal(sceneDigest(scene), inlineBuild.digest);
+});
+
+test('an error a kernel raises on the worker comes back as the same class and message', async () => {
+ const raised = answerKernelRequest({ name: 'pattern', args: [{ type: 'nope' }] });
+ assert.equal(raised.response.error.name, 'TypeError');
+ assert.equal(typeof raised.response.error.message, 'string');
+ const raising = {
+ postMessage() {
+ setTimeout(() => raising.onmessage?.({ data: { error: { name: 'RangeError', message: 'Light bake passed maxSeconds (20).' } } }), 0);
+ },
+ terminate() {},
+ };
+ await assert.rejects(
+ buildWithKernels(() => runKernel('lightBake', [[], {}, {}], () => 'inline'), { createWorker: () => raising, available: true }),
+ error => error instanceof RangeError && error.message === 'Light bake passed maxSeconds (20).',
+ );
+});
+
+test('cancelling stops the build and ends the worker', async () => {
+ const silent = { terminated: false, postMessage() {}, terminate() { silent.terminated = true; } };
+ const controller = new AbortController();
+ const pending = buildWithKernels(() => runKernel('pattern', [{ size: 1 }], () => 'inline'), {
+ createWorker: () => silent,
+ available: true,
+ signal: controller.signal,
+ });
+ setTimeout(() => controller.abort(), 5);
+ await assert.rejects(pending, error => error.name === 'AbortError');
+ assert.equal(silent.terminated, true);
+});
+
+test('kernel keys follow the bytes of the input and refuse data that cannot be cloned', () => {
+ const positions = new Float32Array([1, 2, 3]);
+ assert.equal(kernelKey('cloth', [positions, { a: 1 }]), kernelKey('cloth', [new Float32Array([1, 2, 3]), { a: 1 }]));
+ assert.notEqual(kernelKey('cloth', [positions]), kernelKey('cloth', [new Float32Array([1, 2, 4])]));
+ assert.notEqual(kernelKey('cloth', [positions]), kernelKey('pattern', [positions]));
+ assert.equal(kernelKey('cloth', [() => 1]), null);
+ assert.equal(kernelKey('cloth', [new Map()]), null);
+});
+
+test('without a session a kernel computes inline', () => {
+ assert.equal(runKernel('pattern', [2, 3], (left, right) => left + right), 5);
+});
diff --git a/tests/support/kernel-offload-build.mjs b/tests/support/kernel-offload-build.mjs
new file mode 100644
index 00000000..8934e1af
--- /dev/null
+++ b/tests/support/kernel-offload-build.mjs
@@ -0,0 +1,8 @@
+// Child process of tests/kernel-offload.test.js: builds the kernel room cold (nothing cached by an earlier build) and
+// prints its digest and the kernels the worker ran, as JSON. Argument: inline or worker.
+import { loadAllAgentSceneModules } from '../../src/agent-scene.js';
+import { buildKernelRoom, sceneDigest } from './kernel-offload-fixture.mjs';
+
+await loadAllAgentSceneModules();
+const { scene, requestedKernels } = await buildKernelRoom(process.argv[2]);
+console.log(JSON.stringify({ digest: sceneDigest(scene), requestedKernels }));
diff --git a/tests/support/kernel-offload-fixture.mjs b/tests/support/kernel-offload-fixture.mjs
new file mode 100644
index 00000000..a24f8856
--- /dev/null
+++ b/tests/support/kernel-offload-fixture.mjs
@@ -0,0 +1,95 @@
+import { createHash } from 'node:crypto';
+import { createAgentScene } from '../../src/agent-scene.js';
+import { buildWithKernels } from '../../src/kernel-offload.js';
+import { answerKernelRequest } from '../../src/kernel-registry.js';
+
+// A scene that reaches every offloaded kernel: uv_unwrap, light bake, cloth and a pattern texture.
+export function kernelRoom() {
+ const box = (id, translation, scale, material) => ({ id, geometry: 'box', material, translation, scale });
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [
+ { id: 'box', type: 'box' },
+ { id: 'crate', type: 'mesh', base: { type: 'box', bevel: 0 }, stack: [{ op: 'uv_unwrap' }] },
+ { id: 'banner', type: 'grid', segments: 6 },
+ ],
+ materials: [
+ { id: 'white', color: [0.8, 0.8, 0.8], roughness: 0.9 },
+ { id: 'lamp', color: [1, 1, 1], emission: 2 },
+ { id: 'wood', pattern: { type: 'wood', resolution: 256 } },
+ ],
+ nodes: [
+ box('floor', [0, -0.05, 0], [4, 0.1, 4], 'white'),
+ box('ceiling', [0, 3.05, 0], [4, 0.1, 4], 'white'),
+ box('back', [0, 1.5, -2.05], [4.2, 3.2, 0.1], 'white'),
+ box('bulb', [0.9, 2.5, 0.6], [0.2, 0.2, 0.2], 'lamp'),
+ { id: 'crate', geometry: 'crate', material: 'wood', translation: [-0.7, 0.4, -0.4] },
+ { id: 'flag', geometry: 'banner', material: 'white', translation: [0.5, 2, 0] },
+ ],
+ camera: { eye: [0, 1.5, 1.9], target: [0, 1.4, -2], fov: 70, near: 0.05, far: 20 },
+ environment: { pointLights: [{ position: [0, 2.7, 0], intensity: 14, radius: 0.1 }], keyIntensity: 0, fillIntensity: 0 },
+ bake: { preset: 'draft', samples: 8, texelsPerUnit: 2 },
+ cloth: { duration: 0.5, sheets: [{ node: 'flag', pin: ['top'] }] },
+ };
+}
+
+/** A worker that answers like the real one, in this process. Input and output cross structuredClone, as they would a real worker. */
+export function createInProcessWorker(requestedKernels = []) {
+ const worker = {
+ terminated: false,
+ postMessage(message) {
+ requestedKernels.push(message.name);
+ const { response } = answerKernelRequest(structuredClone(message));
+ setTimeout(() => worker.onmessage?.({ data: structuredClone(response) }), 0);
+ },
+ terminate() {
+ worker.terminated = true;
+ },
+ };
+ return worker;
+}
+
+export function digestOf(value) {
+ const hash = createHash('sha256');
+ const visit = (item) => {
+ if (ArrayBuffer.isView(item)) {
+ hash.update(Buffer.from(item.buffer, item.byteOffset, item.byteLength));
+ } else if (Array.isArray(item)) {
+ item.forEach(visit);
+ } else if (item && typeof item === 'object') {
+ for (const key of Object.keys(item).sort()) {
+ hash.update(key);
+ visit(item[key]);
+ }
+ } else {
+ hash.update(String(item));
+ }
+ };
+ visit(value);
+ return hash.digest('hex');
+}
+
+const TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'emissiveMap', 'lightMap'];
+
+/** Hash of everything a render reads from the scene: geometry and textures at rest, then geometry with the cloth in motion. */
+export function sceneDigest(scene) {
+ const atRest = scene.parts.map(part => [part.geometry, TEXTURE_FIELDS.map(field => part.material[field])]);
+ scene.sampleMotion(0.4);
+ const inMotion = scene.parts.map(part => part.geometry);
+ const { seconds, ...bakeReport } = scene.inspect().bake;
+ return digestOf({ atRest, inMotion, bakeReport });
+}
+
+/** Builds the room cold, in this process, either plainly or through `buildWithKernels` with an in-process worker. */
+export async function buildKernelRoom(mode) {
+ const requestedKernels = [];
+ if (mode === 'inline') {
+ return { scene: createAgentScene(kernelRoom()), requestedKernels };
+ }
+ const scene = await buildWithKernels(() => {
+ const built = createAgentScene(kernelRoom());
+ built.parts.forEach(part => void part.material.map);
+ return built;
+ }, { createWorker: () => createInProcessWorker(requestedKernels), available: true });
+ return { scene, requestedKernels };
+}
diff --git a/tests/support/preview-harness.mjs b/tests/support/preview-harness.mjs
index fdaa5cd0..de1a8792 100644
--- a/tests/support/preview-harness.mjs
+++ b/tests/support/preview-harness.mjs
@@ -66,6 +66,8 @@ export function previewHarness() {
? value => scene[field](JSON.parse(JSON.stringify(value ?? {}))) : scene[field] });
},
needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, loadAllAgentSceneModules, allAgentSceneModulesLoaded,
+ // The VM has no Worker, as in Node: builds stay synchronous, the way the preview falls back without workers.
+ buildWithKernels: build => build(), kernelWorkersAvailable: () => false,
// The harness loads Manifold from node_modules directly, so the preview's served-file loader is ignored.
setManifoldModuleLoader: () => {},
needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader: () => {},
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 8ca43649..9573eaaa 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -37,6 +37,7 @@ export default defineConfig({
'light-bake': 'src/light-bake.js',
'path-tracer': 'src/path-tracer.js',
'path-tracer-worker': 'src/path-tracer-worker.js',
+ 'kernel-worker': 'src/kernel-worker.js',
'texture-set': 'src/texture-set.js',
'agent-scene': 'src/agent-scene.js',
'agent-asset': 'src/agent-asset.js',