Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(holo): rebuild the sticker faces as a constrained Delaunay mesh so the peel curls instead of tearing
nirholas3739e5030c8a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 56b0f73da..21f982f1a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-10-01+- **Avatar pictures show a natural standing pose instead of a T-pose**: The small pictures of avatars around the site, on Spotlight cards, in the Monitor fleet list, on Characters and on the Rankings board, were drawn with every avatar standing arms out in a stiff T. Avatar pictures are now drawn with the avatar standing naturally, arms relaxed at its sides, using the same posing the live 3D viewer uses, and that works for every skeleton style the viewer already understands. Props, vehicles and creatures are drawn exactly as they were made. Avatar pictures also keep their colored backdrop and their real textures again, where some had come out on plain black with bare white materials. Every avatar picture drawn from now on uses the new pose, and the older pictures can now be redrawn in place. (`/spotlight`) `[fix]`+- **Avatars no longer open in a T-pose, and Spotlight shows one avatar instead of two**: On an Agent Spotlight page the avatar's preview picture, which is rendered arms out, never went away once the live 3D avatar loaded, so a second, T-posed copy stood behind the real one for as long as the page was open. The picture now gives way the moment the live avatar is ready. Separately, every embedded 3D avatar briefly showed its arms-out rest pose while its idle animation loaded and then faded in from it. The avatar now stays hidden until it is standing in its idle, then fades in, everywhere the avatar component is used. (`/spotlight`) `[fix]`- **Trading agents stop leaking SOL on every trade and can now ride a runner**: A full review of the autonomous trading fleet found the biggest loss was not bad trades: every buy opened a token account that no sale ever closed, stranding more SOL in rent than the agents lost trading. Agents now close it after every exit so the rent comes back. The take-initials ladder also works as designed now: once an agent has its stake back, the rest rides on its trailing stop with no clock and no early take-profit, instead of being sold on the next check. The crossing strategy no longer buys coins that have already graduated or sit on a dead curve, profit percentages are reported against the real stake, and the outcome labels that teach the Oracle are flowing again. (`/sniper/experiments`) `[fix, improvement]`## 2026-09-30diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 3f23ec5ca..e27efa10b 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -50,7 +50,7 @@ bottom.| Model detail page (`/m/:id`) | [pages/model.html](pages/model.html) `→ /m/:id`, page module [src/model-page.js](src/model-page.js) + pure helpers [src/model-lib.js](src/model-lib.js) + [src/model.css](src/model.css), backend [api/forge-creation.js](api/forge-creation.js) (`?related=&view=` + voted state; `DELETE`, scoped to the owning `x-forge-client`, lets a creator erase a creation, its stored GLB, preview, and recorded source uploads included) and [api/forge-comments.js](api/forge-comments.js), store reads [api/_lib/forge-store.js](api/_lib/forge-store.js) (`getPublicCreation`/`listRelated`/`recordCreationView`), schema [api/_lib/migrations/20260805120000_model_page.sql](api/_lib/migrations/20260805120000_model_page.sql) | Live | Every finished forge model as a first-class page in the classic model-platform detail layout: interactive viewer hero with AR and fullscreen, title + creator card with a real follow button (follow graph), live triangle/vertex stats from `GET /api/3d/inspect` (nothing persisted, nothing invented), the full prompt as the description, honest attribute chips, anonymous likes shared with the Forge-Off vote rail (`forge_votes`, same `forge:cid` id), a real page-view counter (`forge_creations.view_count`), a signed-in comment thread (`forge_comments`, bell-notifies the creator via the `comment` event type), paid remix via the existing x402 rail, embed/share/download, and a same-category suggested-models rail. Linked from the Details button on `/creations` cards and the Forge showcase. Tests: [tests/model-lib.test.js](tests/model-lib.test.js) || Labs (hidden-gems hub) | [pages/labs.html](pages/labs.html) + [src/labs.js](src/labs.js) `→ /labs` | In-repo | Data-driven discovery hub: renders every `data/pages.json` entry flagged `showcase: true` as a live card (status check + iframe preview), filterable by category || Playground (drop-in .glb viewer) | [pages/playground.html](pages/playground.html) `→ /playground` | Live | A 3D scene sandbox with nothing to install: drop or pick a `.glb` and it renders in `<model-viewer>` with animation playback, environment and background presets, auto-rotate, shadow and exposure controls, live file stats, and a copy-ready embed snippet. The file never leaves the browser (it is read as a blob URL), so the failure path carries the weight: a model that will not parse, a stalled download, or a blocked model-viewer CDN lands in an in-viewer error card with Retry and a file picker rather than an endless spinner. |-| Holo Sticker (procedural foil demo) | [pages/holo.html](pages/holo.html) `→ /holo`, app [src/holo.js](src/holo.js), styles [src/holo.css](src/holo.css) | Live | A real-time holographic foil sticker rendered with physical materials, fully procedural (no assets fetched): tilt it with the pointer, peel the corner (vertex-shader cylinder roll), switch foil styles, die-cut arbitrary typed text via a marching-squares vectorizer, and download the frame as a PNG |+| Holo Sticker (procedural foil demo) | [pages/holo.html](pages/holo.html) `→ /holo`, app [src/holo.js](src/holo.js), bendable extrusion [src/holo-geometry.js](src/holo-geometry.js), styles [src/holo.css](src/holo.css) | Live | A real-time holographic foil sticker rendered with physical materials, fully procedural (no assets fetched): tilt it with the pointer, peel the corner (vertex-shader cylinder roll over faces rebuilt as a constrained Delaunay mesh with an interior lattice, so they curl instead of tearing), switch foil styles, die-cut arbitrary typed text via a marching-squares vectorizer, and download the frame as a PNG || Machine Atlas (code-generated machines) | [pages/assembly.html](pages/assembly.html) `→ /assembly`, app [src/assembly.js](src/assembly.js), styles [src/assembly.css](src/assembly.css), geometry [src/assembly/](src/assembly/) | Live | Two working machines with no model files behind them: a nine-cylinder radial aero engine and a coupled steam locomotive, generated at runtime from their dimensions (revolved profiles, extruded sections, lofted NACA blade stations). Motion is solved, not keyframed: pistons follow the exact planar slider-crank and the locomotive valve gear closes a four-bar chain every frame by circle intersection. Live dimension sliders rebuild the geometry, explode and structure views take it apart, hover names any part, subassemblies toggle, and the Source panel prints the generating calls from the live values. Every configuration is a shareable link; export as GLB or save a PNG frame. Docs: [src/assembly/README.md](src/assembly/README.md). Tests: [tests/assembly-machines.test.js](tests/assembly-machines.test.js) || Examples gallery | [pages/examples.html](pages/examples.html) `→ /examples`, curated snippets [public/examples.js](public/examples.js), generated index renderer [public/examples-index.js](public/examples-index.js), styles [public/examples.css](public/examples.css), hosted example tree [public/examples/](public/examples) built by [scripts/build-hosted-examples.mjs](scripts/build-hosted-examples.mjs) | Live | Two halves. The top is 17 copy-paste snippets that RUN on the page, grouped into four lanes (avatars and embeds, 3D models, agents, agent economy) behind a sticky jump nav and a text/tag filter that folds away lanes as they empty (a deep link always beats an active filter): each is a complete document loading the production CDN bundle into an iframe, so "Run" executes exactly the code shown, and the model/agent/economy lanes call the live CORS-open production APIs rather than illustrating them (free text→3D at `/api/v1/ai/text-to-3d`, free text→speech at `/api/v1/ai/tts` played through the new `speakAudio()` viseme path, `/api/3d/inspect`, the 112-clip `/animations/manifest.json`, `/api/forged`, the public no-auth MCP server at `/api/mcp-studio` for both `tools/list` and a live `look_at_model` render-and-critique, the 402 quote from `/api/x402/forge`, `/api/pump/launches`). The `agent-from-files` card loads a real manifest from `/examples/coach-leo/manifest.json`: `npm run build:examples` publishes [examples/coach-leo/](examples/coach-leo) and its wave skill into `public/examples/` with body/image URIs rewritten absolute, so the manifest resolves the same way off-site as it does here. The bottom is every example that ships in the repo, generated by [scripts/build-examples-index.mjs](scripts/build-examples-index.mjs) scanning every `examples/` directory into [data/examples.json](data/examples.json), mirrored to the served [public/examples.json](public/examples.json) by [scripts/mirror-examples-index.mjs](scripts/mirror-examples-index.mjs) (`npm run build:examples` runs all three). Because it is scanned, the page cannot advertise a deleted example or miss an added one; each card carries the files it contains and the command that runs it. Tests: [tests/examples-page.test.js](tests/examples-page.test.js), [tests/examples-index.test.js](tests/examples-index.test.js) || Cookbook (runnable recipes) | Index [pages/cookbook.html](pages/cookbook.html) `-> /cookbook`, recipe viewer [pages/recipe.html](pages/recipe.html) `-> /cookbook/<slug>`, manifest [public/cookbook-manifest.js](public/cookbook-manifest.js), styles [public/cookbook.css](public/cookbook.css), recipe prose [docs/cookbook/](docs/cookbook), runnable files [public/cookbook/recipes/](public/cookbook/recipes), notebook export [public/cookbook/self-correcting-3d/](public/cookbook/self-correcting-3d) | Live | The sibling of the Examples gallery, and deliberately a different thing: an example is a snippet you read on the page, a recipe is a file you download and run. Five recipes, each one executed against the live API before it was published: a standard-library text-to-3D CLI, a parallel asset-pack builder that emits a manifest plus a gallery, an MCP server that hands Claude Code or Cursor a 3D tool, a CI budget gate over [api/3d/inspect.js](api/3d/inspect.js), and the function-calling-plus-vision notebook also submitted to the OpenAI Cookbook. The manifest is the single source of truth for both surfaces; recipe prose is markdown under `docs/cookbook/` fetched by the viewer, so adding a recipe is a manifest entry plus a `.md` plus the file itself. Route order is load-bearing in both [vercel.json](vercel.json) and the dev middleware: the notebook's static export must be matched before the generic `/cookbook/<slug>` rule or the viewer shadows it. Docs: [public/cookbook/recipes/README.md](public/cookbook/recipes/README.md). Tests: [tests/cookbook.test.js](tests/cookbook.test.js) |diff --git a/data/changelog.json b/data/changelog.jsonindex d8fe0affa..678255582 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -8,6 +8,13 @@"tags": ["fix", "sdk"],"link": "/docs/web-component"},+ {+ "date": "2026-10-01",+ "title": "The Holo Sticker corner now peels in one smooth curl",+ "summary": "Peeling the corner of the Holo Sticker used to break the sticker apart: around a third of the way the curled edge showed stair steps, past 40% a shard stuck out, and at full peel the corner crumpled. The flat front and back of the sticker were made of a few long triangles with no points inside, so they could not bend where the fold crossed them. Both faces are now built from an even mesh of small triangles that share their edge exactly with the rim, so the corner rolls into a clean curl at every point of the slider, for every mark, every foil and any text you die-cut, holes in letters included.",+ "tags": ["fix"],+ "link": "/holo"+ },{"date": "2026-10-01","title": "Search the 3D asset catalog from any AI client without an account",diff --git a/package-lock.json b/package-lock.jsonindex 7a7254782..b7885eaad 100644--- a/package-lock.json+++ b/package-lock.json@@ -114,6 +114,7 @@"@kamino-finance/farms-sdk": "^3.2.26","@kamino-finance/klend-sdk": "^12.0.0","@kamino-finance/scope-sdk": "^10.2.6",+ "@kninnug/constrainautor": "^4.1.0","@leeoniya/ufuzzy": "^1.0.19","@mediapipe/tasks-vision": "^0.10.35","@metaplex-foundation/genesis": "^0.43.0",@@ -184,6 +185,7 @@"compression": "^1.8.2","cron-parser": "^5.10.0","dat.gui": "^0.7.9",+ "delaunator": "^5.1.0","dompurify": "^3.4.15","draco3dgltf": "^1.5.7","esbuild": "^0.28.1",@@ -13498,6 +13500,15 @@"integrity": "sha512-4AOeU+P5UuE/4nOUkmcQdW5y7i9ndt1cQd/3iUe+LTz3RxESf/W/5lg4B74HbDMMv8PHnPnGCQFH45kBcrQYoQ==","license": "MIT"},+ "node_modules/@kninnug/constrainautor": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/@kninnug/constrainautor/-/constrainautor-4.1.0.tgz",+ "integrity": "sha512-YEkGtzMewRxPRZuK1QmFDmELwaSL4LSLmc0WXTmpT8AqdcR/Ueu77fiJZ2lwOwXUX8aBJpHuy/e/06/Ve2dPNQ==",+ "license": "ISC",+ "dependencies": {+ "robust-predicates": "^3.0.1"+ }+ },"node_modules/@leeoniya/ufuzzy": {"version": "1.0.19","license": "MIT"@@ -34703,6 +34714,15 @@"integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==","license": "MIT"},+ "node_modules/delaunator": {+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.1.0.tgz",+ "integrity": "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==",+ "license": "ISC",+ "dependencies": {+ "robust-predicates": "^3.0.2"+ }+ },"node_modules/delay": {"version": "5.0.0","license": "MIT",@@ -46839,6 +46859,12 @@"rlp": "bin/rlp"}},+ "node_modules/robust-predicates": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz",+ "integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==",+ "license": "Unlicense"+ },"node_modules/rolldown": {"version": "1.2.8","resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.8.tgz",diff --git a/package.json b/package.jsonindex c72e72895..6e998e0ef 100644--- a/package.json+++ b/package.json@@ -558,6 +558,7 @@"@kamino-finance/farms-sdk": "^3.2.26","@kamino-finance/klend-sdk": "^12.0.0","@kamino-finance/scope-sdk": "^10.2.6",+ "@kninnug/constrainautor": "^4.1.0","@leeoniya/ufuzzy": "^1.0.19","@mediapipe/tasks-vision": "^0.10.35","@metaplex-foundation/genesis": "^0.43.0",@@ -628,6 +629,7 @@"compression": "^1.8.2","cron-parser": "^5.10.0","dat.gui": "^0.7.9",+ "delaunator": "^5.1.0","dompurify": "^3.4.15","draco3dgltf": "^1.5.7","esbuild": "^0.28.1",diff --git a/public/changelog-recent.json b/public/changelog-recent.jsonindex 2692a02d4..9d2cd596c 100644--- a/public/changelog-recent.json+++ b/public/changelog-recent.json@@ -1,14 +1,34 @@{- "generated_at": "2026-10-01T07:14:48.480Z",+ "generated_at": "2026-10-01T09:43:06.643Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},- "total": 3804,+ "total": 3806,"complete": false,"full_feed": "/changelog.json","entries": [+ {+ "date": "2026-10-01",+ "type": "update",+ "title": "Avatar pictures show a natural standing pose instead of a T-pose",+ "summary": "The small pictures of avatars around the site, on Spotlight cards, in the Monitor fleet list, on Characters and on the Rankings board, were drawn with every avatar standing arms out in a stiff T. Avatar pictures are now drawn with the avatar standing naturally, arms relaxed at its sides, using the same posing the live 3D viewer uses, and that works for every skeleton style the viewer already understands. Props, vehicles and creatures are drawn exactly as they were made. Avatar pictures also keep their colored backdrop and their real textures again, where some had come out on plain black with bare white materials. Every avatar picture drawn from now on uses the new pose, and the older pictures can now be redrawn in place.",+ "link": "/spotlight",+ "tags": [+ "fix"+ ]+ },+ {+ "date": "2026-10-01",+ "type": "update",+ "title": "Avatars no longer open in a T-pose, and Spotlight shows one avatar instead of two",+ "summary": "On an Agent Spotlight page the avatar's preview picture, which is rendered arms out, never went away once the live 3D avatar loaded, so a second, T-posed copy stood behind the real one for as long as the page was open. The picture now gives way the moment the live avatar is ready. Separately, every embedded 3D avatar briefly showed its arms-out rest pose while its idle animation loaded and then faded in from it. The avatar now stays hidden until it is standing in its idle, then fades in, everywhere the avatar component is used.",+ "link": "/spotlight",+ "tags": [+ "fix"+ ]+ },{"date": "2026-10-01","type": "update",@@ -1559,26 +1579,6 @@"tags": ["launch"]- },- {- "date": "2026-09-09",- "type": "launch",- "title": "Docs · Rivalries",- "summary": "What changed on the trader board: who passed whom, who just arrived, and who is closing. Derived from close timestamps rather than a snapshot table, so the matchups work retroactively and cannot disagree with the leaderboard.",- "link": "/docs/rivalries",- "tags": [- "launch"- ]- },- {- "date": "2026-09-09",- "type": "launch",- "title": "Docs · Trader card embed",- "summary": "Put a live three.ws trader on any page with one script tag. The card shows the verified on-chain record and lets readers fork a coin or ghost-copy the trader, signing with their own wallet.",- "link": "/docs/trader-card-embed",- "tags": [- "launch"- ]}]}diff --git a/public/changelog.json b/public/changelog.jsonindex a6b4d7937..a55bfe3de 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,31 @@{- "generated_at": "2026-10-01T07:14:48.458Z",+ "generated_at": "2026-10-01T09:43:06.614Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-10-01",+ "type": "update",+ "title": "Avatar pictures show a natural standing pose instead of a T-pose",+ "summary": "The small pictures of avatars around the site, on Spotlight cards, in the Monitor fleet list, on Characters and on the Rankings board, were drawn with every avatar standing arms out in a stiff T. Avatar pictures are now drawn with the avatar standing naturally, arms relaxed at its sides, using the same posing the live 3D viewer uses, and that works for every skeleton style the viewer already understands. Props, vehicles and creatures are drawn exactly as they were made. Avatar pictures also keep their colored backdrop and their real textures again, where some had come out on plain black with bare white materials. Every avatar picture drawn from now on uses the new pose, and the older pictures can now be redrawn in place.",+ "link": "/spotlight",+ "tags": [+ "fix"+ ]+ },+ {+ "date": "2026-10-01",+ "type": "update",+ "title": "Avatars no longer open in a T-pose, and Spotlight shows one avatar instead of two",+ "summary": "On an Agent Spotlight page the avatar's preview picture, which is rendered arms out, never went away once the live 3D avatar loaded, so a second, T-posed copy stood behind the real one for as long as the page was open. The picture now gives way the moment the live avatar is ready. Separately, every embedded 3D avatar briefly showed its arms-out rest pose while its idle animation loaded and then faded in from it. The avatar now stays hidden until it is standing in its idle, then fades in, everywhere the avatar component is used.",+ "link": "/spotlight",+ "tags": [+ "fix"+ ]+ },{"date": "2026-10-01","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 69e3bc2ce..72298e57e 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,22 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws: features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Avatar pictures show a natural standing pose instead of a T-pose</title>+ <link>https://three.ws/spotlight</link>+ <guid isPermaLink="false">2026-10-01:Avatar pictures show a natural standing pose instead of a T-pose</guid>+ <pubDate>Thu, 01 Oct 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The small pictures of avatars around the site, on Spotlight cards, in the Monitor fleet list, on Characters and on the Rankings board, were drawn with every avatar standing arms out in a stiff T. Avatar pictures are now drawn with the avatar standing naturally, arms relaxed at its sides, using the same posing the live 3D viewer uses, and that works for every skeleton style the viewer already understands. Props, vehicles and creatures are drawn exactly as they were made. Avatar pictures also keep their colored backdrop and their real textures again, where some had come out on plain black with bare white materials. Every avatar picture drawn from now on uses the new pose, and the older pictures can now be redrawn in place.</description>+ </item>+ <item>+ <title>Avatars no longer open in a T-pose, and Spotlight shows one avatar instead of two</title>+ <link>https://three.ws/spotlight</link>+ <guid isPermaLink="false">2026-10-01:Avatars no longer open in a T-pose, and Spotlight shows one avatar instead of two</guid>+ <pubDate>Thu, 01 Oct 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>On an Agent Spotlight page the avatar's preview picture, which is rendered arms out, never went away once the live 3D avatar loaded, so a second, T-posed copy stood behind the real one for as long as the page was open. The picture now gives way the moment the live avatar is ready. Separately, every embedded 3D avatar briefly showed its arms-out rest pose while its idle animation loaded and then faded in from it. The avatar now stays hidden until it is standing in its idle, then fades in, everywhere the avatar component is used.</description>+ </item><item><title>Trading agents stop leaking SOL on every trade and can now ride a runner</title><link>https://three.ws/sniper/experiments</link>diff --git a/public/features.json b/public/features.jsonindex c4de43d65..fd83ca167 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-10-01T06:21:35.244Z",+ "generated_at": "2026-10-01T09:43:06.601Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/holo-geometry.js b/src/holo-geometry.jsnew file mode 100644index 000000000..a986b058d--- /dev/null+++ b/src/holo-geometry.js@@ -0,0 +1,310 @@+// Bendable extrusion for the holo sticker.+//+// THREE.ExtrudeGeometry triangulates each flat face from its outline alone, so a+// face is a fan of long slivers running edge to edge with no vertex inside. The+// peel is a per-vertex cylinder roll, and a triangle can only bend at its+// vertices: a sliver that crosses the fold line stays straight, cuts a chord+// through the curl, and reads as stair steps, then shards, then a crumple.+//+// extrudeBendable keeps ExtrudeGeometry's side walls and bevels (they are made+// of short quads along a dense outline, so they already bend), and rebuilds both+// flat faces as a constrained Delaunay triangulation of the exact same outline+// points plus an even triangular lattice of interior points. Every face edge is+// then shorter than maxEdge, so the roll has a vertex every few degrees of arc,+// and because the face reuses the walls' outline vertices bit for bit, nothing+// can open a crack along the rim when it curls.++import * as THREE from 'three';+import Delaunator from 'delaunator';+import Constrainautor from '@kninnug/constrainautor';++// ExtrudeGeometry drops index-adjacent points closer than this (scaled by the+// coordinate magnitude) before it builds the walls. The face outline has to+// drop exactly the same points or the rim stops sharing vertices with the wall.+const MERGE_EPS = 1e-10;++function dropOverlapping(points) {+ const out = points.slice();+ let prev = out[0];+ for (let i = 1; i <= out.length; i++) {+ const idx = i % out.length;+ const cur = out[idx];+ const scale = Math.max(Math.abs(cur.x), Math.abs(cur.y), Math.abs(prev.x), Math.abs(prev.y));+ const dx = cur.x - prev.x;+ const dy = cur.y - prev.y;+ if (dx * dx + dy * dy <= MERGE_EPS * MERGE_EPS * scale * scale) {+ out.splice(idx, 1);+ i--;+ continue;+ }+ prev = cur;+ }+ return out;+}++// Rings of one shape (outer first, then holes) exactly as ExtrudeGeometry+// sees them, so the face rim and the wall share every vertex.+function shapeRings(shape, curveSegments) {+ const { shape: outer, holes } = shape.extractPoints(curveSegments);+ return [outer, ...holes].map(dropOverlapping).filter((ring) => ring.length >= 3);+}++// Uniform bucket grid over the ring segments, for the "is this lattice point+// too close to the rim" test.+function segmentIndex(rings, cell) {+ const buckets = new Map();+ const key = (ix, iy) => ix * 73856093 ^ iy * 19349663;+ for (const ring of rings) {+ for (let i = 0; i < ring.length; i++) {+ const a = ring[i];+ const b = ring[(i + 1) % ring.length];+ const x0 = Math.floor(Math.min(a.x, b.x) / cell);+ const x1 = Math.floor(Math.max(a.x, b.x) / cell);+ const y0 = Math.floor(Math.min(a.y, b.y) / cell);+ const y1 = Math.floor(Math.max(a.y, b.y) / cell);+ for (let ix = x0; ix <= x1; ix++) {+ for (let iy = y0; iy <= y1; iy++) {+ const k = key(ix, iy);+ const list = buckets.get(k);+ if (list) list.push(a, b);+ else buckets.set(k, [a, b]);+ }+ }+ }+ }+ return (x, y, radius) => {+ const r2 = radius * radius;+ const cx = Math.floor(x / cell);+ const cy = Math.floor(y / cell);+ for (let ix = cx - 1; ix <= cx + 1; ix++) {+ for (let iy = cy - 1; iy <= cy + 1; iy++) {+ const list = buckets.get(key(ix, iy));+ if (!list) continue;+ for (let j = 0; j < list.length; j += 2) {+ if (segmentDist2(x, y, list[j], list[j + 1]) < r2) return true;+ }+ }+ }+ return false;+ };+}++function segmentDist2(px, py, a, b) {+ const vx = b.x - a.x;+ const vy = b.y - a.y;+ const len2 = vx * vx + vy * vy;+ const t = len2 > 0 ? Math.max(0, Math.min(1, ((px - a.x) * vx + (py - a.y) * vy) / len2)) : 0;+ const dx = a.x + vx * t - px;+ const dy = a.y + vy * t - py;+ return dx * dx + dy * dy;+}++// Even-odd scanline fill: the x spans of row y that lie inside the shape.+function rowSpans(rings, y) {+ const xs = [];+ for (const ring of rings) {+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {+ const a = ring[j];+ const b = ring[i];+ if (a.y > y !== b.y > y) xs.push(a.x + ((y - a.y) * (b.x - a.x)) / (b.y - a.y));+ }+ }+ xs.sort((p, q) => p - q);+ const spans = [];+ for (let i = 0; i + 1 < xs.length; i += 2) spans.push([xs[i], xs[i + 1]]);+ return spans;+}++// Interior points on an equilateral lattice of pitch `spacing`, kept at least+// a third of a pitch clear of the rim so no sliver forms against it.+function latticePoints(rings, spacing) {+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;+ for (const ring of rings) {+ for (const p of ring) {+ if (p.x < minX) minX = p.x;+ if (p.x > maxX) maxX = p.x;+ if (p.y < minY) minY = p.y;+ if (p.y > maxY) maxY = p.y;+ }+ }+ const clearance = spacing * 0.35;+ const nearRim = segmentIndex(rings, clearance);+ const rowH = (spacing * Math.sqrt(3)) / 2;+ const pts = [];+ let row = 0;+ for (let y = minY + rowH * 0.5; y < maxY; y += rowH, row++) {+ const shift = row % 2 ? spacing * 0.5 : 0;+ for (const [xa, xb] of rowSpans(rings, y)) {+ const start = Math.ceil((xa - minX - shift) / spacing) * spacing + minX + shift;+ for (let x = start; x < xb; x += spacing) {+ if (!nearRim(x, y, clearance)) pts.push(x, y);+ }+ }+ }+ return pts;+}++/**+ * Triangulate one flat face of a shape so no edge is longer than about+ * `maxEdge`: a constrained Delaunay triangulation of the rim points plus an+ * interior lattice, keeping only the triangles inside the shape.+ *+ * @param {THREE.Vector2[][]} rings outer ring first, then holes+ * @param {number} maxEdge target edge length+ * @returns {{ coords: Float64Array, triangles: number[] }} 2D points and+ * counter-clockwise index triples+ */+export function triangulateFace(rings, maxEdge) {+ const rimCount = rings.reduce((n, r) => n + r.length, 0);+ const inner = latticePoints(rings, maxEdge);++ // A frame well outside the shape keeps every rim edge off the convex hull,+ // so the hull triangles are always exterior and seed the inside/outside fill.+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;+ for (const ring of rings) {+ for (const p of ring) {+ if (p.x < minX) minX = p.x;+ if (p.x > maxX) maxX = p.x;+ if (p.y < minY) minY = p.y;+ if (p.y > maxY) maxY = p.y;+ }+ }+ const pad = Math.max(maxX - minX, maxY - minY) * 0.1 + maxEdge;+ const frame = [minX - pad, minY - pad, maxX + pad, minY - pad, maxX + pad, maxY + pad, minX - pad, maxY + pad];++ const coords = new Float64Array(rimCount * 2 + inner.length + frame.length);+ const edges = [];+ let n = 0;+ for (const ring of rings) {+ const first = n;+ for (let i = 0; i < ring.length; i++) {+ coords[n * 2] = ring[i].x;+ coords[n * 2 + 1] = ring[i].y;+ edges.push([n, i + 1 < ring.length ? n + 1 : first]);+ n++;+ }+ }+ coords.set(inner, n * 2);+ coords.set(frame, n * 2 + inner.length);++ const del = new Delaunator(coords);+ const con = new Constrainautor(del);+ con.constrainAll(edges);++ // Flood fill from the hull: crossing a rim edge flips inside/outside.+ const { triangles, halfedges } = del;+ const triCount = triangles.length / 3;+ const parity = new Int8Array(triCount).fill(-1);+ const queue = [];+ for (let e = 0; e < halfedges.length; e++) {+ if (halfedges[e] !== -1) continue;+ const t = Math.floor(e / 3);+ if (parity[t] === -1) {+ parity[t] = 0;+ queue.push(t);+ }+ }+ while (queue.length) {+ const t = queue.pop();+ for (let k = 0; k < 3; k++) {+ const e = t * 3 + k;+ const opp = halfedges[e];+ if (opp === -1) continue;+ const nt = Math.floor(opp / 3);+ if (parity[nt] !== -1) continue;+ parity[nt] = parity[t] ^ (con.isConstrained(e) ? 1 : 0);+ queue.push(nt);+ }+ }++ // Emit every kept triangle counter-clockwise in the y-up shape plane, so its+ // front face looks toward +z.+ const out = [];+ for (let t = 0; t < triCount; t++) {+ if (parity[t] !== 1) continue;+ const a = triangles[t * 3];+ const b = triangles[t * 3 + 1];+ const c = triangles[t * 3 + 2];+ const cross =+ (coords[b * 2] - coords[a * 2]) * (coords[c * 2 + 1] - coords[a * 2 + 1]) -+ (coords[b * 2 + 1] - coords[a * 2 + 1]) * (coords[c * 2] - coords[a * 2]);+ if (cross > 0) out.push(a, b, c);+ else out.push(a, c, b);+ }+ return { coords, triangles: out };+}++/**+ * ExtrudeGeometry whose flat faces are finely and evenly triangulated, so a+ * vertex-shader bend (the sticker peel) curls them smoothly.+ *+ * @param {THREE.Shape[]} shapes+ * @param {object} options ExtrudeGeometry options (bevel required, no path)+ * @param {number} maxEdge longest edge allowed across a flat face+ * @returns {THREE.BufferGeometry} indexed geometry with position, normal, uv;+ * group 0 is the faces, group 1 the walls and bevels+ */+export function extrudeBendable(shapes, options, maxEdge) {+ const curveSegments = options.curveSegments ?? 12;+ const depth = options.depth ?? 1;+ const bevelThickness = options.bevelEnabled ? (options.bevelThickness ?? 0.2) : 0;+ const zBottom = -bevelThickness;+ const zTop = depth + bevelThickness;++ const pos = [];+ const nor = [];+ const uv = [];+ const capIndex = [];+ const wallIndex = [];++ for (const shape of shapes) {+ const rings = shapeRings(shape, curveSegments);+ if (!rings.length) continue;++ const { coords, triangles } = triangulateFace(rings, maxEdge);+ const used = new Map();+ const vertexAt = (i, z, nz) => {+ const k = nz > 0 ? i * 2 + 1 : i * 2;+ let v = used.get(k);+ if (v === undefined) {+ v = pos.length / 3;+ const x = coords[i * 2];+ const y = coords[i * 2 + 1];+ pos.push(x, y, z);+ nor.push(0, 0, nz);+ uv.push(x, y);+ used.set(k, v);+ }+ return v;+ };+ for (let t = 0; t < triangles.length; t += 3) {+ const [a, b, c] = [triangles[t], triangles[t + 1], triangles[t + 2]];+ capIndex.push(vertexAt(a, zTop, 1), vertexAt(b, zTop, 1), vertexAt(c, zTop, 1));+ capIndex.push(vertexAt(a, zBottom, -1), vertexAt(c, zBottom, -1), vertexAt(b, zBottom, -1));+ }++ const walls = new THREE.ExtrudeGeometry(shape, { ...options, curveSegments });+ const wp = walls.attributes.position.array;+ const wn = walls.attributes.normal.array;+ const wu = walls.attributes.uv.array;+ for (const g of walls.groups) {+ if (g.materialIndex !== 1) continue;+ for (let i = g.start; i < g.start + g.count; i++) {+ wallIndex.push(pos.length / 3);+ pos.push(wp[i * 3], wp[i * 3 + 1], wp[i * 3 + 2]);+ nor.push(wn[i * 3], wn[i * 3 + 1], wn[i * 3 + 2]);+ uv.push(wu[i * 2], wu[i * 2 + 1]);+ }+ }+ walls.dispose();+ }++ const geometry = new THREE.BufferGeometry();+ geometry.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));+ geometry.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));+ geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));+ geometry.setIndex([...capIndex, ...wallIndex]);+ geometry.addGroup(0, capIndex.length, 0);+ geometry.addGroup(capIndex.length, wallIndex.length, 1);+ return geometry;+}diff --git a/src/holo.js b/src/holo.jsindex 31a2c82d4..f14a4171d 100644--- a/src/holo.js+++ b/src/holo.js@@ -14,6 +14,7 @@// cylinder, normals rotate with it, so the lighting on the curled lip is real.import * as THREE from 'three';+import { extrudeBendable } from './holo-geometry.js';const $ = (id) => document.getElementById(id);@@ -243,6 +244,14 @@ const WORLD_W = 3.1; // sticker width in world unitsconst BASE_DEPTH = 0.028;const MARK_DEPTH = 0.05;+// The peel rolls the sticker around a cylinder whose radius grows with the+// peel amount. Faces need a vertex every few degrees of that roll to curl+// instead of folding into facets, so their longest edge is pinned to the+// tightest radius: about 14 degrees of arc per lattice edge, about 19 at the rim.+const PEEL_RADIUS_MIN = 0.17;+const PEEL_RADIUS_GAIN = 0.18;+const FACE_EDGE = PEEL_RADIUS_MIN * 0.24;+function buildStickerGeometry(markDraw) {const markCanvas = makeCanvas(RASTER);markDraw(markCanvas.getContext('2d'), RASTER);@@ -270,21 +279,21 @@ function buildStickerGeometry(markDraw) {const markShapes = contoursToShapes(markContours, transform);if (!baseShapes.length) return null;- const base = new THREE.ExtrudeGeometry(baseShapes, {+ const base = extrudeBendable(baseShapes, {depth: BASE_DEPTH,bevelEnabled: true,bevelThickness: 0.016,bevelSize: 0.016,bevelSegments: 3,- });+ }, FACE_EDGE);const mark = markShapes.length- ? new THREE.ExtrudeGeometry(markShapes, {+ ? extrudeBendable(markShapes, {depth: MARK_DEPTH,bevelEnabled: true,bevelThickness: 0.02,bevelSize: 0.02,bevelSegments: 4,- })+ }, FACE_EDGE): null;if (mark) mark.translate(0, 0, BASE_DEPTH + 0.002);@@ -585,7 +594,7 @@ function init(renderer) {peelUniforms.uFoldT.value = amount <= 0.001? cornerT + 1: cornerT - amount * reach;- peelUniforms.uRadius.value = 0.17 + amount * 0.18;+ peelUniforms.uRadius.value = PEEL_RADIUS_MIN + amount * PEEL_RADIUS_GAIN;}/* interaction: pointer tilt with spring, drag for full control */diff --git a/tests/holo-geometry.test.js b/tests/holo-geometry.test.jsnew file mode 100644index 000000000..95e1df449--- /dev/null+++ b/tests/holo-geometry.test.js@@ -0,0 +1,146 @@+// The holo sticker peel bends geometry per vertex, so the flat faces have to+// carry interior vertices and short edges, and their rim has to be the very+// same vertices as the side walls or the curl opens a crack.+import { describe, it, expect } from 'vitest';+import * as THREE from 'three';+import { extrudeBendable } from '../src/holo-geometry.js';++const MAX_EDGE = 0.04;+const OPTIONS = { depth: 0.028, bevelEnabled: true, bevelThickness: 0.016, bevelSize: 0.016, bevelSegments: 3 };++// Dense outlines like the marching-squares tracer produces (sub-0.01 spacing).+function circle(cx, cy, r, n, clockwise = false) {+ const pts = [];+ for (let i = 0; i < n; i++) {+ const a = (i / n) * Math.PI * 2 * (clockwise ? -1 : 1);+ pts.push(new THREE.Vector2(cx + r * Math.cos(a), cy + r * Math.sin(a)));+ }+ return pts;+}++// Straight, axis-aligned edges sampled densely: long runs of exactly collinear+// rim points, which is what a die-cut bar or a block letter traces to.+function rect(x0, y0, x1, y1, step, clockwise = false) {+ const pts = [];+ const run = (ax, ay, bx, by) => {+ const n = Math.max(1, Math.round(Math.hypot(bx - ax, by - ay) / step));+ for (let i = 0; i < n; i++) pts.push(new THREE.Vector2(ax + ((bx - ax) * i) / n, ay + ((by - ay) * i) / n));+ };+ run(x0, y0, x1, y0);+ run(x1, y0, x1, y1);+ run(x1, y1, x0, y1);+ run(x0, y1, x0, y0);+ return clockwise ? pts.reverse() : pts;+}++function disc() {+ const shape = new THREE.Shape(circle(0, 0, 1.3, 1000));+ shape.holes.push(new THREE.Path(circle(0.5, 0, 0.3, 220, true)));+ shape.holes.push(new THREE.Path(circle(-0.5, 0.1, 0.22, 160, true)));+ return { shapes: [shape], area: Math.PI * (1.3 ** 2 - 0.3 ** 2 - 0.22 ** 2) };+}++// Two islands, one shaped like a block "O" with a rectangular counter.+function blockLetters() {+ const o = new THREE.Shape(rect(-1.5, -0.6, -0.3, 0.6, 0.007));+ o.holes.push(new THREE.Path(rect(-1.15, -0.3, -0.65, 0.3, 0.007, true)));+ const bar = new THREE.Shape(rect(0, -0.6, 1.5, -0.25, 0.007));+ return { shapes: [o, bar], area: 1.2 * 1.2 - 0.5 * 0.6 + 1.5 * 0.35 };+}++function faceStats(geometry, top) {+ const pos = geometry.attributes.position;+ const index = geometry.index.array;+ const face = geometry.groups.find((g) => g.materialIndex === 0);+ const zTop = OPTIONS.depth + OPTIONS.bevelThickness;+ const onFace = (v) => Math.abs(pos.getZ(v) - (top ? zTop : -OPTIONS.bevelThickness)) < 1e-6;+ const key = (v) => `${pos.getX(v)},${pos.getY(v)}`;+ const edgeUse = new Map();+ let area = 0;+ let maxEdge = 0;+ let wrongWinding = 0;+ const verts = new Set();+ for (let i = face.start; i < face.start + face.count; i += 3) {+ const tri = [index[i], index[i + 1], index[i + 2]];+ if (!tri.every(onFace)) continue;+ const [a, b, c] = tri;+ const cross =+ (pos.getX(b) - pos.getX(a)) * (pos.getY(c) - pos.getY(a)) -+ (pos.getY(b) - pos.getY(a)) * (pos.getX(c) - pos.getX(a));+ area += Math.abs(cross) / 2;+ if (top ? cross <= 0 : cross >= 0) wrongWinding++;+ for (const [u, v] of [[a, b], [b, c], [c, a]]) {+ maxEdge = Math.max(maxEdge, Math.hypot(pos.getX(u) - pos.getX(v), pos.getY(u) - pos.getY(v)));+ const k = [key(u), key(v)].sort().join('|');+ edgeUse.set(k, (edgeUse.get(k) || 0) + 1);+ }+ tri.forEach((v) => verts.add(key(v)));+ }+ const rimEdges = [...edgeUse].filter(([, n]) => n === 1).map(([k]) => k);+ const rimVerts = new Set(rimEdges.flatMap((k) => k.split('|')));+ return { area, maxEdge, wrongWinding, rimEdges, interior: verts.size - rimVerts.size };+}++// Every edge of the wall triangles, keyed by its two (x, y, z) endpoints.+function wallEdges(geometry, z) {+ const pos = geometry.attributes.position;+ const index = geometry.index.array;+ const wall = geometry.groups.find((g) => g.materialIndex === 1);+ const at = (v) => Math.abs(pos.getZ(v) - z) < 1e-6;+ const key = (v) => `${pos.getX(v)},${pos.getY(v)}`;+ const edges = new Set();+ for (let i = wall.start; i < wall.start + wall.count; i += 3) {+ const tri = [index[i], index[i + 1], index[i + 2]];+ for (const [u, v] of [[tri[0], tri[1]], [tri[1], tri[2]], [tri[2], tri[0]]]) {+ if (at(u) && at(v)) edges.add([key(u), key(v)].sort().join('|'));+ }+ }+ return edges;+}++describe('extrudeBendable', () => {+ for (const [name, build] of [['disc with two holes', disc], ['block letters with collinear rims', blockLetters]]) {+ describe(name, () => {+ const { shapes, area } = build();+ const geometry = extrudeBendable(shapes, OPTIONS, MAX_EDGE);++ for (const top of [true, false]) {+ const side = top ? 'top' : 'bottom';+ const stats = faceStats(geometry, top);++ it(`${side} face has interior vertices for the roll to bend`, () => {+ expect(stats.interior).toBeGreaterThan(area / (MAX_EDGE * MAX_EDGE));+ });++ it(`${side} face has no edge much longer than the bound`, () => {+ expect(stats.maxEdge).toBeLessThan(MAX_EDGE * 1.5);+ });++ it(`${side} face covers exactly the shape, holes left open`, () => {+ expect(stats.area).toBeCloseTo(area, 2);+ });++ it(`${side} face points ${top ? 'up' : 'down'}`, () => {+ expect(stats.wrongWinding).toBe(0);+ });++ it(`${side} face rim is welded to the side walls`, () => {+ const z = top ? OPTIONS.depth + OPTIONS.bevelThickness : -OPTIONS.bevelThickness;+ const walls = wallEdges(geometry, z);+ const loose = stats.rimEdges.filter((e) => !walls.has(e));+ expect(stats.rimEdges.length).toBeGreaterThan(0);+ expect(loose).toEqual([]);+ });+ }++ it('keeps the walls and bevels identical to ExtrudeGeometry', () => {+ const reference = new THREE.ExtrudeGeometry(shapes, OPTIONS);+ const wallCount = reference.groups+ .filter((g) => g.materialIndex === 1)+ .reduce((n, g) => n + g.count, 0);+ expect(geometry.groups.find((g) => g.materialIndex === 1).count).toBe(wallCount);+ reference.dispose();+ });+ });+ }+});