Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add bounded sculpt brushes and conforming surface patches

Nguyen Xuan An61a01023c753
diff --git a/.gitignore b/.gitignore
index 78905426..1df87459 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,6 +12,8 @@ public/morph-targets.md
public/skinning.md
public/physics.md
public/export-glb.md
+public/sculpt.md
+public/surface.md
artifacts/
.env
.env.*
diff --git a/README.md b/README.md
index c2ac606a..b10b0181 100644
--- a/README.md
+++ b/README.md
@@ -170,6 +170,9 @@ The source trailer includes an [offline physics recording](docs/film-physics.md)
The source renderer also supports [relative GPU morph targets](docs/morph-targets.md) for position and normal changes before skinning, including deterministic eyelid animation in the film. This feature is not in the published `0.3.3` package.
The source [glTF morph bridge](docs/gltf-morph.md) preserves relative targets, independent instance weights and linear, step or cubic weight animations.
The source [GLB exporter](docs/export-glb.md) preserves opaque vertex colors, UVs and independent HDR emission alongside static morph snapshots.
+
+Source-only [sculpt brushes](docs/sculpt.md) apply bounded inflation, directional displacement and neighborhood smoothing through serializable strokes.
+The [surface patch addon](docs/surface.md) clips a badge onto a curved mesh with geometric clearance and follows its retained rigid transform.
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/capability-audit.md b/docs/capability-audit.md
index 67d0633f..f9a8ef54 100644
--- a/docs/capability-audit.md
+++ b/docs/capability-audit.md
@@ -19,6 +19,8 @@ The Blender references describe authoring capabilities. Their interpolation and
| --- | --- | --- | --- |
| Scene graph | Shared hierarchy, local transforms, pivots and atomic reparenting integrated in source | Constraints, dynamic node editing, package release | Nested transforms and arbitrary seeks reproduce identical poses |
| Modeling | Base primitives, lathe, hole extrusion with bevels, and curve tubes integrated in source | Mesh editing, subdivision, modifiers, package release | Edited models retain topology, normals, UVs, and export behavior |
+| Sculpting | Static inflation, directional displacement and Laplacian smoothing strokes integrated in source | Interactive brushes, remeshing, volume preservation, package release | Deterministic strokes preserve source geometry, seams and finite normals |
+| Surface attachment | Projector-clipped static curved patches with local geometric clearance integrated in source | Mesh intersection detection, nearest-point shrinkwrap, posed surfaces, package release | Curved badges stay visible and rigid reverse seeks reproduce the same pixels |
| Animation curves | Linear, step, smooth and Hermite tangent interpolation in source | Curve editor; package release verification | Known curve samples, quaternion normalization, and continuous velocity checks |
| Animation composition | Weighted clips and absolute-time crossfades integrated in source | Additive motion, layer masks, events, package verification | Walking and gestures blend without pose discontinuities |
| Character deformation | Rigid joints, GPU skinning, relative position/normal morphs and skeletal GLB animation integrated in source | IK, retargeting, recognizable facial assets, package release | Animated imported character, expressions, and joint contact tests |
diff --git a/docs/sculpt.md b/docs/sculpt.md
new file mode 100644
index 00000000..4857e369
--- /dev/null
+++ b/docs/sculpt.md
@@ -0,0 +1,50 @@
+# Sculpt with brush data
+
+Available in the current source, after published version 0.3.3. The optional addon does not add Three.js to the core renderer.
+
+```js
+import { sphere } from '@codepawlhq/67js';
+import { sculptGeometry } from '@codepawlhq/67js/addons/sculpt';
+
+const geometry = sculptGeometry(sphere(64, 40), [
+ { type: 'inflate', center: [0, 0.7, 0.7], radius: 0.6, strength: 0.12 },
+ { type: 'displace', center: [0, 0, 1], radius: 0.35, strength: -0.08, direction: [0, 0, 1] },
+ { type: 'smooth', center: [0, 0, 1], radius: 0.5, strength: 0.15 },
+]);
+```
+
+Assign the result to a part before creating `Renderer67`. It copies positions, normals, triangle indices, UVs and RGB colors. The source remains unchanged. Replaying the same strokes produces the same geometry. Each stroke reads positions produced by previous strokes.
+
+## Brushes and units
+
+All centers, radii and displacements use geometry-local units.
+
+| Type | Behavior | Strength |
+| --- | --- | --- |
+| `inflate` | Move along the original mesh normals, averaged at exact coincident positions. | Signed distance; negative values deflate. |
+| `displace` | Move along the supplied nonzero `direction`, normalized by the addon. | Signed distance. |
+| `smooth` | Move toward the mean of connected triangle neighbors. One Jacobi step reads a fixed position snapshot. | Blend from 0 to 1. |
+
+For normalized distance `t = distance / radius`, the radial influence is `1 - 10t³ + 15t⁴ - 6t⁵` inside the brush and zero outside. Its first and second derivatives vanish at the center and boundary, avoiding an abrupt ridge where the brush ends. Inflate uses the input normals throughout one call, so a long sequence does not repeatedly rebuild normals. Separate calls allow later inflation to follow newly sculpted normals.
+
+Laplacian smoothing can shrink volume and soften boundaries. It does not preserve volume or guarantee collision-free topology.
+
+## Seams and normals
+
+Vertices with exactly equal input Float32 positions move together. This preserves duplicated UV seams. Nearly coincident positions are not welded, and separate shells at the same position are treated as one group. Cancelling normals at coincident positions throw rather than choosing an arbitrary direction.
+
+Normals are rebuilt from area-weighted triangle cross products using double-precision accumulators before conversion to Float32. This avoids overflow or underflow of normal accumulation on small or large finite meshes. Vertices with identical original positions and normals share the recomputed direction. Different original normals retain authored hard-edge splits.
+
+Unreferenced vertices retain their original normals. Cancelling normals at referenced vertices throw. UV coordinates, colors and topology are preserved, so stretching the surface also stretches an existing texture.
+
+## Bounds and unsupported operations
+
+`sculptGeometry(geometry, strokes, options)` accepts static indexed geometry with Float32 positions and unit normals, plus Uint32 triangle indices. Skin and morph channels are rejected. Empty or zero-strength stroke lists return an independent copy.
+
+Defaults are `maxVertices: 250000`, `maxTriangles: 500000`, `maxStrokes: 256`, and `maxVertexVisits: 20000000`. Each limit is checked before copying geometry. `maxVertexVisits` bounds vertex count multiplied by stroke count. Smoothing also visits bounded triangle adjacency. These limits bound inputs and work, not total browser memory. Exact-position maps, neighbor sets and normal reconstruction require additional temporary memory.
+
+Nonfinite data and newly collapsed triangles throw. Strong strokes can still fold or intersect surfaces. Sculpting does not detect those intersections, remesh, perform Boolean operations, update rig weights or provide a viewport brush editor.
+
+Renderer geometry buffers remain static. Rebuilding this mesh every animation frame causes CPU work and new GPU uploads. Compatible relative targets can instead be constructed once and animated through [morph poses](./morph-targets.md).
+
+The brush model follows the normal displacement and neighborhood smoothing described in the [Blender sculpting manual](https://docs.blender.org/manual/en/latest/sculpt_paint/sculpting/index.html). This API is a bounded code tool, not Blender feature parity.
diff --git a/docs/surface.md b/docs/surface.md
new file mode 100644
index 00000000..396e6a86
--- /dev/null
+++ b/docs/surface.md
@@ -0,0 +1,69 @@
+# Fit a patch to a curved surface
+
+Available in the current source, after published version 0.3.3. The optional addon reuses Three.js DecalGeometry without adding it to the core renderer.
+
+```js
+import { sphere } from '@codepawlhq/67js';
+import { createSurfacePatch } from '@codepawlhq/67js/addons/surface';
+
+const target = {
+ name: 'Shell',
+ geometry: sphere(64, 40),
+ matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]),
+ material: { color: [0.03, 0.2, 0.3], metallic: 0.2, roughness: 0.4 },
+};
+const badge = {
+ name: 'Badge',
+ geometry: createSurfacePatch(target, {
+ position: [0, 0, 0.9], size: [0.6, 0.4, 0.4], clearance: 0.001,
+ }),
+ matrix: target.matrix,
+ material: { color: [1, 0.2, 0.02], metallic: 0, roughness: 0.5 },
+};
+// Pass [target, badge] to Renderer67.
+// Mutate the retained target.matrix, then call renderer.updateParts([target, badge]).
+```
+
+The projector clips target triangles into a standalone patch that follows their curved shape. It generates new projector UVs and normalized interpolated normals. Original RGB colors, UVs, maps and materials are not copied. The patch uses its own material.
+
+Sharing the retained matrix keeps both objects together through rigid translation, rotation, affine scale and shear. Replacing only the target matrix breaks that relationship. Reflection also follows the renderer's existing winding behavior.
+
+## Projector and clearance
+
+`createSurfacePatch(targetPart, options)` uses target-local coordinates for every option.
+
+| Option | Default | Meaning |
+| --- | --- | --- |
+| `position` | `[0, 0, 0]` | Center of the clipping box. |
+| `rotation` | `[0, 0, 0]` | XYZ Euler radians. Projector +Z faces outward from the target. |
+| `size` | `[1, 1, 1]` | Positive width, height and depth of the clipping box. |
+| `clearance` | `0.001` | Nonnegative local offset along interpolated surface normals. |
+| `maxAngle` | `Math.PI / 2` | Maximum angle between geometric face normal and projector +Z. Must exceed zero. |
+| `maxVertices` | `250000` | Conservative clipping reservation and output vertex cap. |
+| `maxTriangles` | `250000` | Input triangle cap. |
+
+Back-facing triangles are excluded. A deep projector can still include several outward-facing layers. A narrow depth and angle select the intended surface. Projectors crossing sharp corners can distort UVs.
+
+Positive clearance moves the patch away from the target, preventing coplanar depth competition in this workflow. Zero clearance deliberately creates a coplanar patch and can produce z-fighting. Constant local clearance does not produce a constant world gap under nonuniform scale.
+
+The addon checks the rounded displacement against each unoffset clipped Float32 triangle. Vanishing geometric gaps, reversed output winding and entirely collapsed output throw. This checks local patch construction, not collision against other scene objects. Three.js clipping rounds the original positions to Float32, so correspondence with authored triangles has finite precision.
+
+## Resource bounds and animation
+
+The input requires finite indexed Float32 positions, unit normals and Uint32 triangle indices. `maxTriangles` bounds input scans. Projector bounds and facing checks reduce candidates before clipping. Conservative allocation reservations can reject a patch with a smaller final output. A smaller projector or larger `maxVertices` cap allows more projections.
+
+Clipping runs during scene construction. The patch is reused each frame, without repeating clipping or allocating new geometry. It follows rigid transforms through the shared matrix. The addon does not provide BVH queries or a total-memory guarantee.
+
+Skin, morph, assembly and procedural target materials reject explicitly. Their visible surfaces differ from the static target geometry. Rebuild the patch after static sculpting, before uploading the new scene. Animated deformation needs a posed surface evaluator and attachment binding, which remain unfinished.
+
+## Three different overlap problems
+
+| Problem | Required response |
+| --- | --- |
+| Nearly coplanar surfaces flicker | Geometric clearance or scoped render depth bias. This addon supplies geometric clearance. |
+| A rigid accessory intersects a curved shell | Adjust the contact transform or deform its footprint. A flat rigid panel cannot fit an arbitrary curved surface completely. |
+| Two closed meshes penetrate or one contains the other | Mesh collision queries and resolution. This addon does not detect these cases. |
+
+Antialiasing, material colors and shadow bias do not repair mesh penetration. This patch is a surface overlay, not a whole-object shrinkwrap modifier.
+
+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.json
index 5d23e6bf..b2e07c88 100644
--- a/package.json
+++ b/package.json
@@ -35,7 +35,9 @@
"docs/film-physics.md",
"docs/morph-targets.md",
"docs/gltf-morph.md",
- "docs/export-glb.md"
+ "docs/export-glb.md",
+ "docs/sculpt.md",
+ "docs/surface.md"
],
"main": "./build/67.module.js",
"module": "./build/67.module.js",
@@ -48,6 +50,8 @@
"./addons/canvas2d": "./build/canvas2d.js",
"./addons/gltf": "./build/gltf.js",
"./addons/modeling": "./build/modeling.js",
+ "./addons/sculpt": "./build/sculpt.js",
+ "./addons/surface": "./build/surface.js",
"./addons/physics": "./build/physics.js",
"./package.json": "./package.json"
},
diff --git a/public/llms.txt b/public/llms.txt
index 084185d7..b03bb187 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -82,6 +82,13 @@ The source GLB exporter preserves opaque linear vertex colors, UVs and independe
Read `docs/export-glb.md` in the matching checkout. Exported GLBs contain a static pose, not serialized animation clips or skeletons.
Texture export remains unsupported and fails explicitly. Procedural shaders and scene environments are not serialized into glTF materials.
+Source-only `addons/sculpt` accepts serializable inflate, displace and smooth strokes and returns new static geometry.
+Read `docs/sculpt.md`. Construct the result before the renderer: changing uploaded CPU positions does not update GPU geometry buffers.
+
+Source-only `addons/surface` creates projector-clipped curved patches. Read `docs/surface.md` for target-local projector and clearance units.
+Share the target's retained matrix to follow rigid motion. Skin, morph, assembly and procedural targets reject rather than returning stale patches.
+Surface clearance prevents overlapping layers in this workflow. It does not detect general mesh penetration or provide whole-object shrinkwrap.
+
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/prepare-release.mjs b/scripts/prepare-release.mjs
index 648fc9b4..6e5607ca 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -35,7 +35,7 @@ await copyFile(resolve(root, 'build-browser/67.module.js'), resolve(releases, me
await 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']) {
+for (const name of ['gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md', 'export-glb.md', 'sculpt.md', 'surface.md']) {
await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));
}
diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjs
index fcf06529..02a5a314 100644
--- a/scripts/smoke-package.mjs
+++ b/scripts/smoke-package.mjs
@@ -37,6 +37,8 @@ import * as film from '67js/addons/film';
import { createMotionScene } from '67js/addons/motion';
import { createCanvas2D } from '67js/addons/canvas2d';
import { parseGltf } from '67js/addons/gltf';
+import { sculptGeometry } from '67js/addons/sculpt';
+import { createSurfacePatch } from '67js/addons/surface';
import { createPhysicsScene, planPhysicsScene } from '67js/addons/physics';
assert.equal(VERSION, '${metadata.version}');
assert.equal(typeof Renderer67, 'function');
@@ -64,6 +66,13 @@ assert.equal(importedMorph.parts[0].material.emission, 4);
importedMorph.dispose();
assert.throws(() => new Renderer67({}, [], { environment: { pointLights: Array(9).fill({ position: [0, 1, 0] }) } }), /at most/, 'Packed renderer must validate light limits before requesting a GPU context.');
assert.ok(box().positions.length > 0);
+const sculptSource = box();
+const sculptOutput = sculptGeometry(sculptSource, [{ type: 'inflate', center: [0, 0, 0], radius: 10, strength: 0.05 }]);
+assert.equal(sculptOutput.positions.length, sculptSource.positions.length);
+assert.notDeepEqual(sculptOutput.positions, sculptSource.positions);
+const packedPatch = createSurfacePatch({ geometry: sculptSource }, { position: [0, 0, 0.5], size: [0.3, 0.3, 0.1] });
+assert.ok(packedPatch.indices.length > 0);
+assert.ok(packedPatch.positions.some((value, index) => index % 3 === 2 && value > 0.5));
const parts = createModel();
assert.equal(parts.length, 574);
assert.ok(parts.every(part => assemblyOffset(part, 1).some(value => value !== 0)));
diff --git a/scripts/smoke-surface-sculpt.mjs b/scripts/smoke-surface-sculpt.mjs
new file mode 100644
index 00000000..eb9a14f2
--- /dev/null
+++ b/scripts/smoke-surface-sculpt.mjs
@@ -0,0 +1,117 @@
+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('**/surface-sculpt-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/surface-sculpt-smoke.html');
+ const report = await page.evaluate(async () => {
+ const { Renderer67, sphere, fitPerspectiveDistance } = await import('/build/67.module.js');
+ const { createSurfacePatch } = await import('/build/surface.js');
+ const { sculptGeometry } = await import('/build/sculpt.js');
+ const canvas = document.querySelector('canvas');
+ const camera = { eye: [1.45, 0.55, 3.9], target: [0, 0, 0], fov: 35 };
+ if (canvas.clientWidth < canvas.clientHeight) {
+ const fitted = fitPerspectiveDistance({ minimum: [-1.35, -1.35, -1.35], maximum: [1.35, 1.35, 1.35] }, camera, canvas.clientWidth / canvas.clientHeight);
+ const originalDistance = Math.hypot(...camera.eye);
+ camera.eye = camera.eye.map(value => value * fitted / originalDistance);
+ }
+ const base = sphere(64, 40);
+ const strokes = [
+ { type: 'inflate', center: [-0.48, 0.3, 0.82], radius: 0.58, strength: 0.3 },
+ { type: 'displace', center: [0.3, -0.25, 0.9], radius: 0.5, strength: -0.22, direction: [0, 0, 1] },
+ { type: 'smooth', center: [0, 0, 1], radius: 1, strength: 0.2 },
+ ];
+ const started = performance.now();
+ const sculpted = sculptGeometry(base, strokes);
+ const sculptMilliseconds = performance.now() - started;
+ const identity = () => new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+ const blue = { color: [0.015, 0.22, 0.34], metallic: 0.3, roughness: 0.3, emission: 0 };
+ const orange = { color: [1, 0.18, 0.01], metallic: 0.05, roughness: 0.6, emission: 0 };
+ const patchTarget = { geometry: base, material: blue };
+ const patchStart = performance.now();
+ const patch = createSurfacePatch(patchTarget, { position: [0, 0, 0.88], size: [1.1, 0.7, 0.5], clearance: 0.001 });
+ const patchMilliseconds = performance.now() - patchStart;
+ const flat = {
+ positions: new Float32Array([-0.55, -0.35, 0.93, 0.55, -0.35, 0.93, 0.55, 0.35, 0.93, -0.55, 0.35, 0.93]),
+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
+ uvs: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),
+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
+ };
+ const cases = [
+ { name: 'flat-penetration', base, patch: flat },
+ { name: 'conforming-patch', base, patch },
+ { name: 'sculpted', base: sculpted },
+ ];
+ const results = [];
+ for (const entry of cases) {
+ const matrix = identity();
+ const parts = [{ name: 'Surface', geometry: entry.base, matrix, material: blue, castShadow: false }];
+ if (entry.patch) parts.push({ name: 'Badge', geometry: entry.patch, matrix, material: orange, castShadow: false });
+ const renderer = new Renderer67(canvas, parts, {
+ world: true, ground: false, samples: 2, pixelRatio: 1, hdr: true, memoryBudgetMiB: 96,
+ environment: { keyStrength: 0.8, fillStrength: 0.5, ambientStrength: 0.4 },
+ });
+ function draw(time) {
+ const angle = Math.sin(time) * 0.25;
+ 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'), error: context.getError() };
+ }
+ const original = draw(0.35);
+ draw(2);
+ const reverse = draw(0.35);
+ const replayExact = original.pixels.every((value, index) => value === reverse.pixels[index]);
+ let orangePixels = 0;
+ for (let offset = 0; offset < original.pixels.length; offset += 4) {
+ if (original.pixels[offset] > original.pixels[offset + 2] * 1.5 && original.pixels[offset] > 80) orangePixels++;
+ }
+ const context = renderer.context;
+ const info = context.getExtension('WEBGL_debug_renderer_info');
+ results.push({ name: entry.name, image: original.image, replayExact, retainedMatrix: parts.every(part => part.matrix === matrix),
+ orangePixels, glError: reverse.error, originalGlError: original.error, memory: renderer.memoryPlan,
+ gpu: info ? context.getParameter(info.UNMASKED_RENDERER_WEBGL) : 'unavailable' });
+ renderer.dispose();
+ }
+ return { sourceVertices: base.positions.length / 3, sourceTriangles: base.indices.length / 3,
+ patchVertices: patch.positions.length / 3, patchTriangles: patch.indices.length / 3,
+ sculptMilliseconds, patchMilliseconds, results };
+ });
+ for (const result of report.results) {
+ await writeFile(`artifacts/surface-${result.name}-${width}x${height}.png`, Buffer.from(result.image.split(',')[1], 'base64'));
+ delete result.image;
+ assert.equal(result.glError, 0);
+ assert.equal(result.originalGlError, 0);
+ assert.equal(result.replayExact, true);
+ assert.equal(result.retainedMatrix, true);
+ }
+ assert.deepEqual(errors, []);
+ assert.ok(report.results[1].orangePixels > report.results[0].orangePixels * 1.5, 'Conforming badge must cover its middle instead of disappearing inside the sphere.');
+ await writeFile(`artifacts/surface-sculpt-${width}x${height}.json`, JSON.stringify(report, null, 2));
+ console.log(JSON.stringify(report, null, 2));
+} finally {
+ await browser.close();
+}
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index b58837f7..8c344847 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -24,6 +24,8 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- Recorded contacts or articulated physics use optional `src/physics.js` and the checkout's `docs/physics.md`.
- A flat scene or axis view uses `src/canvas2d.js`, `src/camera.js` and `src/view2d.js`.
- A GLB asset viewer uses the optional `src/gltf.js` addon and `src/asset-viewer.js`.
+- 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`.
- 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 b873ed87..1e99ca62 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -111,6 +111,10 @@ Skinning and textured materials still reject at export. Check the decoder's capa
The optional `{ shadows: false }` update option suits flat scenes without moving shadow casters.
+Static `sculptGeometry` strokes return new geometry before renderer upload. Read `docs/sculpt.md` for seam and work limits.
+`createSurfacePatch` clips a curved overlay with target-local clearance. Read `docs/surface.md` and share the target's retained matrix.
+It rejects skin, morph, assembly and procedural targets. It does not detect arbitrary mesh penetration or provide animated shrinkwrap.
+
`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/sculpt.js b/src/sculpt.js
new file mode 100644
index 00000000..33c2cbc2
--- /dev/null
+++ b/src/sculpt.js
@@ -0,0 +1,249 @@
+function finite(value, name) {
+ if (!Number.isFinite(value) || !Number.isFinite(Math.fround(value))) {
+ throw new TypeError(`${name} must be a finite Float32 value.`);
+ }
+ return value;
+}
+
+function vector(input, name) {
+ if ((!Array.isArray(input) && !ArrayBuffer.isView(input)) || input.length !== 3) {
+ throw new TypeError(`${name} must contain three components.`);
+ }
+ return Array.from(input, value => finite(value, name));
+}
+
+function limit(value, maximum, name) {
+ if (!Number.isSafeInteger(value) || value < 1 || value > maximum) {
+ throw new RangeError(`${name} must be an integer from 1 to ${maximum}.`);
+ }
+}
+
+function validateGeometry(geometry, maxVertices, maxTriangles) {
+ const { positions, normals, indices } = geometry ?? {};
+ 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('Sculpting requires indexed Float32 positions and normals with Uint32 triangles.');
+ }
+ const count = positions.length / 3;
+ if (count > maxVertices || indices.length / 3 > maxTriangles) {
+ throw new RangeError('Sculpt geometry exceeds maxVertices or maxTriangles.');
+ }
+ if (geometry.morphTargets || geometry.skinIndices || geometry.skinWeights) {
+ throw new TypeError('Sculpting requires static geometry without morph or skin channels.');
+ }
+ for (const value of positions) finite(value, 'position');
+ for (let offset = 0; offset < normals.length; offset += 3) {
+ if (!normals.subarray(offset, offset + 3).every(Number.isFinite) ||
+ Math.abs(Math.hypot(...normals.subarray(offset, offset + 3)) - 1) > 0.001) {
+ throw new TypeError('Sculpt normals must be finite unit vectors.');
+ }
+ }
+ for (const index of indices) {
+ if (index >= count) throw new RangeError('Sculpt triangle index is out of bounds.');
+ }
+ for (const [channel, size] of [['uvs', 2], ['colors', 3]]) {
+ if (geometry[channel] === undefined) continue;
+ if (!(geometry[channel] instanceof Float32Array) || geometry[channel].length !== count * size ||
+ !geometry[channel].every(Number.isFinite)) {
+ throw new TypeError(`Sculpt ${channel} must match the vertex count and contain finite floats.`);
+ }
+ }
+ return count;
+}
+
+function prepareStrokes(strokes) {
+ return strokes.map(stroke => {
+ if (!['inflate', 'displace', 'smooth'].includes(stroke?.type)) {
+ throw new TypeError('Sculpt stroke type must be inflate, displace or smooth.');
+ }
+ const center = vector(stroke.center, 'center');
+ const radius = finite(stroke.radius, 'radius');
+ const strength = finite(stroke.strength, 'strength');
+ if (Math.fround(radius) <= 0) throw new RangeError('Brush radius must remain positive at Float32 precision.');
+ if (stroke.type === 'smooth' && (strength < 0 || strength > 1)) {
+ throw new RangeError('Smooth strength must be within zero and one.');
+ }
+ let direction;
+ if (stroke.type === 'displace') {
+ direction = vector(stroke.direction, 'direction');
+ const length = Math.hypot(...direction);
+ if (length === 0) throw new RangeError('Displace direction cannot be zero.');
+ direction = direction.map(value => value / length);
+ }
+ return { type: stroke.type, center, radius, strength, direction };
+ });
+}
+
+function positionGroups(geometry, count, smooth) {
+ const lookup = new Map();
+ const groups = [];
+ const groupIds = new Uint32Array(count);
+ for (let vertex = 0; vertex < count; vertex++) {
+ const offset = vertex * 3;
+ const point = Array.from(geometry.positions.subarray(offset, offset + 3));
+ const key = point.join(',');
+ let groupId = lookup.get(key);
+ if (groupId === undefined) {
+ groupId = groups.length;
+ lookup.set(key, groupId);
+ groups.push({ point, normal: [0, 0, 0], neighbors: smooth ? new Set() : null });
+ }
+ groupIds[vertex] = groupId;
+ for (let axis = 0; axis < 3; axis++) groups[groupId].normal[axis] += geometry.normals[offset + axis];
+ }
+ for (const group of groups) {
+ const length = Math.hypot(...group.normal);
+ if (!length) throw new RangeError('Coincident vertices have cancelling normals; separate the overlapping surfaces.');
+ group.normal = group.normal.map(value => value / length);
+ }
+ if (smooth) {
+ for (let offset = 0; offset < geometry.indices.length; offset += 3) {
+ const triangle = Array.from(geometry.indices.subarray(offset, offset + 3), index => groupIds[index]);
+ for (let corner = 0; corner < 3; corner++) {
+ const first = triangle[corner];
+ const second = triangle[(corner + 1) % 3];
+ if (first === second) continue;
+ groups[first].neighbors.add(second);
+ groups[second].neighbors.add(first);
+ }
+ }
+ }
+ return { groups, groupIds };
+}
+
+function applyStroke(groups, stroke) {
+ const next = stroke.type === 'smooth' ? groups.map(group => [...group.point]) : null;
+ for (let index = 0; index < groups.length; index++) {
+ const group = groups[index];
+ const distance = Math.hypot(...group.point.map((value, axis) => value - stroke.center[axis]));
+ if (distance >= stroke.radius || stroke.strength === 0) continue;
+ const relative = distance / stroke.radius;
+ // Quintic falloff has zero first and second derivatives at both ends.
+ const falloff = 1 - relative ** 3 * (10 + relative * (-15 + 6 * relative));
+ if (stroke.type === 'smooth') {
+ if (!group.neighbors.size) continue;
+ const mean = [0, 0, 0];
+ for (const neighbor of group.neighbors) {
+ for (let axis = 0; axis < 3; axis++) mean[axis] += groups[neighbor].point[axis] / group.neighbors.size;
+ }
+ for (let axis = 0; axis < 3; axis++) {
+ next[index][axis] += (mean[axis] - group.point[axis]) * stroke.strength * falloff;
+ }
+ } else {
+ const direction = stroke.type === 'inflate' ? group.normal : stroke.direction;
+ for (let axis = 0; axis < 3; axis++) group.point[axis] += direction[axis] * stroke.strength * falloff;
+ }
+ }
+ if (next) groups.forEach((group, index) => { group.point = next[index]; });
+ for (const group of groups) {
+ for (const value of group.point) finite(value, 'Sculpt result');
+ }
+}
+
+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;
+ const third = 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]);
+ return Math.hypot(
+ edgeFirst[1] * edgeSecond[2] - edgeFirst[2] * edgeSecond[1],
+ edgeFirst[2] * edgeSecond[0] - edgeFirst[0] * edgeSecond[2],
+ edgeFirst[0] * edgeSecond[1] - edgeFirst[1] * edgeSecond[0],
+ );
+}
+
+function validateResult(source, result) {
+ let drawable = false;
+ for (let offset = 0; offset < result.indices.length; offset += 3) {
+ const area = triangleArea(result.positions, result.indices, offset);
+ if (area > 0) drawable = true;
+ if (!area && triangleArea(source.positions, source.indices, offset) > 0) {
+ throw new RangeError('Sculpt stroke collapsed a triangle at Float32 precision. Reduce strength.');
+ }
+ }
+ if (!drawable) throw new RangeError('Sculpt geometry has no drawable triangles.');
+}
+
+/** Apply serializable construction-time brush strokes without mutating the source. */
+export function sculptGeometry(geometry, strokes, {
+ maxVertices = 250_000, maxTriangles = 500_000, maxStrokes = 256, maxVertexVisits = 20_000_000,
+} = {}) {
+ limit(maxVertices, 1_000_000, 'maxVertices');
+ limit(maxTriangles, 2_000_000, 'maxTriangles');
+ limit(maxStrokes, 4096, 'maxStrokes');
+ limit(maxVertexVisits, 100_000_000, 'maxVertexVisits');
+ const count = validateGeometry(geometry, maxVertices, maxTriangles);
+ if (!Array.isArray(strokes) || strokes.length > maxStrokes) throw new RangeError('Strokes exceed maxStrokes or are not an array.');
+ if (count * strokes.length > maxVertexVisits) throw new RangeError('Sculpting exceeds maxVertexVisits; split or reduce the strokes.');
+ const prepared = prepareStrokes(strokes);
+ const result = {
+ positions: new Float32Array(geometry.positions),
+ normals: new Float32Array(geometry.normals),
+ indices: new Uint32Array(geometry.indices),
+ };
+ for (const channel of ['uvs', 'colors']) {
+ if (geometry[channel]) result[channel] = new Float32Array(geometry[channel]);
+ }
+ if (!prepared.some(stroke => stroke.strength !== 0)) {
+ validateResult(geometry, result);
+ return result;
+ }
+ const { groups, groupIds } = positionGroups(geometry, count, prepared.some(stroke => stroke.type === 'smooth'));
+ for (const stroke of prepared) applyStroke(groups, stroke);
+ for (let vertex = 0; vertex < count; vertex++) result.positions.set(groups[groupIds[vertex]].point, vertex * 3);
+ validateResult(geometry, result);
+ result.normals = recomputeNormals(geometry, result.positions);
+ return result;
+}
diff --git a/src/surface.js b/src/surface.js
new file mode 100644
index 00000000..6af630b8
--- /dev/null
+++ b/src/surface.js
@@ -0,0 +1,208 @@
+import { BufferAttribute, BufferGeometry, Euler, Matrix4, Mesh, Vector3 } from 'three';
+import { DecalGeometry } from 'three/addons/geometries/DecalGeometry.js';
+
+const PROCEDURAL_TAGS = new Set(['armor', 'floor', 'water', 'foliage', 'grass', 'terrain', 'fire', 'smoke']);
+const OPTION_FIELDS = new Set(['position', 'rotation', 'size', 'clearance', 'maxAngle', 'maxVertices', 'maxTriangles']);
+
+function finiteFloat(value, label) {
+ if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isFinite(Math.fround(value))) {
+ throw new TypeError(`${label} must be a finite Float32 value.`);
+ }
+ return Math.fround(value);
+}
+
+function vector(input, fallback, label) {
+ const values = input ?? fallback;
+ if ((!Array.isArray(values) && !ArrayBuffer.isView(values)) || values.length !== 3) {
+ throw new TypeError(`${label} requires three components.`);
+ }
+ return Array.from(values, value => finiteFloat(value, label));
+}
+
+function limit(value, minimum, label) {
+ if (!Number.isSafeInteger(value) || value < minimum || value > 1_000_000) {
+ throw new RangeError(`${label} must be an integer within ${minimum} and 1000000.`);
+ }
+ return value;
+}
+
+function validateTarget(target, maxTriangles) {
+ const geometry = target?.geometry;
+ if (!geometry || typeof geometry !== 'object') throw new TypeError('Surface patches require a target part with geometry.');
+ if (target.skin || geometry.skinIndices !== undefined || geometry.skinWeights !== undefined) {
+ throw new RangeError('Surface patches cannot follow skinning. Use a static target.');
+ }
+ if (target.morph || geometry.morphTargets !== undefined) throw new RangeError('Surface patches cannot follow morphing. Use a static target.');
+ if (target.assembly) throw new RangeError('Surface patches cannot follow assembly shader offsets. Use a static target.');
+ if (PROCEDURAL_TAGS.has(target.material?.tag)) throw new RangeError('Surface patches require a standard material target without procedural deformation or shading.');
+ const positions = geometry.positions;
+ const normals = geometry.normals;
+ const indices = geometry.indices;
+ if (!(indices instanceof Uint32Array) || indices.length === 0 || indices.length % 3 !== 0) {
+ throw new TypeError('Target indices require a nonempty Uint32Array of triangles.');
+ }
+ if (indices.length / 3 > maxTriangles) throw new RangeError('Surface target exceeds maxTriangles. Reduce target detail or raise the limit.');
+ if (!(positions instanceof Float32Array) || positions.length === 0 || positions.length % 3 !== 0 || positions.length / 3 > maxTriangles * 3) {
+ throw new TypeError('Target positions require bounded nonempty Float32 XYZ vertices.');
+ }
+ if (!(normals instanceof Float32Array) || normals.length !== positions.length) throw new TypeError('Target normals require matching Float32 XYZ vertices.');
+ for (let offset = 0; offset < positions.length; offset += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ if (!Number.isFinite(positions[offset + axis]) || !Number.isFinite(normals[offset + axis])) throw new RangeError('Surface target vertices and normals must remain finite.');
+ }
+ const length = Math.hypot(normals[offset], normals[offset + 1], normals[offset + 2]);
+ if (Math.abs(length - 1) > 0.001) throw new RangeError('Surface target normals require unit vectors.');
+ }
+ for (const index of indices) if (index >= positions.length / 3) throw new RangeError('Surface target index exceeds the vertex count.');
+ return geometry;
+}
+
+function candidateIndices(geometry, projectorInverse, direction, size, maxAngle, maxVertices) {
+ const indices = [];
+ const points = [new Vector3(), new Vector3(), new Vector3()];
+ const projected = [new Vector3(), new Vector3(), new Vector3()];
+ const normal = new Vector3();
+ const edge = new Vector3();
+ const face = new Vector3();
+ const minimumFacing = Math.max(0, Math.cos(maxAngle));
+ let vertexBound = 0;
+ let drawable = false;
+ for (let offset = 0; offset < geometry.indices.length; offset += 3) {
+ for (let corner = 0; corner < 3; corner++) points[corner].fromArray(geometry.positions, geometry.indices[offset + corner] * 3);
+ face.subVectors(points[1], points[0]).cross(edge.subVectors(points[2], points[0]));
+ const area = Math.hypot(face.x, face.y, face.z);
+ if (area === 0) continue;
+ drawable = true;
+ face.multiplyScalar(1 / area);
+ const facing = face.dot(direction);
+ if (facing <= 0 || facing < minimumFacing) continue;
+ for (let corner = 0; corner < 3; corner++) {
+ normal.fromArray(geometry.normals, geometry.indices[offset + corner] * 3);
+ if (normal.dot(face) <= 0) throw new RangeError('Surface target normals must face outward with their triangles.');
+ projected[corner].copy(points[corner]).applyMatrix4(projectorInverse);
+ }
+ let outside = false;
+ let clippingPlanes = 0;
+ for (let axis = 0; axis < 3; axis++) {
+ const minimum = Math.min(projected[0].getComponent(axis), projected[1].getComponent(axis), projected[2].getComponent(axis));
+ const maximum = Math.max(projected[0].getComponent(axis), projected[1].getComponent(axis), projected[2].getComponent(axis));
+ const halfSize = size[axis] / 2;
+ if (minimum > halfSize || maximum < -halfSize) outside = true;
+ if (maximum > halfSize) clippingPlanes++;
+ if (minimum < -halfSize) clippingPlanes++;
+ }
+ if (outside) continue;
+ // Each of the six maintained clipping passes can double triangle fragments.
+ vertexBound += 3 * 2 ** clippingPlanes;
+ if (vertexBound > maxVertices) throw new RangeError('Surface clipping reservation exceeds maxVertices. Reduce the projector or raise the limit.');
+ indices.push(geometry.indices[offset], geometry.indices[offset + 1], geometry.indices[offset + 2]);
+ }
+ if (!drawable) throw new RangeError('Surface target has no drawable triangles.');
+ if (indices.length === 0) throw new RangeError('Surface projector misses all outward-facing target triangles.');
+ return indices;
+}
+
+function patchGeometry(source, clearance, maxVertices) {
+ const sourcePositions = source.getAttribute('position').array;
+ const sourceNormals = source.getAttribute('normal').array;
+ const sourceUvs = source.getAttribute('uv').array;
+ const vertexCount = sourcePositions.length / 3;
+ if (vertexCount === 0) throw new RangeError('Surface projector clips to an empty patch.');
+ if (vertexCount > maxVertices) throw new RangeError('Surface output exceeds maxVertices.');
+ const positions = new Float32Array(sourcePositions);
+ const normals = new Float32Array(sourceNormals);
+ const uvs = new Float32Array(sourceUvs);
+ for (let vertex = 0; vertex < vertexCount; vertex++) {
+ const offset = vertex * 3;
+ const length = Math.hypot(normals[offset], normals[offset + 1], normals[offset + 2]);
+ if (!Number.isFinite(length) || length === 0) throw new RangeError('Surface projection produced an invalid normal.');
+ let displacement = 0;
+ for (let axis = 0; axis < 3; axis++) {
+ normals[offset + axis] /= length;
+ positions[offset + axis] = sourcePositions[offset + axis] + normals[offset + axis] * clearance;
+ if (!Number.isFinite(positions[offset + axis])) throw new RangeError('Surface clearance exceeds finite Float32 coordinates.');
+ displacement += (positions[offset + axis] - sourcePositions[offset + axis]) * normals[offset + axis];
+ }
+ if (clearance > 0 && displacement <= 0) throw new RangeError('Surface clearance collapses at Float32 precision. Increase clearance or center the target locally.');
+ for (let axis = 0; axis < 2; axis++) {
+ const value = uvs[vertex * 2 + axis];
+ if (!Number.isFinite(value) || value < -1e-6 || value > 1 + 1e-6) throw new RangeError('Surface projection produced invalid projector UVs.');
+ }
+ }
+ const indices = [];
+ const first = new Vector3();
+ const second = new Vector3();
+ const third = new Vector3();
+ const edge = new Vector3();
+ const sourceFirst = new Vector3();
+ const sourceSecond = new Vector3();
+ const sourceThird = new Vector3();
+ const sourceFace = new Vector3();
+ const displacement = new Vector3();
+ for (let vertex = 0; vertex < vertexCount; vertex += 3) {
+ sourceFirst.fromArray(sourcePositions, vertex * 3);
+ sourceSecond.fromArray(sourcePositions, (vertex + 1) * 3).sub(sourceFirst);
+ sourceThird.fromArray(sourcePositions, (vertex + 2) * 3).sub(sourceFirst);
+ sourceFace.crossVectors(sourceSecond, sourceThird);
+ const sourceArea = Math.hypot(sourceFace.x, sourceFace.y, sourceFace.z);
+ if (sourceArea === 0) continue;
+ sourceFace.multiplyScalar(1 / sourceArea);
+ if (clearance > 0) {
+ for (let corner = 0; corner < 3; corner++) {
+ const offset = (vertex + corner) * 3;
+ displacement.set(positions[offset] - sourcePositions[offset], positions[offset + 1] - sourcePositions[offset + 1], positions[offset + 2] - sourcePositions[offset + 2]);
+ if (displacement.dot(sourceFace) <= 0) throw new RangeError('Surface clearance cannot create a positive triangle-plane gap at Float32 precision. Increase clearance or center the target locally.');
+ }
+ }
+ first.fromArray(positions, vertex * 3);
+ second.fromArray(positions, (vertex + 1) * 3).sub(first);
+ third.fromArray(positions, (vertex + 2) * 3).sub(first);
+ edge.crossVectors(second, third);
+ if (Math.hypot(edge.x, edge.y, edge.z) === 0 || edge.dot(sourceFace) <= 0) {
+ throw new RangeError('Surface clearance collapses or reverses a triangle. Reduce clearance.');
+ }
+ indices.push(vertex, vertex + 1, vertex + 2);
+ }
+ if (indices.length === 0) throw new RangeError('Surface output has no drawable triangles at Float32 precision.');
+ return { positions, normals, uvs, indices: new Uint32Array(indices) };
+}
+
+/** Static conforming patch. Projector and clearance use target-local coordinates.
+ * Share target.matrix on the patch part to follow rigid affine animation.
+ * RGB, original UVs, textures and material are not copied from the target.
+ */
+export function createSurfacePatch(target, options = {}) {
+ if (!options || typeof options !== 'object' || Array.isArray(options)) throw new TypeError('Surface options require an object.');
+ for (const field of Object.keys(options)) if (!OPTION_FIELDS.has(field)) throw new TypeError(`Unsupported surface option ${field}.`);
+ const position = vector(options.position, [0, 0, 0], 'position');
+ const rotation = vector(options.rotation, [0, 0, 0], 'rotation').map(value => value % (Math.PI * 2));
+ const size = vector(options.size, [1, 1, 1], 'size');
+ if (size.some(value => value <= 0)) throw new RangeError('Surface projector size must stay positive after Float32 conversion.');
+ const clearance = finiteFloat(options.clearance ?? 0.001, 'clearance');
+ if (clearance < 0) throw new RangeError('Surface clearance must be nonnegative.');
+ if (options.clearance > 0 && clearance === 0) throw new RangeError('Surface clearance collapses at Float32 precision. Increase clearance.');
+ const maxAngle = options.maxAngle ?? Math.PI / 2;
+ if (!Number.isFinite(maxAngle) || maxAngle <= 0 || maxAngle > Math.PI / 2) throw new RangeError('maxAngle must be greater than zero and at most PI/2.');
+ const maxVertices = limit(options.maxVertices ?? 250_000, 3, 'maxVertices');
+ const maxTriangles = limit(options.maxTriangles ?? 250_000, 1, 'maxTriangles');
+ const geometry = validateTarget(target, maxTriangles);
+ const orientation = new Euler(...rotation, 'XYZ');
+ const projector = new Matrix4().makeRotationFromEuler(orientation).setPosition(...position);
+ const inverse = projector.clone().invert();
+ const direction = new Vector3(0, 0, 1).transformDirection(projector);
+ const selected = candidateIndices(geometry, inverse, direction, size, maxAngle, maxVertices);
+ const source = new BufferGeometry();
+ let decal;
+ try {
+ source.setAttribute('position', new BufferAttribute(geometry.positions, 3));
+ source.setAttribute('normal', new BufferAttribute(geometry.normals, 3));
+ source.setIndex(new BufferAttribute(new Uint32Array(selected), 1));
+ const mesh = new Mesh(source, null);
+ // Identity matrix keeps DecalGeometry output in target-local space.
+ decal = new DecalGeometry(mesh, new Vector3(...position), orientation, new Vector3(...size));
+ return patchGeometry(decal, clearance, maxVertices);
+ } finally {
+ decal?.dispose();
+ source.dispose();
+ }
+}
diff --git a/tests/sculpt.test.js b/tests/sculpt.test.js
new file mode 100644
index 00000000..f1cbad9a
--- /dev/null
+++ b/tests/sculpt.test.js
@@ -0,0 +1,116 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { sphere, box } from '../src/geometry.js';
+import { sculptGeometry } from '../src/sculpt.js';
+
+function plane() {
+ return {
+ positions: new Float32Array([-1, -1, 0, 1, -1, 0, 0, 1, 0, 0, 0, 0]),
+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
+ indices: new Uint32Array([0, 1, 3, 1, 2, 3, 2, 0, 3]),
+ uvs: new Float32Array([0, 0, 1, 0, 0.5, 1, 0.5, 0.5]),
+ };
+}
+
+test('directional sculpt uses literal quintic falloff and preserves independent channels', () => {
+ const source = plane();
+ const snapshot = structuredClone(source);
+ const stroke = { type: 'displace', center: [0, 0, 0], radius: 2, strength: 0.5, direction: [0, 0, 20] };
+ const output = sculptGeometry(source, [stroke]);
+ assert.equal(output.positions[11], 0.5);
+ assert.equal(output.positions[8], 0.25);
+ assert.deepEqual(source, snapshot);
+ assert.deepEqual(output.uvs, source.uvs);
+ assert.notEqual(output.indices, source.indices);
+ assert.notEqual(output.uvs, source.uvs);
+ assert.deepEqual(output, sculptGeometry(source, [stroke]));
+ for (let offset = 0; offset < output.normals.length; offset += 3) {
+ assert.ok(Math.abs(Math.hypot(...output.normals.subarray(offset, offset + 3)) - 1) < 1e-6);
+ }
+});
+
+test('inflate and deflate use original normals and leave vertices outside brush unchanged', () => {
+ const source = sphere(16, 12);
+ for (const strength of [-0.15, 0.15]) {
+ const output = sculptGeometry(source, [{ type: 'inflate', center: [0, 1, 0], radius: 0.6, strength }]);
+ assert.ok(Math.abs(output.positions[1] - (1 + strength)) < 1e-6);
+ assert.equal(output.positions.at(-2), source.positions.at(-2));
+ }
+});
+
+test('exact coincident position seams move together while authored normal splits stay separate', () => {
+ const source = box();
+ const result = sculptGeometry(source, [{ type: 'inflate', center: [0, 0, 0], radius: 10, strength: 0.1 }]);
+ const seen = new Map();
+ for (let offset = 0; offset < source.positions.length; offset += 3) {
+ const key = source.positions.subarray(offset, offset + 3).join(',');
+ const output = result.positions.subarray(offset, offset + 3);
+ if (seen.has(key)) assert.deepEqual(output, seen.get(key));
+ seen.set(key, output);
+ }
+ assert.ok(result.normals.some((value, offset) => offset % 3 === 2 && value > 0.99));
+ assert.ok(result.normals.some((value, offset) => offset % 3 === 0 && value > 0.99));
+});
+
+test('Laplacian smoothing uses one immutable neighborhood snapshot for each stroke', () => {
+ const source = plane();
+ source.positions[11] = 1;
+ const output = sculptGeometry(source, [{ type: 'smooth', center: [0, 0, 1], radius: 0.5, strength: 0.5 }]);
+ assert.equal(output.positions[11], 0.5);
+ assert.ok(Math.abs(output.positions[10] + 1 / 6) < 1e-7);
+ assert.deepEqual(output.positions.subarray(0, 9), source.positions.subarray(0, 9));
+});
+
+test('invalid sculpt data, unsupported deformation and work budgets fail without source mutation', () => {
+ const source = plane();
+ const snapshot = structuredClone(source);
+ const stroke = { type: 'inflate', center: [0, 0, 0], radius: 1, strength: 0.1 };
+ assert.throws(() => sculptGeometry(source, [stroke], { maxVertices: 3 }), /maxVertices/);
+ assert.throws(() => sculptGeometry(source, [stroke], { maxVertexVisits: 3 }), /maxVertexVisits/);
+ assert.throws(() => sculptGeometry(source, [stroke], { maxTriangles: 2 }), /maxTriangles/);
+ assert.throws(() => sculptGeometry(source, [stroke, stroke], { maxStrokes: 1 }), /maxStrokes/);
+ assert.throws(() => sculptGeometry(source, [{ ...stroke, radius: 1e-50 }]), /radius/);
+ assert.throws(() => sculptGeometry(source, [{ ...stroke, type: 'smooth', strength: 1.1 }]), /strength/);
+ assert.throws(() => sculptGeometry(source, [{ ...stroke, type: 'displace', direction: [0, 0, 0] }]), /direction/);
+ assert.throws(() => sculptGeometry(source, [{ ...stroke, center: [Infinity, 0, 0] }]), /Float32/);
+ assert.throws(() => sculptGeometry({ ...source, morphTargets: [] }, [stroke]), /static/);
+ assert.throws(() => sculptGeometry({ ...source, skinIndices: new Uint16Array(16) }, [stroke]), /static/);
+ assert.deepEqual(source, snapshot);
+});
+
+test('sculpt rejects collapsed output triangles and retains source when the operation fails', () => {
+ const source = plane();
+ const snapshot = structuredClone(source);
+ assert.throws(() => sculptGeometry(source, [{ type: 'displace', center: [0, 0, 0], radius: 1, strength: 1, direction: [0, -1, 0] }]), /collapsed/);
+ assert.deepEqual(source, snapshot);
+});
+
+test('normal reconstruction remains accurate for very small and large finite meshes', () => {
+ for (const size of [1, 1e20, 1e-24]) {
+ const source = {
+ positions: new Float32Array([0, 0, 0, size, 0, 0, 0, size, 0]),
+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]),
+ indices: new Uint32Array([0, 1, 2]),
+ };
+ const output = sculptGeometry(source, [{ type: 'displace', center: [0, 0, 0], radius: size / 10, strength: size, direction: [0, 0, 1] }]);
+ for (const component of output.normals) assert.ok(Math.abs(component - 1 / Math.sqrt(3)) < 1e-6);
+ }
+});
+
+test('UV seam duplication does not change area-weighted sculpt normals', () => {
+ const source = {
+ positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -2, 0]),
+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
+ indices: new Uint32Array([0, 1, 2, 1, 0, 3]),
+ };
+ const split = {
+ positions: new Float32Array([...source.positions, 0, 0, 0, 1, 0, 0]),
+ normals: new Float32Array([...source.normals, 0, 0, 1, 0, 0, 1]),
+ indices: new Uint32Array([0, 1, 2, 5, 4, 3]),
+ };
+ const strokes = [{ type: 'displace', center: [0, 1, 0], radius: 0.1, strength: 1, direction: [0, 0, 1] }];
+ const ordinary = sculptGeometry(source, strokes);
+ const seamed = sculptGeometry(split, strokes);
+ assert.deepEqual(ordinary.normals.subarray(0, 3), seamed.normals.subarray(0, 3));
+ assert.deepEqual(ordinary.normals.subarray(0, 3), seamed.normals.subarray(12, 15));
+});
diff --git a/tests/surface.test.js b/tests/surface.test.js
new file mode 100644
index 00000000..cb377b7b
--- /dev/null
+++ b/tests/surface.test.js
@@ -0,0 +1,232 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { BufferGeometry, Euler, Matrix4, Triangle, Vector3 } from 'three';
+import { mat4 } from 'gl-matrix';
+import { sphere } from '../src/geometry.js';
+import { createSurfacePatch } from '../src/surface.js';
+
+test('a very narrow angle includes a perfectly aligned face', () => {
+ const target = {
+ geometry: {
+ positions: new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]),
+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
+ },
+ };
+ const patch = createSurfacePatch(target, { size: [3, 3, 1], clearance: 0, maxAngle: 1e-8 });
+ assert.equal(patch.indices.length, 6);
+});
+
+const PROJECTOR = { position: [0, 0, 1], size: [0.8, 0.5, 0.4] };
+
+function target(geometry = sphere(32, 20)) {
+ return { name: 'curved target', geometry, matrix: mat4.create(), material: { tag: 'standard', color: [0.3, 0.4, 0.5], metallic: 0, roughness: 0.7 } };
+}
+
+function planeGeometry() {
+ return {
+ positions: new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]),
+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
+ };
+}
+
+function closestSurfaceDistance(point, geometry) {
+ const triangle = new Triangle();
+ const nearest = new Vector3();
+ let minimum = Infinity;
+ for (let offset = 0; offset < geometry.indices.length; offset += 3) {
+ triangle.a.fromArray(geometry.positions, geometry.indices[offset] * 3);
+ triangle.b.fromArray(geometry.positions, geometry.indices[offset + 1] * 3);
+ triangle.c.fromArray(geometry.positions, geometry.indices[offset + 2] * 3);
+ triangle.closestPointToPoint(point, nearest);
+ minimum = Math.min(minimum, point.distanceTo(nearest));
+ }
+ return minimum;
+}
+
+test('surface patch conforms to actual curved triangles, projects bounded UVs and adds local normal clearance', () => {
+ const part = target();
+ const flush = createSurfacePatch(part, { ...PROJECTOR, clearance: 0 });
+ const raised = createSurfacePatch(part, { ...PROJECTOR, clearance: 0.002 });
+ assert.ok(flush.indices.length > 6);
+ assert.deepEqual(flush.indices, raised.indices);
+ assert.deepEqual(flush.uvs, raised.uvs);
+ let minimumDepth = Infinity;
+ let maximumDepth = -Infinity;
+ for (let vertex = 0; vertex < flush.positions.length / 3; vertex++) {
+ const offset = vertex * 3;
+ const point = new Vector3().fromArray(flush.positions, offset);
+ assert.ok(closestSurfaceDistance(point, part.geometry) < 8e-8, 'point must lie on an authored triangle, not an analytic sphere');
+ assert.ok(Math.abs(point.x) <= 0.4000001);
+ assert.ok(Math.abs(point.y) <= 0.2500001);
+ assert.ok(point.z >= 0.8 - 1e-7 && point.z <= 1.2 + 1e-7);
+ minimumDepth = Math.min(minimumDepth, point.z);
+ maximumDepth = Math.max(maximumDepth, point.z);
+ const normal = new Vector3().fromArray(raised.normals, offset);
+ assert.ok(Math.abs(normal.length() - 1) < 1e-6);
+ const difference = new Vector3().fromArray(raised.positions, offset).sub(point);
+ assert.ok(Math.abs(difference.length() - 0.002) < 1e-7);
+ assert.ok(difference.dot(normal) > 0.0019999);
+ for (let axis = 0; axis < 2; axis++) assert.ok(flush.uvs[vertex * 2 + axis] >= -1e-6 && flush.uvs[vertex * 2 + axis] <= 1 + 1e-6);
+ }
+ assert.ok(maximumDepth - minimumDepth > 0.04, 'patch must curve with the target');
+});
+
+test('projector rotation maps plane coordinates to UVs and filters reversed target faces', () => {
+ const part = target(planeGeometry());
+ const options = { position: [0, 0, 0], rotation: [0, 0, 0.7], size: [0.8, 0.5, 0.2], clearance: 0 };
+ const patch = createSurfacePatch(part, options);
+ const inverse = new Matrix4().makeRotationFromEuler(new Euler(...options.rotation)).invert();
+ for (let vertex = 0; vertex < patch.positions.length / 3; vertex++) {
+ const projected = new Vector3().fromArray(patch.positions, vertex * 3).applyMatrix4(inverse);
+ assert.ok(Math.abs(patch.uvs[vertex * 2] - (0.5 + projected.x / 0.8)) < 1e-6);
+ assert.ok(Math.abs(patch.uvs[vertex * 2 + 1] - (0.5 + projected.y / 0.5)) < 1e-6);
+ }
+ const reversed = planeGeometry();
+ reversed.indices.set([0, 2, 1, 0, 3, 2]);
+ reversed.normals.fill(0);
+ for (let offset = 2; offset < reversed.normals.length; offset += 3) reversed.normals[offset] = -1;
+ assert.throws(() => createSurfacePatch(target(reversed), { position: [0, 0, 0] }), /misses/);
+ const flippedProjector = createSurfacePatch(target(reversed), { position: [0, 0, 0], rotation: [0, Math.PI, 0] });
+ assert.ok(flippedProjector.normals[2] < 0);
+});
+
+test('thick projector on a closed mesh only emits the outward-facing side and maxAngle narrows the patch', () => {
+ const part = target();
+ const broad = createSurfacePatch(part, { position: [0, 0, 0], size: [3, 3, 3], clearance: 0 });
+ const narrow = createSurfacePatch(part, { position: [0, 0, 0], size: [3, 3, 3], clearance: 0, maxAngle: 0.3 });
+ assert.ok(narrow.indices.length < broad.indices.length);
+ for (let offset = 2; offset < broad.positions.length; offset += 3) assert.ok(broad.positions[offset] >= -1e-7);
+ assert.throws(() => createSurfacePatch(part, { position: [0, 0, 10], size: [1, 1, 1] }), /misses/);
+});
+
+test('local patch shares affine target transforms across arbitrary backward and forward animation seeks', () => {
+ const part = target();
+ const patch = createSurfacePatch(part, PROJECTOR);
+ const patchPart = { geometry: patch, matrix: part.matrix };
+ const saved = new Float32Array(patch.positions);
+ const sample = time => {
+ mat4.identity(part.matrix);
+ mat4.translate(part.matrix, part.matrix, [time, -2, 0.5]);
+ mat4.rotateY(part.matrix, part.matrix, time * 0.7);
+ mat4.scale(part.matrix, part.matrix, [-2, 3, 0.5]);
+ part.matrix[4] += 0.25;
+ return new Vector3().fromArray(patch.positions).applyMatrix4(new Matrix4().fromArray(patchPart.matrix)).toArray();
+ };
+ const expected = sample(2);
+ sample(7);
+ sample(-1);
+ assert.deepEqual(sample(2), expected);
+ assert.equal(patchPart.matrix, part.matrix);
+ assert.deepEqual(patch.positions, saved);
+ assert.deepEqual(createSurfacePatch(part, PROJECTOR), patch, 'creation depends only on target-local geometry');
+});
+
+test('surface creation leaves offset source arrays and projector inputs untouched, including the sphere seam', () => {
+ const part = target();
+ const original = new Float32Array(part.geometry.positions);
+ const storage = new Float32Array(original.length + 6).fill(99);
+ storage.set(original, 3);
+ part.geometry.positions = storage.subarray(3, original.length + 3);
+ const options = { position: [1, 0, 0], rotation: [0, Math.PI / 2, 0], size: [0.7, 0.5, 0.4], clearance: 0.001 };
+ const savedOptions = structuredClone(options);
+ const savedNormals = new Float32Array(part.geometry.normals);
+ const savedIndices = new Uint32Array(part.geometry.indices);
+ const patch = createSurfacePatch(part, options);
+ assert.deepEqual(part.geometry.positions, original);
+ assert.deepEqual(part.geometry.normals, savedNormals);
+ assert.deepEqual(part.geometry.indices, savedIndices);
+ assert.deepEqual(options, savedOptions);
+ assert.equal(storage[0], 99);
+ const points = new Map();
+ let seamMatches = 0;
+ for (let offset = 0; offset < patch.positions.length; offset += 3) {
+ const key = Array.from(patch.positions.slice(offset, offset + 3), value => Math.round(value * 1e6)).join(',');
+ const attributes = [...patch.normals.slice(offset, offset + 3), ...patch.uvs.slice(offset / 3 * 2, offset / 3 * 2 + 2)];
+ if (points.has(key)) {
+ const previous = points.get(key);
+ for (let component = 0; component < attributes.length; component++) assert.ok(Math.abs(attributes[component] - previous[component]) < 2e-6);
+ seamMatches++;
+ }
+ points.set(key, attributes);
+ }
+ assert.ok(seamMatches > 0, 'shared clipped vertices retain matching seam positions');
+ assert.equal(patch.colors, undefined);
+});
+
+test('surface geometry and options reject malformed data, unsupported deformation and unsafe clearance', () => {
+ for (const options of [null, { unknown: 1 }, { size: [0, 1, 1] }, { size: [1e-50, 1, 1] }, { size: [1, 1] },
+ { position: [Infinity, 0, 0] }, { rotation: [0, NaN, 0] }, { clearance: -1 }, { clearance: 1e40 },
+ { clearance: 1e-50 }, { maxAngle: 0 }, { maxAngle: Math.PI }, { maxVertices: 2 }, { maxTriangles: 0 }]) {
+ assert.throws(() => createSurfacePatch(target(), options));
+ }
+ for (const field of ['skin', 'morph', 'assembly']) assert.throws(() => createSurfacePatch({ ...target(), [field]: {} }, PROJECTOR), /cannot follow/);
+ for (const tag of ['water', 'grass', 'foliage', 'terrain', 'floor', 'fire', 'smoke', 'armor']) {
+ assert.throws(() => createSurfacePatch({ ...target(), material: { tag } }, PROJECTOR), /standard material/);
+ }
+ for (const [field, values] of [['positions', new Float64Array(12)], ['normals', new Float32Array(12)],
+ ['indices', new Uint16Array([0, 1, 2])], ['indices', new Uint32Array([0, 1, 99])]]) {
+ const geometry = planeGeometry();
+ geometry[field] = values;
+ assert.throws(() => createSurfacePatch(target(geometry)));
+ }
+ for (const field of ['positions', 'normals']) {
+ const geometry = planeGeometry();
+ geometry[field][0] = NaN;
+ assert.throws(() => createSurfacePatch(target(geometry)), /finite/);
+ }
+ const collapsed = planeGeometry();
+ collapsed.positions.fill(0);
+ assert.throws(() => createSurfacePatch(target(collapsed)), /no drawable/);
+ assert.throws(() => createSurfacePatch(target(), { ...PROJECTOR, clearance: 1e-12 }), /collapses/);
+});
+
+test('surface reservations reject before clipping while bounded local projection accepts a full detailed sphere', () => {
+ const part = target(sphere());
+ assert.throws(() => createSurfacePatch(part, { ...PROJECTOR, maxTriangles: 100 }), /maxTriangles/);
+ assert.throws(() => createSurfacePatch(part, { ...PROJECTOR, maxVertices: 3 }), /reservation/);
+ const patch = createSurfacePatch(part, { ...PROJECTOR, maxVertices: 4000 });
+ assert.ok(patch.positions.length / 3 < 4000);
+ const flush = createSurfacePatch(target(planeGeometry()), { size: [3, 3, 1], clearance: 0, maxVertices: 6 });
+ assert.equal(flush.positions.length / 3, 6);
+});
+
+test('surface budget and invalid-input failures precede source and DecalGeometry buffer construction', () => {
+ const part = target();
+ const original = BufferGeometry.prototype.setAttribute;
+ let attributeCalls = 0;
+ BufferGeometry.prototype.setAttribute = function (...argumentsList) {
+ attributeCalls++;
+ return original.apply(this, argumentsList);
+ };
+ try {
+ assert.throws(() => createSurfacePatch(part, { ...PROJECTOR, maxVertices: 3 }), /reservation/);
+ assert.throws(() => createSurfacePatch(part, { ...PROJECTOR, maxTriangles: 1 }), /maxTriangles/);
+ assert.throws(() => createSurfacePatch(part, { ...PROJECTOR, size: [1, 0, 1] }), /positive/);
+ assert.equal(attributeCalls, 0);
+ } finally {
+ BufferGeometry.prototype.setAttribute = original;
+ }
+});
+
+test('clearance rejects smooth-normal movement that rounds entirely tangent to a high-coordinate face', () => {
+ const geometry = planeGeometry();
+ const height = Math.fround(1e20);
+ for (let offset = 0; offset < geometry.positions.length; offset += 3) {
+ geometry.positions[offset + 2] = height;
+ geometry.normals.set([Math.sqrt(0.75), 0, 0.5], offset);
+ }
+ const options = { position: [0, 0, height], size: [3, 3, 1] };
+ const flush = createSurfacePatch(target(geometry), { ...options, clearance: 0 });
+ assert.equal(flush.indices.length, 6);
+ assert.throws(() => createSurfacePatch(target(geometry), { ...options, clearance: 0.001 }), /triangle-plane gap/);
+});
+
+test('large smooth-normal clearance cannot publish a reversed or collapsed patch triangle', () => {
+ const geometry = planeGeometry();
+ geometry.indices = new Uint32Array([0, 1, 2]);
+ const normals = [[0.9, 0, Math.sqrt(0.19)], [-0.9, 0, Math.sqrt(0.19)], [-0.9, 0, Math.sqrt(0.19)], [0, 0, 1]];
+ geometry.normals.set(normals.flat());
+ assert.throws(() => createSurfacePatch(target(geometry), { size: [3, 3, 1], clearance: 2 }), /reverses a triangle/);
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index bb4db8ac..d8976f0c 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -19,6 +19,8 @@ export default defineConfig({
canvas2d: 'src/canvas2d.js',
gltf: 'src/gltf.js',
modeling: 'src/modeling.js',
+ sculpt: 'src/sculpt.js',
+ surface: 'src/surface.js',
physics: 'src/physics.js',
},
formats: ['es'],