3D engine that AI agents drive
Add bounded shrinkwrap and GPU morph workflow
Nguyen Xuan An644c90c134de
diff --git a/.gitignore b/.gitignoreindex 31603e70..35de688d 100644--- a/.gitignore+++ b/.gitignore@@ -16,6 +16,11 @@ public/sculpt.mdpublic/surface.mdpublic/mesh-query.mdpublic/primitives.md+public/shrinkwrap.md+public/scene-graph.md+public/modeling.md+public/animation-curves.md+public/animation-mixer.mdartifacts/.env.env.*diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6f86d786..6f8099ff 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@## Unreleased+- Add bounded nearest-surface and directional shrinkwrap with counted queries, atomic output and shared normal reconstruction.- Add owned, bounded BVH mesh queries for static surface contact, ray hits and validated closed-solid containment.- Close primitive seams exactly in Float32 and validate detail counts before geometry allocation.- Add retained scene hierarchy, pivots and atomic reparenting with world pose preservation.diff --git a/README.md b/README.mdindex 94f6caed..2b88de0a 100644--- a/README.md+++ b/README.md@@ -177,6 +177,8 @@ The [surface patch addon](docs/surface.md) clips a badge onto a curved mesh withSource-only [mesh queries](docs/mesh-query.md) use owned BVH indices to detect boundary contact, ray hits and containment between validated closed solids.Surface contact does not measure penetration depth or diagnose z-fighting. Queries accept static geometry and explicit affine transforms.The [primitive contract](docs/primitives.md) defines bounded subdivision counts and exact seam closure for mesh validation.+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 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/docs/guide.md b/docs/guide.mdindex 17619ed7..0b79916d 100644--- a/docs/guide.md+++ b/docs/guide.md@@ -274,4 +274,17 @@ Core exports are available from `67js`:`67js/addons/canvas2d`: 2D recipes. `67js/addons/gltf`: optional asset decoding. These are separate imports to keep the core smaller.-67.js currently targets WebGL2. There is no WebGPU backend, general physics engine, mesh editor, skeletal animation or Blender-style authoring UI. Adaptive quality, GPU timing and picking are roadmap work. See the homepage's release files for the installed version and the roadmap for planned behavior.+67.js targets WebGL2. The published `0.3.3` package does not include the newer source APIs below. Check the installed package version and release metadata before using them.++## Current source additions++The current checkout adds authoring and animation APIs through separate modules:++- [Scene hierarchy](scene-graph.md), [procedural modeling](modeling.md), [animation curves](animation-curves.md) and [clip mixing](animation-mixer.md).+- [Skeletal animation](skinning.md), [relative morph targets](morph-targets.md) and [glTF morph animation](gltf-morph.md).+- [Recorded Rapier physics](physics.md), including contacts, joints, limits and bounded motors.+- [Static sculpt brushes](sculpt.md), [curved surface patches](surface.md) and [BVH mesh queries](mesh-query.md).+- [Static shrinkwrap](shrinkwrap.md) through nearest-surface or directional projection, with bounded work and explicit miss handling.+- [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.diff --git a/docs/mesh-query.md b/docs/mesh-query.mdindex 34724d8b..8b049f24 100644--- a/docs/mesh-query.md+++ b/docs/mesh-query.md@@ -143,6 +143,9 @@ A hit returns `{ point, distance, triangle, barycentric }`.Rays test both triangle sides.Ray hits can land on edges, so a single public ray hit does not establish solid containment.+The source index also supplies counted target-local `nearest()` and `project()` helpers.+Read the [shrinkwrap query contract](shrinkwrap.md#target-local-query-helpers) before mixing their coordinates with world-space rays.+## Design choice and referencesTwo designs were considered: explicit owned indices with matrix arguments, and an implicit scene cache borrowing mutable geometry buffers.diff --git a/docs/shrinkwrap.md b/docs/shrinkwrap.mdnew file mode 100644index 00000000..aa867f7e--- /dev/null+++ b/docs/shrinkwrap.md@@ -0,0 +1,179 @@+# Static mesh shrinkwrap++`shrinkwrapGeometry` moves source vertices onto a target triangle surface and returns new static geometry.+It supports nearest-surface queries and projection along one direction.+The output uses target-local coordinates.+Share the target part's matrix when rendering the output beside that target.++```js+import { shrinkwrapGeometry } from '67js/addons/shrinkwrap';++const { geometry, stats } = shrinkwrapGeometry(sourceGeometry, targetGeometry, {+ sourceToTarget: sourceToTargetMatrix,+ mode: 'project',+ direction: [0, 0, -1],+ maxDistance: 2,+ clearance: 0.003,+});++const wrappedPart = {+ geometry,+ matrix: targetPart.matrix,+ material: sourcePart.material,+};+```++## Coordinates and query modes++`sourceToTarget` maps source-local positions into target-local positions before querying.+It defaults to the identity matrix.+Supply 16 finite, Float32-representable components in column-major order.+The matrix must remain affine and nonsingular after Float32 rounding.+Nonuniform scaling and shear are supported when the resulting triangles remain drawable.++`mode: 'nearest'` finds the nearest point on the target's triangles.+`mode: 'project'` finds the first triangle hit along `direction`.+The direction uses target-local coordinates and must remain nonzero.+Projection tests both triangle sides and uses only the positive ray direction.+Each mode measures distance in target-local units.+Under nonuniform target scaling, this distance differs from world-space Euclidean distance.++The target uses its actual polygonal surface, not an analytic sphere or an interpolated smooth surface.+Nearest wrapping onto a coarse convex mesh can pull several source vertices onto the same edge or vertex.+This can collapse triangles even when both input meshes are valid.+Refine the target surface or use directional projection for a suitable footprint.+At a hard crease, a nearest point can belong to several triangles.+Equal-distance queries select the lowest original triangle index among the visited candidates.++## Options and work limits++| Option | Default | Contract |+| --- | --- | --- |+| `mode` | `'nearest'` | `'nearest'` or `'project'` |+| `sourceToTarget` | Identity | Nonsingular affine matrix |+| `direction` | None | Required only for project mode |+| `maxDistance` | Infinity | Nonnegative Float32-representable number or Infinity |+| `clearance` | 0 | Nonnegative finite Float32-representable number |+| `onMiss` | `'error'` | `'error'` or `'keep'` |+| `maxVertices` | 250000 | Integer from 1 through 1000000, applied to both meshes |+| `maxTriangles` | 250000 | Integer from 1 through 1000000, applied to both meshes |+| `maxQueries` | 250000 | Integer from 1 through 1000000 |+| `maxTriangleTests` | 20000000 | Total callback budget from 1 through 100000000 |+| `memoryBudgetMiB` | 64 | Target index allocation estimate, greater than 0 through 1024 |++The implementation builds one target BVH and reuses it for all source vertices.+Exactly coincident source positions form one query group, including UV seams and hard edges.+`maxQueries` bounds those groups.+Each query receives the remaining total triangle budget.+Triangle callbacks count on both hits and misses.+Budget exhaustion throws and releases the target index.++The source vertex and triangle limits also bound the output buffers.+The memory estimate does not cap the whole process or include every temporary JavaScript object.++## Output and misses++The return value is `{ geometry, stats }`.+The geometry contains new Float32 positions and normals, copied Uint32 indices, and copied optional Float32 UVs and RGB colors.+It preserves the original vertex count, triangle topology, and UV/color values.+The source and target buffers remain unchanged, including after an error.+No partially wrapped geometry is published.++`stats` contains `queriedVertices`, `matchedVertices`, `missedVertices`, and `triangleTests`.+The first three fields count unique exact-position groups, not duplicate seam vertices.+With `onMiss: 'error'`, any missing hit throws.+With `onMiss: 'keep'`, missing groups retain their transformed source positions.+Normals are rebuilt for the complete resulting mesh, including transitions between kept and matched vertices.++Normal reconstruction joins matching original position-and-normal groups.+This joins smooth UV seams while preserving authored hard-normal splits.+It uses Double-precision area sums before writing unit Float32 normals.+Unused vertices retain their transformed authored normals.++## Clearance and numerical limits++Clearance offsets each matched vertex along the actual geometric normal of its matched target triangle.+The normal follows the target triangle's index winding.+It does not use interpolated shading normals.+Positive clearance must produce a positive outward face gap after Float32 rounding.+The implementation rejects an offset that collapses or moves only tangent to that face.++The result must retain drawable triangles with a conservative Float32 altitude margin.+The implementation rejects triangles that flip or fold relative to the transformed source.+It also rejects triangles that face away from the aggregate normals of their matched target triangles.+A source reflection can reverse its winding and trigger this check.+Large surface changes can rotate triangles beyond this supported orientation range.++Clearance at separate matched vertices does not prove clearance for the entire connecting triangle.+Long source edges can cross a concave target or bridge a sharp crease.+The operation does not detect every self-intersection or target penetration.+Increase source resolution and inspect the resulting mesh before using it for a close surface overlay.+Use a clipped surface patch when the geometry must follow the target's existing triangles exactly.++The target index normalizes positions for Double-precision queries.+Its triangles must exceed a normalized minimum altitude of `1e-8`.+Each query origin must remain within `1e6` normalized units.+Output positions must remain finite in Float32, and world precision can still collapse a mesh under its eventual render matrix.+The operation does not validate that later matrix or guarantee a constant world-space clearance.++## Static scope and design++Both meshes require indexed Float32 XYZ positions and Uint32 triangles.+The source also requires finite unit Float32 normals.+Optional UV and RGB channels must match its vertex count and contain finite Float32 values.+The operation rejects skin and morph channels.+The caller must also exclude surfaces changed by shader displacement or procedural deformation.++Moving the shared target matrix moves the wrapped geometry rigidly without rebuilding it.+Changing the target's vertex positions requires another shrinkwrap operation.++Two designs were considered: a retained mutable modifier with an implicit target cache, and a static operation returning geometry plus diagnostics.+The static operation makes publication atomic and gives the caller control over rebuilds and resource ownership.+It also keeps animation seeks independent of previous query calls.++The mode distinction follows Blender's documented [Nearest Surface Point and Project shrinkwrap methods](https://docs.blender.org/manual/en/latest/modeling/modifiers/deform/shrinkwrap.html).+This module does not implement Blender's vertex groups, subdivision, snapping modes, culling controls, or animated modifier stack.++## Target-local query helpers++`createMeshQueryIndex` also exposes `nearest(point, options)` and `project(ray)`.+Both return `{ hit, triangleTests }`, so misses preserve work diagnostics.+`hit` is `null` or `{ point, distance, triangle, barycentric, normal }`.+Positions, distances, directions, and geometric normals use the original target-local frame.+`triangle` identifies an original target triangle.+`barycentric` follows that triangle's three original index entries.++Nearest options accept `maxDistance` and `maxTriangleTests`.+Projection accepts `origin`, `direction`, `maxDistance`, and `maxTriangleTests`.++Each helper defaults to 2000000 triangle callbacks.+Their callback budgets accept integers from 1 through 100000000.+An exhausted query throws after its BVH traversal unwinds, so the index remains usable.+The existing world-space `raycast(matrix, ray)` API retains its hit-or-null return contract.++## Animate the result once it is built++Construct shrinkwrap before creating the renderer.+When the source and output share a local coordinate frame and topology, their difference can become a relative GPU morph target.+This avoids rebuilding the BVH and wrapping every vertex on each animation frame.++```js+import { createMorphPose } from '67js';++const wrapped = shrinkwrapGeometry(source, target, { mode: 'project', direction: [0, 0, -1] }).geometry;+const animatedGeometry = {+ ...source,+ morphTargets: [{+ positions: Float32Array.from(source.positions, (value, index) => wrapped.positions[index] - value),+ normals: Float32Array.from(source.normals, (value, index) => wrapped.normals[index] - value),+ }],+};+const morph = createMorphPose(1);+// Assign animatedGeometry and morph to the part before constructing Renderer67.+// Update morph.weights[0] between zero and one before renderer.updateParts(parts).+```++Intermediate shapes need their own collision checks.+Safe endpoints do not prove that an interpolated mesh avoids every obstacle.++These APIs are available in the source build. The published `0.3.3` npm package does not include them.diff --git a/docs/surface.md b/docs/surface.mdindex 396e6a86..f8134694 100644--- a/docs/surface.md+++ b/docs/surface.md@@ -66,4 +66,8 @@ Skin, morph, assembly and procedural target materials reject explicitly. Their vAntialiasing, material colors and shadow bias do not repair mesh penetration. This patch is a surface overlay, not a whole-object shrinkwrap modifier.+The source [shrinkwrap addon](shrinkwrap.md) moves existing mesh vertices while retaining topology and UVs.+Use [mesh queries](mesh-query.md) to check actual triangle contact or validated solid containment.+Neither tool automatically resolves collisions or binds to an animated skin.+The implementation follows the maintained [Three.js decal API](https://threejs.org/docs/pages/DecalGeometry.html). The distinction between render depth bias and geometry placement also appears in [Three.js material documentation](https://threejs.org/docs/pages/Material.html).diff --git a/package.json b/package.jsonindex d62d0500..827d6c9f 100644--- a/package.json+++ b/package.json@@ -39,7 +39,8 @@"docs/sculpt.md","docs/surface.md","docs/mesh-query.md",- "docs/primitives.md"+ "docs/primitives.md",+ "docs/shrinkwrap.md"],"main": "./build/67.module.js","module": "./build/67.module.js",@@ -55,6 +56,7 @@"./addons/sculpt": "./build/sculpt.js","./addons/surface": "./build/surface.js","./addons/mesh-query": "./build/mesh-query.js",+ "./addons/shrinkwrap": "./build/shrinkwrap.js","./addons/physics": "./build/physics.js","./package.json": "./package.json"},diff --git a/public/llms.txt b/public/llms.txtindex 14e228ea..52256f2e 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -95,6 +95,11 @@ Surface contact does not prove volume penetration or identify z-fighting. NeverPass current affine matrices explicitly, rebuild after geometry edits, and preserve budget/precision errors instead of treating them as misses.Read `docs/primitives.md` for subdivision bounds and exact seam closure. Skin, morph and shader-deformed surfaces require geometry matching the visible pose.+Source-only `addons/shrinkwrap` returns {geometry,stats} in target-local coordinates. Read `docs/shrinkwrap.md` before choosing nearest/project modes.+Supply sourceToTarget explicitly for different local frames. Share the target matrix with the output part and keep the total callback budget.+Nearest projection can collapse vertices on coarse meshes; preserve the error and refine the target or choose a suitable projection direction.+Vertex clearance does not certify whole-triangle clearance. Compatible static output can become a GPU morph target without repeating queries per frame.+GLB support excludes transparent and double-sided materials and compressed geometry. Unsupported features require visible errors.The optional GLB decoder uses Three.js GLTFLoader. The renderer remains 67.js.diff --git a/scripts/benchmark-mesh-query.mjs b/scripts/benchmark-mesh-query.mjsnew file mode 100644index 00000000..0ccec4b9--- /dev/null+++ b/scripts/benchmark-mesh-query.mjs@@ -0,0 +1,74 @@+import assert from 'node:assert/strict';+import { mkdir, writeFile } from 'node:fs/promises';+import { constants, setPriority } from 'node:os';+import { Triangle, Vector3 } from 'three';+import { sphere } from '../src/geometry.js';+import { createMeshQueryIndex } from '../src/mesh-query.js';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const segments = Number(process.argv[2] ?? 32);+const rings = Number(process.argv[3] ?? 20);+const geometry = sphere(segments, rings);+const queries = Array.from({ length: 96 }, (_, index) => {+ const elevation = (index / 95 - 0.5) * Math.PI * 0.8;+ const longitude = index * 2.399963229728653;+ const radius = 0.5 + (index % 4) * 0.6;+ return Array.from(new Float32Array([+ Math.cos(longitude) * Math.cos(elevation) * radius,+ Math.sin(elevation) * radius,+ Math.sin(longitude) * Math.cos(elevation) * radius,+ ]));+});+const triangles = [];+for (let offset = 0; offset < geometry.indices.length; offset += 3) {+ triangles.push(new Triangle(...Array.from(geometry.indices.subarray(offset, offset + 3), index =>+ new Vector3().fromArray(geometry.positions, index * 3))));+}+const referenceStarted = performance.now();+const reference = queries.map(point => {+ const origin = new Vector3(...point);+ const candidate = new Vector3();+ const closest = new Vector3();+ let distanceSquared = Infinity;+ for (const triangle of triangles) {+ triangle.closestPointToPoint(origin, candidate);+ const distance = candidate.distanceToSquared(origin);+ if (distance < distanceSquared) {+ distanceSquared = distance;+ closest.copy(candidate);+ }+ }+ return { point: closest.toArray(), distance: Math.sqrt(distanceSquared) };+});+const referenceMilliseconds = performance.now() - referenceStarted;+const buildStarted = performance.now();+const index = createMeshQueryIndex(geometry);+const buildMilliseconds = performance.now() - buildStarted;+const queryStarted = performance.now();+const accelerated = queries.map(point => index.nearest(point, { maxTriangleTests: 10000 }));+const queryMilliseconds = performance.now() - queryStarted;+let maximumPointError = 0;+let maximumDistanceError = 0;+for (let offset = 0; offset < reference.length; offset++) {+ const expected = reference[offset];+ const actual = accelerated[offset].hit;+ assert.ok(actual);+ maximumPointError = Math.max(maximumPointError, Math.hypot(...actual.point.map((value, axis) => value - expected.point[axis])));+ maximumDistanceError = Math.max(maximumDistanceError, Math.abs(actual.distance - expected.distance));+}+const triangleTests = accelerated.reduce((total, result) => total + result.triangleTests, 0);+const exhaustiveTriangleTests = queries.length * triangles.length;+const report = {+ fixture: `96 deterministic local-space nearest queries against sphere(${segments},${rings})`,+ vertexCount: index.info.vertexCount, triangleCount: index.info.triangleCount,+ queryCount: queries.length, buildMilliseconds, queryMilliseconds, referenceMilliseconds,+ triangleTests, exhaustiveTriangleTests, maximumPointError, maximumDistanceError,+ estimatedIndexBytes: index.info.estimatedBytes,+};+index.dispose();+assert.ok(maximumPointError < 1e-6);+assert.ok(maximumDistanceError < 1e-6);+assert.ok(triangleTests < exhaustiveTriangleTests);+await mkdir('artifacts', { recursive: true });+await writeFile(`artifacts/mesh-query-nearest-benchmark-${segments}x${rings}.json`, JSON.stringify(report, null, 2));+console.log(JSON.stringify(report, null, 2));diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjsindex 95b84054..bb129921 100644--- a/scripts/prepare-release.mjs+++ b/scripts/prepare-release.mjs@@ -35,7 +35,12 @@ await copyFile(resolve(root, 'build-browser/67.module.js'), resolve(releases, meawait copyFile(resolve(root, 'CHANGELOG.md'), resolve(root, 'public/changelog.md'));await copyFile(resolve(root, 'docs/guide.md'), resolve(root, 'public/guide.md'));await copyFile(resolve(root, 'docs/gltf.md'), resolve(root, 'public/gltf.md'));-for (const name of ['gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md', 'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md']) {+const sourceDocuments = [+ 'scene-graph.md', 'modeling.md', 'animation-curves.md', 'animation-mixer.md',+ 'gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md',+ 'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md', 'shrinkwrap.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.mjsindex 271d39ab..3d14fd0e 100644--- a/scripts/smoke-package.mjs+++ b/scripts/smoke-package.mjs@@ -40,6 +40,7 @@ import { parseGltf } from '67js/addons/gltf';import { sculptGeometry } from '67js/addons/sculpt';import { createSurfacePatch } from '67js/addons/surface';import { createMeshQueryIndex, createMeshPairQuery } from '67js/addons/mesh-query';+import { shrinkwrapGeometry } from '67js/addons/shrinkwrap';import { createPhysicsScene, planPhysicsScene } from '67js/addons/physics';assert.equal(VERSION, '${metadata.version}');assert.equal(typeof Renderer67, 'function');@@ -87,6 +88,16 @@ queryMatrix[12] = 4;assert.equal(solidQuery.evaluate(outerMatrix, queryMatrix).kind, 'separate');const queryHit = solidIndex.raycast(outerMatrix, { origin: [0.2, 0.3, 6], direction: [0, 0, -1] });assert.ok(Math.abs(queryHit.distance - 4) < 1e-6);+const nearestHit = solidIndex.nearest([0.1, 0.1, 1]);+assert.ok(Math.abs(nearestHit.hit.distance - 0.5) < 1e-6);+assert.ok(nearestHit.triangleTests > 0);+const projectedHit = solidIndex.project({ origin: [0.1, 0.1, 1], direction: [0, 0, -1] });+assert.ok(Math.abs(projectedHit.hit.point[2] - 0.5) < 1e-6);+const wrappedPatch = shrinkwrapGeometry(packedPatch, queryGeometry, { clearance: 0.002, maxDistance: 1 });+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));solidIndex.dispose();const parts = createModel();assert.equal(parts.length, 574);diff --git a/scripts/smoke-shrinkwrap.mjs b/scripts/smoke-shrinkwrap.mjsnew file mode 100644index 00000000..5d26189e--- /dev/null+++ b/scripts/smoke-shrinkwrap.mjs@@ -0,0 +1,159 @@+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('**/shrinkwrap-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/shrinkwrap-smoke.html');+ const report = await page.evaluate(async () => {+ const { Renderer67, sphere, fitPerspectiveDistance, createMorphPose } = await import('/build/67.module.js');+ const { shrinkwrapGeometry } = await import('/build/shrinkwrap.js');+ const { createMeshQueryIndex, createMeshPairQuery } = await import('/build/mesh-query.js');+ const positions = [];+ const normals = [];+ const uvs = [];+ const indices = [];+ const columns = 48;+ const rows = 32;+ for (let row = 0; row <= rows; row++) {+ for (let column = 0; column <= columns; column++) {+ positions.push((column / columns - 0.5) * 1.4, (row / rows - 0.5) * 0.9, 1.4);+ normals.push(0, 0, 1);+ uvs.push(column / columns, row / rows);+ }+ }+ for (let row = 0; row < rows; row++) {+ for (let column = 0; column < columns; column++) {+ const first = row * (columns + 1) + column;+ indices.push(first, first + 1, first + columns + 2, first, first + columns + 2, first + columns + 1);+ }+ }+ const source = { positions: new Float32Array(positions), normals: new Float32Array(normals), uvs: new Float32Array(uvs), indices: new Uint32Array(indices) };+ const target = sphere(128, 80);+ const queryMatrix = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);+ const targetIndex = createMeshQueryIndex(target);+ const sourceBefore = source.positions.slice();+ const cases = [{ name: 'before', geometry: source, stats: null }];+ for (const mode of ['nearest', 'project']) {+ const started = performance.now();+ const result = shrinkwrapGeometry(source, target, { mode, ...(mode === 'project' ? { direction: [0, 0, -1] } : {}), clearance: 0.003, maxDistance: 2 });+ const milliseconds = performance.now() - started;+ const wrappedIndex = createMeshQueryIndex(result.geometry);+ const surfaceRelation = createMeshPairQuery(targetIndex, wrappedIndex).evaluate(queryMatrix, queryMatrix);+ wrappedIndex.dispose();+ cases.push({ name: mode, ...result, milliseconds, surfaceRelation });+ }+ targetIndex.dispose();+ const projected = cases.find(entry => entry.name === 'project').geometry;+ const morph = createMorphPose(1);+ morph.weights[0] = 1;+ cases.push({ name: 'project-morph', stats: null, morph, geometry: {+ ...source,+ morphTargets: [{+ positions: Float32Array.from(source.positions, (value, index) => projected.positions[index] - value),+ normals: Float32Array.from(source.normals, (value, index) => projected.normals[index] - value),+ }],+ } });+ const canvas = document.querySelector('canvas');+ const camera = { eye: [2.6, 0.6, 3.8], target: [0, 0, 0.25], fov: 35 };+ const fitted = fitPerspectiveDistance({ minimum: [-1.2, -1.2, -1.2], maximum: [1.2, 1.2, 1.5] }, camera, canvas.clientWidth / canvas.clientHeight);+ const distance = Math.hypot(...camera.eye.map((value, axis) => value - camera.target[axis]));+ camera.eye = camera.eye.map((value, axis) => camera.target[axis] + (value - camera.target[axis]) * fitted / distance);+ const results = [];+ let projectedPixels;+ let gpu;+ for (const entry of cases) {+ const matrix = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);+ const parts = [+ { name: 'Target', geometry: target, matrix, material: { color: [0.015, 0.22, 0.34], metallic: 0.3, roughness: 0.3, emission: 0 }, castShadow: false },+ { name: 'Wrap', geometry: entry.geometry, matrix, ...(entry.morph ? { morph: entry.morph } : {}),+ material: { color: [1, 0.18, 0.01], metallic: 0.05, roughness: 0.45, emission: 0 }, castShadow: false },+ ];+ const renderer = new Renderer67(canvas, parts, {+ world: true, ground: false, samples: 2, pixelRatio: 1, hdr: true, memoryBudgetMiB: 96,+ environment: { keyIntensity: 0.8, fillIntensity: 0.5, ambientIntensity: 0.4 },+ });+ function draw(time, morphWeight = time === 2 ? 0 : 1) {+ if (entry.morph) entry.morph.weights[0] = morphWeight;+ const angle = Math.sin(time) * 0.2;+ matrix[0] = Math.cos(angle);+ matrix[2] = -Math.sin(angle);+ matrix[8] = Math.sin(angle);+ matrix[10] = Math.cos(angle);+ renderer.updateParts(parts);+ renderer.render({ ...camera, time: 0, effects: { grain: 0, bloom: { strength: 0 } } });+ const context = renderer.context;+ const pixels = new Uint8Array(canvas.width * canvas.height * 4);+ context.readPixels(0, 0, canvas.width, canvas.height, context.RGBA, context.UNSIGNED_BYTE, pixels);+ return { pixels, image: canvas.toDataURL('image/png'), glError: context.getError() };+ }+ const original = draw(0.4);+ const rendererInfo = renderer.context.getExtension('WEBGL_debug_renderer_info');+ gpu = rendererInfo ? renderer.context.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL) : 'unavailable';+ if (entry.name === 'project') projectedPixels = original.pixels;+ let control;+ let morphChangedChannels;+ let morphEndpointDifference;+ if (entry.morph) {+ control = draw(0.4, 0);+ morphChangedChannels = original.pixels.reduce((total, value, index) => total + Number(value !== control.pixels[index]), 0);+ morphEndpointDifference = original.pixels.reduce((maximum, value, index) => Math.max(maximum, Math.abs(value - projectedPixels[index])), 0);+ }+ draw(2);+ const reverse = draw(0.4);+ let orangePixels = 0;+ for (let offset = 0; offset < original.pixels.length; offset += 4) {+ if (original.pixels[offset] > 80 && original.pixels[offset] > original.pixels[offset + 2] * 1.5) orangePixels++;+ }+ results.push({ name: entry.name, image: original.image, stats: entry.stats, milliseconds: entry.milliseconds,+ surfaceRelation: entry.surfaceRelation,+ replayExact: original.pixels.every((value, index) => value === reverse.pixels[index]),+ retainedMatrix: parts.every(part => part.matrix === matrix), glError: original.glError, reverseGlError: reverse.glError,+ retainedMorph: !entry.morph || parts[1].morph === entry.morph,+ controlImage: control?.image, morphChangedChannels, morphEndpointDifference,+ orangePixels, memory: renderer.memoryPlan });+ renderer.dispose();+ }+ return { vertices: source.positions.length / 3, triangles: source.indices.length / 3,+ targetVertices: target.positions.length / 3, targetTriangles: target.indices.length / 3,+ sourceUnchanged: source.positions.every((value, index) => value === sourceBefore[index]), gpu, results };+ });+ for (const result of report.results) {+ await writeFile(`artifacts/shrinkwrap-${result.name}-${width}x${height}.png`, Buffer.from(result.image.split(',')[1], 'base64'));+ delete result.image;+ if (result.controlImage) {+ await writeFile(`artifacts/shrinkwrap-${result.name}-start-${width}x${height}.png`, Buffer.from(result.controlImage.split(',')[1], 'base64'));+ delete result.controlImage;+ assert.ok(result.morphChangedChannels > 100);+ assert.ok(result.morphEndpointDifference <= 6);+ }+ assert.equal(result.glError, 0);+ assert.equal(result.reverseGlError, 0);+ assert.equal(result.replayExact, true);+ assert.equal(result.retainedMatrix, true);+ assert.equal(result.retainedMorph, true);+ assert.ok(result.orangePixels > 100);+ if (result.stats) assert.equal(result.stats.missedVertices, 0);+ if (result.surfaceRelation) assert.equal(result.surfaceRelation.kind, 'surface-disjoint');+ }+ await writeFile(`artifacts/shrinkwrap-${width}x${height}.json`, JSON.stringify(report, null, 2));+ console.log(JSON.stringify(report, null, 2));+ assert.equal(report.sourceUnchanged, true);+ assert.deepEqual(errors, []);+} finally {+ await browser.close();+}diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex 767ab49d..e459f0b0 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -27,6 +27,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.- Static brush sculpting uses optional `src/sculpt.js` and the checkout's `docs/sculpt.md`.- 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`.- 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.mdindex beae5306..c49de189 100644--- a/skills/build-67js-scene/references/scene-contract.md+++ b/skills/build-67js-scene/references/scene-contract.md@@ -120,6 +120,12 @@ Pass current affine matrices to `createMeshPairQuery(...).evaluate()`; rebuild iClosed-solid containment requires two `solid: true` indices. Surface contact does not prove volume penetration or z-fighting.Use `docs/primitives.md` for exact seam closure and preallocation bounds. Preserve indeterminate and budget errors rather than reporting a miss.+Static `shrinkwrapGeometry(source, target, options)` returns new target-local geometry and query statistics.+Read `docs/shrinkwrap.md` for nearest/project modes, total query budgets and explicit miss handling.+Share the target matrix with the wrapped part. Local distances are not world distances under nonuniform target scale.+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.+`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/geometry-normals.js b/src/geometry-normals.jsnew file mode 100644index 00000000..87ef805e--- /dev/null+++ b/src/geometry-normals.js@@ -0,0 +1,49 @@+export function recomputeNormals(source, positions, fallbackNormals = source.normals) {+ const groups = new Map();+ const vertexGroups = new Array(positions.length / 3);+ const normals = new Float32Array(positions.length);+ for (let vertex = 0; vertex < positions.length / 3; vertex++) {+ const offset = vertex * 3;+ // Preserve authored hard edges while joining identical UV seam vertices.+ const key = `${source.positions.subarray(offset, offset + 3).join(',')}:${source.normals.subarray(offset, offset + 3).join(',')}`;+ let group = groups.get(key);+ if (!group) {+ group = { vertices: [], normal: [0, 0, 0], referenced: false };+ groups.set(key, group);+ }+ group.vertices.push(vertex);+ vertexGroups[vertex] = group;+ }+ for (let offset = 0; offset < source.indices.length; offset += 3) {+ const first = source.indices[offset] * 3;+ const second = source.indices[offset + 1] * 3;+ const third = source.indices[offset + 2] * 3;+ const edgeFirst = [0, 1, 2].map(axis => positions[second + axis] - positions[first + axis]);+ const edgeSecond = [0, 1, 2].map(axis => positions[third + axis] - positions[first + axis]);+ // Number accumulators avoid Float32 cross-product overflow/underflow on valid small/large meshes.+ const normal = [+ edgeFirst[1] * edgeSecond[2] - edgeFirst[2] * edgeSecond[1],+ edgeFirst[2] * edgeSecond[0] - edgeFirst[0] * edgeSecond[2],+ edgeFirst[0] * edgeSecond[1] - edgeFirst[1] * edgeSecond[0],+ ];+ if (Math.hypot(...normal) === 0) continue;+ for (let corner = 0; corner < 3; corner++) {+ const group = vertexGroups[source.indices[offset + corner]];+ group.referenced = true;+ for (let axis = 0; axis < 3; axis++) group.normal[axis] += normal[axis];+ }+ }+ for (const group of groups.values()) {+ const length = Math.hypot(...group.normal);+ if (group.referenced && (!Number.isFinite(length) || length === 0)) {+ throw new RangeError('Sculpt normals cancel at a referenced vertex. Reduce the stroke or repair topology.');+ }+ for (const vertex of group.vertices) {+ const offset = vertex * 3;+ for (let axis = 0; axis < 3; axis++) {+ normals[offset + axis] = group.referenced ? group.normal[axis] / length : fallbackNormals[offset + axis];+ }+ }+ }+ return normals;+}diff --git a/src/mesh-query.js b/src/mesh-query.jsindex 12368ccb..b31b2442 100644--- a/src/mesh-query.js+++ b/src/mesh-query.js@@ -5,6 +5,8 @@ const records = new WeakMap();const EPSILON = 1e-9;const INDEX_OPTIONS = new Set(['maxTriangles', 'maxVertices', 'memoryBudgetMiB', 'solid', 'maxValidationPairs']);const PAIR_OPTIONS = new Set(['mode', 'maxTriangleTests']);+const NEAREST_OPTIONS = new Set(['maxDistance', 'maxTriangleTests']);+const PROJECT_OPTIONS = new Set(['origin', 'direction', 'maxDistance', 'maxTriangleTests']);const DIRECTIONS = [[0, 0, 1], [1, 0.41421356237, 0.73205080757], [0.61803398875, 1, 0.27182818285], [0.17320508075, 0.44721359550, 1], [-1, 0.31622776602, 0.14142135624], [0.22360679775, -1, 0.70710678118]];function optionsObject(options, fields) {@@ -290,6 +292,84 @@ function containment(record, point, counter) {throw new RangeError('Solid containment is indeterminate after bounded ray retries.');}+function localVector(input, name) {+ if ((!Array.isArray(input) && !ArrayBuffer.isView(input)) || input.length !== 3 ||+ !Array.from(input).every(value => typeof value === 'number' && Number.isFinite(value) && Number.isFinite(Math.fround(value)))) {+ throw new TypeError(`${name} requires three finite Float32-representable components.`);+ }+ return new Vector3(...input);+}++function queryLocalSurface(record, pointInput, directionInput, options) {+ const originalPoint = localVector(pointInput, 'Query point');+ const point = originalPoint.clone().sub(record.center).multiplyScalar(1 / record.scale);+ if (Math.max(...point.toArray().map(Math.abs)) > 1e6) throw new RangeError('Query point exceeds the normalized precision domain.');+ const maximum = options.maxDistance ?? Infinity;+ if ((maximum !== Infinity && (!Number.isFinite(maximum) || !Number.isFinite(Math.fround(maximum)))) || maximum < 0) {+ throw new RangeError('maxDistance must be nonnegative and Float32-representable, or Infinity.');+ }+ const counter = budget(integer(options.maxTriangleTests ?? 2_000_000, 100_000_000, 'maxTriangleTests'), 'maxTriangleTests');+ let ray;+ if (directionInput !== undefined) {+ const direction = localVector(directionInput, 'Projection direction');+ if (direction.length() === 0) throw new RangeError('Projection direction must be nonzero.');+ ray = new Ray(point, direction.normalize());+ }+ let bestDistance = maximum / record.scale;+ let bestLocalDistance = maximum;+ let bestTriangle = Infinity;+ let bestPoint;+ let bestNormal;+ let bestWeights;+ let failure;+ const candidate = new Vector3();+ const candidateLocal = new Vector3();+ const boundsPoint = new Vector3();+ record.bvh.shapecast({+ boundsTraverseOrder(bounds) {+ if (!ray) return bounds.clampPoint(point, boundsPoint).distanceTo(point);+ // Ray.intersectBox returns the exit when the origin is inside. The lower bound is zero there.+ if (bounds.containsPoint(point)) return 0;+ return ray.intersectBox(bounds, boundsPoint) ? boundsPoint.distanceTo(point) : Infinity;+ },+ intersectsBounds: (bounds, leaf, score) => Number.isFinite(score) && score <= bestDistance + EPSILON,+ intersectsTriangle(triangle, triangleIndex) {+ try {+ counter.charge();+ if (ray) {+ if (!ray.intersectTriangle(triangle.a, triangle.b, triangle.c, false, candidate)) return false;+ } else {+ triangle.closestPointToPoint(point, candidate);+ }+ const distance = candidate.distanceTo(point);+ if (!Number.isFinite(distance)) throw new RangeError('Surface query exceeds the numerical precision domain.');+ candidateLocal.copy(candidate).multiplyScalar(record.scale).add(record.center);+ const localDistance = candidateLocal.distanceTo(originalPoint);+ // Apply the caller's cutoff in its original frame, avoiding normalized subtraction at exact endpoints.+ if (localDistance > bestLocalDistance || (localDistance === bestLocalDistance && triangleIndex >= bestTriangle)) return false;+ const weights = triangle.getBarycoord(candidate, new Vector3());+ const normal = triangle.getNormal(new Vector3());+ if (!weights || !weights.toArray().every(Number.isFinite) || normal.length() === 0) throw new RangeError('Surface query has invalid triangle coordinates.');+ bestDistance = distance;+ bestLocalDistance = localDistance;+ bestTriangle = triangleIndex;+ bestPoint = candidateLocal.clone();+ bestWeights = weights;+ bestNormal = normal;+ return false;+ } catch (error) {+ failure = error;+ return true;+ }+ },+ });+ if (failure) throw failure;+ if (!bestPoint) return { hit: null, triangleTests: counter.tests };+ const distance = bestLocalDistance;+ if (!Number.isFinite(distance) || !bestPoint.toArray().every(value => Number.isFinite(Math.fround(value)))) throw new RangeError('Surface query hit exceeds finite Float32 coordinates.');+ return { hit: { point: bestPoint.toArray(), distance, triangle: bestTriangle, barycentric: bestWeights.toArray(), normal: bestNormal.toArray() }, triangleTests: counter.tests };+}+/** Copies static geometry into a private normalized BVH. Returned handles expose no Three.js objects. */export function createMeshQueryIndex(geometry, options = {}) {optionsObject(options, INDEX_OPTIONS);@@ -321,6 +401,15 @@ export function createMeshQueryIndex(geometry, options = {}) {solid,memoryPlan,info: Object.freeze({ vertexCount: metadata.vertexCount, triangleCount: metadata.triangleCount, estimatedBytes: reservedBytes }),+ nearest(point, options = {}) {+ optionsObject(options, NEAREST_OPTIONS);+ return queryLocalSurface(live(handle), point, undefined, options);+ },+ project(ray) {+ optionsObject(ray, PROJECT_OPTIONS);+ if (ray.direction === undefined) throw new TypeError('Projection requires direction.');+ return queryLocalSurface(live(handle), ray.origin, ray.direction, ray);+ },raycast(matrix, ray) {const current = live(handle);const state = matrixState(current, matrix);diff --git a/src/sculpt.js b/src/sculpt.jsindex 33c2cbc2..85ed7ea9 100644--- a/src/sculpt.js+++ b/src/sculpt.js@@ -1,3 +1,5 @@+import { recomputeNormals } from './geometry-normals.js';+function finite(value, name) {if (!Number.isFinite(value) || !Number.isFinite(Math.fround(value))) {throw new TypeError(`${name} must be a finite Float32 value.`);@@ -141,56 +143,6 @@ function applyStroke(groups, stroke) {}}-function recomputeNormals(source, positions) {- const groups = new Map();- const vertexGroups = new Array(positions.length / 3);- const normals = new Float32Array(positions.length);- for (let vertex = 0; vertex < positions.length / 3; vertex++) {- const offset = vertex * 3;- // Preserve authored hard edges while joining identical UV seam vertices.- const key = `${source.positions.subarray(offset, offset + 3).join(',')}:${source.normals.subarray(offset, offset + 3).join(',')}`;- let group = groups.get(key);- if (!group) {- group = { vertices: [], normal: [0, 0, 0], referenced: false };- groups.set(key, group);- }- group.vertices.push(vertex);- vertexGroups[vertex] = group;- }- for (let offset = 0; offset < source.indices.length; offset += 3) {- const first = source.indices[offset] * 3;- const second = source.indices[offset + 1] * 3;- const third = source.indices[offset + 2] * 3;- const edgeFirst = [0, 1, 2].map(axis => positions[second + axis] - positions[first + axis]);- const edgeSecond = [0, 1, 2].map(axis => positions[third + axis] - positions[first + axis]);- // Number accumulators avoid Float32 cross-product overflow/underflow on valid small/large meshes.- const normal = [- edgeFirst[1] * edgeSecond[2] - edgeFirst[2] * edgeSecond[1],- edgeFirst[2] * edgeSecond[0] - edgeFirst[0] * edgeSecond[2],- edgeFirst[0] * edgeSecond[1] - edgeFirst[1] * edgeSecond[0],- ];- if (Math.hypot(...normal) === 0) continue;- for (let corner = 0; corner < 3; corner++) {- const group = vertexGroups[source.indices[offset + corner]];- group.referenced = true;- for (let axis = 0; axis < 3; axis++) group.normal[axis] += normal[axis];- }- }- for (const group of groups.values()) {- const length = Math.hypot(...group.normal);- if (group.referenced && (!Number.isFinite(length) || length === 0)) {- throw new RangeError('Sculpt normals cancel at a referenced vertex. Reduce the stroke or repair topology.');- }- for (const vertex of group.vertices) {- const offset = vertex * 3;- for (let axis = 0; axis < 3; axis++) {- normals[offset + axis] = group.referenced ? group.normal[axis] / length : source.normals[offset + axis];- }- }- }- return normals;-}-function triangleArea(positions, indices, offset) {const first = indices[offset] * 3;const second = indices[offset + 1] * 3;diff --git a/src/shrinkwrap.js b/src/shrinkwrap.jsnew file mode 100644index 00000000..f7ed94f2--- /dev/null+++ b/src/shrinkwrap.js@@ -0,0 +1,170 @@+import { Matrix3, Matrix4, Vector3 } from 'three';+import { createMeshQueryIndex } from './mesh-query.js';+import { recomputeNormals } from './geometry-normals.js';++const OPTIONS = new Set(['sourceToTarget', 'mode', 'direction', 'maxDistance', 'clearance', 'onMiss', 'maxVertices', 'maxTriangles', 'maxQueries', 'maxTriangleTests', 'memoryBudgetMiB']);++function finite(value, label) {+ if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isFinite(Math.fround(value))) throw new TypeError(`${label} must remain finite in Float32.`);+ return value;+}++function limit(value, maximum, label) {+ if (!Number.isSafeInteger(value) || value < 1 || value > maximum) throw new RangeError(`${label} must be an integer from 1 through ${maximum}.`);+ return value;+}++function transform(input) {+ if (input === undefined) return new Matrix4();+ if ((!Array.isArray(input) && !ArrayBuffer.isView(input)) || input.length !== 16) throw new TypeError('sourceToTarget requires 16 affine components.');+ const components = Array.from(input, value => Math.fround(finite(value, 'sourceToTarget')));+ if (components[3] !== 0 || components[7] !== 0 || components[11] !== 0 || components[15] !== 1) throw new RangeError('sourceToTarget must be affine.');+ const matrix = new Matrix4().fromArray(components);+ if (!Number.isFinite(matrix.determinant()) || matrix.determinant() === 0) throw new RangeError('sourceToTarget must remain nonsingular.');+ return matrix;+}++function faceNormal(positions, indices, offset) {+ const first = indices[offset] * 3;+ const second = indices[offset + 1] * 3;+ const third = indices[offset + 2] * 3;+ const edgeFirst = new Vector3(positions[second] - positions[first], positions[second + 1] - positions[first + 1], positions[second + 2] - positions[first + 2]);+ const edgeSecond = new Vector3(positions[third] - positions[first], positions[third + 1] - positions[first + 1], positions[third + 2] - positions[first + 2]);+ const normal = new Vector3().crossVectors(edgeFirst, edgeSecond);+ const longest = Math.max(edgeFirst.length(), edgeSecond.length(), edgeFirst.clone().sub(edgeSecond).length());+ return { normal, altitude: normal.length() / longest };+}++function validateSource(source, maxVertices, maxTriangles) {+ const { positions, normals, indices } = source ?? {};+ if (!(positions instanceof Float32Array) || positions.length < 9 || positions.length % 3 ||+ !(normals instanceof Float32Array) || normals.length !== positions.length ||+ !(indices instanceof Uint32Array) || !indices.length || indices.length % 3) throw new TypeError('Shrinkwrap requires Float32 positions and normals with Uint32 triangles.');+ if (source.skinIndices !== undefined || source.skinWeights !== undefined || source.morphTargets !== undefined) throw new TypeError('Shrinkwrap requires static geometry without skin or morph channels.');+ const count = positions.length / 3;+ if (count > maxVertices || indices.length / 3 > maxTriangles) throw new RangeError('Source exceeds maxVertices or maxTriangles.');+ for (const value of positions) finite(value, 'Source 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 TypeError('Source normals must be finite unit vectors.');+ }+ for (const index of indices) if (index >= count) throw new RangeError('Source index exceeds the vertex count.');+ for (const [channel, size] of [['uvs', 2], ['colors', 3]]) {+ if (source[channel] !== undefined && (!(source[channel] instanceof Float32Array) || source[channel].length !== count * size || !source[channel].every(Number.isFinite))) {+ throw new TypeError(`Source ${channel} must contain finite Float32 values matching the vertex count.`);+ }+ }+ for (let offset = 0; offset < indices.length; offset += 3) {+ if (!(faceNormal(positions, indices, offset).altitude > 0)) throw new RangeError('Source contains a degenerate triangle.');+ }+ return count;+}++function validateTriangles(before, after, indices, hitNormals) {+ for (let offset = 0; offset < indices.length; offset += 3) {+ const original = faceNormal(before, indices, offset);+ const output = faceNormal(after, indices, offset);+ const maximum = Math.max(...Array.from(indices.subarray(offset, offset + 3)).flatMap(vertex => Array.from(after.subarray(vertex * 3, vertex * 3 + 3), Math.abs)));+ if (!Number.isFinite(output.altitude) || output.altitude <= maximum * 2 ** -21 + 2 ** -149) throw new RangeError('Shrinkwrap collapses a triangle within Float32 precision. Reduce projection or clearance.');+ if (output.normal.dot(original.normal) <= 0) throw new RangeError('Shrinkwrap flips or folds a triangle relative to the transformed source.');+ const targetNormal = new Vector3();+ let allMatched = true;+ for (let corner = 0; corner < 3; corner++) {+ const vertex = indices[offset + corner];+ if (!hitNormals[vertex]) allMatched = false;+ else targetNormal.add(hitNormals[vertex]);+ }+ // A closest point at a hard crease can select a perpendicular neighboring face.+ if (allMatched && output.normal.dot(targetNormal) < 0) throw new RangeError('Shrinkwrap triangle faces away from its matched target surface.');+ }+}++/** Construct a new static target-local mesh using one disposable target BVH. */+export function shrinkwrapGeometry(source, target, options = {}) {+ if (!options || typeof options !== 'object' || Array.isArray(options)) throw new TypeError('Shrinkwrap options require an object.');+ for (const field of Object.keys(options)) if (!OPTIONS.has(field)) throw new TypeError(`Unsupported shrinkwrap option ${field}.`);+ const maxVertices = limit(options.maxVertices ?? 250_000, 1_000_000, 'maxVertices');+ const maxTriangles = limit(options.maxTriangles ?? 250_000, 1_000_000, 'maxTriangles');+ const maxQueries = limit(options.maxQueries ?? 250_000, 1_000_000, 'maxQueries');+ const maxTriangleTests = limit(options.maxTriangleTests ?? 20_000_000, 100_000_000, 'maxTriangleTests');+ const count = validateSource(source, maxVertices, maxTriangles);+ const matrix = transform(options.sourceToTarget);+ const normalMatrix = new Matrix3().getNormalMatrix(matrix);+ if (!normalMatrix.elements.every(Number.isFinite)) throw new RangeError('sourceToTarget normal transform exceeds the precision domain.');+ const mode = options.mode ?? 'nearest';+ if (mode !== 'nearest' && mode !== 'project') throw new RangeError('Shrinkwrap mode must be nearest or project.');+ let direction;+ if (mode === 'project') {+ if ((!Array.isArray(options.direction) && !ArrayBuffer.isView(options.direction)) || options.direction.length !== 3) throw new TypeError('Project mode requires a target-local direction.');+ direction = Array.from(options.direction, value => finite(value, 'direction'));+ if (Math.hypot(...direction) === 0) throw new RangeError('Projection direction must be nonzero.');+ } else if (options.direction !== undefined) throw new TypeError('direction applies only to project mode.');+ const maxDistance = options.maxDistance ?? Infinity;+ if (maxDistance !== Infinity) finite(maxDistance, 'maxDistance');+ if (maxDistance < 0) throw new RangeError('maxDistance must be nonnegative.');+ const clearance = finite(options.clearance ?? 0, 'clearance');+ if (clearance < 0) throw new RangeError('clearance must be nonnegative.');+ const onMiss = options.onMiss ?? 'error';+ if (onMiss !== 'error' && onMiss !== 'keep') throw new RangeError('onMiss must be error or keep.');++ const before = new Float32Array(source.positions.length);+ const fallbackNormals = new Float32Array(source.normals.length);+ const point = new Vector3();+ for (let vertex = 0; vertex < count; vertex++) {+ const offset = vertex * 3;+ point.fromArray(source.positions, offset).applyMatrix4(matrix);+ for (const value of point.toArray()) finite(value, 'Transformed position');+ before.set(point.toArray(), offset);+ point.fromArray(source.normals, offset).applyMatrix3(normalMatrix).normalize();+ if (!point.toArray().every(Number.isFinite) || point.length() === 0) throw new RangeError('Transformed source normal is invalid.');+ fallbackNormals.set(point.toArray(), offset);+ }+ const groups = new Map();+ for (let vertex = 0; vertex < count; vertex++) {+ const offset = vertex * 3;+ const key = source.positions.subarray(offset, offset + 3).join(',');+ if (!groups.has(key)) groups.set(key, []);+ groups.get(key).push(vertex);+ }+ if (groups.size > maxQueries) throw new RangeError('Shrinkwrap exceeds maxQueries. Reduce source detail.');+ const result = { positions: new Float32Array(before), normals: null, indices: new Uint32Array(source.indices) };+ for (const channel of ['uvs', 'colors']) if (source[channel] !== undefined) result[channel] = new Float32Array(source[channel]);+ const hitNormals = new Array(count);+ const stats = { queriedVertices: 0, matchedVertices: 0, missedVertices: 0, triangleTests: 0 };+ const index = createMeshQueryIndex(target, { maxVertices, maxTriangles, memoryBudgetMiB: options.memoryBudgetMiB ?? 64 });+ try {+ for (const vertices of groups.values()) {+ const remaining = maxTriangleTests - stats.triangleTests;+ if (remaining <= 0) throw new RangeError('Shrinkwrap maxTriangleTests exhausted. Reduce source detail or raise the budget.');+ const origin = before.subarray(vertices[0] * 3, vertices[0] * 3 + 3);+ const query = mode === 'nearest'+ ? index.nearest(origin, { maxDistance, maxTriangleTests: remaining })+ : index.project({ origin, direction, maxDistance, maxTriangleTests: remaining });+ stats.queriedVertices++;+ stats.triangleTests += query.triangleTests;+ if (!query.hit) {+ stats.missedVertices++;+ if (onMiss === 'error') throw new RangeError(`Shrinkwrap missed source vertex ${vertices[0]}. Change maxDistance, direction, or onMiss.`);+ continue;+ }+ stats.matchedVertices++;+ const normal = new Vector3(...query.hit.normal);+ const roundedPoint = query.hit.point.map(Math.fround);+ const moved = query.hit.point.map((value, axis) => Math.fround(finite(value + query.hit.normal[axis] * clearance, 'Shrinkwrap position')));+ if (clearance > 0) {+ const displacement = new Vector3(...moved).sub(new Vector3(...roundedPoint));+ const actualGap = new Vector3(...moved).sub(new Vector3(...query.hit.point)).dot(normal);+ if (displacement.dot(normal) <= 0 || actualGap <= 0) throw new RangeError('Clearance collapses against the geometric face at Float32 precision. Increase clearance or reduce coordinates.');+ }+ for (const vertex of vertices) {+ result.positions.set(moved, vertex * 3);+ hitNormals[vertex] = normal;+ }+ }+ validateTriangles(before, result.positions, result.indices, hitNormals);+ result.normals = recomputeNormals(source, result.positions, fallbackNormals);+ return { geometry: result, stats };+ } finally {+ index.dispose();+ }+}diff --git a/tests/shrinkwrap.test.js b/tests/shrinkwrap.test.jsnew file mode 100644index 00000000..cdf56093--- /dev/null+++ b/tests/shrinkwrap.test.js@@ -0,0 +1,231 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { Matrix4, Vector3 } from 'three';+import { sphere, box } from '../src/geometry.js';+import { createMeshQueryIndex } from '../src/mesh-query.js';+import { shrinkwrapGeometry } from '../src/shrinkwrap.js';+import { sculptGeometry } from '../src/sculpt.js';++test('projected queries keep inside-bound hits and prune distant stacked surfaces', () => {+ const positions = [];+ const indices = [];+ for (let layer = 1; layer <= 32; layer++) {+ const offset = positions.length / 3;+ positions.push(-1, -1, layer, 1, -1, layer, 1, 1, layer, -1, 1, layer);+ indices.push(offset, offset + 1, offset + 2, offset, offset + 2, offset + 3);+ }+ const index = createMeshQueryIndex({ positions: new Float32Array(positions), indices: new Uint32Array(indices) });+ const inside = index.project({ origin: [0.1, 0.2, 1.5], direction: [0, 0, 1], maxDistance: 0.5 });+ assert.equal(inside.hit.distance, 0.5);+ assert.equal(inside.hit.point[2], 2);+ const outside = index.project({ origin: [0.1, 0.2, 0], direction: [0, 0, 1] });+ assert.equal(outside.hit.distance, 1);+ assert.ok(outside.triangleTests < indices.length / 3);+ const miss = index.project({ origin: [0.1, 0.2, 33], direction: [0, 0, 1] });+ assert.equal(miss.hit, null);+ assert.equal(miss.triangleTests, 0);+ index.dispose();+});++function plane(z = 0, extent = 1) {+ return {+ positions: new Float32Array([-extent, -extent, z, extent, -extent, z, extent, extent, z, -extent, extent, z]),+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),+ uvs: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),+ colors: new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1]),+ };+}++function unitNormals(geometry) {+ for (let offset = 0; offset < geometry.normals.length; offset += 3) assert.ok(Math.abs(Math.hypot(...geometry.normals.subarray(offset, offset + 3)) - 1) < 1e-6);+}++test('nearest and directional projection wrap to a literal plane with physical clearance', () => {+ for (const mode of ['nearest', 'project']) {+ const source = plane(1, 0.3);+ const target = plane(0, 2);+ const snapshot = structuredClone(source);+ const targetSnapshot = structuredClone(target);+ const options = { mode, clearance: 0.125, maxDistance: 1 };+ if (mode === 'project') options.direction = [0, 0, -1];+ const { geometry, stats } = shrinkwrapGeometry(source, target, options);+ assert.deepEqual(stats.queriedVertices, 4);+ assert.equal(stats.matchedVertices, 4);+ assert.equal(stats.missedVertices, 0);+ assert.ok(stats.triangleTests > 0);+ for (let offset = 0; offset < source.positions.length; offset += 3) {+ assert.equal(geometry.positions[offset], source.positions[offset]);+ assert.equal(geometry.positions[offset + 1], source.positions[offset + 1]);+ assert.equal(geometry.positions[offset + 2], 0.125);+ }+ assert.deepEqual(geometry.indices, source.indices);+ assert.deepEqual(geometry.colors, source.colors);+ assert.deepEqual(geometry.uvs, source.uvs);+ assert.notEqual(geometry.indices, source.indices);+ assert.deepEqual(source, snapshot);+ assert.deepEqual(target, targetSnapshot);+ unitNormals(geometry);+ }+});++test('target-local nearest and project queries return original triangle coordinates and count misses', () => {+ const index = createMeshQueryIndex(plane());+ const nearest = index.nearest([0.2, 0.1, 1]);+ assert.equal(nearest.hit.distance, 1);+ assert.ok(Math.abs(nearest.hit.point[2]) < 1e-12);+ assert.ok(nearest.hit.normal[0] === 0 && nearest.hit.normal[1] === 0 && nearest.hit.normal[2] === 1);+ assert.ok(nearest.hit.barycentric.every(value => value >= 0));+ assert.equal(index.nearest([0, 0, 0], { maxDistance: 0 }).hit.distance, 0);+ const miss = index.project({ origin: [0, 0, 1], direction: [0, 0, 1] });+ assert.equal(miss.hit, null);+ assert.ok(miss.triangleTests > 0, 'ray reaches the leaf but misses its triangles');+ const far = index.nearest([0, 0, 1], { maxDistance: 0.5 });+ assert.equal(far.hit, null);+ assert.ok(far.triangleTests > 0);+ assert.throws(() => index.nearest([0, 0, 1], { unknown: true }), /Unsupported/);+ assert.throws(() => index.project({ origin: [0, 0, 1], direction: [0, 0, 0] }), /nonzero/);+ assert.throws(() => index.project({ origin: [0, 0, 1] }), /direction/);+ assert.throws(() => index.nearest([0, 0, 1], { maxTriangleTests: 1 }), /exhausted/);+ assert.ok(index.nearest([0, 0, 1]).hit);+ index.dispose();+});++test('sphere projection follows actual triangle planes rather than an analytic sphere', () => {+ const target = sphere(16, 12);+ const source = plane(1.3, 0.25);+ const index = createMeshQueryIndex(target);+ for (const mode of ['nearest', 'project']) {+ const options = { mode, clearance: 0, maxDistance: 2 };+ if (mode === 'project') options.direction = [0, 0, -1];+ const output = shrinkwrapGeometry(source, target, options);+ for (let vertex = 0; vertex < 4; vertex++) {+ const origin = source.positions.subarray(vertex * 3, vertex * 3 + 3);+ const query = mode === 'project' ? index.project({ origin, direction: [0, 0, -1] }) : index.nearest(origin);+ const triangle = query.hit.triangle;+ const first = new Vector3().fromArray(target.positions, target.indices[triangle * 3] * 3);+ const point = new Vector3().fromArray(output.geometry.positions, vertex * 3);+ assert.ok(Math.abs(point.sub(first).dot(new Vector3(...query.hit.normal))) < 1e-7);+ }+ unitNormals(output.geometry);+ }+ const raised = shrinkwrapGeometry(source, target, { mode: 'project', direction: [0, 0, -1], clearance: 0.01 });+ for (let vertex = 0; vertex < 4; vertex++) {+ const query = index.project({ origin: source.positions.subarray(vertex * 3, vertex * 3 + 3), direction: [0, 0, -1] });+ const actual = new Vector3().fromArray(raised.geometry.positions, vertex * 3).sub(new Vector3(...query.hit.point)).dot(new Vector3(...query.hit.normal));+ assert.ok(Math.abs(actual - 0.01) < 1e-7);+ }+ index.dispose();+});++test('misses throw atomically by default and keep only the transformed source when requested', () => {+ const source = plane(1, 0.3);+ const snapshot = structuredClone(source);+ assert.throws(() => shrinkwrapGeometry(source, plane(0, 2), { maxDistance: 0.25 }), /missed source/);+ const kept = shrinkwrapGeometry(source, plane(0, 2), { maxDistance: 0.25, onMiss: 'keep' });+ assert.deepEqual(kept.geometry.positions, source.positions);+ assert.equal(kept.stats.missedVertices, 4);+ assert.equal(kept.stats.matchedVertices, 0);+ assert.ok(kept.stats.triangleTests > 0);+ assert.throws(() => shrinkwrapGeometry(source, plane(0, 2), { maxDistance: 0.25, onMiss: 'keep', maxTriangleTests: kept.stats.triangleTests - 1 }), /exhausted/);+ assert.throws(() => shrinkwrapGeometry(source, plane(), { mode: 'project', direction: [0, 0, 1] }), /missed source/);+ assert.deepEqual(source, snapshot);+});++test('partial keep misses preserve transformed vertices and rebuild normals for the resulting slope', () => {+ const source = plane(1, 0.3);+ source.positions[2] = 0.2;+ source.positions[11] = 0.2;+ const output = shrinkwrapGeometry(source, plane(0, 2), { maxDistance: 0.5, onMiss: 'keep' });+ assert.equal(output.stats.matchedVertices, 2);+ assert.equal(output.stats.missedVertices, 2);+ assert.equal(output.geometry.positions[2], 0);+ assert.equal(output.geometry.positions[5], 1);+ unitNormals(output.geometry);+});++test('total callback and unique-position budgets fail without poisoning subsequent operations', () => {+ const source = plane(1, 0.3);+ const target = plane(0, 2);+ const baseline = shrinkwrapGeometry(source, target);+ assert.equal(baseline.stats.triangleTests, 8);+ assert.throws(() => shrinkwrapGeometry(source, target, { maxTriangleTests: 7 }), /exhausted/);+ assert.throws(() => shrinkwrapGeometry(source, target, { maxQueries: 3 }), /maxQueries/);+ assert.deepEqual(shrinkwrapGeometry(source, target), baseline);+});++test('source affine transforms use target-local coordinates and retain UVs and color byte offsets', () => {+ const source = plane(1, 0.3);+ const matrix = new Matrix4().makeScale(2, 0.5, 3).setPosition(0.2, 0.1, 0);+ const storage = new Float32Array(source.colors.length + 4);+ storage.set(source.colors, 2);+ source.colors = storage.subarray(2, -2);+ const output = shrinkwrapGeometry(source, plane(0, 2), { sourceToTarget: matrix.toArray(), mode: 'project', direction: [0, 0, -1], maxDistance: 3 });+ for (let offset = 0; offset < source.positions.length; offset += 3) {+ assert.ok(Math.abs(output.geometry.positions[offset] - (source.positions[offset] * 2 + Math.fround(0.2))) < 1e-7);+ assert.ok(Math.abs(output.geometry.positions[offset + 1] - (source.positions[offset + 1] * 0.5 + Math.fround(0.1))) < 1e-7);+ assert.equal(output.geometry.positions[offset + 2], 0);+ }+ assert.deepEqual(output.geometry.colors, source.colors);+ unitNormals(output.geometry);+});++test('coincident position seams move together while authored hard-normal groups remain separate', () => {+ const source = box(0, 1);+ for (let offset = 0; offset < source.positions.length; offset++) source.positions[offset] *= 2;+ const target = box(0, 1);+ const output = shrinkwrapGeometry(source, target);+ assert.equal(output.stats.queriedVertices, 8);+ assert.ok(source.positions.length / 3 > 8);+ const seen = new Map();+ const normals = new Map();+ for (let offset = 0; offset < source.positions.length; offset += 3) {+ const key = source.positions.subarray(offset, offset + 3).join(',');+ const point = output.geometry.positions.subarray(offset, offset + 3).join(',');+ if (seen.has(key)) assert.equal(point, seen.get(key));+ seen.set(key, point);+ if (!normals.has(key)) normals.set(key, new Set());+ normals.get(key).add(output.geometry.normals.subarray(offset, offset + 3).join(','));+ }+ assert.ok(Array.from(normals.values()).some(group => group.size === 3));+ unitNormals(output.geometry);+});++test('invalid geometry, options, precision collapse, backfaces and clearance failure reject', () => {+ const source = plane(1, 0.3);+ const target = plane(0, 2);+ for (const options of [{ unknown: 1 }, { clearance: -1 }, { maxDistance: -1 }, { mode: 'wrong' }, { onMiss: 'wrong' }, { direction: [0, 0, -1] }, { mode: 'project' }, { maxVertices: 3 }, { memoryBudgetMiB: 0.000001 }, { sourceToTarget: new Matrix4().makeScale(0, 1, 1).toArray() }]) assert.throws(() => shrinkwrapGeometry(source, target, options));+ const malformed = structuredClone(source);+ malformed.normals[0] = 10;+ assert.throws(() => shrinkwrapGeometry(malformed, target), /unit vectors/);+ for (const field of ['morphTargets', 'skinIndices', 'skinWeights']) assert.throws(() => shrinkwrapGeometry({ ...source, [field]: [] }, target), /static geometry/);+ const reversed = structuredClone(source);+ reversed.indices.reverse();+ assert.throws(() => shrinkwrapGeometry(reversed, target), /faces away/);+ assert.throws(() => shrinkwrapGeometry(source, target, { clearance: 1e-50 }), /Clearance collapses/);+ const huge = plane(1e20, 1e15);+ assert.throws(() => shrinkwrapGeometry(huge, huge, { clearance: 1 }), /Clearance collapses/);+ const collapsed = plane(0, 0.3);+ collapsed.positions[0] = collapsed.positions[3];+ collapsed.positions[1] = collapsed.positions[4];+ assert.throws(() => shrinkwrapGeometry(collapsed, target), /degenerate/);+ assert.throws(() => shrinkwrapGeometry(source, target, { sourceToTarget: new Matrix4().makeRotationX(Math.PI / 2).setPosition(0, 0, 1).toArray(), mode: 'project', direction: [0, 0, -1] }), /collapses/);+});++test('normalized queries and Double normal sums support small and large finite local meshes', () => {+ for (const scale of [1e-30, 1e30]) {+ const source = plane(scale, 0.3 * scale);+ const output = shrinkwrapGeometry(source, plane(0, 2 * scale), { clearance: 0.01 * scale });+ assert.ok(Math.abs(output.geometry.positions[2] / scale - 0.01) < 1e-8);+ unitNormals(output.geometry);+ }+});++test('shared normal extraction preserves sculpt literal falloff and no-op behavior', () => {+ const source = plane();+ assert.deepEqual(sculptGeometry(source, []), source);+ const sculpted = sculptGeometry(source, [{ type: 'displace', center: [0, 0, 0], radius: 2, strength: 0.5, direction: [0, 0, 1] }]);+ assert.ok(sculpted.positions[2] > 0);+ assert.deepEqual(sculpted.uvs, source.uvs);+ unitNormals(sculpted);+});diff --git a/vite.lib.config.js b/vite.lib.config.jsindex ea9552b2..032ebea7 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -22,6 +22,7 @@ export default defineConfig({sculpt: 'src/sculpt.js',surface: 'src/surface.js','mesh-query': 'src/mesh-query.js',+ shrinkwrap: 'src/shrinkwrap.js',physics: 'src/physics.js',},formats: ['es'],