Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add bounded modeling tools and an interactive lantern study

Nguyen Xuan An81959c85d3ab
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ebb074da..80702479 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,10 @@
## Unreleased
+- Add retained scene hierarchy, pivots and atomic reparenting with world pose preservation.
+- Add bounded lathe, extrusion with holes and bevels, and curve tube modeling through an optional addon.
+- Add a lantern modeling study with textured materials, orbit controls and PNG capture.
+- Add torus surface and cap UVs for textured materials.
- Add Hermite animation curves with explicit tangents and retained playback buffers.
- Add absolute-time clip mixing, weighted actions and crossfades with deterministic seeking.
- Import and render normal, metallic/roughness, occlusion and emissive texture maps.
diff --git a/docs/capability-audit.md b/docs/capability-audit.md
index 517620af..9bd90908 100644
--- a/docs/capability-audit.md
+++ b/docs/capability-audit.md
@@ -17,14 +17,14 @@ The Blender references describe authoring capabilities. Their interpolation and
| Area | Current implementation | Missing work | Completion evidence |
| --- | --- | --- | --- |
-| Scene graph | Flat part matrices and custom demo rigs | Shared hierarchy, local transforms, pivots, constraints | Nested transforms and arbitrary seeks reproduce identical poses |
-| Modeling | Box, sphere, cylinder, torus, and procedural sampled surfaces | Mesh editing, extrusion, lathe, curves, bevel, subdivision, modifiers | Edited models retain topology, normals, UVs, and export behavior |
+| 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 |
| 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 parts | Skinning, morph targets, IK, retargeting | Animated imported character, expressions, and joint contact tests |
| Camera authoring | Manually coded shot endpoints | Paths, tracking, focus targets, lens presets | Reviewed moving shot previews across aspect ratios |
| Film authoring | Scene-specific shot list and player | Shared timeline, shot editing, transitions, audio cues | Edited timeline seeks and exports deterministically |
-| Asset import | Opaque glTF meshes, base-color texture, rigid animation | Deformation, material maps, transparency, compression, streaming | Blender fixtures preserve geometry, materials, and animation |
+| Asset import | Opaque glTF meshes, five material maps and rigid animation integrated in source | Deformation, transparency, compression, streaming, package release | Blender fixtures preserve geometry, materials, and animation |
| Materials | Factors and five PBR texture channels integrated in source | Layered materials, advanced extensions, authored tangents, package verification | Reference material scenes and texture budget checks |
| Lighting | Directional shadows and procedural studio illumination | Configurable lights, HDR environments, baked lighting, reflection probes | Reference lighting scenes, stable shadows, and measured render cost |
| Image rendering | HDR, bloom, grading, MSAA, FXAA | Depth of field, motion blur, temporal sampling, render passes | Reviewed stills and moving previews with measured artifacts |
diff --git a/docs/modeling.md b/docs/modeling.md
new file mode 100644
index 00000000..64742093
--- /dev/null
+++ b/docs/modeling.md
@@ -0,0 +1,71 @@
+# Profile, contour and path modeling
+
+These tools are available in the current source. They are not in the published 0.3.3 package.
+The optional modeling entry uses the installed Three.js geometry algorithms and converts their output to 67.js meshes.
+The core renderer does not import the modeling addon.
+
+```js
+import { lathe, extrude, tube } from '@codepawlhq/67js/addons/modeling';
+
+const vessel = lathe([[0, 0], [0.6, 0], [0.8, 1], [0.6, 2], [0, 2]]);
+const panel = extrude([[-2, -2], [2, -2], [2, 2], [-2, 2]], {
+ holes: [[[-1, -1], [-1, 1], [1, 1], [1, -1]]],
+ depth: 0.2,
+ bevel: 0.03,
+});
+const cable = tube([[0, 0, 0], [1, 1, 0], [2, 0, 1]], { radius: 0.04 });
+```
+
+Each result has Float32 positions, normalized normals and UV channel zero, plus Uint32 triangle indices.
+Pass it as a part's `geometry` to `Renderer67`. Inputs are copied. Repeated instances can share the returned mesh.
+These generators run when constructing a scene, rather than every frame.
+
+## Lathe
+
+`lathe(profile, { segments = 64, startAngle = 0, sweep = 2π, maxVertices = 250000 })`
+revolves radius/height pairs around Y. Radii must be nonnegative, with at least one positive radius.
+Angles use radians. Large start angles normalize modulo one turn before evaluation.
+Segments range from 3 to 2048. UVs preserve the longitudinal seam.
+
+Profiles with radius-zero ends meet the axis. Partial sweeps and open profile ends remain open.
+Folded profiles can intersect themselves. This tool is not a solid Boolean solver.
+
+## Extrude
+
+`extrude(contour, { holes = [], depth = 1, steps = 1, bevel = 0, bevelThickness = bevel, bevelSegments = 3, maxVertices = 250000 })`
+extrudes a simple XY polygon along positive Z. Holes must remain strictly inside the contour and cannot overlap, touch or nest.
+Both polygon winding directions are accepted. A duplicated closing point is optional.
+Bevels extend the caps from `-bevelThickness` to `depth + bevelThickness`.
+
+Steps range from 1 to 256. Bevel segments range from 1 to 32.
+Large bevels can intersect on narrow or concave shapes. Inspect the result and reduce bevel size to fit the local clearance.
+The base contour validation does not establish that an arbitrary bevel produces a manifold solid.
+
+## Tube
+
+`tube(path, { radius = 0.1, segments = 64, radialSegments = 12, closed = false, maxVertices = 250000 })`
+sweeps a circular cross-section along a centripetal Catmull-Rom curve through XYZ points.
+Open paths need two points. Closed paths need three. Closed paths join the final sample back to the first.
+Open tube ends have no caps. Paths can intersect themselves.
+
+Segments range from 3 to 2048. Radial segments range from 3 to 128.
+
+## Resource and precision limits
+
+Each generator accepts at most 4096 input points. Extrusion applies that limit across its contour and holes.
+Vertex estimates are checked before geometry allocation. `maxVertices` can range from 3 to 1000000.
+This bounds geometry size, not total browser memory.
+
+Account for maps, instance counts and render targets separately.
+Polygon intersection validation uses quadratic edge comparisons, bounded by the input limit.
+Nonfinite output, invalid normals and entirely collapsed Float32 meshes throw.
+Center small geometry near the origin and place it with part transforms when working at large world coordinates.
+
+## API choice
+
+Plain point arrays keep profiles serializable and avoid exposing Three.js classes through the API.
+Accepting Three.js Shape/Curve objects offers custom curve subclasses, but couples callers to that dependency and weakens input bounds.
+The addon reuses Three.js triangulation, bevel construction and curve frames. THIRD-PARTY-NOTICES.md contains its license.
+
+The Aster lantern at `/modeling.html` combines these tools with texture channels and the shared scene graph.
+It is a procedural modeling demonstration, not a mesh editor or a Blender feature parity claim.
diff --git a/index.html b/index.html
index b2766722..ec66cfc6 100644
--- a/index.html
+++ b/index.html
@@ -36,6 +36,7 @@
<section id="examples" class="examples" aria-labelledby="examples-title">
<h2 id="examples-title">Interactive showcase</h2><p>Explore a machine, a world, a film or your own model</p>
<div class="gallery">
+ <a class="example" href="./modeling.html"><img src="./previews/modeling.webp" alt="A porcelain and brass lantern built with profile, extrusion and curve tools" width="1280" height="720" loading="lazy" /><div class="example-caption"><h3>Aster lantern</h3><span>Modeling <span aria-hidden="true">↗</span></span></div><p>Explore curved brass rails, a turned pedestal and animated clockwork rings</p></a>
<a class="example" href="./object.html"><img src="./previews/wall-e.webp" alt="WALL·E model rendered in 67.js" width="1280" height="720" fetchpriority="high" /><div class="example-caption"><h3>WALL·E</h3><span>Object studio <span aria-hidden="true">↗</span></span></div><p>Explore the exterior or separate 574 parts to inspect the machinery</p></a>
<a class="example" href="./nature.html"><img src="./previews/nature.webp" alt="A winding stream through Silverwater valley" width="1280" height="720" /><div class="example-caption"><h3>Silverwater valley</h3><span>Nature <span aria-hidden="true">↗</span></span></div><p>Move through the landscape and change the light and wind</p></a>
<a class="example" href="./film.html"><img src="./previews/film-contact.webp" alt="Scenes from the Oppenheimer 3D trailer study rendered in 67.js" width="1280" height="720" loading="lazy" /><div class="example-caption"><h3>Oppenheimer</h3><span>Short film <span aria-hidden="true">↗</span></span></div><p>Explore a 3D trailer study with an original synthesized score</p></a>
diff --git a/modeling.html b/modeling.html
new file mode 100644
index 00000000..3a5ffeef
--- /dev/null
+++ b/modeling.html
@@ -0,0 +1,30 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="description" content="An original mechanical lantern built with 67.js profile, extrusion and curve tools." />
+ <title>Aster lantern · 67.js</title>
+ <link rel="icon" href="/favicon.svg" />
+ </head>
+ <body>
+ <a class="skip-link" href="#content">Skip to content</a>
+ <header class="navigation">
+ <a class="brand" href="/" aria-label="67.js home">67<span>.js</span></a>
+ <nav aria-label="Library"><a href="/downloads.html">Downloads</a><a href="/docs.html">Docs</a></nav>
+ </header>
+ <main id="content" class="modeling-study">
+ <div class="study-heading"><div><h1>Aster lantern</h1><p>A turned porcelain base, a spiral brass cage, and a little clockwork.</p></div><a href="/docs.html#parts">Modeling tools</a></div>
+ <section class="modeling-stage" aria-label="Interactive lantern study">
+ <canvas id="modeling-canvas" tabindex="0" aria-label="3D mechanical lantern. Drag or use arrow keys to orbit. Scroll or use plus and minus to zoom. Press Space to pause animation."></canvas>
+ </section>
+ <div class="study-actions"><p id="modeling-stat" aria-live="off"></p><div><button id="modeling-play">Pause</button><button id="modeling-reset">Reset view</button><button id="modeling-save">Save PNG</button></div></div>
+ <p id="modeling-notice" role="status" hidden><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="m9 9 6 6m0-6-6 6"/></svg><span></span></p>
+ </main>
+ <footer class="site-footer" aria-label="Site footer">
+ <div class="footer-introduction"><a class="brand" href="/" aria-label="67.js home">67<span>.js</span></a><p>Browser 3D, from scene to film.<br>Made by <a href="https://codepawl.com">CodePawl</a>.</p></div>
+ <div class="footer-links"><a href="https://github.com/anxuanng/67.js" data-icon="github">GitHub</a><a href="https://www.npmjs.com/package/@codepawlhq/67js">npm</a><a href="/changelog.md">Changelog</a><a href="/license.txt">MIT license</a></div>
+ </footer>
+ <script type="module" src="/src/modeling-player.js"></script>
+ </body>
+</html>
diff --git a/package.json b/package.json
index 7c5ad813..848784ca 100644
--- a/package.json
+++ b/package.json
@@ -21,7 +21,12 @@
"docs/gltf.md",
"docs/guide.md",
"docs/verification.md",
- "docs/release-verification.md"
+ "docs/release-verification.md",
+ "docs/animation-curves.md",
+ "docs/animation-mixer.md",
+ "docs/material-maps.md",
+ "docs/modeling.md",
+ "docs/scene-graph.md"
],
"main": "./build/67.module.js",
"module": "./build/67.module.js",
@@ -33,6 +38,7 @@
"./addons/motion": "./build/motion.js",
"./addons/canvas2d": "./build/canvas2d.js",
"./addons/gltf": "./build/gltf.js",
+ "./addons/modeling": "./build/modeling.js",
"./package.json": "./package.json"
},
"scripts": {
diff --git a/public/previews/modeling.webp b/public/previews/modeling.webp
new file mode 100644
index 00000000..1550dc4d
Binary files /dev/null and b/public/previews/modeling.webp differ
diff --git a/scripts/render-media.mjs b/scripts/render-media.mjs
index 364c987d..6e8a3a30 100644
--- a/scripts/render-media.mjs
+++ b/scripts/render-media.mjs
@@ -27,7 +27,7 @@ export function parseRenderOptions(values) {
const presetName = options.preset ?? (backend === 'cpu' ? 'cpu' : 'balanced');
const preset = RENDER_PRESETS[presetName];
const aspect = options.aspect ?? 'landscape';
- if (!preset || !['image', 'video', 'stills'].includes(kind) || !['gpu', 'cpu'].includes(backend) || !['film', 'nature', 'object', 'motion', 'view2d', 'assets'].includes(scene) || !['landscape', 'portrait', 'square'].includes(aspect)) throw new Error('Unknown render kind, backend, scene, aspect or preset.');
+ if (!preset || !['image', 'video', 'stills'].includes(kind) || !['gpu', 'cpu'].includes(backend) || !['film', 'nature', 'object', 'motion', 'view2d', 'assets', 'modeling'].includes(scene) || !['landscape', 'portrait', 'square'].includes(aspect)) throw new Error('Unknown render kind, backend, scene, aspect or preset.');
if (options.asset && scene !== 'assets') throw new Error('The asset file option requires --scene assets.');
const numberOption = (name, fallback, minimum, maximum) => {
const value = Number(options[name] ?? fallback);
@@ -45,7 +45,7 @@ export function parseRenderOptions(values) {
const height = Math.round(numberOption('height', defaultHeight, 64, 4096));
if (kind === 'video' && (width % 2 || height % 2)) throw new Error('Video dimensions must be even for yuv420p output.');
const fps = numberOption('fps', preset.fps, 1, 60);
- const duration = numberOption('duration', scene === 'film' ? FILM_DURATION : scene === 'motion' ? 12 : 32, 0.1, 240);
+ const duration = numberOption('duration', scene === 'film' ? FILM_DURATION : ['motion', 'modeling'].includes(scene) ? 12 : 32, 0.1, 240);
const time = numberOption('time', scene === 'assets' ? 0 : 3, 0, 3600);
const start = numberOption('start', 0, 0, 3600);
const memory = numberOption('memory', preset.memoryBudgetMiB, 32, 1024);
diff --git a/scripts/smoke-modeling.mjs b/scripts/smoke-modeling.mjs
new file mode 100644
index 00000000..bc756faa
--- /dev/null
+++ b/scripts/smoke-modeling.mjs
@@ -0,0 +1,80 @@
+import assert from 'node:assert/strict';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { constants, setPriority } from 'node:os';
+import { chromium } from 'playwright';
+
+setPriority(constants.priority.PRIORITY_BELOW_NORMAL);
+await mkdir('artifacts', { recursive: true });
+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: 1440, height: 900 } });
+ const errors = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await page.goto(`${process.argv[2] ?? 'http://127.0.0.1:5173'}/modeling.html`);
+ await page.waitForFunction(() => window.__scene?.renderer || window.__modelingError);
+ assert.equal(await page.evaluate(() => window.__modelingError), undefined);
+ await page.locator('#modeling-play').click();
+ assert.equal(await page.locator('#modeling-play').getAttribute('aria-pressed'), 'false');
+ const report = await page.evaluate(() => {
+ const { scene, renderer, renderAt } = window.__scene;
+ const sample = time => {
+ renderAt(time);
+ const gl = renderer.context;
+ const pixels = new Uint8Array(renderer.canvas.width * renderer.canvas.height * 4);
+ gl.readPixels(0, 0, renderer.canvas.width, renderer.canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
+ let checksum = 2166136261;
+ for (const value of pixels) checksum = Math.imul(checksum ^ value, 16777619) >>> 0;
+ return { checksum, matrices: scene.parts.map(part => Array.from(part.matrix)), error: gl.getError() };
+ };
+ const first = sample(1);
+ const next = sample(6);
+ const repeated = sample(1);
+ const root = scene.graph.getNode('Lantern assembly');
+ root.localMatrix[12] = 0.25;
+ const moved = sample(1);
+ root.localMatrix[12] = 0;
+ renderAt(1);
+ return { first, next, repeated, moved, draws: renderer.batches.length, parts: scene.parts.length, memory: renderer.memoryPlan };
+ });
+ assert.deepEqual(report.first, report.repeated, 'Backward seek changed a deterministic frame');
+ assert.notDeepEqual(report.first.matrices, report.next.matrices);
+ assert.notEqual(report.first.checksum, report.next.checksum, 'Animated gears did not change pixels');
+ assert.notEqual(report.first.checksum, report.moved.checksum, 'Parent transform did not change pixels');
+ assert.equal(report.first.error, 0);
+ assert.equal(report.next.error, 0);
+ assert.equal(report.moved.error, 0);
+ const canvas = page.locator('#modeling-canvas');
+ await canvas.focus();
+ await page.keyboard.press('ArrowRight');
+ await page.keyboard.press('+');
+ await page.screenshot({ path: 'artifacts/modeling-desktop.png' });
+ const downloadReady = page.waitForEvent('download');
+ await page.locator('#modeling-save').click();
+ const download = await downloadReady;
+ await download.saveAs('artifacts/modeling-saved.png');
+ for (const width of [390, 320]) {
+ await page.setViewportSize({ width, height: 844 });
+ await page.screenshot({ path: `artifacts/modeling-mobile-${width}.png` });
+ assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), `Horizontal overflow at ${width}`);
+ }
+ await page.emulateMedia({ reducedMotion: 'reduce' });
+ await page.reload();
+ await page.waitForFunction(() => window.__scene?.renderer);
+ assert.equal(await page.locator('#modeling-play').getAttribute('aria-pressed'), 'false');
+ await page.evaluate(() => { document.documentElement.style.fontSize = '200%'; });
+ assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), 'Text resizing caused horizontal overflow');
+ await page.evaluate(() => window.__scene.renderer.context.getExtension('WEBGL_lose_context').loseContext());
+ await page.waitForFunction(() => window.__modelingError === 'Graphics context lost');
+ assert.equal(await page.locator('#modeling-play').isDisabled(), true);
+ assert.match(await page.locator('#modeling-notice').innerText(), /Reload/);
+ assert.deepEqual(errors, []);
+ for (const sample of ['first', 'next', 'repeated', 'moved']) delete report[sample].matrices;
+ await writeFile('artifacts/modeling-smoke.json', JSON.stringify(report, null, 2));
+ console.log(JSON.stringify(report));
+} finally {
+ await browser.close();
+}
diff --git a/src/geometry.js b/src/geometry.js
index 241fc182..1580b2cd 100644
--- a/src/geometry.js
+++ b/src/geometry.js
@@ -36,7 +36,16 @@ function surface(columns, rows, sample) {
triangle(first + 1, below + 1, below);
}
}
- return geometry(positions, normals, indices);
+ const result = geometry(positions, normals, indices);
+ result.uvs = new Float32Array((columns + 1) * (rows + 1) * 2);
+ for (let row = 0; row <= rows; row++) {
+ for (let column = 0; column <= columns; column++) {
+ const offset = (row * (columns + 1) + column) * 2;
+ result.uvs[offset] = column / columns;
+ result.uvs[offset + 1] = row / rows;
+ }
+ }
+ return result;
}
export function sphere(segments = 64, rings = 40) {
@@ -46,14 +55,6 @@ export function sphere(segments = 64, rings = 40) {
const position = [Math.sin(elevation) * Math.cos(angle), Math.cos(elevation), Math.sin(elevation) * Math.sin(angle)];
return { position, normal: position };
});
- result.uvs = new Float32Array((segments + 1) * (rings + 1) * 2);
- for (let row = 0; row <= rings; row++) {
- for (let column = 0; column <= segments; column++) {
- const offset = (row * (segments + 1) + column) * 2;
- result.uvs[offset] = column / segments;
- result.uvs[offset + 1] = row / rings;
- }
- }
return result;
}
@@ -72,6 +73,7 @@ export function torus(tubeRadius = 0.08, segments = 96, sides = 24, arc = FULL_T
const positions = [...body.positions];
const normals = [...body.normals];
const indices = [...body.indices];
+ const uvs = [...body.uvs];
for (const end of [0, 1]) {
const angle = start + arc * end;
const direction = end === 0 ? -1 : 1;
@@ -79,18 +81,20 @@ export function torus(tubeRadius = 0.08, segments = 96, sides = 24, arc = FULL_T
const center = positions.length / 3;
positions.push(Math.cos(angle), Math.sin(angle), 0);
normals.push(...normal);
+ uvs.push(0.5, 0.5);
for (let index = 0; index <= sides; index++) {
const tubeAngle = index / sides * FULL_TURN;
const radial = 1 + tubeRadius * Math.cos(tubeAngle);
positions.push(radial * Math.cos(angle), radial * Math.sin(angle), tubeRadius * Math.sin(tubeAngle));
normals.push(...normal);
+ uvs.push(0.5 + Math.cos(tubeAngle) * 0.5, 0.5 + Math.sin(tubeAngle) * 0.5);
}
for (let index = 0; index < sides; index++) {
const first = center + index + 1;
indices.push(center, end === 0 ? first : first + 1, end === 0 ? first + 1 : first);
}
}
- return geometry(positions, normals, indices);
+ return { ...geometry(positions, normals, indices), uvs: new Float32Array(uvs) };
}
export function cylinder(segments = 80, bevel = 0.025, bevelSegments = 6) {
diff --git a/src/modeling-player.js b/src/modeling-player.js
new file mode 100644
index 00000000..ac467bfc
--- /dev/null
+++ b/src/modeling-player.js
@@ -0,0 +1,131 @@
+import './modeling-style.css';
+import './brand.js';
+import './site-theme.css';
+import { Renderer67 } from './renderer.js';
+import { createLanternScene } from './modeling-scene.js';
+import { mountButton } from './site-controls.js';
+
+const canvas = document.querySelector('#modeling-canvas');
+const notice = document.querySelector('#modeling-notice');
+const query = new URLSearchParams(location.search);
+const exporting = query.get('export') === '1';
+const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)');
+function brushedMaps() {
+ const normal = document.createElement('canvas');
+ const packed = document.createElement('canvas');
+ normal.width = normal.height = packed.width = packed.height = 256;
+ const normalContext = normal.getContext('2d');
+ const packedContext = packed.getContext('2d');
+ const normals = normalContext.createImageData(256, 256);
+ const surfaces = packedContext.createImageData(256, 256);
+ for (let row = 0; row < 256; row++) {
+ for (let column = 0; column < 256; column++) {
+ const offset = (row * 256 + column) * 4;
+ const brushed = Math.sin(row * 3.7 + Math.sin(column * 0.3) * 0.15);
+ normals.data.set([128, Math.round(128 + brushed * 4), 255, 255], offset);
+ surfaces.data.set([255, Math.round(218 + brushed * 15), 255, 255], offset);
+ }
+ }
+ normalContext.putImageData(normals, 0, 0);
+ packedContext.putImageData(surfaces, 0, 0);
+ return { normalMap: { image: normal, colorSpace: 'linear' }, metallicRoughnessMap: { image: packed, colorSpace: 'linear' }, normalScale: [0.5, 0.5] };
+}
+const scene = createLanternScene({ textures: { brass: brushedMaps() } });
+const state = { time: 0, playing: !exporting && !reducedMotion.matches, yaw: Math.atan2(4.2, 5.2), pitch: 0.23, distance: 6.87 };
+let scheduled = 0;
+let lastTime = performance.now();
+let pointer;
+let renderer;
+let failed = false;
+document.body.classList.toggle('modeling-export', exporting);
+function boundedOption(name, fallback, minimum, maximum) {
+ const value = Number(query.get(name) ?? fallback);
+ return Number.isFinite(value) ? Math.max(minimum, Math.min(maximum, value)) : fallback;
+}
+if (exporting) {
+ const stage = document.querySelector('.modeling-stage');
+ stage.style.width = `${boundedOption('width', 1280, 64, 4096)}px`;
+ stage.style.height = `${boundedOption('height', 720, 64, 4096)}px`;
+}
+function fail(error) {
+ failed = true;
+ state.playing = false;
+ play.update({ label: 'Animate', 'aria-pressed': false, disabled: true });
+ notice.hidden = false;
+ notice.querySelector('span').textContent = `The scene could not render: ${error.message}. Reload the page to retry.`;
+ window.__modelingError = error.message;
+}
+function renderAt(time) {
+ const frame = scene.sample(time, canvas.clientWidth / canvas.clientHeight);
+ if (!exporting) {
+ const distance = state.distance * (canvas.clientWidth < canvas.clientHeight ? 1.15 : 1);
+ frame.eye = [Math.sin(state.yaw) * Math.cos(state.pitch) * distance, 1.35 + Math.sin(state.pitch) * distance, Math.cos(state.yaw) * Math.cos(state.pitch) * distance];
+ }
+ renderer.updateParts(scene.parts);
+ renderer.render(frame);
+ return frame;
+}
+function tick(now) {
+ scheduled = 0;
+ if (document.hidden) return;
+ if (state.playing) state.time += Math.min(0.1, Math.max(0, (now - lastTime) / 1000));
+ lastTime = now;
+ try { renderAt(state.time); } catch (error) { fail(error); }
+ if (state.playing) invalidate();
+}
+function invalidate() {
+ if (!failed && !scheduled && !document.hidden) scheduled = requestAnimationFrame(tick);
+}
+function setPlaying(value) {
+ state.playing = value;
+ lastTime = performance.now();
+ play.update({ label: value ? 'Pause' : 'Animate', 'aria-pressed': value });
+ invalidate();
+}
+const play = mountButton(document.querySelector('#modeling-play'), { label: state.playing ? 'Pause' : 'Animate', 'aria-pressed': state.playing, onClick: () => setPlaying(!state.playing) });
+mountButton(document.querySelector('#modeling-reset'), { onClick: () => { state.yaw = Math.atan2(4.2, 5.2); state.pitch = 0.23; state.distance = 6.87; invalidate(); } });
+const save = mountButton(document.querySelector('#modeling-save'), { onClick: async () => {
+ save.update({ disabled: true, label: 'Saving…' });
+ try {
+ renderAt(state.time);
+ const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
+ if (!blob) throw new Error('PNG encoding returned no image');
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = '67js-aster-lantern.png';
+ link.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+ } catch (error) { fail(error); }
+ finally { save.update({ disabled: false, label: 'Save PNG' }); }
+} });
+try {
+ renderer = new Renderer67(canvas, scene.parts, { ground: true, hdr: true, samples: boundedOption('samples', 4, 1, 8), pixelRatio: exporting ? 1 : Math.min(devicePixelRatio, 1.5), memoryBudgetMiB: boundedOption('memory', 256, 32, 1024) });
+ const triangles = scene.parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);
+ document.querySelector('#modeling-stat').textContent = `${scene.parts.length} parts · ${renderer.batches.length} draws · ${Math.round(triangles / 1000)}k triangles`;
+ window.__scene = { scene, renderer, duration: 12, renderAt, pause: () => setPlaying(false) };
+ window.renderAt = renderAt;
+ renderAt(0);
+ if (state.playing) invalidate();
+} catch (error) { fail(error); }
+canvas.addEventListener('pointerdown', event => { canvas.setPointerCapture(event.pointerId); canvas.focus({ preventScroll: true }); pointer = { id: event.pointerId, x: event.clientX, y: event.clientY }; });
+canvas.addEventListener('pointermove', event => {
+ if (!pointer || pointer.id !== event.pointerId) return;
+ state.yaw -= (event.clientX - pointer.x) * 0.008;
+ state.pitch = Math.max(-1.2, Math.min(1.2, state.pitch + (event.clientY - pointer.y) * 0.008));
+ pointer.x = event.clientX;
+ pointer.y = event.clientY;
+ invalidate();
+});
+for (const event of ['pointerup', 'pointercancel', 'lostpointercapture']) canvas.addEventListener(event, () => { pointer = null; });
+canvas.addEventListener('wheel', event => { event.preventDefault(); state.distance = Math.max(1.5, Math.min(30, state.distance * Math.exp(event.deltaY * 0.001))); invalidate(); }, { passive: false });
+canvas.addEventListener('keydown', event => {
+ const actions = { ArrowLeft: () => { state.yaw -= 0.1; }, ArrowRight: () => { state.yaw += 0.1; }, ArrowUp: () => { state.pitch = Math.min(1.2, state.pitch + 0.1); }, ArrowDown: () => { state.pitch = Math.max(-1.2, state.pitch - 0.1); }, '+': () => { state.distance = Math.max(1.5, state.distance * 0.9); }, '-': () => { state.distance = Math.min(30, state.distance * 1.1); }, ' ': () => setPlaying(!state.playing) };
+ if (actions[event.key]) { event.preventDefault(); actions[event.key](); invalidate(); }
+});
+const observer = new ResizeObserver(() => { if (renderer && !failed) { renderer.resize(); invalidate(); } });
+observer.observe(canvas);
+document.addEventListener('visibilitychange', () => { lastTime = performance.now(); if (!document.hidden) invalidate(); });
+reducedMotion.addEventListener('change', event => { if (event.matches && state.playing) setPlaying(false); });
+canvas.addEventListener('webglcontextlost', event => { event.preventDefault(); if (scheduled) cancelAnimationFrame(scheduled); scheduled = 0; fail(new Error('Graphics context lost')); });
+window.addEventListener('pagehide', () => { if (scheduled) cancelAnimationFrame(scheduled); observer.disconnect(); renderer?.dispose(); });
diff --git a/src/modeling-scene.js b/src/modeling-scene.js
new file mode 100644
index 00000000..71c2e50f
--- /dev/null
+++ b/src/modeling-scene.js
@@ -0,0 +1,87 @@
+import { mat4, quat } from 'gl-matrix';
+import { lathe, extrude, tube } from './modeling.js';
+import { cylinder, sphere, torus } from './geometry.js';
+import { createSceneGraph } from './scene-graph.js';
+
+/** Original mechanical lantern study built with reusable profile, contour and path tools. */
+export function createLanternScene({ textures = {} } = {}) {
+ const parts = [];
+ const brass = { tag: 'metal', color: [0.46, 0.26, 0.085], metallic: 0.92, roughness: 0.3, ...textures.brass };
+ const porcelain = { tag: 'ceramic', color: [0.58, 0.68, 0.65], metallic: 0.05, roughness: 0.26, ...textures.porcelain };
+ const dark = { tag: 'metal', color: [0.025, 0.041, 0.044], metallic: 0.76, roughness: 0.36, ...textures.brass };
+ const glow = { tag: 'light', color: [0.72, 0.33, 0.08], metallic: 0.05, roughness: 0.2, emissiveColor: [1, 0.42, 0.08], emission: 2.2 };
+ const steel = { tag: 'metal', color: [0.33, 0.43, 0.45], metallic: 0.95, roughness: 0.22 };
+ const meshes = {
+ base: lathe([[0, 0.04], [0.7, 0.04], [0.82, 0.075], [0.86, 0.13], [0.86, 0.2], [0.82, 0.25], [0.7, 0.27], [0.65, 0.32], [0.63, 0.41], [0.6, 0.43], [0, 0.43]], { segments: 128 }),
+ bowl: lathe([[0, 0.45], [0.34, 0.45], [0.48, 0.5], [0.6, 0.58], [0.66, 0.69], [0.67, 0.76], [0.65, 0.8], [0.61, 0.81], [0.6, 0.76], [0.56, 0.65], [0.46, 0.6], [0.3, 0.58], [0, 0.58]], { segments: 128 }),
+ crown: lathe([[0, 2.16], [0.4, 2.16], [0.64, 2.21], [0.68, 2.25], [0.65, 2.3], [0.53, 2.33], [0.46, 2.39], [0.4, 2.5], [0.25, 2.59], [0.16, 2.61], [0.16, 2.65], [0.08, 2.68], [0, 2.68]], { segments: 128 }),
+ arch: tube([[0.6, 0.76, 0], [0.88, 1.04, 0.08], [0.86, 1.53, 0.2], [0.63, 1.98, 0.23], [0.54, 2.22, 0]], { radius: 0.035, segments: 72, radialSegments: 12 }),
+ innerArch: tube([[0.5, 0.69, 0], [0.62, 1.03, 0], [0.62, 1.63, 0], [0.48, 2.08, 0], [0.5, 2.2, 0]], { radius: 0.014, segments: 56, radialSegments: 8 }),
+ bead: sphere(40, 24), bolt: cylinder(8, 0.04, 3), ring: torus(0.014, 96, 12),
+ };
+ const contour = Array.from({ length: 160 }, (_, index) => {
+ const angle = index / 160 * Math.PI * 2;
+ const radius = index % 4 < 2 ? 0.72 : 0.685;
+ return [Math.cos(angle) * radius, Math.sin(angle) * radius];
+ });
+ const hole = Array.from({ length: 96 }, (_, index) => {
+ const angle = index / 96 * Math.PI * 2;
+ return [Math.cos(angle) * 0.6, Math.sin(angle) * 0.6];
+ });
+ meshes.gear = extrude(contour, { holes: [hole], depth: 0.032, bevel: 0.004, bevelSegments: 2 });
+ function add(name, geometry, material, position = [0, 0, 0], scale = [1, 1, 1], angles = [0, 0, 0]) {
+ const matrix = mat4.fromRotationTranslationScale(mat4.create(), quat.fromEuler(quat.create(), ...angles), position, scale);
+ parts.push({ name, geometry, material, matrix });
+ return parts.at(-1);
+ }
+ add('Turned porcelain pedestal', meshes.base, porcelain);
+ add('Machined lower reflector', meshes.bowl, brass);
+ add('Turned brass crown', meshes.crown, brass);
+ add('Suspended opal emitter', meshes.bead, glow, [0, 1.47, 0], [0.3, 0.53, 0.3]);
+ add('Crown jewel', meshes.bead, steel, [0, 2.73, 0], [0.085, 0.09, 0.085]);
+ add('Lower jewel', meshes.bead, glow, [0, 0.7, 0], [0.16, 0.1, 0.16]);
+ const rotating = [];
+ for (let index = 0; index < 8; index++) {
+ const angle = index / 8 * 360;
+ add(`Spiral cage rail ${index}`, meshes.arch, brass, [0, 0, 0], [1, 1, 1], [0, angle, 0]);
+ add(`Inner cage rail ${index}`, meshes.innerArch, dark, [0, 0, 0], [1, 1, 1], [0, angle + 22.5, 0]);
+ }
+ for (const height of [0.84, 1.13, 1.81, 2.12]) {
+ const radius = height < 1 || height > 2 ? 0.63 : 0.78;
+ add(`Cage collar ${height}`, meshes.ring, brass, [0, height, 0], [radius, radius, radius], [90, 0, 0]);
+ }
+ for (let index = 0; index < 3; index++) {
+ const gear = add(`Clockwork ring ${index}`, meshes.gear, index === 1 ? steel : brass, [0, 0.36 + index * 0.035, 0], [1, 1, 1], [-90, 0, 0]);
+ rotating.push({ part: gear, base: mat4.clone(gear.matrix), speed: index % 2 ? -0.08 : 0.06 });
+ }
+ for (let index = 0; index < 24; index++) {
+ const angle = index / 24 * Math.PI * 2;
+ add(`Base fastener ${index}`, meshes.bolt, steel, [Math.cos(angle) * 0.78, 0.266, Math.sin(angle) * 0.78], [0.024, 0.015, 0.024]);
+ }
+ for (let index = 0; index < 8; index++) {
+ const angle = index / 8 * Math.PI * 2;
+ add(`Emitter suspension ${index}`, meshes.innerArch, steel, [0, 0.2, 0], [0.4, 0.8, 0.4], [0, index / 8 * 360, 0]);
+ add(`Crown fastener ${index}`, meshes.bolt, steel, [Math.cos(angle) * 0.5, 2.355, Math.sin(angle) * 0.5], [0.021, 0.012, 0.021]);
+ }
+ const graph = createSceneGraph([
+ { name: 'Lantern assembly' },
+ ...parts.map(part => ({ ...part, parent: 'Lantern assembly' })),
+ ]);
+ for (const entry of rotating) entry.localMatrix = graph.getNode(entry.part.name).localMatrix;
+ return {
+ name: 'Aster lantern', parts: graph.parts, graph,
+ sample(time = 0, aspect = 16 / 9) {
+ if (!Number.isFinite(time) || !Number.isFinite(aspect) || aspect <= 0) throw new TypeError('Scene time and aspect must be finite, with positive aspect.');
+ for (const entry of rotating) {
+ entry.localMatrix.set(entry.base);
+ mat4.rotateZ(entry.localMatrix, entry.localMatrix, time * entry.speed);
+ }
+ graph.update();
+ const distance = aspect < 1 ? 1.15 : 1;
+ return {
+ eye: [4.2 * distance, 2.9, 5.2 * distance], target: [0, 1.35, 0], fov: 32, time,
+ effects: { bloom: { strength: 0.16, threshold: 1, radius: 1.2 }, saturation: 0.93, contrast: 1.04, temperature: 0.03, vignette: 0.11, grain: 0.004 },
+ };
+ },
+ };
+}
diff --git a/src/modeling-style.css b/src/modeling-style.css
new file mode 100644
index 00000000..612e0e18
--- /dev/null
+++ b/src/modeling-style.css
@@ -0,0 +1,25 @@
+@import './home.css';
+.modeling-study { width:min(1352px,calc(100% - 48px)); margin:28px auto 60px; }
+.study-heading { display:flex; align-items:center; justify-content:space-between; gap:24px; margin-bottom:24px; }
+.study-heading h1 { font-size:32px; letter-spacing:-1px; margin:0 0 8px; }
+.study-heading p { margin:0; color:var(--muted); line-height:1.6; }
+.study-heading > a { color:var(--muted); white-space:nowrap; font-size:14px; }
+.modeling-stage { height:min(68vh,720px); min-height:400px; background:#1d2425; border-radius:24px; overflow:hidden; }
+#modeling-canvas { display:block; width:100%; height:100%; touch-action:none; }
+#modeling-canvas:focus-visible { outline-offset:-4px; }
+.study-actions { display:flex; align-items:center; justify-content:space-between; gap:24px; margin-top:20px; }
+.study-actions p { margin:0; font-size:13px; color:var(--muted); }
+.study-actions > div { display:flex; gap:8px; flex-wrap:wrap; }
+#modeling-notice { line-height:1.6; color:var(--text); }
+#modeling-notice:not([hidden]) { display:flex; align-items:center; gap:10px; }
+.modeling-export .navigation, .modeling-export .site-footer, .modeling-export .study-heading, .modeling-export .study-actions, .modeling-export .skip-link { display:none; }
+.modeling-export .modeling-study { margin:0; width:100%; }
+.modeling-export .modeling-stage { position:fixed; inset:0; width:100%; height:100%; min-height:0; border-radius:0; }
+@media (max-width:700px) {
+ .modeling-study { width:calc(100% - 32px); margin-top:22px; }
+ .study-heading { display:block; }
+ .study-heading > a { display:inline-block; margin-top:12px; }
+ .study-heading h1 { font-size:28px; }
+ .modeling-stage { height:58vh; min-height:350px; }
+ .study-actions { align-items:flex-start; flex-direction:column; gap:14px; }
+}
diff --git a/src/modeling.js b/src/modeling.js
new file mode 100644
index 00000000..bf98775c
--- /dev/null
+++ b/src/modeling.js
@@ -0,0 +1,189 @@
+import { LatheGeometry, ExtrudeGeometry, TubeGeometry, CatmullRomCurve3, Shape, Path, Vector2, Vector3 } from 'three';
+
+const MAX_INPUT_POINTS = 4096;
+const DEFAULT_VERTEX_LIMIT = 250_000;
+
+function finite(value, name) {
+ if (!Number.isFinite(value) || !Number.isFinite(Math.fround(value))) throw new TypeError(`${name} must be a finite float.`);
+ return Math.fround(value);
+}
+
+function integer(value, minimum, maximum, name) {
+ if (!Number.isInteger(value) || value < minimum || value > maximum) throw new RangeError(`${name} must be an integer within ${minimum} and ${maximum}.`);
+ return value;
+}
+
+function pointsFrom(input, size, minimum, name) {
+ if (!Array.isArray(input) || input.length < minimum || input.length > MAX_INPUT_POINTS) throw new RangeError(`${name} needs ${minimum} to ${MAX_INPUT_POINTS} points.`);
+ const points = input.map(point => {
+ if ((!Array.isArray(point) && !ArrayBuffer.isView(point)) || point.length !== size) throw new TypeError(`${name} points need ${size} components.`);
+ return Array.from(point, value => finite(value, name));
+ });
+ for (let index = 1; index < points.length; index++) {
+ if (points[index].every((value, axis) => value === points[index - 1][axis])) throw new RangeError(`${name} cannot contain consecutive duplicate points.`);
+ }
+ return points;
+}
+
+function checkBudget(vertices, maximum) {
+ integer(maximum, 3, 1_000_000, 'maxVertices');
+ if (vertices > maximum) throw new RangeError(`Modeling requires up to ${vertices} vertices, exceeding maxVertices ${maximum}. Reduce detail.`);
+}
+
+function meshFrom(source, maximum) {
+ try {
+ const position = source.getAttribute('position');
+ checkBudget(position.count, maximum);
+ const normal = source.getAttribute('normal');
+ const uv = source.getAttribute('uv');
+ const positions = new Float32Array(position.array);
+ const normals = new Float32Array(normal.array);
+ const uvs = new Float32Array(uv.array);
+ const indices = source.index ? new Uint32Array(source.index.array) : Uint32Array.from({ length: position.count }, (_, index) => index);
+ 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) || length === 0) throw new RangeError('Modeling produced an invalid normal. Adjust the profile or contour.');
+ for (let axis = 0; axis < 3; axis++) normals[offset + axis] /= length;
+ }
+ for (const value of positions) if (!Number.isFinite(value)) throw new RangeError('Modeling geometry exceeds the finite Float32 range. Reduce coordinates.');
+ for (const value of uvs) if (!Number.isFinite(value)) throw new RangeError('Modeling produced invalid UVs. Adjust the profile or contour.');
+ let drawable = false;
+ for (let offset = 0; offset < indices.length; offset += 3) {
+ const first = indices[offset] * 3;
+ const second = indices[offset + 1] * 3;
+ const third = indices[offset + 2] * 3;
+ const ax = positions[second] - positions[first];
+ const ay = positions[second + 1] - positions[first + 1];
+ const az = positions[second + 2] - positions[first + 2];
+ const bx = positions[third] - positions[first];
+ const by = positions[third + 1] - positions[first + 1];
+ const bz = positions[third + 2] - positions[first + 2];
+ if (Math.hypot(ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx) > 0) {
+ drawable = true;
+ break;
+ }
+ }
+ if (!drawable) throw new RangeError('Modeling collapsed at Float32 precision. Center geometry locally and position it with a transform.');
+ return { positions, normals, uvs, indices };
+ } finally {
+ source.dispose();
+ }
+}
+
+/** Revolve a radius/height profile around Y, using the installed Three.js geometry implementation. */
+export function lathe(profile, { segments = 64, startAngle = 0, sweep = Math.PI * 2, maxVertices = DEFAULT_VERTEX_LIMIT } = {}) {
+ integer(segments, 3, 2048, 'segments');
+ finite(startAngle, 'startAngle');
+ startAngle %= Math.PI * 2;
+ finite(sweep, 'sweep');
+ if (sweep <= 0 || sweep > Math.PI * 2) throw new RangeError('sweep must be greater than zero and at most one full turn.');
+ const points = pointsFrom(profile, 2, 2, 'profile');
+ if (points.some(point => point[0] < 0) || !points.some(point => point[0] > 0)) throw new RangeError('Profile radii must be nonnegative, with at least one positive radius.');
+ checkBudget((segments + 1) * points.length, maxVertices);
+ return meshFrom(new LatheGeometry(points.map(point => new Vector2(...point)), segments, startAngle, sweep), maxVertices);
+}
+
+function orientation(first, second, third) {
+ return (second[0] - first[0]) * (third[1] - first[1]) - (second[1] - first[1]) * (third[0] - first[0]);
+}
+
+function onSegment(first, second, point) {
+ return orientation(first, second, point) === 0 && point[0] >= Math.min(first[0], second[0]) && point[0] <= Math.max(first[0], second[0]) && point[1] >= Math.min(first[1], second[1]) && point[1] <= Math.max(first[1], second[1]);
+}
+
+function intersects(first, second, third, fourth) {
+ const a = orientation(first, second, third);
+ const b = orientation(first, second, fourth);
+ const c = orientation(third, fourth, first);
+ const d = orientation(third, fourth, second);
+ return Math.sign(a) !== Math.sign(b) && Math.sign(c) !== Math.sign(d) ||
+ a === 0 && onSegment(first, second, third) || b === 0 && onSegment(first, second, fourth) ||
+ c === 0 && onSegment(third, fourth, first) || d === 0 && onSegment(third, fourth, second);
+}
+
+function ringFrom(input, name) {
+ const points = pointsFrom(input, 2, 3, name);
+ if (points[0].every((value, axis) => value === points.at(-1)[axis])) points.pop();
+ if (points.length < 3) throw new RangeError(`${name} needs three distinct points.`);
+ let area = 0;
+ for (let index = 0; index < points.length; index++) {
+ const next = (index + 1) % points.length;
+ area += points[index][0] * points[next][1] - points[next][0] * points[index][1];
+ for (let other = index + 1; other < points.length; other++) {
+ const otherNext = (other + 1) % points.length;
+ if (other === next || otherNext === index) continue;
+ if (intersects(points[index], points[next], points[other], points[otherNext])) throw new RangeError(`${name} cannot intersect or touch itself.`);
+ }
+ }
+ if (area === 0) throw new RangeError(`${name} must enclose a nonzero area.`);
+ return points;
+}
+
+function inside(point, ring) {
+ let result = false;
+ for (let index = 0, previous = ring.length - 1; index < ring.length; previous = index++) {
+ const a = ring[index];
+ const b = ring[previous];
+ if ((a[1] > point[1]) !== (b[1] > point[1]) && point[0] < (b[0] - a[0]) * (point[1] - a[1]) / (b[1] - a[1]) + a[0]) result = !result;
+ }
+ return result;
+}
+
+function ringsIntersect(first, second) {
+ for (let a = 0; a < first.length; a++) {
+ for (let b = 0; b < second.length; b++) {
+ if (intersects(first[a], first[(a + 1) % first.length], second[b], second[(b + 1) % second.length])) return true;
+ }
+ }
+ return false;
+}
+
+/** Extrude a simple XY contour and disjoint enclosed holes along positive Z. */
+export function extrude(contour, {
+ holes = [], depth = 1, steps = 1, bevel = 0, bevelThickness = bevel,
+ bevelSegments = 3, maxVertices = DEFAULT_VERTEX_LIMIT,
+} = {}) {
+ depth = finite(depth, 'depth');
+ bevel = finite(bevel, 'bevel');
+ bevelThickness = finite(bevelThickness, 'bevelThickness');
+ if (depth <= 0 || bevel < 0 || bevelThickness < 0) throw new RangeError('depth must be positive and bevel dimensions must be nonnegative.');
+ integer(steps, 1, 256, 'steps');
+ integer(bevelSegments, 1, 32, 'bevelSegments');
+ if (!Array.isArray(holes) || holes.length > 128) throw new RangeError('holes must be an array with at most 128 rings.');
+ const inputPoints = (contour?.length ?? 0) + holes.reduce((count, hole) => count + (hole?.length ?? 0), 0);
+ if (inputPoints > MAX_INPUT_POINTS + holes.length + 1) throw new RangeError(`Contours and holes must contain at most ${MAX_INPUT_POINTS} total points.`);
+ const outer = ringFrom(contour, 'contour');
+ const inner = holes.map((hole, index) => ringFrom(hole, `hole ${index}`));
+ const totalPoints = outer.length + inner.reduce((count, ring) => count + ring.length, 0);
+ if (totalPoints > MAX_INPUT_POINTS) throw new RangeError(`Contours and holes must contain at most ${MAX_INPUT_POINTS} total points.`);
+ const beveled = bevel > 0 || bevelThickness > 0;
+ checkBudget(6 * (totalPoints + inner.length * 2 - 2) + 6 * totalPoints * (steps + (beveled ? bevelSegments * 2 : 0)), maxVertices);
+ for (let index = 0; index < inner.length; index++) {
+ if (!inside(inner[index][0], outer) || ringsIntersect(outer, inner[index])) throw new RangeError('Every hole must lie strictly inside the contour.');
+ for (let other = 0; other < index; other++) {
+ if (ringsIntersect(inner[index], inner[other]) || inside(inner[index][0], inner[other]) || inside(inner[other][0], inner[index])) throw new RangeError('Holes cannot overlap, touch or contain each other.');
+ }
+ }
+ const shape = new Shape(outer.map(point => new Vector2(...point)));
+ shape.holes = inner.map(ring => new Path(ring.map(point => new Vector2(...point))));
+ return meshFrom(new ExtrudeGeometry(shape, {
+ depth, steps, bevelEnabled: beveled, bevelSize: bevel, bevelThickness, bevelSegments,
+ }), maxVertices);
+}
+
+/** Sweep a circular tube along a centripetal Catmull-Rom curve. */
+export function tube(path, {
+ radius = 0.1, segments = 64, radialSegments = 12, closed = false,
+ maxVertices = DEFAULT_VERTEX_LIMIT,
+} = {}) {
+ radius = finite(radius, 'radius');
+ if (radius <= 0 || typeof closed !== 'boolean') throw new RangeError('radius must be positive and closed must be boolean.');
+ integer(segments, 3, 2048, 'segments');
+ integer(radialSegments, 3, 128, 'radialSegments');
+ const points = pointsFrom(path, 3, closed ? 3 : 2, 'path');
+ if (closed && points[0].every((value, axis) => value === points.at(-1)[axis])) points.pop();
+ if (points.length < (closed ? 3 : 2)) throw new RangeError('The path has too few distinct points.');
+ checkBudget((segments + 1) * (radialSegments + 1), maxVertices);
+ const curve = new CatmullRomCurve3(points.map(point => new Vector3(...point)), closed, 'centripetal');
+ return meshFrom(new TubeGeometry(curve, segments, radius, radialSegments, closed), maxVertices);
+}
diff --git a/tests/modeling.test.js b/tests/modeling.test.js
new file mode 100644
index 00000000..13d18149
--- /dev/null
+++ b/tests/modeling.test.js
@@ -0,0 +1,120 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { lathe, extrude, tube } from '../src/modeling.js';
+import { torus } from '../src/geometry.js';
+
+function validate(mesh) {
+ assert.ok(mesh.positions instanceof Float32Array);
+ assert.ok(mesh.normals instanceof Float32Array);
+ assert.ok(mesh.uvs instanceof Float32Array);
+ assert.ok(mesh.indices instanceof Uint32Array);
+ assert.equal(mesh.positions.length, mesh.normals.length);
+ assert.equal(mesh.uvs.length, mesh.positions.length / 3 * 2);
+ for (const values of [mesh.positions, mesh.normals, mesh.uvs]) assert.ok(values.every(Number.isFinite));
+ for (let index = 0; index < mesh.normals.length; index += 3) assert.ok(Math.abs(Math.hypot(...mesh.normals.subarray(index, index + 3)) - 1) < 1e-6);
+ for (const index of mesh.indices) assert.ok(index < mesh.positions.length / 3);
+}
+
+function signedVolume(mesh) {
+ let volume = 0;
+ for (let index = 0; index < mesh.indices.length; index += 3) {
+ const a = mesh.indices[index] * 3;
+ const b = mesh.indices[index + 1] * 3;
+ const c = mesh.indices[index + 2] * 3;
+ const p = mesh.positions;
+ volume += (p[a] * (p[b + 1] * p[c + 2] - p[b + 2] * p[c + 1]) +
+ p[a + 1] * (p[b + 2] * p[c] - p[b] * p[c + 2]) +
+ p[a + 2] * (p[b] * p[c + 1] - p[b + 1] * p[c])) / 6;
+ }
+ return volume;
+}
+
+test('lathe produces shared indexed geometry with normalized normals and UV seam', () => {
+ const mesh = lathe([[0, 0], [1, 0], [1, 2], [0, 2]], { segments: 128 });
+ validate(mesh);
+ assert.equal(mesh.positions.length / 3, 129 * 4);
+ assert.ok(Math.abs(signedVolume(mesh) - Math.PI * 2) < 0.004);
+ assert.equal(mesh.uvs[0], 0);
+ assert.equal(mesh.uvs.at(-2), 1);
+ const partial = lathe([[1, 0], [1, 2]], { segments: 8, sweep: Math.PI });
+ assert.equal(partial.positions.length / 3, 18);
+ validate(partial);
+});
+
+test('concave extrusion and holes retain literal area, depth and outward winding', () => {
+ const contour = [[0, 0], [3, 0], [3, 1], [1, 1], [1, 3], [0, 3]];
+ const concave = extrude(contour, { depth: 2 });
+ validate(concave);
+ assert.ok(Math.abs(signedVolume(concave) - 10) < 1e-6);
+ const outer = [[-2, -2], [2, -2], [2, 2], [-2, 2]];
+ const hole = [[-1, -1], [-1, 1], [1, 1], [1, -1]];
+ const hollow = extrude(outer, { holes: [hole], depth: 0.5 });
+ validate(hollow);
+ assert.ok(Math.abs(signedVolume(hollow) - 6) < 1e-6);
+ const reversed = extrude([...outer].reverse(), { holes: [[...hole].reverse()], depth: 0.5 });
+ assert.ok(Math.abs(signedVolume(reversed) - 6) < 1e-6);
+ assert.deepEqual(contour, [[0, 0], [3, 0], [3, 1], [1, 1], [1, 3], [0, 3]]);
+});
+
+test('beveled extrusion has finite geometry and extends its end caps by the requested thickness', () => {
+ const mesh = extrude([[-1, -1], [1, -1], [1, 1], [-1, 1]], { depth: 0.5, bevel: 0.1, bevelSegments: 6 });
+ validate(mesh);
+ let minimum = Infinity;
+ let maximum = -Infinity;
+ for (let index = 2; index < mesh.positions.length; index += 3) {
+ minimum = Math.min(minimum, mesh.positions[index]);
+ maximum = Math.max(maximum, mesh.positions[index]);
+ }
+ assert.ok(Math.abs(minimum + 0.1) < 1e-6);
+ assert.ok(Math.abs(maximum - 0.6) < 1e-6);
+ assert.ok(signedVolume(mesh) > 2);
+});
+
+test('tube follows straight and closed paths with retained topology and finite seam data', () => {
+ const straight = tube([[0, 0, 0], [0, 2, 0]], { radius: 0.2, segments: 16, radialSegments: 24 });
+ validate(straight);
+ for (let index = 0; index < straight.positions.length; index += 3) {
+ assert.ok(Math.abs(Math.hypot(straight.positions[index], straight.positions[index + 2]) - 0.2) < 1e-6);
+ }
+ const closed = tube([[1, 0, 0], [0, 0, 1], [-1, 0, 0], [0, 0, -1]], { closed: true, segments: 48 });
+ validate(closed);
+ const first = closed.positions.subarray(0, 39);
+ const last = closed.positions.subarray(closed.positions.length - 39);
+ for (let index = 0; index < first.length; index++) assert.ok(Math.abs(first[index] - last[index]) < 1e-6);
+});
+
+test('invalid topology and allocation requests fail before generating a mesh', () => {
+ assert.throws(() => lathe([[1, 0], [1, 1]], { segments: 2048, maxVertices: 100 }), /maxVertices/);
+ assert.throws(() => lathe([[-1, 0], [1, 1]]), /radii/);
+ assert.throws(() => lathe([[1, 0], [1, 0]]), /duplicate/);
+ assert.throws(() => tube([[0, 0, 0], [1, 0, 0]], { radius: 0 }), /radius/);
+ assert.throws(() => tube([[0, 0, 0], [1, 0, 0]], { closed: true }), /points/);
+ assert.throws(() => extrude([[0, 0], [2, 2], [0, 2], [2, 0]]), /intersect/);
+ assert.throws(() => extrude([[0, 0], [1, 0], [2, 0]]), /area/);
+ const contour = [[0, 0], [4, 0], [4, 4], [0, 4]];
+ assert.throws(() => extrude(contour, { holes: [[[3, 3], [5, 3], [5, 5], [3, 5]]] }), /inside/);
+ const hole = [[1, 1], [2, 1], [2, 2], [1, 2]];
+ assert.throws(() => extrude(contour, { holes: [hole, hole] }), /overlap/);
+ assert.throws(() => extrude(contour, { steps: 256, maxVertices: 100 }), /maxVertices/);
+ assert.throws(() => extrude([[0, 0], [Infinity, 0], [0, 1]]), /finite/);
+});
+
+test('Float32 collapse is rejected and large lathe angles retain drawable geometry', () => {
+ assert.throws(() => tube([[1e10, 0, 1e10], [1e10, 2, 1e10]], { radius: 0.1, segments: 8, radialSegments: 8 }), /collapsed/);
+ const largeAngle = lathe([[1, 0], [1, 2]], { startAngle: 1e20, segments: 8 });
+ validate(largeAngle);
+ const reference = lathe([[1, 0], [1, 2]], { startAngle: 1e20 % (Math.PI * 2), segments: 8 });
+ assert.deepEqual(largeAngle.positions, reference.positions);
+ assert.throws(() => extrude([[0, 0], [1, 0], [0, 1]], { depth: 1e-50 }), /positive/);
+});
+
+test('torus maps cover both surface seams and partial arc caps', () => {
+ for (const arc of [Math.PI * 2, Math.PI]) {
+ const mesh = torus(0.08, 16, 8, arc);
+ validate(mesh);
+ assert.equal(mesh.uvs[0], 0);
+ assert.equal(mesh.uvs[16 * 2], 1);
+ assert.ok(mesh.uvs.every(value => value >= 0 && value <= 1));
+ if (arc === Math.PI) assert.deepEqual(Array.from(mesh.uvs.subarray(17 * 9 * 2, 17 * 9 * 2 + 2)), [0.5, 0.5]);
+ }
+});
diff --git a/vite.config.js b/vite.config.js
index 192ba340..7b706cf0 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -8,5 +8,21 @@ const headers = {
export default defineConfig({
server: { headers },
preview: { headers },
- build: { rolldownOptions: { input: { home: 'index.html', downloads: 'downloads.html', object: 'object.html', nature: 'nature.html', film: 'film.html', motion: 'motion.html', view2d: 'view2d.html', assets: 'assets.html', guide: 'getting-started.html', docs: 'docs.html' } } },
+ build: {
+ rolldownOptions: {
+ input: {
+ home: 'index.html',
+ downloads: 'downloads.html',
+ object: 'object.html',
+ nature: 'nature.html',
+ film: 'film.html',
+ motion: 'motion.html',
+ modeling: 'modeling.html',
+ view2d: 'view2d.html',
+ assets: 'assets.html',
+ guide: 'getting-started.html',
+ docs: 'docs.html',
+ },
+ },
+ },
});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 2a6f7dca..b7b180ce 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -15,6 +15,7 @@ export default defineConfig({
motion: 'src/motion.js',
canvas2d: 'src/canvas2d.js',
gltf: 'src/gltf.js',
+ modeling: 'src/modeling.js',
},
formats: ['es'],
fileName: (_, entry) => entry === 'core' ? '67.module.js' : `${entry}.js`,