Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add retained surface attachments for morph and skin poses

Nguyen Xuan An0436286725fe
diff --git a/.gitignore b/.gitignore
index 8377066b..cff3b1be 100644
--- a/.gitignore
+++ b/.gitignore
@@ -34,3 +34,4 @@ public/camera-path.md
public/lighting.md
public/volumetric.md
public/film-physics.md
+public/surface-attachment.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8f078067..d5b72c4e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,10 @@
# Changelog
+## Unreleased
+
+- Add retained rigid surface attachments that follow relative morphs, four-influence skinning and world transforms.
+- Separate source package checks from published npm consumer checks with verified archive integrity.
+
## 0.4.0
- Add four-influence GPU skinning, relative position/normal morphs and glTF morph weight animation.
diff --git a/README.md b/README.md
index 7b90867d..f53fe70b 100644
--- a/README.md
+++ b/README.md
@@ -180,6 +180,10 @@ The [primitive contract](docs/primitives.md) defines bounded subdivision counts
The source [shrinkwrap addon](docs/shrinkwrap.md) wraps static vertices with nearest-surface or directional projection queries, preserving topology and UVs.
Compatible results can become relative GPU morph targets, so animation reuses the computed shape instead of repeating the vertex queries every frame.
+The current source adds [surface attachments](docs/surface-attachment.md) for rigid accessories following a selected triangle through morphing and skinning.
+The retained frame uses world-space clearance and samples three bound vertices without rebuilding a BVH every frame.
+This addon is newer than npm `0.4.0`. It does not certify clearance over an accessory's entire footprint.
+
The trailer's rigid actor joints now use authored clips, with attached headwear and hands moving together.
The [optional asset addon](docs/gltf.md) loads glTF/GLB meshes, base-color textures, opaque vertex colors and rigid node animation.
diff --git a/ROADMAP.md b/ROADMAP.md
index 033550ee..1a9b9818 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -14,6 +14,11 @@ This document separates shipping capabilities from work in progress. Performance
- Orthographic front, right and top views, plus flat XY scenes with pan, zoom and capture.
- glTF/GLB mesh input, base-color textures, opaque vertex colors and rigid node animation.
- Landscape, portrait and square presets, time ranges and a generic capture interface for scenes and imported assets.
+- Retained scene graphs, lathe and extrusion modeling, authored camera paths and deterministic clip mixing.
+- Four-influence GPU skinning, relative morph targets and glTF morph weight animations.
+- Material maps, local point lights and depth-clipped volumetric fog.
+- Optional recorded Rapier physics with contacts, joint limits and bounded motors.
+- Static sculpt brushes, clipped surface patches, shrinkwrap and bounded mesh contact and containment queries.
## Next
@@ -25,5 +30,7 @@ This document separates shipping capabilities from work in progress. Performance
## Longer term
-Evaluate WebGPU after collecting WebGL2 bottleneck measurements. Add skinning, morph targets and more glTF materials as bounded asset support grows.
+Evaluate WebGPU after collecting WebGL2 bottleneck measurements.
+Extend deformation with surface bindings, remeshing and authored humanoid rigs.
+Improve character assets and cinematic environments through measured rendering and inspected reference frames.
Blender is the visual quality reference for authored scenes. Rendering parity and universal speed advantages remain goals that need evidence.
diff --git a/docs/guide.md b/docs/guide.md
index 67d84b60..8add3ac8 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -288,3 +288,6 @@ The current checkout adds authoring and animation APIs through separate modules:
- [GLB snapshot export](export-glb.md), including vertex colors, UVs, HDR emission and current morph weights.
These APIs do not provide a Blender-style editor, WebGPU backend or general asset compatibility. Mesh queries operate on static geometry. They do not automatically resolve collisions or diagnose z-fighting. The physics addon requires its separate Rapier dependency. See each module's contract for limits and disposal requirements.
+
+The current source also adds [surface attachments](surface-attachment.md), newer than npm `0.4.0`.
+These retained rigid frames follow selected triangles through morphing and skinning without rebuilding a mesh query index each frame.
diff --git a/docs/surface-attachment.md b/docs/surface-attachment.md
new file mode 100644
index 00000000..ce793ec5
--- /dev/null
+++ b/docs/surface-attachment.md
@@ -0,0 +1,155 @@
+# Retained triangle attachments
+
+This addon exists in the current source build, newer than npm `0.4.0`.
+
+`createSurfaceAttachment` follows one triangle through rigid transforms, relative morphs, and skinning.
+It returns a retained rigid world matrix for an accessory placed at a barycentric point.
+The accessory's local positive Z axis faces along the posed triangle's geometric winding.
+
+```js
+import { createSurfaceAttachment } from '67js/addons/surface-attachment';
+
+const attachment = createSurfaceAttachment(targetPart, {
+ triangle: hit.triangle,
+ barycentric: hit.barycentric,
+ clearance: 0.003,
+ rotation: 0,
+});
+const accessoryPart = {
+ geometry: accessoryGeometry,
+ matrix: attachment.matrix,
+ material: accessoryMaterial,
+};
+
+// Update the target's retained matrix, morph weights, and skin palette first.
+attachment.update();
+renderer.updateParts([targetPart, accessoryPart]);
+```
+
+`triangle` uses the original target index-buffer triangle number.
+This matches the triangle number from `createMeshQueryIndex` ray hits.
+The binding uses that triangle's three original index entries in order.
+An attachment does not perform another raycast or choose another triangle during updates.
+
+## Binding options
+
+| Option | Default | Contract |
+| --- | --- | --- |
+| `triangle` | Required | Integer from zero through the target triangle count minus one |
+| `barycentric` | Required | Three nonnegative finite Float32-representable components |
+| `clearance` | 0 | Nonnegative finite Float32-representable distance in world units |
+| `rotation` | 0 | Finite Float32-representable twist in radians about local positive Z |
+| `maxVertices` | 250000 | Integer from 1 through 1000000 |
+| `maxTriangles` | 250000 | Integer from 1 through 1000000 |
+
+The barycentric components must sum to one within `1e-6`.
+The binding copies and normalizes those components before use.
+It also copies the clearance and rotation values.
+Changing the caller's option arrays after binding does not change the attachment.
+Unknown option fields cause an error.
+
+The target requires Float32 XYZ positions and matching finite unit Float32 normals.
+Its nonempty triangle index buffer must use `Uint32Array`.
+The retained target matrix must use `Float32Array(16)`.
+It must remain finite, affine, and nonsingular.
+Binding checks all target vertices and triangle indices within the supplied budgets.
+It rejects degenerate base triangles.
+
+Morph and skin bindings use the renderer's existing geometry validators.
+These validators check all declared channels and the initial deformation pose once at binding.
+Morph targets require the matching retained morph pose.
+Skin channels require the matching retained mesh-local joint palette.
+The constructor evaluates the initial attachment before returning it.
+
+## Frame and clearance
+
+The position is the barycentric point on the three posed world vertices.
+The local X axis follows triangle edge zero-to-one.
+The local Z axis is the normalized cross product of edges zero-to-one and zero-to-two.
+The local Y axis completes the right-handed orthonormal frame.
+`rotation` twists X and Y around Z.
+The output matrix carries unit scale and does not inherit target shear or nonuniform scale.
+
+Static target reflections reverse the geometric winding and therefore reverse the attachment's Z axis.
+This frame does not use interpolated vertex normals or morphed shading normals.
+If an animated triangle reverses its winding without collapsing at the sampled time, its attachment frame follows that winding.
+The operation does not track unsampled intermediate times.
+
+Clearance moves the barycentric point along that geometric Z axis in world units.
+It remains a world distance under target nonuniform scaling and shear.
+Positive clearance must produce a positive outward face gap after the translation rounds to Float32.
+The implementation also checks that the offset changes the rounded base position outward.
+A collapsed or tangent-only offset causes an error.
+Zero clearance places the rounded origin on the sampled surface without promising depth-buffer separation.
+
+## Deformation order and precision
+
+The attachment adds relative morph position deltas to each selected base vertex.
+It then applies the weighted four-influence skin matrix and the target world matrix.
+The skin influences use the renderer's normalized Float32 weights.
+The implementation preserves the resulting homogeneous coordinate and divides each world vertex by it.
+The barycentric frame therefore follows the visible post-divide geometric triangle.
+
+Intermediate matrix and vertex operations round to Float32 and reject nonfinite results.
+Frame construction uses Double precision before publishing a Float32 matrix.
+The CPU calculation follows the renderer's deformation order, but GPU fused arithmetic can produce small rounding differences.
+It does not promise bit-identical GPU positions.
+The attachment also does not follow shader displacement beyond morph and skin deformation.
+
+The selected triangle must retain a minimum altitude above a conservative world precision margin.
+That margin uses approximately four Float32 units at the largest posed world coordinate.
+Large translations can reject small triangles even when every input remains finite.
+Collapsed triangles, singular weighted skin transforms, and unsupported reflected skin transforms cause errors.
+Skin reflection restrictions match the renderer.
+
+## Snapshots, identities, and updates
+
+Binding snapshots only the selected three base positions, selected morph position deltas, and twelve skin influence entries.
+Static channel contents follow the renderer's immutable-upload contract.
+Changing those contents in place does not change an existing attachment.
+Rebind after rebuilding or uploading edited geometry.
+
+The binding retains the target part, geometry, matrix, channel buffers, and pose identities.
+Replacing those identities requires another binding.
+Morph target objects and channel identities must also remain unchanged.
+The output handle is frozen, while its matrix remains a retained mutable buffer for renderer use.
+Treat that output matrix as owned by the attachment.
+
+`update()` reads current retained matrix values, morph weights, and referenced joint matrices.
+It returns the same `Float32Array(16)` on every successful call.
+The update performs no BVH build, mesh reconstruction, GPU readback, or full palette scan.
+Its work depends on three vertices, at most 64 morph targets, and at most twelve skin influences.
+Static geometry contents are not rescanned during an update.
+
+Validation uses a private pending matrix before publishing the retained output.
+An error leaves the last successful matrix unchanged.
+After repairing the invalid pose or restoring an identity, another update can succeed.
+Sampling current pose values in arbitrary order gives the same matrix for the same pose.
+The attachment does not advance an animation clock or remember previous pose values.
+
+An update validates only the selected triangle and its referenced palette entries.
+It does not certify unrelated vertices or unused joints.
+Run the renderer's full validation when committing the target's complete pose.
+
+## Supported targets and limits
+
+Assembly shader offsets are unsupported.
+The vertex-deforming tags `water`, `foliage`, `grass`, `fire`, and `smoke` are unsupported.
+Morphed or skinned targets also reject the renderer's procedural `terrain` and `floor` tags.
+Static `terrain` and `floor` targets retain their geometry-based attachment frame.
+Standard material changes do not change the binding.
+
+This attachment positions a rigid accessory at one contact point.
+It does not conform the accessory's footprint to a curved surface.
+It does not certify accessory clearance, prevent every mesh intersection, remesh a decal, or reproduce Blender's Surface Deform modifier.
+Use shrinkwrap for static vertex projection and a surface patch for clipped triangle overlays.
+
+Two designs were considered: rebuilding a full posed mesh and BVH, or retaining one sparse triangle binding.
+The sparse binding keeps update work bounded and avoids repeated mesh allocation.
+It preserves an explicit original triangle identity instead of silently choosing a new surface point after deformation.
+
+## References
+
+[Three.js Mesh](https://threejs.org/docs/pages/Mesh.html) documents vertex sampling with morphing and skinning.
+[Blender Surface Deform](https://docs.blender.org/manual/en/3.6/modeling/modifiers/deform/surface_deform.html) describes binding an entire surface to another deforming mesh.
+The sparse rigid attachment here does not implement that full modifier.
diff --git a/package.json b/package.json
index 18474177..4bb1424b 100644
--- a/package.json
+++ b/package.json
@@ -40,7 +40,8 @@
"docs/surface.md",
"docs/mesh-query.md",
"docs/primitives.md",
- "docs/shrinkwrap.md"
+ "docs/shrinkwrap.md",
+ "docs/surface-attachment.md"
],
"main": "./build/67.module.js",
"module": "./build/67.module.js",
@@ -57,6 +58,7 @@
"./addons/surface": "./build/surface.js",
"./addons/mesh-query": "./build/mesh-query.js",
"./addons/shrinkwrap": "./build/shrinkwrap.js",
+ "./addons/surface-attachment": "./build/surface-attachment.js",
"./addons/physics": "./build/physics.js",
"./package.json": "./package.json"
},
diff --git a/public/llms.txt b/public/llms.txt
index 0f0f64b1..c1a553e5 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -102,6 +102,11 @@ Vertex clearance does not certify whole-triangle clearance. Compatible static ou
GLB support excludes transparent and double-sided materials and compressed geometry. Unsupported features require visible errors.
+The current source adds `addons/surface-attachment`, newer than npm `0.4.0`. Read `docs/surface-attachment.md` before binding.
+Bind a triangle and barycentric coordinates once. Assign the retained attachment.matrix to the accessory.
+Update the target morph/skin/world pose, call attachment.update(), then upload target and accessory through renderer.updateParts().
+Clearance uses world units and the geometric face normal. This rigid point attachment does not guarantee clearance over the entire accessory footprint.
+
The optional GLB decoder uses Three.js GLTFLoader. The renderer remains 67.js.
Adaptive quality, GPU timing and picking are roadmap work. Speed claims require comparable scenes, hardware, settings and measurements.
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index d98e9ea2..6d66d57a 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -40,6 +40,7 @@ const sourceDocuments = [
'gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md',
'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md', 'shrinkwrap.md',
'camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',
+ 'surface-attachment.md',
];
for (const name of sourceDocuments) {
await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));
diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjs
index 3d14fd0e..59ed51e8 100644
--- a/scripts/smoke-package.mjs
+++ b/scripts/smoke-package.mjs
@@ -18,17 +18,29 @@ assert.ok((await readFile('build/67.module.js')).length < 150000, 'The core must
const consumer = await mkdtemp(resolve(tmpdir(), '67js-consumer-'));
await writeFile(resolve(consumer, 'package.json'), JSON.stringify({ private: true, type: 'module' }));
const npmCli = process.env.npm_execpath ?? resolve(dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js');
+const published = process.argv.includes('--published');
// Release preparation preserves the registry archive for an already-published version.
// Validate the current source through a separate local pack, without replacing that archive.
-const sourcePack = spawnSync(process.execPath, [npmCli, 'pack', '--ignore-scripts', '--json', '--pack-destination', consumer], { windowsHide: true, encoding: 'utf8' });
-assert.equal(sourcePack.status, 0, sourcePack.stderr);
-const sourcePackResult = JSON.parse(sourcePack.stdout);
-const packedSource = Array.isArray(sourcePackResult) ? sourcePackResult[0] : sourcePackResult[metadata.name];
-assert.ok(packedSource?.filename, 'npm pack must return a source archive.');
-assert.ok(packedSource.size < 1024 * 1024, 'The current source package must fit within a 1 MiB archive.');
-const sourceArchive = resolve(consumer, packedSource.filename);
-const installed = spawnSync(process.execPath, [npmCli, 'install', `67js@file:${sourceArchive.replaceAll('\\', '/')}`, '@dimforge/[email protected]', '--ignore-scripts', '--no-audit', '--no-fund'], { cwd: consumer, windowsHide: true, encoding: 'utf8' });
+let installTarget;
+if (published) {
+ assert.equal(release.registryPublished, true, 'Published consumer checks require registry-backed release metadata.');
+ installTarget = `67js@npm:${metadata.name}@${metadata.version}`;
+} else {
+ const sourcePack = spawnSync(process.execPath, [npmCli, 'pack', '--ignore-scripts', '--json', '--pack-destination', consumer], { windowsHide: true, encoding: 'utf8' });
+ assert.equal(sourcePack.status, 0, sourcePack.stderr);
+ const sourcePackResult = JSON.parse(sourcePack.stdout);
+ const packedSource = Array.isArray(sourcePackResult) ? sourcePackResult[0] : sourcePackResult[metadata.name];
+ assert.ok(packedSource?.filename, 'npm pack must return a source archive.');
+ assert.ok(packedSource.size < 1024 * 1024, 'The current source package must fit within a 1 MiB archive.');
+ const sourceArchive = resolve(consumer, packedSource.filename);
+ installTarget = `67js@file:${sourceArchive.replaceAll('\\', '/')}`;
+}
+const installed = spawnSync(process.execPath, [npmCli, 'install', installTarget, '@dimforge/[email protected]', '--ignore-scripts', '--no-audit', '--no-fund'], { cwd: consumer, windowsHide: true, encoding: 'utf8' });
assert.equal(installed.status, 0, installed.stderr);
+if (published) {
+ const installedLock = JSON.parse(await readFile(resolve(consumer, 'package-lock.json'), 'utf8'));
+ assert.equal(installedLock.packages['node_modules/67js'].integrity, release.integrity, 'Installed npm package differs from release integrity.');
+}
const example = `import assert from 'node:assert/strict';
import { VERSION, Renderer67, box, assemblyOffset, cameraView, fitPerspectiveDistance, createAnimationClip, sampleAnimationClip, EFFECT_PRESETS, createMorphPose, MAX_MORPH_TARGETS, exportGlb } from '67js';
import { createModel } from '67js/addons/model';
@@ -98,6 +110,24 @@ assert.equal(wrappedPatch.stats.missedVertices, 0);
assert.deepEqual(wrappedPatch.geometry.indices, packedPatch.indices);
assert.deepEqual(wrappedPatch.geometry.uvs, packedPatch.uvs);
assert.ok(wrappedPatch.geometry.positions.every((value, index) => index % 3 !== 2 || Math.abs(value - 0.502) < 1e-6));
+if (${!published}) {
+ const { createSurfaceAttachment } = await import('67js/addons/surface-attachment');
+ const attachmentMatrix = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+ const attachmentMorph = createMorphPose(1);
+ const target = { matrix: attachmentMatrix, morph: attachmentMorph, geometry: {
+ positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]),
+ indices: new Uint32Array([0, 1, 2]),
+ morphTargets: [{ positions: new Float32Array([0, 0, 0.2, 0, 0, 0.2, 0, 0, 0.2]) }],
+ } };
+ const attachment = createSurfaceAttachment(target, { triangle: 0, barycentric: [0.2, 0.3, 0.5], clearance: 0.002 });
+ const retainedMatrix = attachment.matrix;
+ attachmentMorph.weights[0] = 1;
+ attachmentMatrix[12] = 2;
+ assert.equal(attachment.update(), retainedMatrix);
+ assert.ok(Math.abs(retainedMatrix[12] - 2.3) < 1e-6);
+ assert.ok(Math.abs(retainedMatrix[14] - 0.202) < 1e-6);
+}
solidIndex.dispose();
const parts = createModel();
assert.equal(parts.length, 574);
@@ -142,4 +172,4 @@ console.log('Clean consumer: core, geometry, addons, real physics contact and al
await writeFile(resolve(consumer, 'check.mjs'), example);
const result = spawnSync(process.execPath, ['check.mjs'], { cwd: consumer, windowsHide: true, encoding: 'utf8' });
assert.equal(result.status, 0, result.stderr);
-console.log(result.stdout.trim());
+console.log(`${published ? 'Published npm' : 'Source archive'} ${metadata.version}: ${result.stdout.trim()}`);
diff --git a/scripts/smoke-surface-attachment.mjs b/scripts/smoke-surface-attachment.mjs
new file mode 100644
index 00000000..c01767d8
--- /dev/null
+++ b/scripts/smoke-surface-attachment.mjs
@@ -0,0 +1,262 @@
+import assert from 'node:assert/strict';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { constants, setPriority } from 'node:os';
+import { chromium } from 'playwright';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+await mkdir('artifacts', { recursive: true });
+const width = Number(process.argv[2] ?? 960);
+const height = Number(process.argv[3] ?? 540);
+const browser = await chromium.launch({
+ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',
+ headless: true,
+ args: ['--enable-webgl', '--ignore-gpu-blocklist'],
+});
+try {
+ const page = await browser.newPage({ viewport: { width, height } });
+ const errors = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await page.route('**/attachment-smoke.html', route => route.fulfill({
+ contentType: 'text/html',
+ body: `<canvas style="width:${width}px;height:${height}px;display:block"></canvas>`,
+ }));
+ await page.goto('http://127.0.0.1:5173/attachment-smoke.html');
+ const report = await page.evaluate(async () => {
+ const { Renderer67, torus, sphere, createMorphPose, createSkinPose, fitPerspectiveDistance } = await import('/build/67.module.js');
+ const { createSurfaceAttachment } = await import('/build/surface-attachment.js');
+ const { createMeshQueryIndex, createMeshPairQuery } = await import('/build/mesh-query.js');
+ const { mat4 } = await import('/node_modules/.vite/deps/gl-matrix.js');
+ const { vertexShader } = await import('/src/shaders.js');
+ const columns = 32;
+ const rows = 20;
+ const vertexCount = (columns + 1) * (rows + 1);
+ const positions = new Float32Array(vertexCount * 3);
+ const normals = new Float32Array(vertexCount * 3);
+ const deltas = new Float32Array(vertexCount * 3);
+ const normalDeltas = new Float32Array(vertexCount * 3);
+ const skinIndices = new Uint16Array(vertexCount * 4);
+ const skinWeights = new Float32Array(vertexCount * 4);
+ const indices = [];
+ for (let row = 0; row <= rows; row++) {
+ for (let column = 0; column <= columns; column++) {
+ const vertex = row * (columns + 1) + column;
+ const horizontal = column / columns;
+ const vertical = row / rows;
+ positions.set([(horizontal - 0.5) * 3.2, (vertical - 0.5) * 2, 0], vertex * 3);
+ normals.set([0, 0, 1], vertex * 3);
+ const height = 0.32 * Math.sin(horizontal * Math.PI) * Math.cos((vertical - 0.5) * Math.PI);
+ const slopeX = 0.32 * Math.PI / 3.2 * Math.cos(horizontal * Math.PI) * Math.cos((vertical - 0.5) * Math.PI);
+ const slopeY = -0.32 * Math.PI / 2 * Math.sin(horizontal * Math.PI) * Math.sin((vertical - 0.5) * Math.PI);
+ const normalLength = Math.hypot(slopeX, slopeY, 1);
+ deltas.set([0, 0, height], vertex * 3);
+ normalDeltas.set([-slopeX / normalLength, -slopeY / normalLength, 1 / normalLength - 1], vertex * 3);
+ skinIndices.set([0, 1, 0, 0], vertex * 4);
+ skinWeights.set([1 - horizontal, horizontal, 0, 0], vertex * 4);
+ if (row < rows && column < columns) {
+ indices.push(vertex, vertex + 1, vertex + columns + 2, vertex, vertex + columns + 2, vertex + columns + 1);
+ }
+ }
+ }
+ const morph = createMorphPose(1);
+ const skin = createSkinPose(2);
+ const matrix = mat4.create();
+ const target = {
+ name: 'Deforming alloy panel',
+ geometry: { positions, normals, indices: new Uint32Array(indices), skinIndices, skinWeights, morphTargets: [{ positions: deltas, normals: normalDeltas }] },
+ morph, skin, matrix,
+ material: { color: [0.025, 0.24, 0.35], metallic: 0.65, roughness: 0.35, emission: 0 },
+ castShadow: false,
+ };
+ const triangle = (10 * columns + 20) * 2;
+ const barycentric = [0.25, 0.35, 0.4];
+ const clearance = 0.003;
+ const attachment = createSurfaceAttachment(target, { triangle, barycentric, clearance, rotation: 0.25 });
+ const badgeGeometry = torus(0.12, 48, 16);
+ for (let offset = 0; offset < badgeGeometry.positions.length; offset += 3) {
+ badgeGeometry.positions[offset] *= 0.16;
+ badgeGeometry.positions[offset + 1] *= 0.16;
+ badgeGeometry.positions[offset + 2] = badgeGeometry.positions[offset + 2] * 0.16 + 0.04;
+ }
+ const jewelGeometry = sphere(32, 20);
+ for (let offset = 0; offset < jewelGeometry.positions.length; offset += 3) {
+ jewelGeometry.positions[offset] *= 0.115;
+ jewelGeometry.positions[offset + 1] *= 0.115;
+ jewelGeometry.positions[offset + 2] = jewelGeometry.positions[offset + 2] * 0.035 + 0.04;
+ }
+ const ring = { name: 'Retained brass ring', geometry: badgeGeometry, matrix: attachment.matrix,
+ material: { color: [0.75, 0.35, 0.035], metallic: 0.85, roughness: 0.23, emission: 0 }, castShadow: false };
+ const jewel = { name: 'Retained amber insert', geometry: jewelGeometry, matrix: attachment.matrix,
+ material: { color: [1, 0.12, 0.005], metallic: 0.05, roughness: 0.25, emission: 0.12 }, castShadow: false };
+ const parts = [target, ring, jewel];
+ const canvas = document.querySelector('canvas');
+ const renderer = new Renderer67(canvas, parts, {
+ world: true, ground: false, hdr: true, samples: 2, pixelRatio: 1, memoryBudgetMiB: 96,
+ environment: { keyIntensity: 0.8, fillIntensity: 0.6, ambientIntensity: 0.4 },
+ });
+ const camera = { eye: [2.4, 1.8, 5], target: [0, 0, 0], fov: 35 };
+ const distance = fitPerspectiveDistance({ minimum: [-2.2, -1.3, -1.2], maximum: [2.2, 1.3, 1.2] }, camera, canvas.clientWidth / canvas.clientHeight);
+ const initialDistance = Math.hypot(...camera.eye);
+ camera.eye = camera.eye.map(value => value * distance / initialDistance);
+ const frame = { ...camera, time: 0, effects: { grain: 0, bloom: { strength: 0 } } };
+ const context = renderer.context;
+ const gpuInfo = context.getExtension('WEBGL_debug_renderer_info');
+ const gpu = gpuInfo ? context.getParameter(gpuInfo.UNMASKED_RENDERER_WEBGL) : context.getParameter(context.RENDERER);
+ const batch = renderer.partLocations.get(target).batch;
+ function shader(type, source) {
+ const result = context.createShader(type);
+ context.shaderSource(result, source);
+ context.compileShader(result);
+ if (!context.getShaderParameter(result, context.COMPILE_STATUS)) throw new Error(context.getShaderInfoLog(result));
+ return result;
+ }
+ const vertex = shader(context.VERTEX_SHADER, vertexShader);
+ const fragment = shader(context.FRAGMENT_SHADER, '#version 300 es\nprecision highp float;out vec4 color;void main(){color=vec4(0.0);}');
+ const program = context.createProgram();
+ context.attachShader(program, vertex);
+ context.attachShader(program, fragment);
+ context.transformFeedbackVaryings(program, ['worldPosition', 'gl_Position'], context.INTERLEAVED_ATTRIBS);
+ context.linkProgram(program);
+ if (!context.getProgramParameter(program, context.LINK_STATUS)) throw new Error(context.getProgramInfoLog(program));
+ const feedback = context.createTransformFeedback();
+ const feedbackBuffer = context.createBuffer();
+ const feedbackData = new Float32Array(vertexCount * 7);
+ context.bindBuffer(context.TRANSFORM_FEEDBACK_BUFFER, feedbackBuffer);
+ context.bufferData(context.TRANSFORM_FEEDBACK_BUFFER, feedbackData.byteLength, context.STREAM_READ);
+ context.bindBuffer(context.TRANSFORM_FEEDBACK_BUFFER, null);
+ const identity = mat4.create();
+ const ringIndex = createMeshQueryIndex(badgeGeometry);
+ const jewelIndex = createMeshQueryIndex(jewelGeometry);
+ function captureVertices() {
+ context.useProgram(program);
+ context.uniformMatrix4fv(context.getUniformLocation(program, 'viewProjection'), false, identity);
+ context.uniform1f(context.getUniformLocation(program, 'skinEnabled'), 1);
+ context.uniform1f(context.getUniformLocation(program, 'morphEnabled'), 1);
+ context.uniform1i(context.getUniformLocation(program, 'morphVertexCount'), vertexCount);
+ context.uniform1i(context.getUniformLocation(program, 'morphTargetCount'), 1);
+ context.uniform1fv(context.getUniformLocation(program, 'morphWeights[0]'), morph.weights);
+ for (const [unit, name, texture] of [[6, 'skinInfluences', batch.influenceTexture.texture], [7, 'jointPalette', batch.skinTexture.texture], [8, 'morphTargets', batch.morphTexture.texture]]) {
+ context.activeTexture(context.TEXTURE0 + unit);
+ context.bindTexture(context.TEXTURE_2D, texture);
+ context.uniform1i(context.getUniformLocation(program, name), unit);
+ }
+ context.bindVertexArray(batch.vertexArray);
+ context.bindTransformFeedback(context.TRANSFORM_FEEDBACK, feedback);
+ context.bindBufferBase(context.TRANSFORM_FEEDBACK_BUFFER, 0, feedbackBuffer);
+ context.enable(context.RASTERIZER_DISCARD);
+ context.beginTransformFeedback(context.POINTS);
+ context.drawArraysInstanced(context.POINTS, 0, vertexCount, 1);
+ context.endTransformFeedback();
+ context.disable(context.RASTERIZER_DISCARD);
+ context.bindTransformFeedback(context.TRANSFORM_FEEDBACK, null);
+ context.bindVertexArray(null);
+ context.bindBuffer(context.TRANSFORM_FEEDBACK_BUFFER, feedbackBuffer);
+ context.getBufferSubData(context.TRANSFORM_FEEDBACK_BUFFER, 0, feedbackData);
+ context.bindBuffer(context.TRANSFORM_FEEDBACK_BUFFER, null);
+ const points = [];
+ const worldPositions = new Float32Array(vertexCount * 3);
+ for (let vertex = 0; vertex < vertexCount; vertex++) {
+ for (let axis = 0; axis < 3; axis++) worldPositions[vertex * 3 + axis] = feedbackData[vertex * 7 + axis] / feedbackData[vertex * 7 + 6];
+ }
+ for (let corner = 0; corner < 3; corner++) {
+ const vertex = target.geometry.indices[triangle * 3 + corner];
+ const offset = vertex * 7;
+ const homogeneous = feedbackData[offset + 6];
+ points.push(Array.from(feedbackData.subarray(offset, offset + 3), value => value / homogeneous));
+ }
+ return { points, worldPositions };
+ }
+ function proof(points) {
+ const edge = points[1].map((value, axis) => value - points[0][axis]);
+ const second = points[2].map((value, axis) => value - points[0][axis]);
+ const cross = [edge[1] * second[2] - edge[2] * second[1], edge[2] * second[0] - edge[0] * second[2], edge[0] * second[1] - edge[1] * second[0]];
+ const normal = cross.map(value => value / Math.hypot(...cross));
+ const center = [0, 1, 2].map(axis => points.reduce((total, point, corner) => total + point[axis] * barycentric[corner], 0));
+ const expected = center.map((value, axis) => value + normal[axis] * clearance);
+ const positionError = Math.hypot(...expected.map((value, axis) => value - attachment.matrix[12 + axis]));
+ const normalError = Math.hypot(...normal.map((value, axis) => value - attachment.matrix[8 + axis]));
+ if (positionError > 2e-6 || normalError > 2e-5) throw new Error(`Attachment diverged from actual GPU triangle: ${positionError}, ${normalError}`);
+ return { positionError, normalError };
+ }
+ const allocations = { buffers: 0, textures: 0, framebuffers: 0, renderbuffers: 0 };
+ for (const [method, key] of [['createBuffer', 'buffers'], ['createTexture', 'textures'], ['createFramebuffer', 'framebuffers'], ['createRenderbuffer', 'renderbuffers']]) {
+ const original = context[method].bind(context);
+ context[method] = (...argumentsList) => {
+ allocations[key]++;
+ return original(...argumentsList);
+ };
+ }
+ const retainedMatrix = attachment.matrix;
+ const frames = [];
+ let baseline;
+ let changedChannels = 0;
+ function pose(time) {
+ morph.weights[0] = 0.5 + Math.sin(time) * 0.45;
+ mat4.fromYRotation(matrix, Math.sin(time * 0.7) * 0.2);
+ mat4.scale(matrix, matrix, [1.1, 0.95, 0.9]);
+ matrix[4] += Math.sin(time * 0.4) * 0.12;
+ matrix[12] = Math.sin(time * 0.6) * 0.2;
+ for (let joint = 0; joint < 2; joint++) {
+ const rotation = mat4.fromYRotation(mat4.create(), Math.sin(time) * (joint === 0 ? 0.5 : -0.5));
+ const pivot = joint === 0 ? -0.8 : 0.8;
+ rotation[12] = pivot - rotation[0] * pivot;
+ rotation[14] = -rotation[2] * pivot;
+ skin.jointMatrices.set(rotation, joint * 16);
+ }
+ attachment.update();
+ renderer.updateParts(parts);
+ renderer.render(frame);
+ const pixels = new Uint8Array(canvas.width * canvas.height * 4);
+ context.readPixels(0, 0, canvas.width, canvas.height, context.RGBA, context.UNSIGNED_BYTE, pixels);
+ const captured = captureVertices();
+ const result = proof(captured.points);
+ const posedIndex = createMeshQueryIndex({ positions: captured.worldPositions, indices: target.geometry.indices });
+ try {
+ for (const [accessoryName, accessoryIndex] of [['ring', ringIndex], ['jewel', jewelIndex]]) {
+ const contact = createMeshPairQuery(posedIndex, accessoryIndex).evaluate(identity, attachment.matrix);
+ if (contact.kind !== 'surface-disjoint') throw new Error(`Fixture ${accessoryName} overlaps the GPU-posed target at ${time}: ${JSON.stringify(contact)}`);
+ }
+ } finally {
+ posedIndex.dispose();
+ }
+ if (context.getError()) throw new Error('Surface attachment smoke generated a graphics error');
+ if (attachment.matrix !== retainedMatrix) throw new Error('Attachment matrix identity changed');
+ if (!baseline) baseline = pixels;
+ else if (time === 0) {
+ if (pixels.some((value, index) => value !== baseline[index])) throw new Error('Reverse pose changed pixels');
+ } else {
+ changedChannels = Math.max(changedChannels, pixels.reduce((count, value, index) => count + (value !== baseline[index] ? 1 : 0), 0));
+ }
+ frames.push({ time, ...result });
+ }
+ for (const time of [0, 1.2, 2.7, 0.5, 0]) pose(time);
+ for (let update = 0; update < 80; update++) {
+ attachment.update();
+ renderer.updateParts(parts, { shadows: false });
+ }
+ pose(1.2);
+ window.__attachmentSmoke = { renderer, frame };
+ const report = { gpu, frames, changedChannels, allocations, estimatedBytes: renderer.memoryPlan.estimatedBytes, vertexCount };
+ ringIndex.dispose();
+ jewelIndex.dispose();
+ context.deleteTransformFeedback(feedback);
+ context.deleteBuffer(feedbackBuffer);
+ context.deleteProgram(program);
+ context.deleteShader(vertex);
+ context.deleteShader(fragment);
+ return report;
+ });
+ assert.deepEqual(errors, []);
+ assert.ok(report.changedChannels > 1000, 'Rendered deformation did not visibly change');
+ assert.deepEqual(report.allocations, { buffers: 0, textures: 0, framebuffers: 0, renderbuffers: 0 });
+ // Render the final presentation after releasing the diagnostic feedback objects.
+ await page.evaluate(() => {
+ const { renderer, frame } = window.__attachmentSmoke;
+ renderer.render(frame);
+ });
+ await page.locator('canvas').screenshot({ path: `artifacts/surface-attachment-${width}x${height}.png` });
+ await page.evaluate(() => window.__attachmentSmoke.renderer.dispose());
+ await writeFile(`artifacts/surface-attachment-${width}x${height}.json`, JSON.stringify(report, null, 2));
+ console.log(JSON.stringify(report));
+} finally {
+ await browser.close();
+}
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index e459f0b0..a73aeed2 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -28,6 +28,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- A curved surface badge uses optional `src/surface.js` and the checkout's `docs/surface.md`.
- Static contact, ray hits or closed-solid containment use optional `src/mesh-query.js` and the checkout's `docs/mesh-query.md`.
- Static vertex wrapping uses optional `src/shrinkwrap.js` and the checkout's `docs/shrinkwrap.md`.
+- A rigid accessory on a morphing or skinned surface uses optional `src/surface-attachment.js` and `docs/surface-attachment.md`.
- An image or video export uses `render-67js-media`.
Read [scene-contract.md](references/scene-contract.md) before creating parts or changing materials.
diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.md
index c49de189..bd0344c4 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -64,7 +64,7 @@ Each light provides `position` and optional `color`, `intensity`, `radius` and `
Read the checkout's `docs/lighting.md` for defaults, numeric limits and frame overrides.
Point lights currently cast no local shadows. Radius limits attenuation without creating an area emitter.
-Source-only `environment.volumeFog` receives directional scattering and shadows in one bounded volume.
+`environment.volumeFog` receives directional scattering and shadows in one bounded volume.
It requires an opaque renderer with `{ hdr: true, depth: true }` and negotiated HDR support.
Read `docs/volumetric.md` for controls, resource cost and limitations before authoring fog.
`frame.environment.volumeFog` replaces the entire constructor fog object, with defaults for omitted fields.
@@ -126,6 +126,12 @@ Share the target matrix with the wrapped part. Local distances are not world dis
Compute once before renderer upload. Matching topology permits relative morph animation instead of rebuilding the BVH every frame.
Vertex clearance does not certify every triangle interior against a curved or nonconvex target. Use the clipping patch for conforming surface overlays.
+Use `createSurfaceAttachment(target, { triangle, barycentric, clearance })` for a rigid accessory following a posed triangle.
+Read `docs/surface-attachment.md`. Share its retained `matrix` with the accessory, update the target pose, then update the attachment before renderer upload.
+The frame follows relative morphs before four-influence skinning. Clearance uses world units and the geometric triangle normal.
+Bind immutable geometry once. This sparse point attachment does not deform the accessory or certify clearance over its footprint.
+This addon follows the current source and is newer than npm `0.4.0`.
+
`cameraView('front' | 'right' | 'top')` returns an orthographic camera with the correct up vector.
`fitOrthographicHeight(bounds, view, aspect)` frames both model width and height.
The `unlit` tag and a front orthographic camera produce flat XY geometry.
diff --git a/src/surface-attachment.js b/src/surface-attachment.js
new file mode 100644
index 00000000..82e89ea2
--- /dev/null
+++ b/src/surface-attachment.js
@@ -0,0 +1,285 @@
+import { mat3 } from 'gl-matrix';
+import { validateMorphGeometry, validateMorphPose, validateMorphTransform } from './morph.js';
+import { validateSkinGeometry, validateSkinPose } from './skinning.js';
+
+const OPTION_FIELDS = new Set(['triangle', 'barycentric', 'clearance', 'rotation', 'maxVertices', 'maxTriangles']);
+const VERTEX_PROCEDURAL_TAGS = new Set(['water', 'foliage', 'grass', 'fire', 'smoke']);
+const DEFORMATION_PROCEDURAL_TAGS = new Set(['water', 'foliage', 'grass', 'terrain', 'floor', 'fire', 'smoke']);
+
+function finiteFloat(value, label) {
+ if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isFinite(Math.fround(value))) {
+ throw new RangeError(`${label} must be finite and Float32-representable.`);
+ }
+ return value;
+}
+
+function limit(value, label) {
+ if (!Number.isSafeInteger(value) || value < 1 || value > 1_000_000) {
+ throw new RangeError(`${label} must be an integer from 1 through 1000000.`);
+ }
+ return value;
+}
+
+function determinant(matrix, offset = 0) {
+ return matrix[offset] * (matrix[offset + 5] * matrix[offset + 10] - matrix[offset + 9] * matrix[offset + 6])
+ - matrix[offset + 4] * (matrix[offset + 1] * matrix[offset + 10] - matrix[offset + 9] * matrix[offset + 2])
+ + matrix[offset + 8] * (matrix[offset + 1] * matrix[offset + 6] - matrix[offset + 5] * matrix[offset + 2]);
+}
+
+function validateMatrix(matrix, offset, label, minimumDeterminant = 0) {
+ for (let component = 0; component < 16; component++) finiteFloat(matrix[offset + component], label);
+ if (matrix[offset + 3] !== 0 || matrix[offset + 7] !== 0 || matrix[offset + 11] !== 0 || matrix[offset + 15] !== 1) {
+ throw new RangeError(`${label} must remain affine.`);
+ }
+ const value = determinant(matrix, offset);
+ if (!Number.isFinite(value) || value === 0 || Math.abs(value) < minimumDeterminant) {
+ throw new RangeError(`${label} must remain nonsingular.`);
+ }
+ return value;
+}
+
+function validateTargetMode(target) {
+ if (target.assembly !== undefined && target.assembly !== null) throw new RangeError('Surface attachments cannot follow assembly shader offsets.');
+ const tag = target.material?.tag;
+ if (VERTEX_PROCEDURAL_TAGS.has(tag) || ((target.skin || target.morph) && DEFORMATION_PROCEDURAL_TAGS.has(tag))) {
+ throw new RangeError('Surface attachment target uses unsupported procedural deformation or a deformed procedural material.');
+ }
+}
+
+function validateGeometry(geometry, maxVertices, maxTriangles) {
+ const { positions, normals, indices } = geometry ?? {};
+ if (!(positions instanceof Float32Array) || positions.length < 9 || positions.length % 3 !== 0 ||
+ !(normals instanceof Float32Array) || normals.length !== positions.length ||
+ !(indices instanceof Uint32Array) || indices.length < 3 || indices.length % 3 !== 0) {
+ throw new TypeError('Surface attachments require indexed Float32 positions/normals and Uint32 triangles.');
+ }
+ const vertexCount = positions.length / 3;
+ const triangleCount = indices.length / 3;
+ if (vertexCount > maxVertices || triangleCount > maxTriangles) throw new RangeError('Attachment target exceeds maxVertices or maxTriangles.');
+ for (const value of positions) finiteFloat(value, 'Target position');
+ for (let offset = 0; offset < normals.length; offset += 3) {
+ const length = Math.hypot(normals[offset], normals[offset + 1], normals[offset + 2]);
+ if (!Number.isFinite(length) || Math.abs(length - 1) > 0.001) throw new RangeError('Target normals must remain finite unit vectors.');
+ }
+ for (const index of indices) if (index >= vertexCount) throw new RangeError('Target triangle index exceeds the vertex count.');
+ for (let offset = 0; offset < indices.length; offset += 3) {
+ const first = indices[offset] * 3;
+ const second = indices[offset + 1] * 3;
+ const third = indices[offset + 2] * 3;
+ const edgeFirstX = positions[second] - positions[first];
+ const edgeFirstY = positions[second + 1] - positions[first + 1];
+ const edgeFirstZ = positions[second + 2] - positions[first + 2];
+ const edgeSecondX = positions[third] - positions[first];
+ const edgeSecondY = positions[third + 1] - positions[first + 1];
+ const edgeSecondZ = positions[third + 2] - positions[first + 2];
+ if (Math.hypot(edgeFirstY * edgeSecondZ - edgeFirstZ * edgeSecondY, edgeFirstZ * edgeSecondX - edgeFirstX * edgeSecondZ, edgeFirstX * edgeSecondY - edgeFirstY * edgeSecondX) === 0) {
+ throw new RangeError('Attachment target contains a degenerate triangle.');
+ }
+ }
+ return { vertexCount, triangleCount };
+}
+
+function rounded(value) {
+ const result = Math.fround(value);
+ if (!Number.isFinite(result)) throw new RangeError('Attachment deformation exceeds finite Float32 arithmetic.');
+ return result;
+}
+
+/** Bind one original triangle and retain a rigid world-space frame for current deformation poses. */
+export function createSurfaceAttachment(target, options = {}) {
+ if (!target || typeof target !== 'object') throw new TypeError('Surface attachments require a target part.');
+ if (!options || typeof options !== 'object' || Array.isArray(options)) throw new TypeError('Attachment options require an object.');
+ for (const field of Object.keys(options)) if (!OPTION_FIELDS.has(field)) throw new TypeError(`Unsupported attachment option ${field}.`);
+ const maxVertices = limit(options.maxVertices ?? 250_000, 'maxVertices');
+ const maxTriangles = limit(options.maxTriangles ?? 250_000, 'maxTriangles');
+ const geometry = target.geometry;
+ const counts = validateGeometry(geometry, maxVertices, maxTriangles);
+ const triangle = options.triangle;
+ if (!Number.isSafeInteger(triangle) || triangle < 0 || triangle >= counts.triangleCount) throw new RangeError('Attachment triangle must reference an original target triangle.');
+ const inputWeights = options.barycentric;
+ if ((!Array.isArray(inputWeights) && !ArrayBuffer.isView(inputWeights)) || inputWeights.length !== 3) throw new TypeError('Attachment barycentric coordinates require three components.');
+ const barycentric = new Float64Array(3);
+ let total = 0;
+ for (let corner = 0; corner < 3; corner++) {
+ const value = finiteFloat(inputWeights[corner], 'Barycentric coordinate');
+ if (value < 0) throw new RangeError('Barycentric coordinates must be nonnegative.');
+ barycentric[corner] = value;
+ total += value;
+ }
+ if (Math.abs(total - 1) > 1e-6) throw new RangeError('Barycentric coordinates must sum to one within 1e-6.');
+ for (let corner = 0; corner < 3; corner++) barycentric[corner] /= total;
+ const clearance = finiteFloat(options.clearance ?? 0, 'Clearance');
+ if (clearance < 0) throw new RangeError('Clearance must be nonnegative.');
+ const rotation = finiteFloat(options.rotation ?? 0, 'Rotation');
+ const cosine = Math.cos(rotation);
+ const sine = Math.sin(rotation);
+ const worldMatrix = target.matrix;
+ if (!(worldMatrix instanceof Float32Array) || worldMatrix.length !== 16) throw new TypeError('Target matrix requires a retained Float32Array of 16 components.');
+ validateTargetMode(target);
+ validateMatrix(worldMatrix, 0, 'Target matrix');
+ const skin = target.skin ?? null;
+ const morph = target.morph ?? null;
+ validateSkinGeometry(geometry, skin);
+ if (skin) validateSkinPose(skin, geometry, worldMatrix);
+ const morphMetadata = validateMorphGeometry(geometry, morph);
+ if (morph) validateMorphTransform(morph, morphMetadata, worldMatrix, skin);
+ const positionsIdentity = geometry.positions;
+ const normalsIdentity = geometry.normals;
+ const indicesIdentity = geometry.indices;
+ const skinIndicesIdentity = geometry.skinIndices;
+ const skinWeightsIdentity = geometry.skinWeights;
+ const palette = skin?.jointMatrices;
+ const paletteLength = palette?.length;
+ const morphWeights = morph?.weights;
+ const selectedPositions = new Float32Array(9);
+ const selectedDeltas = new Float32Array((morphMetadata?.targetCount ?? 0) * 9);
+ const selectedJoints = new Uint32Array(12);
+ const selectedWeights = new Float32Array(12);
+ for (let corner = 0; corner < 3; corner++) {
+ const vertex = geometry.indices[triangle * 3 + corner];
+ selectedPositions.set(geometry.positions.subarray(vertex * 3, vertex * 3 + 3), corner * 3);
+ for (let targetIndex = 0; targetIndex < (morphMetadata?.targetCount ?? 0); targetIndex++) {
+ const deltas = morphMetadata.targets[targetIndex].positions;
+ if (deltas) selectedDeltas.set(deltas.subarray(vertex * 3, vertex * 3 + 3), targetIndex * 9 + corner * 3);
+ }
+ if (skin) {
+ let skinTotal = 0;
+ for (let influence = 0; influence < 4; influence++) skinTotal += geometry.skinWeights[vertex * 4 + influence];
+ for (let influence = 0; influence < 4; influence++) {
+ selectedJoints[corner * 4 + influence] = geometry.skinIndices[vertex * 4 + influence];
+ selectedWeights[corner * 4 + influence] = Math.fround(geometry.skinWeights[vertex * 4 + influence] / skinTotal);
+ }
+ }
+ }
+ const matrix = new Float32Array(16);
+ const pending = new Float32Array(16);
+ pending[15] = 1;
+ const vertex = new Float32Array(4);
+ vertex[3] = 1;
+ const blended = new Float32Array(16);
+ const combined = new Float32Array(16);
+ const worldVertices = new Float64Array(9);
+ const normalWorkspace = new Float32Array(9);
+
+ function update() {
+ if (target.geometry !== geometry || geometry.positions !== positionsIdentity || geometry.normals !== normalsIdentity || geometry.indices !== indicesIdentity ||
+ positionsIdentity.length !== counts.vertexCount * 3 || normalsIdentity.length !== counts.vertexCount * 3 || indicesIdentity.length !== counts.triangleCount * 3 ||
+ target.matrix !== worldMatrix || worldMatrix.length !== 16 || (target.skin ?? null) !== skin || (target.morph ?? null) !== morph ||
+ geometry.skinIndices !== skinIndicesIdentity || geometry.skinWeights !== skinWeightsIdentity || skin?.jointMatrices !== palette || palette?.length !== paletteLength || morph?.weights !== morphWeights) {
+ throw new Error('Attachment target buffer or pose identities changed. Bind a new attachment.');
+ }
+ if (skin && (skinIndicesIdentity.length !== counts.vertexCount * 4 || skinWeightsIdentity.length !== counts.vertexCount * 4)) {
+ throw new Error('Attachment skin channel lengths changed. Bind a new attachment.');
+ }
+ validateTargetMode(target);
+ const worldDeterminant = validateMatrix(worldMatrix, 0, 'Target matrix');
+ if (!mat3.normalFromMat4(normalWorkspace, worldMatrix)) throw new RangeError('Target matrix has no finite normal transform.');
+ for (let component = 0; component < 9; component++) finiteFloat(normalWorkspace[component], 'Target normal transform');
+ if (morph) {
+ validateMorphPose(morph, morphMetadata);
+ for (let targetIndex = 0; targetIndex < morphMetadata.targetCount; targetIndex++) {
+ const channels = morphMetadata.targets[targetIndex];
+ if ((channels.positions && channels.positions.length !== counts.vertexCount * 3) || (channels.normals && channels.normals.length !== counts.vertexCount * 3)) {
+ throw new Error('Attachment morph channel lengths changed. Bind a new attachment.');
+ }
+ }
+ }
+ if (skin) {
+ for (let influence = 0; influence < 12; influence++) validateMatrix(palette, selectedJoints[influence] * 16, 'Referenced joint palette', 1e-10);
+ }
+ for (let corner = 0; corner < 3; corner++) {
+ for (let axis = 0; axis < 3; axis++) {
+ let coordinate = selectedPositions[corner * 3 + axis];
+ for (let targetIndex = 0; targetIndex < (morphMetadata?.targetCount ?? 0); targetIndex++) {
+ coordinate = rounded(coordinate + rounded(selectedDeltas[targetIndex * 9 + corner * 3 + axis] * morphWeights[targetIndex]));
+ }
+ vertex[axis] = coordinate;
+ }
+ if (skin) {
+ for (let component = 0; component < 16; component++) {
+ let coefficient = 0;
+ for (let influence = 0; influence < 4; influence++) {
+ const offset = corner * 4 + influence;
+ coefficient = rounded(coefficient + rounded(palette[selectedJoints[offset] * 16 + component] * selectedWeights[offset]));
+ }
+ blended[component] = coefficient;
+ }
+ const blendedDeterminant = determinant(blended);
+ if (!Number.isFinite(blendedDeterminant) || Math.abs(blendedDeterminant) < 1e-8) throw new RangeError('Attachment has a singular weighted skin transform.');
+ if (blendedDeterminant * worldDeterminant < 0) throw new RangeError('Reflected weighted skin transforms are unsupported by the renderer.');
+ for (let column = 0; column < 4; column++) {
+ for (let row = 0; row < 4; row++) {
+ let coefficient = 0;
+ for (let axis = 0; axis < 4; axis++) coefficient = rounded(coefficient + rounded(worldMatrix[axis * 4 + row] * blended[column * 4 + axis]));
+ combined[column * 4 + row] = coefficient;
+ }
+ }
+ } else {
+ combined.set(worldMatrix);
+ }
+ let homogeneous = 0;
+ for (let axis = 0; axis < 4; axis++) homogeneous = rounded(homogeneous + rounded(combined[axis * 4 + 3] * vertex[axis]));
+ if (!(homogeneous > 0)) throw new RangeError('Attachment has an invalid homogeneous vertex coordinate.');
+ for (let row = 0; row < 3; row++) {
+ let coordinate = 0;
+ for (let axis = 0; axis < 4; axis++) coordinate = rounded(coordinate + rounded(combined[axis * 4 + row] * vertex[axis]));
+ worldVertices[corner * 3 + row] = finiteFloat(coordinate / homogeneous, 'Posed world vertex');
+ }
+ }
+ const edgeX = worldVertices[3] - worldVertices[0];
+ const edgeY = worldVertices[4] - worldVertices[1];
+ const edgeZ = worldVertices[5] - worldVertices[2];
+ const otherX = worldVertices[6] - worldVertices[0];
+ const otherY = worldVertices[7] - worldVertices[1];
+ const otherZ = worldVertices[8] - worldVertices[2];
+ const crossX = edgeY * otherZ - edgeZ * otherY;
+ const crossY = edgeZ * otherX - edgeX * otherZ;
+ const crossZ = edgeX * otherY - edgeY * otherX;
+ const edgeLength = Math.hypot(edgeX, edgeY, edgeZ);
+ const area = Math.hypot(crossX, crossY, crossZ);
+ const longest = Math.max(edgeLength, Math.hypot(otherX, otherY, otherZ), Math.hypot(otherX - edgeX, otherY - edgeY, otherZ - edgeZ));
+ let maximumCoordinate = 0;
+ for (let component = 0; component < 9; component++) maximumCoordinate = Math.max(maximumCoordinate, Math.abs(worldVertices[component]));
+ const altitude = area / longest;
+ if (!Number.isFinite(altitude) || altitude <= maximumCoordinate * 2 ** -21 + 2 ** -149) throw new RangeError('Attachment triangle collapses within Float32 world precision.');
+ const tangentX = edgeX / edgeLength;
+ const tangentY = edgeY / edgeLength;
+ const tangentZ = edgeZ / edgeLength;
+ const normalX = crossX / area;
+ const normalY = crossY / area;
+ const normalZ = crossZ / area;
+ const secondX = normalY * tangentZ - normalZ * tangentY;
+ const secondY = normalZ * tangentX - normalX * tangentZ;
+ const secondZ = normalX * tangentY - normalY * tangentX;
+ pending[0] = tangentX * cosine + secondX * sine;
+ pending[1] = tangentY * cosine + secondY * sine;
+ pending[2] = tangentZ * cosine + secondZ * sine;
+ pending[4] = secondX * cosine - tangentX * sine;
+ pending[5] = secondY * cosine - tangentY * sine;
+ pending[6] = secondZ * cosine - tangentZ * sine;
+ pending[8] = normalX;
+ pending[9] = normalY;
+ pending[10] = normalZ;
+ let originX = 0;
+ let originY = 0;
+ let originZ = 0;
+ for (let corner = 0; corner < 3; corner++) {
+ originX += worldVertices[corner * 3] * barycentric[corner];
+ originY += worldVertices[corner * 3 + 1] * barycentric[corner];
+ originZ += worldVertices[corner * 3 + 2] * barycentric[corner];
+ }
+ pending[12] = finiteFloat(originX + normalX * clearance, 'Attachment translation');
+ pending[13] = finiteFloat(originY + normalY * clearance, 'Attachment translation');
+ pending[14] = finiteFloat(originZ + normalZ * clearance, 'Attachment translation');
+ if (clearance > 0) {
+ const gap = (pending[12] - originX) * normalX + (pending[13] - originY) * normalY + (pending[14] - originZ) * normalZ;
+ const movement = (pending[12] - Math.fround(originX)) * normalX + (pending[13] - Math.fround(originY)) * normalY + (pending[14] - Math.fround(originZ)) * normalZ;
+ if (!(gap > 0 && movement > 0)) throw new RangeError('Attachment clearance collapses against the geometric face at Float32 precision.');
+ }
+ matrix.set(pending);
+ return matrix;
+ }
+
+ update();
+ return Object.freeze({ matrix, update });
+}
diff --git a/tests/surface-attachment.test.js b/tests/surface-attachment.test.js
new file mode 100644
index 00000000..bc868285
--- /dev/null
+++ b/tests/surface-attachment.test.js
@@ -0,0 +1,269 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { mat3 } from 'gl-matrix';
+import { Matrix4, Vector3 } from 'three';
+import { createSurfaceAttachment } from '../src/surface-attachment.js';
+import { createMorphPose } from '../src/morph.js';
+import { createSkinPose } from '../src/skinning.js';
+import { createMeshQueryIndex } from '../src/mesh-query.js';
+
+const bind = { triangle: 0, barycentric: [0.2, 0.3, 0.5] };
+
+function target() {
+ return {
+ geometry: { positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]), indices: new Uint32Array([0, 1, 2]) },
+ matrix: new Float32Array(new Matrix4().elements),
+ material: { tag: 'standard' },
+ };
+}
+
+function close(actual, expected, tolerance = 1e-6) {
+ assert.equal(actual.length, expected.length);
+ for (let component = 0; component < actual.length; component++) assert.ok(Math.abs(actual[component] - expected[component]) <= tolerance, `component ${component}: ${actual[component]} versus ${expected[component]}`);
+}
+
+function rigid(matrix) {
+ const first = new Vector3().fromArray(matrix, 0);
+ const second = new Vector3().fromArray(matrix, 4);
+ const third = new Vector3().fromArray(matrix, 8);
+ assert.ok(Math.abs(first.length() - 1) < 1e-6);
+ assert.ok(Math.abs(second.length() - 1) < 1e-6);
+ assert.ok(Math.abs(third.length() - 1) < 1e-6);
+ assert.ok(Math.abs(first.dot(second)) < 1e-6);
+ assert.ok(Math.abs(first.dot(third)) < 1e-6);
+ assert.ok(new Vector3().crossVectors(first, second).distanceTo(third) < 1e-6);
+}
+
+function deformable() {
+ const part = target();
+ part.geometry.morphTargets = [{ positions: new Float32Array([0, 0, 1, 0, 0, 2, 0, 0, 3]) }];
+ part.morph = createMorphPose(1);
+ part.skin = createSkinPose(2);
+ part.geometry.skinIndices = new Uint16Array([0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0]);
+ part.geometry.skinWeights = new Float32Array([0.25, 0.25, 0, 0, 0.25, 0.25, 0, 0, 0.25, 0.25, 0, 0]);
+ return part;
+}
+
+test('literal static binding is retained, rigid and compatible with original mesh-query hits', () => {
+ const part = target();
+ const attachment = createSurfaceAttachment(part, { ...bind, clearance: 0.125 });
+ close(attachment.matrix.subarray(12, 15), [0.3, 0.5, 0.125]);
+ rigid(attachment.matrix);
+ assert.equal(attachment.update(), attachment.matrix);
+ const index = createMeshQueryIndex(part.geometry);
+ const hit = index.raycast(part.matrix, { origin: [0.25, 0.25, 1], direction: [0, 0, -1] });
+ const fromHit = createSurfaceAttachment(part, { triangle: hit.triangle, barycentric: hit.barycentric });
+ close(fromHit.matrix.subarray(12, 15), [0.25, 0.25, 0]);
+ const twisted = createSurfaceAttachment(part, { ...bind, rotation: Math.PI / 2 });
+ close(twisted.matrix.subarray(0, 3), [0, 1, 0]);
+ close(twisted.matrix.subarray(4, 7), [-1, 0, 0]);
+ index.dispose();
+});
+
+test('world affine transforms give rigid axes, geometric reflected winding, and constant world clearance', () => {
+ for (const reflection of [1, -1]) {
+ const part = target();
+ const transform = new Matrix4().makeRotationX(0.4).multiply(new Matrix4().makeScale(reflection * 2, 3, 0.5));
+ transform.elements[4] += 0.6;
+ transform.setPosition(4, -2, 1);
+ part.matrix.set(transform.elements);
+ const attachment = createSurfaceAttachment(part, { ...bind, clearance: 0.2 });
+ const vertices = [new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(0, 1, 0)].map(point => point.applyMatrix4(new Matrix4().fromArray(part.matrix)));
+ const firstEdge = vertices[1].clone().sub(vertices[0]);
+ const normal = new Vector3().crossVectors(firstEdge, vertices[2].clone().sub(vertices[0])).normalize();
+ const center = vertices[0].clone().multiplyScalar(0.2).addScaledVector(vertices[1], 0.3).addScaledVector(vertices[2], 0.5);
+ close(attachment.matrix.subarray(8, 11), normal.toArray());
+ close(attachment.matrix.subarray(0, 3), firstEdge.normalize().toArray());
+ close(attachment.matrix.subarray(12, 15), center.addScaledVector(normal, 0.2).toArray());
+ rigid(attachment.matrix);
+ }
+});
+
+test('relative morph runs before normalized four-influence skin and mesh world transformation', () => {
+ const part = deformable();
+ part.morph.weights[0] = 1;
+ part.skin.jointMatrices.set(new Matrix4().makeScale(1, 1, 2).elements, 0);
+ part.skin.jointMatrices.set(new Matrix4().makeTranslation(0, 0, 4).elements, 16);
+ part.matrix[12] = 3;
+ const attachment = createSurfaceAttachment(part, bind);
+ // Normalized .25+.25 influences become .5+.5. Z = (2*z + z+4)/2.
+ close(attachment.matrix.subarray(12, 15), [3.3, 0.5, 5.45]);
+ const expectedNormal = new Vector3(-1.5, -3, 1).normalize();
+ close(attachment.matrix.subarray(8, 11), expectedNormal.toArray());
+ rigid(attachment.matrix);
+});
+
+test('homogeneous normalized Float32 weights follow the post-divide geometric triangle', () => {
+ const part = target();
+ part.skin = createSkinPose(3);
+ part.geometry.skinIndices = new Uint16Array([0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0]);
+ part.geometry.skinWeights = new Float32Array([0.1, 0.2, 0.3, 0, 0.1, 0.2, 0.3, 0, 0.1, 0.2, 0.3, 0]);
+ part.skin.jointMatrices[28] = 3;
+ part.skin.jointMatrices[44] = 6;
+ part.matrix[12] = 2;
+ const attachment = createSurfaceAttachment(part, bind);
+ let total = 0;
+ for (let influence = 0; influence < 4; influence++) total += part.geometry.skinWeights[influence];
+ const first = Math.fround(part.geometry.skinWeights[0] / total);
+ const second = Math.fround(part.geometry.skinWeights[1] / total);
+ const third = Math.fround(part.geometry.skinWeights[2] / total);
+ const sum = Math.fround(Math.fround(first + second) + third);
+ const blendedTranslation = Math.fround(Math.fround(second * 3) + Math.fround(third * 6));
+ const worldTranslation = Math.fround(blendedTranslation + Math.fround(2 * sum));
+ close(attachment.matrix.subarray(12, 15), [worldTranslation / sum + 0.3, 0.5, 0], 2e-6);
+});
+
+test('different influences at each selected vertex change the geometric frame rather than a shared rigid skin pose', () => {
+ const part = target();
+ part.skin = createSkinPose(2);
+ part.skin.jointMatrices[30] = 2;
+ part.geometry.skinIndices = new Uint16Array([0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0]);
+ part.geometry.skinWeights = new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 0.5, 0.5, 0, 0]);
+ const attachment = createSurfaceAttachment(part, bind);
+ close(attachment.matrix.subarray(12, 15), [0.3, 0.5, 1.1]);
+ close(attachment.matrix.subarray(8, 11), new Vector3(-2, -1, 1).normalize().toArray());
+ rigid(attachment.matrix);
+});
+
+test('arbitrary pose order returns the same matrices and makes no per-update matrix allocation', context => {
+ const part = deformable();
+ const attachment = createSurfaceAttachment(part, bind);
+ const retained = attachment.matrix;
+ context.mock.method(mat3, 'create', () => { throw new Error('Per-frame normal matrix allocation'); });
+ const sample = time => {
+ part.morph.weights[0] = time * 0.25;
+ part.skin.jointMatrices[28] = time;
+ part.matrix[13] = time * 0.5;
+ assert.equal(attachment.update(), retained);
+ return new Float32Array(retained);
+ };
+ const forward = [0, 1, 2].map(sample);
+ assert.deepEqual(sample(2), forward[2]);
+ assert.deepEqual(sample(0), forward[0]);
+ assert.deepEqual(sample(1), forward[1]);
+});
+
+test('static channel contents use immutable-upload snapshots while replacements require rebinding', () => {
+ const part = deformable();
+ part.morph.weights[0] = 0.5;
+ const attachment = createSurfaceAttachment(part, bind);
+ const expected = new Float32Array(attachment.matrix);
+ part.geometry.positions.fill(100);
+ part.geometry.indices.fill(0);
+ part.geometry.morphTargets[0].positions.fill(10);
+ part.geometry.skinIndices.fill(1);
+ part.geometry.skinWeights.fill(0);
+ assert.deepEqual(attachment.update(), expected);
+ const original = part.geometry.positions;
+ part.geometry.positions = new Float32Array(original);
+ assert.throws(() => attachment.update(), /identities changed/);
+ assert.deepEqual(attachment.matrix, expected);
+ part.geometry.positions = original;
+ assert.deepEqual(attachment.update(), expected);
+ const originalWeights = part.morph.weights;
+ part.morph.weights = new Float32Array(originalWeights);
+ assert.throws(() => attachment.update(), /identities changed/);
+ part.morph.weights = originalWeights;
+ assert.deepEqual(attachment.update(), expected);
+});
+
+test('option snapshots and restored target identities recover without changing the retained output', () => {
+ const part = deformable();
+ const barycentric = [0.2, 0.3, 0.5];
+ const attachment = createSurfaceAttachment(part, { triangle: 0, barycentric, clearance: 0.1 });
+ const expected = new Float32Array(attachment.matrix);
+ barycentric.fill(0);
+ assert.deepEqual(attachment.update(), expected);
+ for (const field of ['matrix', 'skin', 'morph']) {
+ const original = part[field];
+ part[field] = field === 'matrix' ? new Float32Array(original) : { ...original };
+ assert.throws(() => attachment.update(), /identities changed/);
+ assert.deepEqual(attachment.matrix, expected);
+ part[field] = original;
+ assert.deepEqual(attachment.update(), expected);
+ }
+ const palette = part.skin.jointMatrices;
+ part.skin.jointMatrices = new Float32Array(palette);
+ assert.throws(() => attachment.update(), /identities changed/);
+ part.skin.jointMatrices = palette;
+ assert.deepEqual(attachment.update(), expected);
+ part.material.tag = 'water';
+ assert.throws(() => attachment.update(), /procedural/);
+ part.material.tag = 'standard';
+ assert.deepEqual(attachment.update(), expected);
+});
+
+test('invalid mutable poses and triangle collapse fail atomically and permit later recovery', () => {
+ const part = deformable();
+ const attachment = createSurfaceAttachment(part, bind);
+ const expected = new Float32Array(attachment.matrix);
+ part.morph.weights[0] = NaN;
+ assert.throws(() => attachment.update(), /finite/);
+ assert.deepEqual(attachment.matrix, expected);
+ part.morph.weights[0] = 0;
+ part.skin.jointMatrices[0] = 0;
+ assert.throws(() => attachment.update(), /nonsingular/);
+ part.skin.jointMatrices[0] = 1;
+ part.matrix[12] = 1e20;
+ assert.throws(() => attachment.update(), /collapses/);
+ part.matrix[12] = 0;
+ assert.deepEqual(attachment.update(), expected);
+ const collapsing = target();
+ collapsing.geometry.morphTargets = [{ positions: new Float32Array([0, 0, 0, -1, 0, 0, 0, -1, 0]) }];
+ collapsing.morph = createMorphPose(1);
+ const collapseAttachment = createSurfaceAttachment(collapsing, bind);
+ collapsing.morph.weights[0] = 1;
+ assert.throws(() => collapseAttachment.update(), /collapses/);
+ assert.ok(collapseAttachment.matrix.every(Number.isFinite));
+ collapsing.morph.weights[0] = 0;
+ assert.deepEqual(collapseAttachment.update(), expected);
+});
+
+test('updates validate only referenced palette entries and selected vertices', () => {
+ const part = target();
+ part.skin = createSkinPose(100);
+ part.geometry.skinIndices = new Uint16Array(12);
+ part.geometry.skinWeights = new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]);
+ const attachment = createSurfaceAttachment(part, bind);
+ part.skin.jointMatrices[99 * 16] = NaN;
+ assert.equal(attachment.update(), attachment.matrix);
+ part.skin.jointMatrices[0] = NaN;
+ assert.throws(() => attachment.update(), /finite/);
+});
+
+test('binding rejects malformed coordinates, work budgets, unsupported tags and deformation contracts', () => {
+ for (const options of [{ triangle: -1 }, { triangle: 1 }, { barycentric: [0, 0, 0] }, { barycentric: [-0.1, 0.5, 0.6] }, { barycentric: [NaN, 0, 1] }, { clearance: -1 }, { rotation: Infinity }, { maxVertices: 2 }, { maxTriangles: 0 }, { unknown: true }]) assert.throws(() => createSurfaceAttachment(target(), { ...bind, ...options }));
+ const nearSum = createSurfaceAttachment(target(), { ...bind, barycentric: [0.2, 0.3, 0.5000005] });
+ assert.ok(nearSum.matrix.every(Number.isFinite));
+ for (const tag of ['water', 'foliage', 'grass', 'fire', 'smoke']) {
+ const part = target();
+ part.material.tag = tag;
+ assert.throws(() => createSurfaceAttachment(part, bind), /procedural/);
+ }
+ const terrain = target();
+ terrain.material.tag = 'terrain';
+ assert.ok(createSurfaceAttachment(terrain, bind));
+ const skinnedTerrain = deformable();
+ skinnedTerrain.material.tag = 'terrain';
+ assert.throws(() => createSurfaceAttachment(skinnedTerrain, bind), /procedural/);
+ const assembly = target();
+ assembly.assembly = {};
+ assert.throws(() => createSurfaceAttachment(assembly, bind), /assembly/);
+ const noPose = target();
+ noPose.geometry.morphTargets = [{ positions: new Float32Array(9) }];
+ assert.throws(() => createSurfaceAttachment(noPose, bind), /pose/);
+ const singular = target();
+ singular.matrix[0] = 0;
+ assert.throws(() => createSurfaceAttachment(singular, bind), /nonsingular/);
+});
+
+test('world clearance must remain outward and nonzero after Float32 rounding', () => {
+ const part = target();
+ assert.throws(() => createSurfaceAttachment(part, { ...bind, clearance: 1e-50 }), /clearance collapses/);
+ part.matrix[14] = 1e6;
+ part.matrix[0] = 100;
+ part.matrix[5] = 100;
+ assert.throws(() => createSurfaceAttachment(part, { ...bind, clearance: 0.001 }), /clearance collapses/);
+ const attachment = createSurfaceAttachment(part, { ...bind, clearance: 1 });
+ assert.equal(attachment.matrix[14], 1e6 + 1);
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 032ebea7..d16d8a13 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -23,6 +23,7 @@ export default defineConfig({
surface: 'src/surface.js',
'mesh-query': 'src/mesh-query.js',
shrinkwrap: 'src/shrinkwrap.js',
+ 'surface-attachment': 'src/surface-attachment.js',
physics: 'src/physics.js',
},
formats: ['es'],